content
stringlengths
5
1.05M
return {'jicht','jichtaanval','jichtig','jichtknobbel','jichtlijder','jichtpijn','jichtaanvallen','jichtige','jichtknobbels','jichtlijders','jichtpijnen'}
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -- -- ───────────────────────────────────────────────── -- -- Plugin: nvim-treesitter -- Github: github.com/nvim-treesitter/nvim-treesitter -- ───────────────────────────────────────────────── -- -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -- -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -- -- ━━━━━━━━━━━━━━━━━━━❰ configs ❱━━━━━━━━━━━━━━━━━━━ -- -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -- require'nvim-treesitter.configs'.setup { -- ensure_installed = "maintained", -- one of "all", "maintained" (parsers with maintainers), or a list of languages -- ignore_install = { "javascript" }, -- List of parsers to ignore installing ensure_installed = {"html", "css", "vim", "lua", "javascript", "typescript", "tsx", "cpp", "c_sharp", "json"}, highlight = { enable = true, -- {"c", "cpp", "dart", "python", "javascript"}, enable = true (false will disable the whole extension) -- disable = { "c", "rust" }, -- list of language that will be disabled custom_captures = { -- Highlight the @foo.bar capture group with the "Identifier" highlight group. ["foo.bar"] = "Identifier" }, -- Setting this to true will run `:h syntax` and tree-sitter at the same time. -- Set this to `true` if you depend on 'syntax' being enabled (like for indentation). -- Using this option may slow down your editor, and you may see some duplicate highlights. -- Instead of true it can also be a list of languages additional_vim_regex_highlighting = true }, rainbow = { enable = true, -- disable = { "jsx", "cpp" }, list of languages you want to disable the plugin for extended_mode = true, -- Also highlight non-bracket delimiters like html tags, boolean or table: lang -> boolean max_file_lines = nil -- Do not enable for files with more than n lines, int -- colors = {}, -- table of hex strings -- termcolors = {} -- table of colour name strings }, playground = { enable = true, disable = {}, updatetime = 25, -- Debounced time for highlighting nodes in the playground from source code persist_queries = false -- Whether the query persists across vim sessions -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -- -- ━━━━━━━━━━━━━━━━━❰ end configs ❱━━━━━━━━━━━━━━━━━ -- -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -- -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -- -- ━━━━━━━━━━━━━━━━━━━❰ Mappings ❱━━━━━━━━━━━━━━━━━━ -- -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -- -- keybindings = { -- toggle_query_editor = 'o', -- toggle_hl_groups = 'i', -- toggle_injected_languages = 't', -- toggle_anonymous_nodes = 'a', -- toggle_language_display = 'I', -- focus_language = 'f', -- unfocus_language = 'F', -- update = 'R', -- goto_node = '<cr>', -- show_help = '?' -- } } } -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -- -- ━━━━━━━━━━━━━━━━━❰ end Mappings ❱━━━━━━━━━━━━━━━━ -- -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ --
-- Since there are two i2c on esp32, I setup one i2c as master and the other one as slave, and read/write them on the esp32 -- slave : -- GPIO25 is assigned as the data signal of i2c slave port -- GPIO26 is assigned as the clock signal of i2c slave port -- master: -- GPIO18 is assigned as the data signal of i2c master port -- GPIO19 is assigned as the clock signal of i2c master port -- connect GPIO18 with GPIO25 -- connect GPIO19 with GPIO26 i2c.setup(i2c.SLAVE,i2c.I2C_0,26,25,40) i2c.setup(i2c.MASTER,i2c.I2C_1,19,18) -- slave write something, master read i2c.write(i2c.SLAVE,i2c.I2C_0,40,"helloworld") c=i2c.read(i2c.MASTER,i2c.I2C_1,40,10) print(c) tmr.delay(5) -- master write something, slave read i2c.write(i2c.MASTER,i2c.I2C_1,40,"test") c=i2c.read(i2c.SLAVE,i2c.I2C_0,40,4) print(c) -- i2c uninstall i2c.uninstall(i2c.I2C_0) i2c.uninstall(i2c.I2C_1)
---create an instance of RunAfter (so tests are independent of each other) ---@return RunAfter local function makeRunAfter() ---@class RunAfter local RunAfter = {} local private = {} if EXPOSE_PRIVATE_FOR_TESTING then RunAfter.private = private end --#region type definitions ---@class Options ---@field immoName string ---@field axisName string ---@field loadFn fun(): string ---@field saveFn fun(content: string) ---@class UserOptions ---@field axisName string ---@field immoName number | string ---@class ScheduledTask ---@field time number @absolute time this task should run at ---@field func string|function @the function to execute (if this is a string, the task will be stored in a slot or tag text; if it's a function, it won't) --#endregion type definitions --#region private members ---@type Options private.options = { axisName = 'Timer' } ---List of all scheduled tasks, sorted by time ascending. --- ---The task that will be executed first is at the start of the list, like this: ---``` ---{ --- {time = 1, ...}, --- ... --- {time = 50, ...}, ---} ---``` ---@type ScheduledTask[] private.scheduledTasks = {} --#endregion private members --#region private functions ---Formats a string or a number into a immoName (string starting with `'#'`). ---This function doesn't check whether the resulting immoName is valid ---@param immoName string | number ---@return string immoName @in the format `'#123'` function private.toImmoName(immoName) if type(immoName) == 'number' then return '#' .. immoName else return immoName end end ---Parses a time value given as a string or number. --- ---All the following time values return `5420` seconds: ---* `5420` (number) ---* `"5420"` (numeric string) ---* `"5420s"` (explicit seconds) ---* `"1h30m20s"` (mix of units) ---* `"1h 30m 20s"` (with spaces) ---* `"1.5h20s"` (with decimals) ---* `"90m20s"` (with "overflow") ---@param timeValue string | number ---@return number @the time in seconds function private.toNumberOfSeconds(timeValue) if type(timeValue) == 'number' then return timeValue elseif type(timeValue) == 'string' then local seconds = 0 local numberPattern, unitPattern = '%d+%.?%d*', '[hms]?' for match in string.gmatch(timeValue, numberPattern .. unitPattern) do local _, _, numeric, unit = string.find(match, string.format('(%s)(%s)', numberPattern, unitPattern)) local number = tonumber(numeric) local multiplier = ({h = 60 * 60, m = 60, s = 1})[unit] or 1 seconds = seconds + (number * multiplier) end -- print(timeValue, '-', string.find(timeValue, '(%d+[hms])')) return seconds end end ---Returns a string representation of the given `value`, which is parsable by Lua ---@param value any ---@return string function private.serialize(value) ---all keywords reserved by Lua, taken from the manual ---@type table<string,boolean|nil> local reservedKeywords = { ['and'] = true, ['break'] = true, ['do'] = true, ['else'] = true, ['elseif'] = true, ['end'] = true, ['false'] = true, ['for'] = true, ['function'] = true, ['goto'] = true, ['if'] = true, ['in'] = true, ['local'] = true, ['nil'] = true, ['not'] = true, ['or'] = true, ['repeat'] = true, ['return'] = true, ['then'] = true, ['true'] = true, ['until'] = true, ['while'] = true } ---checks whether `key` is an identifier according to the Lua specification (§3.1) ---@param key any ---@return boolean local function isIdentifier(key) if type(key) ~= 'string' then return false elseif reservedKeywords[key] then return false elseif string.match(key, '^[_%a][_%d%a]*$') then -- "any string of letters, digits, and underscores, not beginning with a digit" return true else return false end end local function serializeRecursively(valueToSerialize, alreadyVisited) local serializers = { ['nil'] = tostring, boolean = tostring, number = tostring, string = function(str) -- use %q-formatting, and replace escaped linebreaks with \n -- extra parentheses to trim the return values of gsub return (string.gsub(string.format('%q', str), '\\\n', '\\n')) end, table = function(tbl) if alreadyVisited[tbl] then error('cannot serialize recursive tables') end alreadyVisited[tbl] = true local serializedSegments = {} local visitedByIpairs = {} for i, v in ipairs(tbl) do visitedByIpairs[i] = true table.insert(serializedSegments, serializeRecursively(v, alreadyVisited)) end for k, v in pairs(tbl) do if not visitedByIpairs[k] then local serializedValue = serializeRecursively(v, alreadyVisited) local segment if isIdentifier(k) then segment = string.format('%s=%s', k, serializedValue) else segment = string.format('[%s]=%s', serializeRecursively(k, alreadyVisited), serializedValue) end table.insert(serializedSegments, segment) end end alreadyVisited[tbl] = nil return string.format('{%s}', table.concat(serializedSegments, ',')) end } local serializer = serializers[type(valueToSerialize)] if serializer == nil then error(string.format('serializing values of type %s is not supported', type(valueToSerialize))) end return serializer(valueToSerialize) end return serializeRecursively(value, {}) end ---Returns the current time (based on the axis position) ---@return number currentTime @current time in seconds function private.getCurrentTime() local _, axisPosition = EEPStructureGetAxis(private.options.immoName, private.options.axisName) return axisPosition end function private.loadFromStorage() local stringFromStorage = private.options.loadFn and private.options.loadFn() or '' local fun, errorMessage = load('return ' .. stringFromStorage, stringFromStorage) if fun == nil then error('data from storage is incomplete: ' .. errorMessage) end local compressedTaskList = fun() for index, value in ipairs(compressedTaskList or {}) do private.scheduledTasks[index] = {time = value[1], func = value[2]} end private.resetTimerAxis() end function private.saveToStorage() if type(private.options.saveFn) ~= 'function' then return end local compressedTaskList = {} for _, task in ipairs(private.scheduledTasks) do if type(task.func) == 'string' then table.insert(compressedTaskList, {task.time, task.func}) end end private.options.saveFn(private.serialize(compressedTaskList)) end function private.resetTimerAxis() local resetInterval = 60 local shouldInsertResetTask = true local _, axisPosition = EEPStructureGetAxis(private.options.immoName, private.options.axisName) local newAxisPosition = axisPosition - resetInterval if newAxisPosition >= 0 then EEPStructureSetAxis(private.options.immoName, private.options.axisName, newAxisPosition) for _, task in ipairs(private.scheduledTasks) do if task.func == private.resetTimerAxis then shouldInsertResetTask = false else task.time = task.time - resetInterval end end private.saveToStorage() end if shouldInsertResetTask then private.insertTask({time = resetInterval, func = private.resetTimerAxis}) end end ---inserts a task at the right place into the list of all scheduled tasks ---@param task ScheduledTask function private.insertTask(task) local index = #private.scheduledTasks while index >= 1 and private.scheduledTasks[index].time > task.time do private.scheduledTasks[index + 1] = private.scheduledTasks[index] index = index - 1 end private.scheduledTasks[index + 1] = task if type(task.func) == 'string' then -- if task.func is a function, it won't get saved anyway private.saveToStorage() end end --#endregion private functions --#region public functions ---@param newOptions UserOptions function RunAfter.setOptions(newOptions) if type(newOptions) ~= 'table' then newOptions = {immoName = newOptions} end if newOptions.axisName then local axisName = newOptions.axisName assert(type(axisName) == 'string', 'axisName muss ein String sein, aber ist vom Typ ' .. type(axisName)) private.options.axisName = axisName end if newOptions.immoName then local immoName = private.toImmoName(newOptions.immoName) assert( type(immoName) == 'string', 'immoName muss eine Zahl oder ein String sein, aber ist vom Typ ' .. type(immoName) ) local CONTINUOUS_MOVEMENT = 1000 local ok = EEPStructureAnimateAxis(immoName, private.options.axisName, CONTINUOUS_MOVEMENT) assert( ok, string.format( 'Die Immobilie %s existiert nicht oder hat keine Achse namens %s', immoName, private.options.axisName ) ) private.options.immoName = immoName end private.loadFromStorage() end ---Executes due tasks. ---This function needs to be called periodically. function RunAfter.tick() local currentTime = private.getCurrentTime() local someTaskWasExecuted = false while private.scheduledTasks[1] ~= nil and private.scheduledTasks[1].time < currentTime do someTaskWasExecuted = true local task = private.scheduledTasks[1] table.remove(private.scheduledTasks, 1) if type(task.func) == 'function' then task.func() else local func, errMsg = load(task.func) if func then func() else error(errMsg) end end end if someTaskWasExecuted then private.saveToStorage() end end ---Registers a task that is executed in the future ---@param delay string|number @delay after which the function should be called, either as a number (in seconds) or as a string like "1m20s" ---@param func string|function @function to be called or name of the function ---@param params? any[] @table of paramaters for the function call, if the function is given as a string function RunAfter.runAfter(delay, func, params) local time = private.getCurrentTime() + private.toNumberOfSeconds(delay) if type(func) == 'string' then local serializedParams = {} for i, param in ipairs(params or {}) do serializedParams[i] = private.serialize(param) end func = string.format('%s(%s)', func, table.concat(serializedParams, ',')) end private.insertTask({time = time, func = func}) end --#endregion public functions return setmetatable( RunAfter, { ---@see RunAfter.runAfter __call = function(self, ...) return RunAfter.runAfter(...) end } ) end --#region module metadata return setmetatable( { _VERSION = {0, 0, 1}, _DESCRIPTION = 'Zeitverzögerte Auführung von Funktionen', _URL = 'https://github.com/EEP-Benny/RunAfter', _LICENSE = 'MIT' }, { ---returns an instance of RunAfter, configured with the given options ---@param options UserOptions ---@return RunAfter __call = function(self, options) local RunAfter = makeRunAfter() RunAfter.setOptions(options) return RunAfter end } ) --#endregion module metadata
-- settings_gui.lua -- -- Version 0.1 -- -- Copyright (C) 2013 David I. Gross. All Rights Reserved. -- -- This software is is protected by the author's copyright, and may not be used, copied, -- modified, merged, published, distributed, sublicensed, and/or sold, without -- written permission of the author. -- -- 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. -- --[[ Allow user to manage settings using dialog screens. --]] local funx = require( "scripts.funx" ) --module table local M = {} local pathToModule = "scripts/dialog/" -- Local settings for an app, e.g. current user, etc. M.values = {} -- This creates a dialog generator function local dialog = require ("scripts.dialog.dialog") -- Be CAREFUL not to use names of existing lua files, e.g. settings.lua unless you mean it!!! local settingsDialogName = "settingsDialog" local signInDialogName = "signinDialog" local newAccountDialogName = "createAccountDialog" -- Should we use Modal dialogs or let them stick around? -- Probably not if we want dialogs to be able to jump around. If we allow modal, -- then dialogs can lose their scenes, not a good thing. local isModal = false -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --[[ Wordpress connection Verify the user with WordPress --]] local mb_api = require ("mb_api") -------------------------------------------- local screenW, screenH = display.contentWidth, display.contentHeight local viewableScreenW, viewableScreenH = display.viewableContentWidth, display.viewableContentHeight local screenOffsetW, screenOffsetH = display.contentWidth - display.viewableContentWidth, display.contentHeight - display.viewableContentHeight local midscreenX = screenW*(0.5) local midscreenY = screenH*(0.5) local error_messages = { email_invalid = "Invalid email", email_exists = "Email already in use", username_invalid = "Username not acceptable", api_key_invalid = "My Mistake: Invalid API key!", user_creation_failed = "Account creation failed, I don't know why.", username_exists = "Username already in use.", } --- Get user information from WordPress -- @param url The URL of the website to contact -- @param username The username -- @param password -- @param onSuccess Function to run on success -- @param onFailure Function to run on failure -- @return local function getUserInfo(url, username, password, onSuccess, onFailure) function onError(result) print ("getUserInfo: ERROR:") funx.dump(result) end function onSuccess(result) print ("getUserInfo: onSuccess:") funx.dump(result) end -------------------------------------------- local url = "http://localhost/photobook/wordpress/" mb_api.getUserInfo(url, username, password, onSuccess, onError) return true end --- Update the settings window with the values -- This is useful after signing in and update the values. -- @return local function updateSettingsDialog() if (dialog.window[settingsDialogName].exists) then local dialogName = "settings" local id = "username" local newText = "You are signed in as <span font='Avenir-Black'>{username}</span> (<span font='Avenir-Black'>{displayname}</span>)" local f = { text = newText } dialog:replaceTextBlock(settingsDialogName, id, f, M.values.user) -- Update the sign in/out button local f = { label = "Sign Out", functionName = "signOutUser", } local id = "signOut" dialog:replaceButton(settingsDialogName, id, f, M.values.user) end end --- Set the conditions table based on the current M.values table -- @return conditions local function setConditions(windowName) local conditions = {} conditions = { signout = M.values.user.authorized or false, -- make sure it is boolean (could be nil!) signin = not M.values.user.authorized, } if (windowName) then dialog.window[windowName].conditions = conditions end --funx.tellUser("setConditions:Authorized:".. tostring(M.values.user.authorized)) return conditions end --- Set the conditions table based on the current M.values table -- @return conditions local function updateConditions(windowName) local conditions = {} conditions = { signout = M.values.user.authorized or false, -- make sure it is boolean (could be nil!) signin = not M.values.user.authorized, } if (windowName) then dialog.window[windowName].conditions = conditions end --funx.tellUser("setConditions:Authorized:".. tostring(M.values.user.authorized)) return conditions end --- Update a dialog.window table to use the current 'values' local function updateDialogParams(windowName) dialog.window[windowName].params.substitutions = M.values.user end ------------------------------------------------------------------------ --- Show a dialog -- @param windowname -- @param values (optional) updated key/value set used for substitutions in fields + texts -- @param conditions (optional) updated conditions table -- @return local function showDialog(windowName) local conditions = updateConditions(windowName) dialog:showWindow(windowName, M.values.user, conditions) end ------------------------------------------------------------------------ --- SIGN IN dialog -- @return local function showSettingsDialog() showDialog(settingsDialogName) end --- If the user exists, update new info about the user taken from the WP website. -- @param results -- @return local function signin_user(results) local username = results.username local password = results.password local url = "http://localhost/photobook/wordpress/" function onError(mb_api_result) funx.tellUser(mb_api_result.error) print ("signin_user: ERROR") funx.dump(mb_api_result) -- Set the conditionals for this dialog dialog.window[signInDialogName].conditions.authorized = false showSettingsDialog() return false end -- I think that Success ONLY means the network transaction worked! function onSuccess(mb_api_result) if (mb_api_result.status == "ok") then funx.tellUser("Sign In for '"..results.username .. "' confirmed.") M.values.user = funx.tableMerge(M.values.user, mb_api_result.user) M.values.user.authorized = true showSettingsDialog() --updateSettingsDialog() return true else funx.tellUser("Sign In for '"..results.username .. "' failed!") return false end end -------------------------------------------- mb_api.getUserInfo(url, username, password, onSuccess, onError) return true end -- --- If the user exists, update new info about the user taken from the WP website. -- @param results -- @return local function verify_user(results) function onError(mb_api_result) funx.tellUser(mb_api_result.error) print ("verify_user: ERROR") funx.dump(mb_api_result) return false end -- I think that Success ONLY means the network transaction worked! function onSuccess(mb_api_result) funx.tellUser("Sign In for '"..results.username .. "' confirmed.") -- Update values --local newvalues = { firstname = result.user.firstname, lastname = result.user.lastname, displayname = result.user.displayname } --dialog:addValuesToDocuments(signInDialogName, newvalues, showSavedFeedback) return true end -------------------------------------------- local username = results.username local password = results.password local url = "http://localhost/photobook/wordpress/" mb_api.getUserInfo(url, username, password, onSuccess, onError) return true end -------------------------------------------------------------------------------- -- Shortcut functions --- Shortcut to show sign-in dialog local function showSignInUserDialog() showDialog(signInDialogName) end --- Shortcut to show the create-new-account dialog local function openCreateNewAccountDialog() showDialog(newAccountDialogName) end --- Show the create new account dialog local function confirmAccount(results) return verify_user(results) end -------------------------------------------------------------------------------- -- If the user exists, update new info about the user taken from the WP website. -- The username, etc., might come back altered, e.g. user --> user_001 -- So we must update the values. -- Return true -> finished with dialog, do closing function -- Return false -> failure, keep dialog open so use can try again local function createNewAccount(results) function onError(mb_api_result) funx.tellUser(mb_api_result.error) print ("createNewAccount:", error_messages[mb_api_result.error]) return false end -- Success ONLY means the network transaction worked! function onSuccess(mb_api_result) if (mb_api_result.status == "error") then funx.tellUser(error_messages[mb_api_result.error]) print ("createNewAccount:", error_messages[mb_api_result.error]) return false else funx.tellUser("Account created.") print ("createNewAccount:", "Account created") -- Get updated values local newvalues = { username = mb_api_result.username, password = mb_api_result.password, email = mb_api_result.email, firstname = mb_api_result.firstname, lastname = mb_api_result.lastname, displayname = mb_api_result.displayname, } -- ***** THIS VALUE???? local showSavedFeedback = false dialog:addValuesToDocuments(newAccountDialogName, newvalues, showSavedFeedback) -- Update the settings dialog, too! dialog:addValuesToDocuments(signInDialogName, newvalues, showSavedFeedback) -- Add values to the main 'values' table M.values.user = funx.tableMerge(M.values.user, newvalues) showSignInUserDialog() return true end end -------------------------------------------- -- In this case, username/pass have to be an admin user -- who can create new accounts!!!! local username = "admin" local password = "nookie" local url = "http://localhost/photobook/wordpress/" mb_api.register_user(url, username, password, results, onSuccess, onError) return false end local function cancelled(results) funx.tellUser ("Cancelled") end ------------------------------------------------------------------------ -- SIGN IN dialog -- Create a dialog window to sign in -- @param dialogName Name of the dialog window -- @return local function createSignInDialog(dialogName) local options = { effect = "fade", time = 250, isModal = isModal, } -- Options for the dialog builder local params = { name = dialogName, substitutions = M.values.user, restoreValues = false, -- restore previous results from disk writeValues = false, -- save the results to disk onSubmitButton = nil, -- set this function or have another scene check dialogResults --onCancelButton = showSettingsDialog, -- set this function or have another scene check dialogResults cancelToSceneName = settingsDialogName, showSavedFeedback = false, -- show "saved" if save succeeds options = options, isModal = isModal, functions = { createNewAccountDialog = openCreateNewAccountDialog, confirmAccount = confirmAccount, signin = { action = signin_user, success = nil, failure = nil, }, }, cancelToSceneName = settingsDialogName, } -- Creates a new dialog scene dialog.new(params) end ------------------------------------------------------------------------ --- Create New account dialog -- @param dialogName Name of the dialog window -- @return local function createNewAccountDialog(dialogName) -- Success just means the network didn't fail! local function onSuccess(results) print ("createNewAccountDialog:onSuccess: ") funx.dump(results) showSignInUserDialog() end local function onFailure(results) funx.tellUser("Error: Probably a network connection error.") end local options = { effect = "fade", time = 250, isModal = isModal, } -- Options for the dialog builder local params = { name = dialogName, substitutions = M.values.user, restoreValues = true, -- restore previous results from disk writeValues = true, -- save the results to disk onSubmitButton = nil, -- set this function or have another scene check dialogResults --onCancelButton = showSettingsDialog, -- set this function or have another scene check dialogResults cancelToSceneName = settingsDialogName, showSavedFeedback = false, -- show "saved" if save succeeds options = options, isModal = isModal, functions = { createAccount = { action = createNewAccount, success = nil, failure = nil, }, }, } ------------------------------------------------------------------------ -- Creates a new dialog scene dialog.new(params) end --- Sign Out in settings dialog -- @return local function signOutUserInSettings() local currentUserName = "" local currentUserFullName = "" -- Update the username text block local dialogName = "settings" M.values.user.authorized = false M.values.user.username = "" M.values.user.password= "" M.values.user.displayname = "" local conditions = { signout = M.values.user.authorized or false, -- make sure it is boolean (could be nil!) signin = not M.values.user.authorized, } dialog:updateDialogByConditions(settingsDialogName, conditions) end ------------------------------------------------------------------------ --- SETTINGS dialog -- @param callback the function to call when user closes/cancels. -- @return local function createSettingsDialog(callback) -- Results are of the last closed dialog, not all results -- Merge these results into the final values that we return to the callback function. local function onCompletion(results) M.values = funx.tableMerge(M.values, results) --dialog:removeWindow(settingsDialogName) if (type(callback) == "function") then callback( M.values ) end end -- Options for the composer local options = { effect = "fade", time = 250, isModal = isModal, } -- Set the INITIAL conditions which control what is displayed. -- Params should update these conditions if the window is recreated local conditions = { signout = M.values.user.authorized or false, -- make sure it is boolean (could be nil!) signin = not M.values.user.authorized, } -- Options for the dialog builder local params = { name = settingsDialogName, substitutions = M.values.user, restoreValues = false, -- restore previous results from disk writeValues = false, -- save the results to disk onSubmitButton = onCompletion, -- set this function or have another scene check dialogResults onCancelButton = onCompletion, -- set this function or have another scene check dialogResults cancelToSceneName = storyboard.getCurrentSceneName(), -- cancel to the scene that called this dialog showSavedFeedback = false, -- show "saved" if save succeeds options = options, isModal = isModal, functions = { createNewAccountDialog = openCreateNewAccountDialog, signOutUser = { action = signOutUserInSettings, success = createSettingsDialog, failure = nil, }, signInUser = { action = showSignInUserDialog, success = nil, failure = nil, }, }, --conditions = conditions, } ------------------------------------------------------------------------ -- Creates a new dialog scene dialog.new(params) end local function init(values, onCompletion) M.values = values createSignInDialog(signInDialogName) createNewAccountDialog(newAccountDialogName) createSettingsDialog(onCompletion) end -- functions M.init = init M.showSettingsDialog = showSettingsDialog M.showDialog = showDialog return M
local playsession = { {"Knugn", {503955}}, {"EPO666", {218193}}, {"wekkka", {482881}}, {"Dammpi", {501429}}, {"untouchablez", {437330}}, {"NikolaB131", {495661}}, {"MovingMike", {486455}}, {"vvictor", {142548}}, {"Croustibax", {153755}}, {"Mrho", {1138}}, {"elvaleto", {446741}}, {"Thymey", {257809}}, {"Sexy_Platypus", {27298}}, {"Hyp3rX", {397313}}, {"Timfee", {299638}}, {"Tcheko", {326281}}, {"Tomy52499", {38219}}, {"exabyte", {71456}}, {"AmiloPL", {133628}}, {"harukine", {175006}}, {"D0pex", {125266}}, {"jackazzm", {137669}}, {"Jitikko", {4204}}, {"moqart", {61769}}, {"William071802", {73137}}, {"Killeraoc", {61418}}, {"dog80", {22539}}, {"vlad02", {4160}} } return playsession
-- Basic Movement Training -- Teaches the basic movement controls. --[[ Lessons: * How to show the mission panel again * Walking * Collecting crates * Health basics * Jumping * Fall damage * Walking and staying on ice * Switching hedgehogs * Bouncing on rubber ]] HedgewarsScriptLoad("/Scripts/Locale.lua") HedgewarsScriptLoad("/Scripts/Tracker.lua") HedgewarsScriptLoad("/Scripts/Utils.lua") local hhs = {} local hog_greenhorn, hog_cappy local crates = {} local switcherGear local tookDamage = false local switchTextDelay = -1 local missionPanelConfirmed = false local missionPanelConfirmedTimer = 0 local turnStarted = false local map = { "\1\74\7\29\135\1\74\8\11\0\1\83\7\135\135", "\1\250\7\135\0\1\204\7\137\135\1\238\7\135\0", "\2\17\7\130\0\2\42\7\110\0\2\74\7\94\0", "\2\106\7\89\0\2\99\7\121\0\2\76\7\128\0", "\2\115\7\98\135\2\147\7\98\0\2\179\7\94\0", "\2\147\7\96\0\2\174\7\89\0\2\145\7\91\135", "\2\115\7\87\0\2\122\7\89\135\2\154\7\89\0", "\2\170\7\89\0\2\179\7\105\135\2\179\7\107\135", "\2\177\7\142\135\2\177\8\105\0\3\74\7\94\135", "\3\74\8\50\0\3\88\7\89\135\3\129\7\89\0", "\3\161\7\91\0\3\193\7\98\0\3\225\7\100\0", "\4\1\7\91\0\4\33\7\89\0\4\65\7\98\0", "\4\97\7\100\0\4\134\7\103\0\4\166\7\100\0", "\4\200\7\98\0\4\232\7\96\0\5\8\7\96\0", "\5\40\7\98\0\5\72\7\98\0\5\107\7\100\0", "\5\139\7\98\0\5\173\7\89\0\5\207\7\94\0", "\5\239\7\100\0\6\15\7\100\0\6\47\7\100\0", "\6\86\7\100\0\6\118\7\100\0\6\153\7\94\0", "\6\185\7\91\0\6\219\7\91\0\6\251\7\98\0", "\7\27\7\103\0\7\61\7\100\0\7\94\7\96\0", "\7\126\7\91\0\7\160\7\94\0\7\192\7\105\0", "\7\224\7\116\0\7\254\7\126\0\8\34\7\123\0", "\8\66\7\119\0\8\98\7\114\0\8\133\7\119\0", "\8\165\7\132\0\8\195\7\142\0\8\229\7\146\0", "\9\5\7\151\0\9\37\7\155\0\9\69\7\164\0", "\9\101\7\174\0\9\131\7\190\0\9\160\7\208\0", "\9\186\7\226\0\9\215\7\240\0\9\250\7\238\0", "\10\26\7\233\0\10\58\7\233\0\10\90\7\235\0", "\10\122\7\238\0\10\154\7\238\0\10\186\7\249\0", "\10\213\8\14\0\10\245\8\9\0\11\3\8\39\0", "\11\24\8\66\0\11\10\8\62\0\10\213\8\5\135", "\10\245\8\7\0\11\21\8\14\0\11\56\8\25\0", "\11\92\8\37\0\11\106\8\43\0\9\85\8\0\147", "\9\83\8\0\0\8\208\7\233\147\3\168\7\197\147", "\8\94\7\197\0\2\83\7\210\147\1\179\7\238\0", "\1\44\7\84\139\1\12\7\87\0\0\238\7\98\0", "\0\211\7\119\0\0\190\7\144\0\0\165\7\164\0", "\0\146\7\190\0\0\140\7\222\0\0\142\7\254\0", "\0\153\8\30\0\0\156\8\37\0\1\7\7\178\139", "\0\247\7\210\0\0\224\7\238\0\0\215\8\14\0", "\0\215\8\18\0\1\5\7\238\139\1\19\8\11\0", "\1\32\8\43\0\1\39\8\62\0\1\67\7\32\136", "\1\69\6\253\0\1\69\6\219\0\1\69\6\187\0", "\1\74\6\155\0\1\80\6\123\0\1\51\6\109\0", "\1\35\6\80\0\1\12\6\105\0\0\243\6\132\0", "\0\233\6\176\0\0\252\6\212\0\1\14\6\240\0", "\0\252\7\13\0\0\233\6\219\0\0\238\6\182\0", "\0\238\6\148\0\1\12\6\164\0\1\9\6\201\0", "\0\236\6\224\0\0\206\6\251\0\0\165\7\32\0", "\0\144\7\57\0\0\124\7\82\0\0\103\7\107\0", "\0\96\7\144\0\0\92\7\176\0\0\112\7\139\0", "\0\121\7\105\0\0\130\7\61\0\0\142\7\25\0", "\0\156\6\251\0\0\188\6\247\0\0\201\6\217\0", "\0\167\6\224\0\0\146\6\251\0\0\130\7\25\0", "\0\112\7\66\0\0\98\7\110\0\0\98\7\142\0", "\0\98\7\174\0\0\101\7\206\0\0\101\7\238\0", "\0\126\8\7\0\0\137\8\14\0\10\46\7\245\136", "\10\14\7\247\0\9\241\7\229\0\9\209\7\222\0", "\9\176\7\226\0\9\138\7\233\0\9\94\7\233\0", "\9\62\7\233\0\9\46\7\235\0\2\53\7\139\136", "\2\21\7\137\0\1\250\7\119\0\1\218\7\116\0", "\1\186\7\119\0\1\151\7\119\0\1\119\7\114\0", "\1\92\7\135\0\1\78\7\132\0" } local function drawMap() for m=1, #map do ParseCommand("draw "..map[m]) end end function onGameInit() GameFlags = gfDisableWind + gfDisableGirders + gfDisableLandObjects + gfOneClanMode + gfInfAttack Map = "" Seed = 0 Theme = "Brick" MapGen = mgDrawn TurnTime = MAX_TURN_TIME Explosives = 0 MinesNum = 0 CaseFreq = 0 WaterRise = 0 HealthDecrease = 0 -- DRAW MAP -- drawMap() ------ HOG LIST ------ AddMissionTeam(-1) hhs[1] = AddMissionHog(100) SetGearPosition(hhs[1], 404, 1714) SetEffect(hhs[1], heResurrectable, 1) hhs[2] = AddMissionHog(100) SetGearPosition(hhs[2], 620, 1538) SetEffect(hhs[2], heResurrectable, 1) HogTurnLeft(hhs[2], true) hhs[3] = AddMissionHog(100) SetGearPosition(hhs[3], 1573, 1824) SetEffect(hhs[3], heResurrectable, 1) hhs[4] = AddHog(loc("Cappy"), 0, 100, "cap_red") SetGearPosition(hhs[4], 2114, 1411) SetEffect(hhs[4], heResurrectable, 1) HogTurnLeft(hhs[4], true) hhs[5] = AddMissionHog(100) SetGearPosition(hhs[5], 1813, 1285) SetEffect(hhs[5], heResurrectable, 1) hog_greenhorn = hhs[1] hog_cappy = hhs[4] for i=1,#hhs do if hhs[i] ~= hog_cappy then if GetHogName(hhs[i]) == loc("Cappy") then SetHogName(hhs[i], loc("Greenhorn")) end if GetHogHat(hhs[i]) == "cap_red" then SetHogHat(hhs[i], "NoHat") end end end SendHealthStatsOff() SendRankingStatsOff() end local function LoadGearData() --BEGIN CORE DATA-- ------ GIRDER LIST ------ PlaceSprite(292, 1488, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(454, 1731, sprAmGirder, 4, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(467, 1653, sprAmGirder, 4, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(611, 1702, sprAmGirder, 5, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(426, 1558, sprAmGirder, 7, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(555, 1558, sprAmGirder, 5, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(649, 1600, sprAmGirder, 7, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1072, 1809, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1040, 1831, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1124, 1805, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1175, 1772, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1226, 1738, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1275, 1705, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1325, 1700, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1342, 1638, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1368, 1560, sprAmGirder, 3, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1390, 1665, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1481, 1716, sprAmGirder, 4, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1625, 1652, sprAmGirder, 7, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(1729, 1596, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1762, 1545, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1563, 1536, sprAmGirder, 5, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(1506, 1392, sprAmGirder, 6, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(1591, 1450, sprAmGirder, 3, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(1650, 1463, sprAmGirder, 1, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(1766, 1492, sprAmGirder, 4, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(1925, 1492, sprAmGirder, 4, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(2114, 1428, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2187, 1435, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2135, 1478, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2284, 1650, sprAmGirder, 4, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2005, 1724, sprAmGirder, 4, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1885, 1562, sprAmGirder, 7, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2252, 1700, sprAmGirder, 2, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(2308, 1803, sprAmGirder, 5, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(2394, 1893, sprAmGirder, 1, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(605, 1761, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1813, 1312, sprAmGirder, 4, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1742, 1260, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1812, 1210, sprAmGirder, 4, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1884, 1260, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1545, 1811, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1577, 1761, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1610, 1811, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1440, 1511, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2082, 1337, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2187, 1273, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2097, 1246, sprAmGirder, 4, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(593, 1465, sprAmGirder, 7, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(684, 1505, sprAmGirder, 5, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2046, 1492, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2064, 1442, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1849, 1426, sprAmGirder, 4, U_LAND_TINT_ICE, nil, nil, nil, lfIce) PlaceSprite(3051, 1957, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(3101, 1956, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(3150, 1954, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(3233, 1962, sprAmGirder, 5, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(3322, 2004, sprAmGirder, 3, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(3391, 2001, sprAmGirder, 1, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(3483, 1982, sprAmGirder, 7, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2770, 1980, sprAmGirder, 4, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2886, 2005, sprAmGirder, 1, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2698, 1891, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2843, 1891, sprAmGirder, 6, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2834, 1771, sprAmGirder, 5, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2706, 1771, sprAmGirder, 7, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2768, 1818, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(2768, 1899, sprAmGirder, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(1760, 1393, sprAmGirder, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) PlaceSprite(516, 1795, sprAmGirder, 4, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) ------ RUBBER LIST ------ PlaceSprite(2151, 1659, sprAmRubber, 3, U_LAND_TINT_NORMAL, nil, nil, nil, lfBouncy) PlaceSprite(2399, 1698, sprAmRubber, 3, U_LAND_TINT_NORMAL, nil, nil, nil, lfBouncy) PlaceSprite(2467, 1553, sprAmRubber, 2, U_LAND_TINT_NORMAL, nil, nil, nil, lfBouncy) PlaceSprite(2279, 1497, sprAmRubber, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfBouncy) PlaceSprite(2414, 1452, sprAmRubber, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfBouncy) PlaceSprite(1860, 1687, sprAmRubber, 1, U_LAND_TINT_NORMAL, nil, nil, nil, lfBouncy) ------ SPRITE LIST ------ PlaceSprite(1297, 1732, sprTargetBee, 0, U_LAND_TINT_NORMAL, nil, nil, nil, lfNormal) ------ CRATE LIST ------ crates[1] = SpawnHealthCrate(401, 1850) -- Jumping crates[2] = SpawnHealthCrate(2639, 1973) -- Final crate crates[3] = SpawnHealthCrate(1969, 1698) -- Rubber crates[4] = SpawnHealthCrate(889, 1829) -- Back Jumping crates[5] = SpawnHealthCrate(1486, 1694) -- Walking on Ice crates[6] = SpawnHealthCrate(2033, 1470) -- Walking on Ice completed crates[7] = SpawnHealthCrate(1198, 1750) -- Back Jumping 2 crates[8] = SpawnSupplyCrate(1851, 1402, amSwitch, 100) -- Switch Hedgehog crates[9] = SpawnHealthCrate(564, 1772) -- Health -- FIXME: Not available in touch because no “precise” button if INTERFACE ~= "touch" then crates[10] = SpawnHealthCrate(2290, 1622) -- Turning Around end end local function victory() SaveMissionVar("Won", "true") ShowMission(loc("Basic Movement Training"), loc("Training complete!"),loc("Congratulations! You have completed the obstacle course!"), 0, 0) SendStat(siGameResult, loc("You have completed the Basic Movement Training!")) SendStat(siCustomAchievement, loc("Congratulations!")) SendStat(siCustomAchievement, loc("Return to the training menu by pressing the “Go back” button.")) PlaySound(sndVictory, CurrentHedgehog) -- Disable controls, end game SetInputMask(0) SetWeapon(amNothing) SetGearMessage(CurrentHedgehog, band(GetGearMessage(CurrentHedgehog), bnot(gmAllStoppable))) EndGame() for i=1,#hhs do SetState(hhs[i], gstWinner) end end local function switchHedgehogText() if CurrentHedgehog == hog_cappy then ShowMission(loc("Basic Movement Training"), loc("Switch Hedgehog (3/3)"), loc("This is Cappy.").."|".. loc("To finish hedgehog selection, just do anything|with him, like walking."), 2, 20000) else local ctrl = "" if INTERFACE == "desktop" then ctrl = loc("Hit the “Switch Hedgehog” key until you have|selected Cappy, the hedgehog with the cap!").."|".. loc("Switch hedgehog: [Tabulator]") else ctrl = loc("Tap the “rotating arrow” button on the left|until you have selected Cappy, the hedgehog with the cap!") end ShowMission(loc("Basic Movement Training"), loc("Switch Hedgehog (2/3)"), loc("You have activated Switch Hedgehog!").."|".. loc("The spinning arrows above your hedgehog show|which hedgehog is selected right now.").."|".. ctrl, 2, 20000) end end function onGearAdd(gear) if GetGearType(gear) == gtSwitcher then switcherGear = gear switchHedgehogText() end end function onGearDelete(gear) local ctrl = "" -- Switching done if GetGearType(gear) == gtSwitcher then switcherGear = nil if CurrentHedgehog == hog_cappy then ShowMission(loc("Basic Movement Training"), loc("Leap of Faith"), loc("Good! You now control Cappy.").."|".. loc("Collect the remaining crates to complete the training."), 2, 0) else if INTERFACE == "desktop" then ctrl = loc("Open ammo menu: [Right click]").."|".. loc("Attack: [Space]") elseif INTERFACE == "touch" then ctrl = loc("Open ammo menu: Tap the [Suitcase]").."|".. loc("Attack: Tap the [Bomb]") end ShowMission(loc("Basic Movement Training"), loc("Switch Hedgehog (Failed!)"), loc("Oops! You have selected the wrong hedgehog! Just try again.").."|".. loc("Select “Switch Hedgehog” from the ammo menu and|hit the “Attack” key to proceed.").."|".. ctrl, 2, 0) end -- Crate collected (or destroyed, but this should not be possible) elseif gear == crates[1] then if INTERFACE == "desktop" then ctrl = loc("Long Jump: [Enter]") elseif INTERFACE == "touch" then ctrl = loc("Long Jump: Tap the [Curvy Arrow] button for long") end ShowMission(loc("Basic Movement Training"), loc("Jumping"), loc("Get the next crate by jumping over the abyss.").."|".. loc("Careful, hedgehogs can't swim!").."|".. ctrl, 2, 5000) elseif gear == crates[2] then victory() elseif gear == crates[4] then if INTERFACE == "desktop" then ctrl = loc("High Jump: [Backspace]").."|"..loc("Back Jump: [Backspace] ×2") elseif INTERFACE == "touch" then ctrl = loc("High Jump: Tap the [Curvy Arrow] shortly").."|"..loc("Back Jump: Double-tap the [Curvy Arrow]") end ShowMission(loc("Basic Movement Training"), loc("Back Jumping (1/2)"), loc("For the next crate, you have to do back jumps.") .. "|" .. loc("To reach higher ground, walk to a ledge, look to the left, then do a back jump.") .. "|" .. ctrl, 2, 6600) elseif gear == crates[7] then if INTERFACE == "desktop" then ctrl = loc("High Jump: [Backspace]").."|"..loc("Back Jump: [Backspace] ×2") elseif INTERFACE == "touch" then ctrl = loc("High Jump: Tap the [Curvy Arrow] shortly").."|"..loc("Back Jump: Double-tap the [Curvy Arrow]") end ShowMission(loc("Basic Movement Training"), loc("Back Jumping (2/2)"), loc("To get over the next obstacles, keep some distance from the wall before you back jump.").."|".. loc("Hint: To jump higher, wait a bit before you hit “High Jump” a second time.").."|".. ctrl, 2, 15000) elseif gear == crates[5] then -- FIXME: Touch doesn't have precise aim yet :( if INTERFACE == "desktop" then ctrl = "|" .. loc("You can also hold down the key for “Precise Aim” to prevent slipping.") .. "|" .. loc("Precise Aim: [Left Shift]") end ShowMission(loc("Basic Movement Training"), loc("Walking on Ice"), loc("These girders are slippery, like ice.").."|".. loc("And you need to move to the top!").."|".. loc("If you don't want to slip away, you have to keep moving!").. ctrl, 2, 9000) elseif gear == crates[6] then -- FIXME: Touch doesn't have precise aim yet :( if INTERFACE == "desktop" then ctrl = "|" .. loc("Remember: Hold down [Left Shift] to prevent slipping") end ShowMission(loc("Basic Movement Training"), loc("A mysterious Box"), loc("The next crate is an utility crate.").."|"..loc("What's in the box, you ask? Let's find out!").. ctrl, 2, 6000) elseif gear == crates[8] then if INTERFACE == "desktop" then ctrl = loc("Open ammo menu: [Right click]").."|".. loc("Attack: [Space]") elseif INTERFACE == "touch" then ctrl = loc("Open ammo menu: Tap the [Suitcase]").."|".. loc("Attack: Tap the [Bomb]") end ShowMission(loc("Basic Movement Training"), loc("Switch Hedgehog (1/3)"), loc("You have collected the “Switch Hedgehog” utility!").."|".. loc("This allows to select any hedgehog in your team!").."|".. loc("Select “Switch Hedgehog” from the ammo menu and|hit the “Attack” key.").."|".. ctrl, 2, 30000) elseif gear == crates[3] then ShowMission(loc("Basic Movement Training"), loc("Rubber"), loc("As you probably noticed, these rubber bands|are VERY elastic. Hedgehogs and many other|things will bounce off without taking any damage.").."|".. loc("Now try to get out of this bounce house|and take the next crate."), 2, 8000) elseif gear == crates[9] then if INTERFACE == "desktop" then ctrl = loc("Look around: [Mouse movement]") .. "|" .. loc("Zoom: [Rotate mouse wheel]") elseif INTERFACE == "touch" then ctrl = loc("Look around: [Tap or swipe on the screen]") .. "|" .. -- multi-touch gesture loc("Zoom: [Pinch] with 2 fingers") end ShowMission(loc("Basic Movement Training"), loc("Health"), loc("You just got yourself some extra health.|The more health your hedgehogs have, the better!").."|".. loc("The health of your current hedgehog|is shown at the top right corner.").."|".. loc("Now go to the next crate.").."|".. ctrl, 2, 11500) elseif gear == crates[10] then -- FIXME: This crate is unused in touch atm ShowMission(loc("Basic Movement Training"), loc("Turning Around"), loc("By the way, you can turn around without walking|by holding down Precise when you hit a walk control.").."|".. loc("Get the final crate to the right to complete the training.").."|".. loc("Turn around: [Left Shift] + [Left]/[Right]") , 2, 8000) end end function onGearDamage(gear) if GetGearType(gear) == gtHedgehog and tookDamage == false and GetX(gear) > 1362 then ShowMission(loc("Basic Movement Training"), loc("Fall Damage"), loc("Ouch! You just took fall damage.").."|".. loc("Better get yourself another health crate to heal your wounds."), 2, 5000) tookDamage = true end end function onSwitch() -- Update help while switching hogs if switcherGear then -- Delay for CurrentHedgehog to update switchTextDelay = 1 end end local function firstMission() -- Here we teach player must know how to show the current mission texts again. -- We force the player to hit Attack before the actual training begins. -- Later, the mission panel key is perma-shown as caption. local ctrl = "" if INTERFACE == "desktop" then ctrl = loc("IMPORTANT: To see the mission panel again, hold the mission panel key.").."| |".. loc("Note: This basic training assumes default controls.").."|".. loc("Mission panel: [M]").."|".. loc("Quit: [Esc]").."|".. loc("Pause: [P]").."| |".. loc("To begin with the training, hit the attack key!").."|".. loc("Attack: [Space]") elseif INTERFACE == "touch" then ctrl = loc("IMPORTANT: To see the mission panel again, pause the game.").."| |".. loc("Pause: Tap the [Pause] button").."| |".. loc("To begin with the training, tap the attack button!").."|".. loc("Attack: Tap the [Bomb]") end ShowMission(loc("Basic Movement Training"), loc("Mission Panel"), loc("This is the mission panel.").."|".. loc("Here you will find the current mission instructions.").."|".. loc("Normally, the mission panel disappears after a few seconds.").."|".. ctrl, 2, 900000, true) -- TODO: This and other training missions are currently hardcoding control names. -- This should be fixed eventually. end function onGameTick20() if switchTextDelay > 0 then switchTextDelay = switchTextDelay - 1 elseif switchTextDelay == 0 then switchHedgehogText() switchTextDelay = -1 end if turnStarted and GameTime % 10000 == 0 and not missionPanelConfirmed then -- Forces the first mission panel to be displayed without time limit firstMission() end if missionPanelConfirmed then missionPanelConfirmedTimer = missionPanelConfirmedTimer + 20 --[[ After confirming the initial mission panel, show the mission panel key as permanent caption so the player can't overlook or forget it. ]] if missionPanelConfirmedTimer > 7000 then if INTERFACE == "desktop" then AddCaption(loc("Press [M] to see the mission texts"), capcolDefault, capgrpMessage2) elseif INTERFACE == "touch" then AddCaption(loc("Tap [Pause] to see the mission texts"), capcolDefault, capgrpMessage2) end end end end function onGearResurrect(gear, vGear) AddCaption(loc("Your hedgehog has been revived!")) if gear == hog_cappy then SetGearPosition(gear, 404, 1714) elseif gear == hog_greenhorn then SetGearPosition(gear, 401, 1850) else -- Generic teleport to Rhombus' cage SetGearPosition(gear, 619, 1559) end if vGear then SetVisualGearValues(vGear, GetX(gear), GetY(gear)) end FollowGear(gear) end function onNewTurn() SwitchHog(hog_greenhorn) FollowGear(hog_greenhorn) if not missionPanelConfirmed then turnStarted = true PlaySound(sndHello, hog_greenhorn) firstMission() end end function onAttack() if not missionPanelConfirmed then -- Mission panel confirmed, release controls PlaySound(sndPlaced) SetInputMask(0xFFFFFFFF) SetSoundMask(sndYesSir, false) PlaySound(sndYesSir, hog_greenhorn) -- First mission: How to walk ShowMission(loc("Basic Movement Training"), loc("First Steps"), loc("Complete the obstacle course.") .."|".. loc("To begin, walk to the crate to the right.").."|".. loc("Walk: [Left]/[Right]"), 2, 7000) missionPanelConfirmed = true end end function onGameStart() -- Disable input to force player to confirm first message SetInputMask(0) SetSoundMask(sndYesSir, true) LoadGearData() ShowMission(loc("Basic Movement Training"), loc("Basic Training"), loc("Complete the obstacle course."), 1, 0) FollowGear(hog_greenhorn) end
local util = require("__bztitanium__.data-util"); if mods["modmashsplinter"] then if mods["modmashsplinterresources"] then util.remove_raw("recipe", "titanium-extraction-process") data.raw.recipe["alien-enrichment-process-to-titanium-ore"].icons = { { icon = "__modmashsplinterresources__/graphics/icons/alien-ooze.png", icon_size = 64}, { icon = "__bztitanium__/graphics/icons/titanium-ore.png", icon_size = 64, icon_mipmaps = 3, scale=0.25, shift= {8, 8}}, } if mods["modmashsplinterenrichment"] then data.raw.recipe["ore-enrichment-process-titanium-ore"].icons = { { icon = "__base__/graphics/icons/fluid/steam.png", icon_size = 64}, { icon = "__bztitanium__/graphics/icons/titanium-ore.png", icon_size = 64, icon_mipmaps = 3, scale=0.25, shift= {8, 8}}, } end end if mods["modmashsplinterrefinement"] then local recipe = data.raw.recipe["titanium-ore-refined_to_plate"] if recipe and recipe.ingredients then for i, ingredient in ipairs(recipe.ingredients) do if ingredient[1] and ingredient[1] == "titanium-ore-refined" then ingredient[2] = 5 end end end if recipe and recipe.normal and recipe.normal.ingredients then for i, ingredient in ipairs(recipe.normal.ingredients) do if ingredient[1] and ingredient[1] == "titanium-ore-refined" then ingredient[2] = 5 end end end if recipe and recipe.expensive and recipe.expensive.ingredients then for i, ingredient in ipairs(recipe.expensive.ingredients) do if ingredient[1] and ingredient[1] == "titanium-ore-refined" then ingredient[2] =10 end end end end if mods["modmashsplinterlogistics"] then util.replace_ingredient("regenerative-transport-belt", "steel-plate", util.me.titanium_plate) util.replace_ingredient("regenerative-splitter", "steel-plate", util.me.titanium_plate) util.replace_ingredient("regenerative-underground-belt-structure", "steel-plate", util.me.titanium_plate) util.replace_ingredient("regenerative-mini-loader", "steel-plate", util.me.titanium_plate) end end
--- High-level database class. -- -- Contains all of the high-level methods to manage databases. This module -- should be used instead of the core modules when possible. -- -- See the @{database.lua} example for more detail. -- -- @classmod luchia.database -- @author Chad Phillips -- @copyright 2011-2015 Chad Phillips require "luchia.conf" local logger = require "luchia.core.log" local log = logger.logger local server = require "luchia.core.server" local string = require "string" local setmetatable = setmetatable local _M = {} --- Create a new database handler object. -- -- @param server_params -- Optional. A table of server connection parameters (identical to -- <code>default.server</code> in @{luchia.conf}. If not provided, a server -- object will be generated from the default server configuration. -- @return A database handler object. -- @usage db = luchia.database:new(server_params) function _M.new(self, server_params) local database = {} database.server = server:new(server_params) setmetatable(database, self) self.__index = self log:debug(string.format([[New database handler]])) return database end --- Make a database-related request to the server. -- -- @param self -- @param method -- Required. The HTTP method. -- @param database_name -- Required. The database name. -- @return The following four values, in this order: response_data, -- response_code, headers, status_code. local function database_call(self, method, database_name) if database_name then local params = { method = method, path = database_name, } local response, response_code, headers, status = self.server:request(params) return response, response_code, headers, status else log:error([[Database name is required]]) end end --- List all databases. -- -- @return Same values as @{database_call}, response_data is a list of databases. -- @usage db:list() -- @see database_call function _M:list() return self:info("_all_dbs") end --- Get information on a database. -- -- @param database_name -- Required. The database to get info from. -- @return Same values as @{database_call}, response_data is a table of database -- information. -- @usage db:info("example_database") -- @see database_call function _M:info(database_name) return database_call(self, "GET", database_name) end --- Create a database. -- -- @param database_name -- Required. The database to create. -- @return Same values as @{database_call}, response_data is a table of the -- request result. -- @usage db:create("example_database") -- @see database_call function _M:create(database_name) return database_call(self, "PUT", database_name) end --- Delete a database. -- -- @param database_name -- Required. The database to delete. -- @return Same values as @{database_call}, response_data is a table of the -- request result. -- @usage db:delete("example_database") -- @see database_call function _M:delete(database_name) return database_call(self, "DELETE", database_name) end --- Check the response for success. -- -- A convenience method to ensure a successful request. -- -- @param response -- Required. The response object returned from the server request. -- @return true if the server responsed with an ok:true, false otherwise. -- @usage operation_succeeded = db:response_ok(response) function _M:response_ok(response) return self.server:response_ok(response) end return _M
local new_player = require("player") local new_obstacle_handler = require("obstacle_handler") local collision = require("collision") function new() local player_list = {} local obstacle_handler = new_obstacle_handler() local function get_player(player_id) for _, player in ipairs(player_list) do if(player.get_id() == player_id) then return player end end return nil end local function add_player(player_id) if(get_player(player_id) == nil) then local player = new_player(player_id) table.insert(player_list, player) end end local function remove_player(index) player = player_list[index] local player_channels = { "lages_movement_x_" .. player.get_id(), "lages_movement_y_" .. player.get_id(), } table.remove(player_list, index) server.mqtt:unsubscribe(player_channels) end local function check_collisions() local obstacle_list = obstacle_handler.get_obstacle_list() for player_index, player in ipairs(player_list) do player.update() for obstacle_index, obstacle in ipairs(obstacle_list) do if(collision.circle(player.get_x(), player.get_y(), player.get_radius(), obstacle.get_x(), obstacle.get_y(), obstacle.get_radius())) then remove_player(player_index) table.remove(obstacle_list, obstacle_index) end end end end local function update(dt) local now = love.timer.getTime() check_collisions() if(#player_list > 0) then if(obstacle_handler.is_time_to_spawn(now)) then obstacle_handler.spawn() end obstacle_handler.reduce_spawn_time(dt) end if(#player_list == 0) then obstacle_handler.reset() end obstacle_handler.update(dt) end local function draw() for _, player in ipairs(player_list) do player.draw() end obstacle_handler.draw() end return { add_player = add_player, get_player = get_player, update = update, draw = draw, } end return new
-- -- Created by IntelliJ IDEA. -- User: RJ -- Date: 03/02/14 -- Time: 09:28 -- To change this template use File | Settings | File Templates. -- require "ISUI/ISCollapsableWindow" require "ISUI/ISRichTextPanel" require "ISUI/ISButton" require "ISUI/ISTabPanel" ---@class ISChat : ISCollapsableWindow ISChat = ISCollapsableWindow:derive("ISChat"); ISChat.maxLine = 50; ISChat.focused = false; ISChat.allChatStreams = {} ISChat.allChatStreams[1] = {name = "say", command = "/say ", shortCommand = "/s ", tabID = 1}; ISChat.allChatStreams[2] = {name = "yell", command = "/yell ", shortCommand = "/y ", tabID = 1}; ISChat.allChatStreams[3] = {name = "whisper", command = "/whisper ", shortCommand = "/w ", tabID = 1}; ISChat.allChatStreams[4] = {name = "faction", command = "/faction ", shortCommand = "/f ", tabID = 1}; ISChat.allChatStreams[5] = {name = "safehouse", command = "/safehouse ", shortCommand = "/sh ", tabID = 1}; ISChat.allChatStreams[6] = {name = "general", command = "/all ", tabID = 1}; ISChat.allChatStreams[7] = {name = "admin", command = "/admin ", shortCommand = "/a ", tabID = 2}; ISChat.defaultTabStream = {} ISChat.defaultTabStream[1] = ISChat.allChatStreams[1]; ISChat.defaultTabStream[2] = ISChat.allChatStreams[7]; -- default min and max opaque values ISChat.minControlOpaque = 0.5; -- a value ISChat.minGeneralOpaque = 0.0; -- a value, not percentage ISChat.maxGeneralOpaque = 1.0; -- a value, not percentage ISChat.minTextEntryOpaque = 0.3; ISChat.maxTextEntryOpaque = 1.0; ISChat.minTextOpaque = 0.8; -- elements name ISChat.textEntryName = "chat text entry" ISChat.tabPanelName = "chat tab panel" ISChat.yResizeWidgetName = "chat bottom y resize widget" ISChat.xyResizeWidgetName = "chat xy resize widget" ISChat.closeButtonName = "chat close button" ISChat.lockButtonName = "chat lock button" ISChat.gearButtonName = "chat gear button" ISChat.textPanelName = "chat text element" ISChat.windowName = "chat window" function ISChat:initialise() self:setUIName(ISChat.windowName); ISCollapsableWindow.initialise(self); self.showTimestamp = getCore():isOptionShowChatTimestamp(); self.showTitle = getCore():isOptionShowChatTitle(); self.minOpaque = getCore():getOptionMinChatOpaque(); -- in percentage self.maxOpaque = getCore():getOptionMaxChatOpaque(); -- in percentage self.fadeTime = getCore():getOptionChatFadeTime(); self.chatFont = getCore():getOptionChatFontSize(); self.opaqueOnFocus = getCore():getOptionChatOpaqueOnFocus(); self:initFade(self.fadeTime); self.fade:update(); self.backgroundColor.a = self.maxOpaque * ISChat.maxGeneralOpaque; self.pin = true; self.borderColor.a = 0.0; end ISChat.initChat = function() local instance = ISChat.instance; if instance.tabCnt == 1 then instance.chatText:setVisible(false); instance:removeChild(instance.chatText); instance.chatText = nil; elseif instance.tabCnt > 1 then instance.panel:setVisible(false); for i = 1, instance.tabCnt do instance.panel:removeView(instance.tabs[i]) end end instance.tabCnt = 0; instance.tabs = {} instance.currentTabID = 0; end function ISChat:createChildren() --window stuff -- Do corner x + y widget local rh = self:resizeWidgetHeight() local resizeWidget = ISResizeWidget:new(self.width-rh, self.height-rh, rh, rh, self); resizeWidget:initialise(); resizeWidget.onMouseDown = ISChat.onMouseDown; resizeWidget.onMouseUp = ISChat.onMouseUp; resizeWidget:setVisible(self.resizable) resizeWidget:bringToTop(); resizeWidget:setUIName(ISChat.xyResizeWidgetName); self:addChild(resizeWidget); self.resizeWidget = resizeWidget; -- Do bottom y widget local resizeWidget2 = ISResizeWidget:new(0, self.height-rh, self.width-rh, rh, self, true); resizeWidget2.anchorLeft = true; resizeWidget2.anchorRight = true; resizeWidget2:initialise(); resizeWidget2.onMouseDown = ISChat.onMouseDown; resizeWidget2.onMouseUp = ISChat.onMouseUp; resizeWidget2:setVisible(self.resizable); resizeWidget2:setUIName(ISChat.yResizeWidgetName); self:addChild(resizeWidget2); self.resizeWidget2 = resizeWidget2; -- close button local th = self:titleBarHeight() self.closeButton = ISButton:new(3, 0, th, th, "", self, self.close); self.closeButton:initialise(); self.closeButton.borderColor.a = 0.0; self.closeButton.backgroundColor.a = 0; self.closeButton.backgroundColorMouseOver.a = 0; self.closeButton:setImage(self.closeButtonTexture); self.closeButton:setUIName(ISChat.closeButtonName); self:addChild(self.closeButton); -- lock button self.lockButton = ISButton:new(self.width - 19, 0, th, th, "", self, ISChat.pin); self.lockButton.anchorRight = true; self.lockButton.anchorLeft = false; self.lockButton:initialise(); self.lockButton.borderColor.a = 0.0; self.lockButton.backgroundColor.a = 0; self.lockButton.backgroundColorMouseOver.a = 0; if self.locked then self.lockButton:setImage(self.chatLockedButtonTexture); else self.lockButton:setImage(self.chatUnLockedButtonTexture); end self.lockButton:setUIName(ISChat.lockButtonName); self:addChild(self.lockButton); self.lockButton:setVisible(true); --gear button self.gearButton = ISButton:new(self.lockButton:getX() - th / 2 - th, 1, th, th, "", self, ISChat.onGearButtonClick); self.gearButton.anchorRight = true; self.gearButton.anchorLeft = false; self.gearButton:initialise(); self.gearButton.borderColor.a = 0.0; self.gearButton.backgroundColor.a = 0; self.gearButton.backgroundColorMouseOver.a = 0; self.gearButton:setImage(getTexture("media/ui/Panel_Icon_Gear.png")); self.gearButton:setUIName(ISChat.gearButtonName); self:addChild(self.gearButton); self.gearButton:setVisible(true); --general stuff self.minimumHeight = 90; self.minimumWidth = 200; self:setResizable(true); self:setDrawFrame(true); self:addToUIManager(); self.tabs = {}; self.tabCnt = 0; self.btnHeight = 25; self.currentTabID = 0; self.inset = 2 self.fontHgt = getTextManager():getFontFromEnum(UIFont.Medium):getLineHeight(); --text entry stuff local inset, EdgeSize, fontHgt = self.inset, 5, self.fontHgt; -- EdgeSize must match UITextBox2.EdgeSize local height = EdgeSize * 2 + fontHgt self.textEntry = ISTextEntryBox:new("", inset, self:getHeight() - 8 - inset - height, self:getWidth() - inset * 2, height); self.textEntry.font = UIFont.Medium self.textEntry:initialise(); self.textEntry:instantiate(); self.textEntry.backgroundColor = {r=0, g=0, b=0, a=0.5}; self.textEntry.borderColor = {r=1, g=1, b=1, a=0.0}; self.textEntry:setHasFrame(true) self.textEntry:setAnchorTop(false); self.textEntry:setAnchorBottom(true); self.textEntry:setAnchorRight(true); self.textEntry.onCommandEntered = ISChat.onCommandEntered; self.textEntry.onTextChange = ISChat.onTextChange; self.textEntry.onPressDown = ISChat.onPressDown; self.textEntry.onPressUp = ISChat.onPressUp; self.textEntry.onOtherKey = ISChat.onOtherKey self.textEntry.onClick = ISChat.onMouseDown; self.textEntry:setUIName(ISChat.textEntryName); -- need to be right this. If it will empty or another then focus will lost on click in chat self.textEntry:setHasFrame(true); self:addChild(self.textEntry) ISChat.maxTextEntryOpaque = self.textEntry:getFrameAlpha(); --tab panel stuff local panelHeight = self.textEntry:getY() - self:titleBarHeight() - self.inset; self.panel = ISTabPanel:new(0, self:titleBarHeight(), self.width - inset, panelHeight); self.panel:initialise(); self.panel.borderColor = { r = 0, g = 0, b = 0, a = 0}; self.panel.onActivateView = ISChat.onActivateView; self.panel.target = self; self.panel:setAnchorTop(true); self.panel:setAnchorLeft(true); self.panel:setAnchorRight(true); self.panel:setAnchorBottom(true); self.panel:setEqualTabWidth(false); self.panel:setVisible(false); self.panel.onRightMouseUp = ISChat.onRightMouseUp; self.panel.onRightMouseDown = ISChat.onRightMouseDown; self.panel.onMouseUp = ISChat.onMouseUp; self.panel.onMouseDown = ISChat.ISTabPanelOnMouseDown; self.panel:setUIName(ISChat.tabPanelName); self:addChild(self.panel); self:bringToTop(); self.textEntry:bringToTop(); self.minimumWidth = self.panel:getWidthOfAllTabs() + 2 * inset; self.minimumHeight = self.textEntry:getHeight() + self:titleBarHeight() + 2 * inset + self.panel.tabHeight + fontHgt * 4; self:unfocus(); self.mutedUsers = {} end function ISChat:setDrawFrame(visible) self.background = visible self.drawFrame = visible if self.closeButton then self.closeButton:setVisible(visible) end end function ISChat:collapse() self.pin = false; self.lockButton:setVisible(true); end function ISChat:close() if not self.locked then ISCollapsableWindow.close(self); end end function ISChat:pin() self.locked = not self.locked; ISChat.focused = not self.locked; if self.locked then self.lockButton:setImage(self.chatLockedButtonTexture); else self.lockButton:setImage(self.chatUnLockedButtonTexture); end end function ISChat:onGearButtonClick() local context = ISContextMenu.get(0, self:getAbsoluteX() + self:getWidth() / 2, self:getAbsoluteY() + self.gearButton:getY()) local timestampOptionName = getText("UI_chat_context_enable_timestamp"); if self.showTimestamp then timestampOptionName = getText("UI_chat_context_disable_timestamp"); end context:addOption(timestampOptionName, ISChat.instance, ISChat.onToggleTimestampPrefix) local tagOptionName = getText("UI_chat_context_enable_tags"); if self.showTitle then tagOptionName = getText("UI_chat_context_disable_tags"); end context:addOption(tagOptionName, ISChat.instance, ISChat.onToggleTagPrefix) local fontSizeOption = context:addOption(getText("UI_chat_context_font_submenu_name"), ISChat.instance); local fontSubMenu = context:getNew(context); context:addSubMenu(fontSizeOption, fontSubMenu); fontSubMenu:addOption(getText("UI_chat_context_font_small"), ISChat.instance, ISChat.onFontSizeChange, "small"); fontSubMenu:addOption(getText("UI_chat_context_font_medium"), ISChat.instance, ISChat.onFontSizeChange, "medium"); fontSubMenu:addOption(getText("UI_chat_context_font_large"), ISChat.instance, ISChat.onFontSizeChange, "large"); if self.chatFont == "small" then fontSubMenu:setOptionChecked(fontSubMenu.options[1], true) elseif self.chatFont == "medium" then fontSubMenu:setOptionChecked(fontSubMenu.options[2], true) elseif self.chatFont == "large" then fontSubMenu:setOptionChecked(fontSubMenu.options[3], true) end local minOpaqueOption = context:addOption(getText("UI_chat_context_opaque_min"), ISChat.instance); local minOpaqueSubMenu = context:getNew(context); context:addSubMenu(minOpaqueOption, minOpaqueSubMenu); local opaques = {0, 0.25, 0.5, 0.75, 1}; for i = 1, #opaques do if logTo01(opaques[i]) <= self.maxOpaque then local option = minOpaqueSubMenu:addOption((opaques[i] * 100) .. "%", ISChat.instance, ISChat.onMinOpaqueChange, opaques[i]) local current = math.floor(self.minOpaque * 1000) local value = math.floor(logTo01(opaques[i]) * 1000) if current == value then minOpaqueSubMenu:setOptionChecked(option, true) end end end local maxOpaqueOption = context:addOption(getText("UI_chat_context_opaque_max"), ISChat.instance); local maxOpaqueSubMenu = context:getNew(context); context:addSubMenu(maxOpaqueOption, maxOpaqueSubMenu); for i = 1, #opaques do if logTo01(opaques[i]) >= self.minOpaque then local option = maxOpaqueSubMenu:addOption((opaques[i] * 100) .. "%", ISChat.instance, ISChat.onMaxOpaqueChange, opaques[i]) local current = math.floor(self.maxOpaque * 1000) local value = math.floor(logTo01(opaques[i]) * 1000) if current == value then maxOpaqueSubMenu:setOptionChecked(option, true) end end end local fadeTimeOption = context:addOption(getText("UI_chat_context_opaque_fade_time_submenu_name"), ISChat.instance); local fadeTimeSubMenu = context:getNew(context); context:addSubMenu(fadeTimeOption, fadeTimeSubMenu); local availFadeTime = {0, 1, 2, 3, 5, 10}; local option = fadeTimeSubMenu:addOption(getText("UI_chat_context_disable"), ISChat.instance, ISChat.onFadeTimeChange, 0) if 0 == self.fadeTime then fadeTimeSubMenu:setOptionChecked(option, true) end for i = 2, #availFadeTime do local time = availFadeTime[i]; option = fadeTimeSubMenu:addOption(time .. " s", ISChat.instance, ISChat.onFadeTimeChange, time) if time == self.fadeTime then fadeTimeSubMenu:setOptionChecked(option, true) end end local opaqueOnFocusOption = context:addOption(getText("UI_chat_context_opaque_on_focus"), ISChat.instance); local opaqueOnFocusSubMenu = context:getNew(context); context:addSubMenu(opaqueOnFocusOption, opaqueOnFocusSubMenu); opaqueOnFocusSubMenu:addOption(getText("UI_chat_context_disable"), ISChat.instance, ISChat.onFocusOpaqueChange, false) opaqueOnFocusSubMenu:addOption(getText("UI_chat_context_enable"), ISChat.instance, ISChat.onFocusOpaqueChange, true) opaqueOnFocusSubMenu:setOptionChecked(opaqueOnFocusSubMenu.options[self.opaqueOnFocus and 2 or 1], true) end function ISChat:createTab() local chatY = self:titleBarHeight() + self.btnHeight + 2 * self.inset; local chatHeight = self.textEntry:getY() - chatY; local chatText = ISRichTextPanel:new(0, chatY, self:getWidth(), chatHeight); chatText.maxLines = 500 chatText:initialise(); chatText.background = false; chatText:setAnchorBottom(true); chatText:setAnchorRight(true); chatText:setAnchorTop(true); chatText:setAnchorLeft(true); chatText.log = {}; chatText.logIndex = 0; chatText.marginTop = 2 chatText.marginBottom = 0 chatText.onRightMouseUp = nil; chatText.render = ISChat.render_chatText chatText.autosetheight = false; chatText:addScrollBars(); chatText.vscroll:setVisible(false); chatText.vscroll.background = false; chatText:ignoreHeightChange() chatText:setVisible(false); chatText.chatTextLines = {}; chatText.chatMessages = {}; chatText.onRightMouseUp = ISChat.onRightMouseUp; chatText.onRightMouseDown = ISChat.onRightMouseDown; chatText.onMouseUp = ISChat.onMouseUp; chatText.onMouseDown = ISChat.onMouseDown; return chatText; end function ISChat:initFade(durationInS) self.fade:init(durationInS * 1000, true); end function ISChat:calcAlpha(defaultMin, defaultMax, fraction) -- default min/max value is not percentage! It's just [0,1] alpha value. -- The self.maxOpaque is current percentage of min/max alpha. self.maxOpaque assigned by player in context chat menu local newMinAlpha = defaultMin + self.minOpaque * (defaultMax - defaultMin); local newMaxAlpha = defaultMin + self.maxOpaque * (defaultMax - defaultMin); -- same as previous return newMinAlpha + fraction * (newMaxAlpha - newMinAlpha); end function ISChat:makeFade(fraction) local min, max = ISChat.minGeneralOpaque, ISChat.maxGeneralOpaque; local alpha = self:calcAlpha(min, max, fraction); self.backgroundColor.a = alpha; min = ISChat.minTextOpaque; alpha = self:calcAlpha(min, max, fraction); self.chatText:setContentTransparency(alpha) if self.tabCnt > 1 then self.panel:setTextTransparency(alpha); end min = ISChat.minControlOpaque; alpha = self:calcAlpha(min, max, fraction); self.widgetTextureColor.a = alpha; self.closeButton.textureColor.a = alpha; self.lockButton.textureColor.a = alpha; self.gearButton.textureColor.a = alpha; if self.tabCnt > 1 then self.panel:setTabsTransparency(alpha); end max = ISChat.maxTextEntryOpaque; min = ISChat.minTextEntryOpaque; alpha = self:calcAlpha(min, max, fraction); self.textEntry:setFrameAlpha(alpha); self.textEntry.backgroundColor.a = alpha; end function ISChat:prerender() ISChat.instance = self self.gearButton.onclick = self.onGearButtonClick self:setDrawFrame(true) if not ISChat.focused then self.fade:update(); end self:makeFade(self.fade:fraction()); local a = self.backgroundColor.a; local r, g, b = self.backgroundColor.r, self.backgroundColor.g, self.backgroundColor.b; self:drawRect(0, 0, self:getWidth(), self:getHeight(), a, r, g, b); local th = self:titleBarHeight() local titlebarAlpha = self:calcAlpha(ISChat.minControlOpaque, ISChat.maxGeneralOpaque, self.fade:fraction()); self:drawTextureScaled(self.titlebarbkg, 2, 1, self:getWidth() - 4, th - 2, titlebarAlpha, 1, 1, 1); if self.servermsg then local x = getCore():getScreenWidth() / 2 - self:getX() local y = getCore():getScreenHeight() / 4 - self:getY(); self:drawTextCentre(self.servermsg, x, y, 1, 0.1, 0.1, 1, UIFont.Title); self.servermsgTimer = self.servermsgTimer - UIManager.getMillisSinceLastRender(); if self.servermsgTimer < 0 then self.servermsg = nil; self.servermsgTimer = 0; end end end function ISChat:render() ISCollapsableWindow.render(self); end function ISChat:render_chatText() self:setStencilRect(0, 0, self.width, self.height) ISRichTextPanel.render(self) self:clearStencilRect() end function ISChat:onContextClear() self.chatText.chatTextLines = {} self.chatText.text = "" self.chatText:paginate() end function ISChat:logChatCommand(command) self.chatText.logIndex = 0; if command and command ~= "" then local newLog = {}; table.insert(newLog, command); for i,v in ipairs(self.chatText.log) do table.insert(newLog, v); if i > 20 then break; end end self.chatText.log = newLog; end end function ISChat:onCommandEntered() local command = ISChat.instance.textEntry:getText(); local chat = ISChat.instance; ISChat.instance:unfocus(); if not command or command == "" then return; end local commandProcessed = false; local chatCommand; local chatStreamName; for _, stream in ipairs(ISChat.allChatStreams) do chatCommand = nil; if luautils.stringStarts(command, stream.command) then chatCommand = stream.command; elseif stream.shortCommand and luautils.stringStarts(command, stream.shortCommand) then chatCommand = stream.shortCommand; end if chatCommand then if chat.currentTabID ~= stream.tabID then showWrongChatTabMessage(chat.currentTabID - 1, stream.tabID - 1, chatCommand); -- from one-based to zero-based commandProcessed = true; break; end chat.chatText.lastChatCommand = chatCommand; local originalCommand = command; command = string.sub(command, #chatCommand); if command ~= "" and command ~= " " then chat:logChatCommand(originalCommand); end chatStreamName = stream.name; break; end end if not chatCommand then if luautils.stringStarts(command, "/") then SendCommandToServer(command); chat:logChatCommand(command); commandProcessed = true; else local defaultStream = ISChat.defaultTabStream[chat.currentTabID]; chatStreamName = defaultStream.name; chat:logChatCommand(command); end end if not commandProcessed then if chatStreamName == "yell" then processShoutMessage(command); elseif chatStreamName == "whisper" then local username = proceedPM(command); chat.chatText.lastChatCommand = chat.chatText.lastChatCommand .. username .. " "; elseif chatStreamName == "faction" then proceedFactionMessage(command); elseif chatStreamName == "safehouse" then processSafehouseMessage(command); elseif chatStreamName == "admin" then processAdminChatMessage(command); elseif chatStreamName == "say" then processSayMessage(command); elseif chatStreamName == "general" then processGeneralMessage(command); end end doKeyPress(false); ISChat.instance.timerTextEntry = 20; end function ISChat.onOtherKey(key) if key == Keyboard.KEY_ESCAPE then ISChat.instance:unfocus(); end end ISChat.onSwitchStream = function() if ISChat.focused then local curTxtPanel = ISChat.instance.chatText local chatStreams = curTxtPanel.chatStreams; for i = 0, #chatStreams do curTxtPanel.streamID = curTxtPanel.streamID % #chatStreams + 1; if checkPlayerCanUseChat(chatStreams[curTxtPanel.streamID].command) then break; end end ISChat.instance.textEntry:setText(chatStreams[curTxtPanel.streamID].command); end end ISChat.onTextChange = function() local t = ISChat.instance.textEntry; local internalText = t:getInternalText(); if ISChat.instance.chatText.lastChatCommand ~= nil then for _, chat in ipairs(ISChat.instance.chatText.chatStreams) do local prefix; if chat.command and luautils.stringStarts(internalText, chat.command) then prefix = chat.command; elseif chat.shortCommand and luautils.stringStarts(internalText, chat.shortCommand) then prefix = chat.shortCommand; end if prefix then if string.sub(t:getText(), prefix:len() + 1, t:getText():len()):len() <= 5 and luautils.stringStarts(internalText, "/") and luautils.stringEnds(internalText, "/") then t:setText("/"); return; end end end if t:getText():len() <= 5 and luautils.stringEnds(internalText, "/") then t:setText("/"); return; end end end function ISChat:focus() self:setVisible(true); ISChat.focused = true; self.textEntry:setEditable(true); self.textEntry:focus(); self.textEntry:ignoreFirstInput(); self.textEntry:setText(self.chatText.lastChatCommand); self.fade:reset(); self.fade:update(); --reset fraction to start value end function ISChat:unfocus() self.textEntry:unfocus(); self.textEntry:setText(""); if ISChat.focused then self.fade:reset(); -- to begin fade. unfocus called when element was unfocused also. end ISChat.focused = false; self.textEntry:setEditable(false); end function ISChat:updateChatPrefixSettings() updateChatSettings(self.chatFont, self.showTimestamp, self.showTitle); for tabNumber, chatText in ipairs(self.tabs) do chatText.text = ""; local newText = ""; chatText.chatTextLines = {}; for i,msg in ipairs(chatText.chatMessages) do local line = msg:getTextWithPrefix() .. " <LINE> "; table.insert(chatText.chatTextLines, line); if i == #chatText.chatMessages then line = string.gsub(line, " <LINE> $", "") end newText = newText .. line; end chatText.text = newText; chatText:paginate(); end end ISChat.onToggleTimestampPrefix = function() local chat = ISChat.instance; chat.showTimestamp = not chat.showTimestamp; if chat.showTimestamp then print("timestamp enabled"); else print("timestamp disabled"); end chat:updateChatPrefixSettings(); end ISChat.onToggleTagPrefix = function() local chat = ISChat.instance; chat.showTitle = not chat.showTitle; if chat.showTitle then print("tags enabled"); else print("tags disabled"); end chat:updateChatPrefixSettings(); end ISChat.onFontSizeChange = function(target, value) if target.chatFont == value then return; end target.chatFont = value; target:updateChatPrefixSettings(); print("Font size switched to " .. value); end ISChat.onMinOpaqueChange = function(target, value) target.minOpaque = logTo01(value); target.backgroundColor.a = target.maxOpaque; getCore():setOptionMinChatOpaque(target.minOpaque); end ISChat.onMaxOpaqueChange = function(target, value) target.maxOpaque = logTo01(value); target.backgroundColor.a = target.maxOpaque; getCore():setOptionMaxChatOpaque(target.maxOpaque); end ISChat.onFadeTimeChange = function(target, value) target.fadeTime = value; target:initFade(target.fadeTime); getCore():setOptionChatFadeTime(value); end ISChat.onFocusOpaqueChange = function(target, value) target.opaqueOnFocus = value; getCore():setOptionChatOpaqueOnFocus(value); end ISChat.addLineInChat = function(message, tabID) local line = message:getTextWithPrefix(); if message:isServerAlert() then ISChat.instance.servermsg = ""; if message:isShowAuthor() then ISChat.instance.servermsg = message:getAuthor() .. ": "; end ISChat.instance.servermsg = ISChat.instance.servermsg .. message:getText(); ISChat.instance.servermsgTimer = 5000; --return; end if user and ISChat.instance.mutedUsers[user] then return end if not ISChat.instance.chatText then ISChat.instance.chatText = ISChat.instance.defaultTab; ISChat.instance:onActivateView(); end local chatText; for i,tab in ipairs(ISChat.instance.tabs) do if tab and tab.tabID == tabID then chatText = tab; break; end end if chatText.tabTitle ~= ISChat.instance.chatText.tabTitle then local alreadyExist = false; for i,blinkedTab in ipairs(ISChat.instance.panel.blinkTabs) do if blinkedTab == chatText.tabTitle then alreadyExist = true; break; end end if alreadyExist == false then table.insert(ISChat.instance.panel.blinkTabs, chatText.tabTitle); end end local vscroll = chatText.vscroll local scrolledToBottom = (chatText:getScrollHeight() <= chatText:getHeight()) or (vscroll and vscroll.pos == 1) if #chatText.chatTextLines > ISChat.maxLine then local newLines = {}; for i,v in ipairs(chatText.chatTextLines) do if i ~= 1 then table.insert(newLines, v); end end table.insert(newLines, line .. " <LINE> "); chatText.chatTextLines = newLines; else table.insert(chatText.chatTextLines, line .. " <LINE> "); end chatText.text = ""; local newText = ""; for i,v in ipairs(chatText.chatTextLines) do if i == #chatText.chatTextLines then v = string.gsub(v, " <LINE> $", "") end newText = newText .. v; end chatText.text = newText; table.insert(chatText.chatMessages, message); chatText:paginate(); if scrolledToBottom then chatText:setYScroll(-10000); end end ISChat.onToggleChatBox = function(key) if ISChat.instance==nil then return; end if key == getCore():getKey("Toggle chat") or key == getCore():getKey("Alt toggle chat") then ISChat.instance:focus(); end local chat = ISChat.instance; if key == getCore():getKey("Switch chat stream") then chat.currentTabID = chat.currentTabID % chat.tabCnt + 1; chat.panel:activateView(chat.tabs[chat.currentTabID].tabTitle); ISChat.instance:onActivateView(); end end ISChat.onKeyKeepPressed = function(key) if ISChat.instance==nil then return; end end function ISChat:calcTabSize() if ISChat.instance.tabCnt == 0 then return {width = self.width, height = self.textEntry:getY() - self.panel:getY()}; elseif ISChat.instance.tabCnt > 0 then return {width = self.panel.width, height = self.panel.height - self.panel.tabHeight - 1}; end end function ISChat:calcTabPos() if ISChat.instance.tabCnt == 0 then return {x = 0, y = self:titleBarHeight() + self.inset}; else return {x = 0, y = self:titleBarHeight() + self.btnHeight + 2 * self.inset}; end end ISChat.onTabAdded = function(tabTitle, tabID) local chat = ISChat.instance; local newTab = chat:createTab(); newTab.parent = chat; newTab.tabTitle = tabTitle; newTab.tabID = tabID; newTab.streamID = 1; newTab.chatStreams = {} for _, stream in ipairs(ISChat.allChatStreams) do if stream.tabID == tabID + 1 then --tabID is zero-based index but stream.tabID is one-based index. table.insert(newTab.chatStreams, stream) end end newTab.lastChatCommand = newTab.chatStreams[newTab.streamID].command; newTab:setUIName("chat text panel with title '" .. tabTitle .. "'"); local pos = chat:calcTabPos(); local size = chat:calcTabSize(); newTab:setY(pos.y); newTab:setHeight(size.height); newTab:setWidth(size.width); if chat.tabCnt == 0 then chat:addChild(newTab); chat.chatText = newTab; chat.chatText:setVisible(true); end if chat.tabCnt == 1 then chat.panel:setVisible(true); chat.chatText:setY(pos.y); chat.chatText:setHeight(size.height); chat.chatText:setWidth(size.width); chat:removeChild(chat.chatText); chat.panel:addView(chat.chatText.tabTitle, chat.chatText); end if chat.tabCnt >= 1 then chat.panel:addView(tabTitle, newTab); chat.minimumWidth = chat.panel:getWidthOfAllTabs() + 2 * chat.inset; end table.insert(chat.tabs, newTab); chat.tabCnt = chat.tabCnt + 1; end ISChat.onTabRemoved = function(tabTitle, tabID) local foundedTab; for i,tab in ipairs(ISChat.instance.tabs) do if tabID == tab.tabID then foundedTab = tab; table.remove(ISChat.instance.tabs, i); break; end end if ISChat.instance.tabCnt > 1 then for i,blinkedTab in ipairs(ISChat.instance.panel.blinkTabs) do if tabTitle == blinkedTab then table.remove(ISChat.instance.panel.blinkTabs, i); break; end end ISChat.instance.panel:removeView(foundedTab); ISChat.instance.minimumWidth = ISChat.instance.panel:getWidthOfAllTabs() + 2 * ISChat.instance.inset; end ISChat.instance.tabCnt = ISChat.instance.tabCnt - 1; if ISChat.instance.tabCnt == 1 then local lastTab = ISChat.instance.tabs[1]; ISChat.instance.panel:setVisible(false); ISChat.instance.panel:removeView(lastTab); ISChat.instance.chatText = lastTab; ISChat.instance:addChild(ISChat.instance.chatText); ISChat.instance.chatText:setVisible(true); end ISChat.instance:onActivateView(); end ISChat.onSetDefaultTab = function(defaultTabTitle) for i,v in ipairs(ISChat.instance.tabs) do if v.tabTitle == defaultTabTitle then ISChat.instance.defaultTab = v; ISChat.instance.currentTabID = i; ISChat.instance.chatText = v; ISChat.instance:onActivateView(); return; end end ISChat.instance.defaultTab = nil; end function ISChat:onActivateView() if self.tabCnt > 1 then self.chatText = self.panel.activeView.view; end for i,blinkedTab in ipairs(self.panel.blinkTabs) do if self.chatText.tabTitle and self.chatText.tabTitle == blinkedTab then table.remove(self.panel.blinkTabs, i); break; end end for i,tab in ipairs(self.tabs) do if tab.tabTitle == self.chatText.tabTitle then self.currentTabID = i; break; end end focusOnTab(self.chatText.tabID) end function ISChat:new (x, y, width, height) local o = {} --o.data = {} o = ISCollapsableWindow:new(x, y, width, height); setmetatable(o, self) self.__index = self o.x = x; o.y = y; o.borderColor = {r=1, g=1, b=1, a=0.7}; o.backgroundColor = {r=0, g=0, b=0, a=1}; o.width = width; o.height = height; o.anchorLeft = true; o.anchorRight = false; o.anchorTop = true; o.anchorBottom = false; o.onRightMouseUp = nil; o.prevBtnTxt = getTexture("media/ui/sGuidePrevBtn.png"); o.nextBtnTxt = getTexture("media/ui/sGuideNextBtn.png"); o.closeBtnTxt = getTexture("media/ui/sGuideCloseBtn.png"); o.chatLockedButtonTexture = getTexture("media/ui/lock.png"); o.chatUnLockedButtonTexture = getTexture("media/ui/lockOpen.png"); o.background = true; o.timerTextEntry = 0; o.servermsg = ""; o.servermsgTimer = 0; o.showTimestamp = true; o.showTitle = true; o.chatFont = "medium"; o.fadeTime = 0; o.minOpaque = 1; -- in percentage o.maxOpaque = 1; -- in percentage o.opaqueOnFocus = true; o.backgroundColor.a = 1.0 * o.maxOpaque; o.fade = UITransition.new() o.fade:setIgnoreUpdateTime(true); ISChat.instance = o; Events.OnTick.Add(ISChat.ontick); return o end function ISChat:onPressDown() local chat = ISChat.instance; local chatText = chat.chatText; chatText.logIndex = chatText.logIndex - 1; if chatText.logIndex < 0 then chatText.logIndex = 0; end if chatText.log and chatText.log[chatText.logIndex] then -- print(ISChat.instance.log[ISChat.instance.logIndex]); chat.textEntry:setText(chatText.log[chatText.logIndex]); else chat.textEntry:setText(""); end end function ISChat:onPressUp() local chat = ISChat.instance; local chatText = chat.chatText; chatText.logIndex = chatText.logIndex + 1; if chatText.logIndex > #chatText.log then chatText.logIndex = #chatText.log; end if chatText.log and chatText.log[chatText.logIndex] then -- print(ISChat.instance.log[ISChat.instance.logIndex]); chat.textEntry:setText(chatText.log[chatText.logIndex]); end end function ISChat:isCursorOnTitlebar(x, y) return y <= self:titleBarHeight(); end function ISChat.onMouseUp(target, x, y) -- check if player clicked on titlebar if target:getUIName() == ISChat.windowName and ISChat.instance.moving then ISCollapsableWindow.onMouseUp(ISChat.instance, x, y); return true; end -- checks if player clicked on text panel if target:getUIName() == ISChat.textPanelName then -- if window focused we should ignore other handlers. if we returns true then another handlers will be ignored -- we ignore clicks on text return ISChat.focused; end -- checks if player clicked on tab panel if target:getUIName() == ISChat.tabPanelName then ISTabPanel.onMouseUp(ISChat.instance.panel, x, y) return ISChat.focused; end -- checks if player clicked on text entry panel if target:getUIName() == ISChat.textEntryName then return ISChat.focused; end -- checks if player clicked on bottom y resize widget if not ISChat.instance.locked and target:getUIName() == ISChat.yResizeWidgetName then ISResizeWidget.onMouseUp(ISChat.instance.resizeWidget2, x, y); return true end -- checks if player clicked on xy resize widget if not ISChat.instance.locked and target:getUIName() == ISChat.xyResizeWidgetName then ISResizeWidget.onMouseUp(ISChat.instance.resizeWidget, x, y); return true end return ISChat.focused; end function ISChat.onMouseDown(target, x, y) -- check if player clicked on titlebar if target:getUIName() == ISChat.windowName and not ISChat.instance.locked and ISChat.instance:isCursorOnTitlebar(x, y) then ISCollapsableWindow.onMouseDown(ISChat.instance, x, y); return true; end -- checks if player clicked on text panel if target:getUIName() == ISChat.textPanelName then -- if window focused we should ignore other handlers. if we returns true then another handlers will be ignored -- we ignore clicks on text return ISChat.focused; end -- checks if player clicked on tab panel if target:getUIName() == ISChat.tabPanelName then ISChat.ISTabPanelOnMouseDown(ISChat.instance.panel, x, y) return ISChat.focused; end -- checks if player clicked on text entry panel if target:getUIName() == ISChat.textEntryName then return ISChat.focused; end -- checks if player clicked on bottom y resize widget if not ISChat.instance.locked and target:getUIName() == ISChat.yResizeWidgetName then ISResizeWidget.onMouseDown(ISChat.instance.resizeWidget2, x, y); return true end -- checks if player clicked on xy resize widget if not ISChat.instance.locked and target:getUIName() == ISChat.xyResizeWidgetName then ISResizeWidget.onMouseDown(ISChat.instance.resizeWidget, x, y); return true end return ISChat.focused; end ISChat.ISTabPanelOnMouseDown = function(target, x, y) if target:getMouseY() >= 0 and target:getMouseY() < target.tabHeight then if target:getScrollButtonAtX(x) == "left" then target:onMouseWheel(-1) return true end if target:getScrollButtonAtX(x) == "right" then target:onMouseWheel(1) return true end local tabIndex = target:getTabIndexAtX(target:getMouseX()) if tabIndex >= 1 and tabIndex <= #target.viewList and ISTabPanel.xMouse == -1 and ISTabPanel.yMouse == -1 then -- if we clicked on a tab, the first time we set up the x,y of the mouse, so next time we can see if the player moved the mouse (moved the tab) ISTabPanel.xMouse = target:getMouseX(); ISTabPanel.yMouse = target:getMouseY(); target.draggingTab = tabIndex - 1; local clickedTab = target.viewList[target.draggingTab + 1]; target:activateView(clickedTab.name) return true end end return false end function ISChat:onRightMouseUp(x, y) if ISChat.focused then return true; end return false; end function ISChat:onRightMouseDown(x, y) if ISChat.focused then return true; end return false; end function ISChat:mute(username) if self.mutedUsers[username] then self.mutedUsers[username] = nil else self.mutedUsers[username] = true end end function ISChat:isMuted(username) return self.mutedUsers[username] ~= nil end -- RJ : Do this because of some delay your last key entered in chat can pop a "KeyPressed" ISChat.ontick = function() if ISChat.instance and ISChat.instance.timerTextEntry > 0 then ISChat.instance.timerTextEntry = ISChat.instance.timerTextEntry - 1; if ISChat.instance.timerTextEntry == 0 then doKeyPress(true); end end end ISChat.unfocusEvent = function() if ISChat.instance == nil then return; end ISChat.instance:unfocus(); end function ISChat:RestoreLayout(name, layout) ISLayoutManager.DefaultRestoreWindow(self, layout) if layout.locked == 'false' then self.locked = false; self.lockButton:setImage(self.chatUnLockedButtonTexture); else self.locked = true; self.lockButton:setImage(self.chatLockedButtonTexture); end self:recalcSize(); end function ISChat:SaveLayout(name, layout) ISLayoutManager.DefaultSaveWindow(self, layout) if self.locked then layout.locked = 'true' else layout.locked = 'false' end end ISChat.createChat = function() if not isClient() then return; end ISChat.chat = ISChat:new(15, getCore():getScreenHeight() - 400, 500, 200); ISChat.chat:initialise(); ISChat.chat:addToUIManager(); ISChat.chat:setVisible(true); ISChat.chat:bringToTop() ISLayoutManager.RegisterWindow('chat', ISChat, ISChat.chat) ISChat.instance:setVisible(true); Events.OnAddMessage.Add(ISChat.addLineInChat); Events.OnMouseDown.Add(ISChat.unfocusEvent); Events.OnKeyPressed.Add(ISChat.onToggleChatBox); Events.OnKeyKeepPressed.Add(ISChat.onKeyKeepPressed); Events.OnTabAdded.Add(ISChat.onTabAdded); Events.OnSetDefaultTab.Add(ISChat.onSetDefaultTab); Events.OnTabRemoved.Add(ISChat.onTabRemoved); Events.SwitchChatStream.Add(ISChat.onSwitchStream) end function logTo01(value) if value < 0.0 or value > 1.0 then error("only [0,1] accepted!"); end if value > 0.0 then return math.log10(value * 100) - 1; end return 0.0; end Events.OnGameStart.Add(ISChat.createChat); Events.OnChatWindowInit.Add(ISChat.initChat)
--[[ helpers for the cbox_grind module (see appropriate lua file). ]] local i = {} -- reference implementation of mkcube which just assigns the result into a table. local mkcube_collect = function(sxmin, symin, szmin, sxmax, symax, szmax) local r = {} r.xmin = sxmin r.ymin = symin r.zmin = szmin r.xmax = sxmax r.ymax = symax r.zmax = szmax return r end i.mkcube_collect = mkcube_collect return i
--- The idle node inherits from the @{action} base node class and plays a configurable animation for a specified -- amount of time. It succeeds when the duration time has elapsed. -- @action idle local action = behaviors.action local idle = behaviors.class("idle", action) behaviors.idle = idle --- Configuration table passed into the constructor function. -- @table config -- @tfield number duration The amount of time to remain idle. -- @tfield string idle_animation The animation to play while the mob is idle. --- Constructs a @{idle} node class instance. -- @tparam config config The configuration options for this @{idle} node function idle:constructor(config) action.constructor(self) self.duration = config.duration self.idle_animation = config.idle_animation or "stand" self.time = self.duration end --- Resets the @{idle} node's state and stateful properties. function idle:reset() action.reset(self) self.time = self.duration end --- Called when the node first runs to set initial values, and idle animation. -- @function on_start -- @param any Any parameters passed to parent node's run call function idle:on_start() if self.idle_animation then bt_mobs.animate(self.object, self.idle_animation) end end --- The main method that handles the processing for this @{idle} node. This node will cause the mob to -- set an idle animation and simply wait for the idle duration amount of time and then succeeds. -- @param ... Any parameters passed to the node's run method -- @return A string representing the enum @{behaviors.states} of "running", or "success". function idle:on_step(...) self.time = self.time-self.object.dtime if self.time <= 0 then return self:succeed() end return self:running() end -- function mobkit.lq_idle(self,duration,anim) -- anim = anim or 'stand' -- local init = true -- local func=function(self) -- if init then -- mobkit.animate(self,anim) -- init=false -- end -- duration = duration-self.dtime -- if duration <= 0 then return true end -- end -- mobkit.queue_low(self,func) -- end
local M = {} local Result = {} Result.__index = Result function Result.new() local tbl = {lines = {}, declaration = {params = {}, param_lines = {}, has_variadic = false}} return setmetatable(tbl, Result) end local function merge(origin, result) for key, value in pairs(result) do local v = origin[key] if vim.tbl_islist(v) then if vim.tbl_islist(value) then vim.list_extend(v, value) else table.insert(v, value) end elseif type(v) == "table" then merge(v, value) else origin[key] = value end end end function Result.merge(self, result) vim.validate({result = {result, "table", true}}) if result == nil then return end merge(self, result) end local State = {} State.__index = State function State.new(stage_name, processor) vim.validate({stage_name = {stage_name, "string"}, processor = {processor, "table"}}) local tbl = {stage_name = stage_name, _processor = processor} return setmetatable(tbl, State) end function State.changed(self, stage_name) vim.validate({stage_name = {stage_name, "string", true}}) if stage_name == nil then return false end return self.stage_name ~= stage_name end function State.process(self, values) local f = self._processor.STAGES[self.stage_name] return f(self._processor, unpack(values)) end function State.transition(self, stage_name) vim.validate({stage_name = {stage_name, "string"}}) return self.new(stage_name, self._processor) end local Parser = {} Parser.__index = Parser M.Parser = Parser function Parser.new(processor, iter) vim.validate({processor = {processor, "table"}, iter = {iter, "function"}}) local state = State.new(processor.FIRST_STAGE, processor) local tbl = { _state = state, _iter = iter, _first_stage = processor.FIRST_STAGE, _completed_stage_names = processor.COMPLETE_STAGE, } return setmetatable(tbl, Parser) end function Parser.parse(self) local nodes = {} local node = Result.new() local iter_values = {} local skip_iter = false while true do if not skip_iter then iter_values = {self._iter()} end if iter_values[1] == nil then break end local result, next_stage, skip = self._state:process(iter_values) skip_iter = skip node:merge(result) if not self._state:changed(next_stage) then goto continue end local state = self._state:transition(next_stage) if next_stage == self._first_stage then table.insert(nodes, node) node = Result.new() end self._state = state ::continue:: end if vim.tbl_contains(self._completed_stage_names, self._state.stage_name) then table.insert(nodes, node) end return nodes end return M
local helpers = require "spec.helpers" local cjson = require "cjson" for _, strategy in helpers.each_strategy() do describe("plugin: cluster-redirect (access) [#" .. strategy .. "]", function() local db, bp, dao local client -- Admin API REST interface local function api_send(method, path, body, forced_port) local api_client = helpers.admin_client() local res, err = api_client:send({ method = method, path = path, headers = { ["Content-Type"] = "application/json" }, body = body, }) if not res then api_client:close() return nil, err end local res_body = res.status ~= 204 and cjson.decode((res:read_body())) api_client:close() return res.status, res_body end setup(function() bp, db, dao = helpers.get_db_utils(strategy) -- start kong assert(helpers.start_kong({ -- set the strategy database = strategy, -- use the custom test template to create a local mock server nginx_conf = "spec/fixtures/custom_nginx.template", -- set the config item to make sure our plugin gets loaded plugins = "bundled,cluster-redirect", -- since Kong CE 0.14 custom_plugins = "cluster-redirect", -- pre Kong CE 0.14 })) assert.same(201, api_send("POST", "/upstreams", { name = "europe_cluster", slots = 10 })) assert.same(201, api_send("POST", "/upstreams", { name = "italy_cluster", slots = 10 })) assert.same(201, api_send("POST", "/upstreams/europe_cluster/targets", { target = "requestloggerbin.herokuapp.com:80"} )) assert.same(201, api_send("POST", "/upstreams/italy_cluster/targets", { target = "mockbin.org:80" })) assert.same(201, api_send("POST", "/services", { name = "europe-service", url = "http://europe_cluster:80/bin/a10f2738-6456-4bae-b5a9-f6c5e0463a66/view", })) assert.same(201, api_send("POST", "/services/europe-service/routes", { paths = { "/local" }, })) assert.same(201, api_send("POST", "/services/europe-service/plugins", { name = "cluster-redirect", config = { redirect = "italy_cluster", } })) end) teardown(function() helpers.stop_kong(nil, true) db:truncate("routes") db:truncate("services") db:truncate("targets") db:truncate("upstreams") end) before_each(function() client = helpers.proxy_client() end) after_each(function() if client then client:close() end end) -- Case 0: request with /local X-Country header (Italy) and X-Region describe("request", function() it("Positive case: matching for italy_cluster", function() local r = assert(client:send { method = "GET", path = "/local", -- makes mockbin return the entire request headers = { ["X-Country"] = "Italy", ["X-Regione"] = "Abruzzo", ["Host"] = "test.com", } }) local body = assert.res_status(200, r) assert.equal("", body) end) -- Case 1: request with /local X-Country header (non-Italy) and X-Region it("Negative case: going streight to europe_cluster", function() local r = assert(client:send { method = "GET", path = "/local", -- makes mockbin return the entire request headers = { ["X-Country"] = "Spain", ["X-Regione"] = "Abruzzo", ["Host"] = "test.com", } }) local body = assert.res_status(200, r) local json = cjson.decode(body) assert.is_string(json.content.text) assert.equal("This is europe_cluster", json.content.text) end) end) describe("request", function() end) end) end
-- HYDRO_TURBINE -- Water turbine: -- Active if flowing >water< above it -- (does not work with other liquids) minetest.register_node("mesecons_hydroturbine:hydro_turbine_off", { drawtype = "nodebox", tiles = {"jeija_hydro_turbine_off.png"}, groups = {dig_immediate=2}, description="Water Turbine", paramtype = "light", selection_box = { type = "fixed", fixed = {{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}, {-0.15, 0.5, -0.15, 0.15, 1.45, 0.15}, {-0.45, 1.15, -0.1, 0.45, 1.45, 0.1}, {-0.1, 1.15, -0.45, 0.1, 1.45, 0.45}}, }, node_box = { type = "fixed", fixed = {{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}, {-0.15, 0.5, -0.15, 0.15, 1.45, 0.15}, {-0.45, 1.15, -0.1, 0.45, 1.45, 0.1}, {-0.1, 1.15, -0.45, 0.1, 1.45, 0.45}}, }, sounds = default.node_sound_stone_defaults(), mesecons = {receptor = { state = mesecon.state.off }} }) minetest.register_node("mesecons_hydroturbine:hydro_turbine_on", { drawtype = "nodebox", tiles = {"jeija_hydro_turbine_on.png"}, drop = "mesecons_hydroturbine:hydro_turbine_off 1", groups = {dig_immediate=2,not_in_creative_inventory=1}, description="Water Turbine", paramtype = "light", selection_box = { type = "fixed", fixed = {{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}, {-0.15, 0.5, -0.15, 0.15, 1.45, 0.15}, {-0.5, 1.15, -0.1, 0.5, 1.45, 0.1}, {-0.1, 1.15, -0.5, 0.1, 1.45, 0.5}}, }, node_box = { type = "fixed", fixed = {{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}, {-0.15, 0.5, -0.15, 0.15, 1.45, 0.15}, {-0.5, 1.15, -0.1, 0.5, 1.45, 0.1}, {-0.1, 1.15, -0.5, 0.1, 1.45, 0.5}}, }, sounds = default.node_sound_stone_defaults(), mesecons = {receptor = { state = mesecon.state.on }} }) minetest.register_abm({ nodenames = {"mesecons_hydroturbine:hydro_turbine_off"}, interval = 1, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local waterpos={x=pos.x, y=pos.y+1, z=pos.z} if minetest.get_node(waterpos).name=="default:water_flowing" then minetest.add_node(pos, {name="mesecons_hydroturbine:hydro_turbine_on"}) minetest.check_for_falling(pos) mesecon.receptor_on(pos) end end, }) minetest.register_abm({ nodenames = {"mesecons_hydroturbine:hydro_turbine_on"}, interval = 1, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local waterpos={x=pos.x, y=pos.y+1, z=pos.z} if minetest.get_node(waterpos).name~="default:water_flowing" then minetest.add_node(pos, {name="mesecons_hydroturbine:hydro_turbine_off"}) minetest.check_for_falling(pos) mesecon.receptor_off(pos) end end, }) minetest.register_craft({ output = "mesecons_hydroturbine:hydro_turbine_off 2", recipe = { {"","default:stick", ""}, {"default:stick", "default:steel_ingot", "default:stick"}, {"","default:stick", ""}, } })
local M = {} function M.attach(bufnr, lang) -- TODO: Fill this with what you need to do when attaching to a buffer end function M.detach(bufnr) -- TODO: Fill this with what you need to do when detaching from a buffer end return M
---@class CS.FairyEditor.FullSearch ---@field public result CS.System.Collections.Generic.List_CS.FairyEditor.FPackageItem ---@type CS.FairyEditor.FullSearch CS.FairyEditor.FullSearch = { } ---@return CS.FairyEditor.FullSearch function CS.FairyEditor.FullSearch.New() end ---@param strName string ---@param strTypes string ---@param includeBrances boolean function CS.FairyEditor.FullSearch:Start(strName, strTypes, includeBrances) end return CS.FairyEditor.FullSearch
--[[ Bagnon Void Storage Localization: Russian --]] local L = LibStub('AceLocale-3.0'):NewLocale('Bagnon-VoidStorage', 'ruRU') if not L then return end L.ConfirmTransfer = 'Вклад этих предметов удалит все изменения и сделает их не продаваемыми и не возвращаемыми.|n|nПродолжить?' L.PurchaseDialog = 'Вы хотите разблокировать Хранилище Бездны?|n|n|cffffd200Цена:|r %s' L.CannotPurchaseDialog = 'У вас недостаточно денег для разблокировки Хранилище Бездны|n|n|cffff2020Цена: %s|r' L.AskMafia = 'Спросить у Мафии' L.Title = 'Хранилище Бездны %s' L.NumDeposit = '%d вложено' L.NumWithdraw = '%d снято'
Harmony.ui.styles = {} -- Eleusis: ForestGreen -- Cyrene: dodger_blue -- Mhaldor: firebrick -- Ashtan: blue_violet -- Hashan: a_darkmagenta -- Targossas: gold Harmony.ui.styles.blackConsole = [[ background-color: #000000; ]] Harmony.ui.styles.buttonActive = [[ background-color: #00654b; border-left: 1px solid rgba(0,0,0,0.7); border-bottom: 1px solid rgba(0,0,0,0.7); font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; ]] Harmony.ui.styles.buttonInactive = [[ background-color: rgba(242,99,73,0.29); border-left: 1px solid rgba(0,0,0,0.7); border-bottom: 1px solid rgba(0,0,0,0.7); font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; ]] Harmony.ui.styles.buttonNormal = [[ background-color: rgba(51,51,51,0.4); border-left: 1px solid rgba(0,0,0,0.7); border-bottom: 1px solid rgba(0,0,0,0.7); font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; ]] function Harmony.ui.styles.calculateBackground(from, to, current, max, min) local gaugeStyle = Harmony.ui.styles.gaugeFront -- What we'll divide by to get the % local base = max - min local div = current - min local r = 0 local g = 0 local b = 0 -- Gives us the change local difference = 1 - (div / base) -- Calculate current values r = from[1] - math.floor((from[1] - to[1]) * difference) g = from[2] - math.floor((from[2] - to[2]) * difference) b = from[3] - math.floor((from[3] - to[3]) * difference) gaugeStyle = gaugeStyle..("background-color: rgba(%s, %s, %s, 1);"):format(r, g, b) return gaugeStyle end Harmony.ui.styles.chatActive = [[ background-color: #043605; border-left: 1px solid black; border-bottom: 2px solid #259237; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; ]] Harmony.ui.styles.chatAlert = [[ background-color: #043605; border-left: 1px solid black; border-bottom: 2px solid #f25118; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; ]] Harmony.ui.styles.chatNormal = [[ background-color: #043605; border-left: 1px solid black; border-bottom: 2px solid #FFFFFF; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; ]] Harmony.ui.styles.cityAshtan = [[ QLabel{ background-color: rgba(138, 43, 226, .8); border: 1px solid #3c076d; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } QLabel::hover { background-color: rgba(138, 43, 226, .8); border: 1px solid #a443ff; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } ]] Harmony.ui.styles.cityCyrene = [[ QLabel{ background-color: rgba(30, 144, 255, .8); border: 1px solid #0461b7; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } QLabel::hover { background-color: rgba(30, 144, 255, .8); border: 1px solid #6db9ff; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } ]] Harmony.ui.styles.cityDelos = [[ QLabel{ background-color: rgba(105, 105, 105, .8); border: 1px solid #3f3f3f; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } QLabel::hover { background-color: rgba(105, 105, 105, .8); border: 1px solid #b7b7b7; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } ]] Harmony.ui.styles.cityEleusis = [[ QLabel{ background-color: rgba(34, 139, 34, .8); border: 1px solid #080c2f; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } QLabel::hover { background-color: rgba(34, 139, 34, .8); border: 1px solid #68ba68; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } ]] Harmony.ui.styles.cityHashan = [[ QLabel{ background-color: rgba(128, 0, 128, .8); border: 1px solid #360035; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } QLabel::hover { background-color: rgba(128, 0, 128, .8); border: 1px solid #b700b5; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } ]] Harmony.ui.styles.cityMhaldor = [[ QLabel{ background-color: rgba(178, 34, 34, .8); border: 1px solid #080c2f; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } QLabel::hover { background-color: rgba(178, 34, 34, .8); border: 1px solid #68ba68; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } ]] Harmony.ui.styles.cityTargossas = [[ QLabel{ background-color: rgba(255, 215, 0, .8); border: 1px solid #ae9300; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } QLabel::hover { background-color: rgba(255, 215, 0, .8); border: 1px solid #ffd800; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } ]] Harmony.ui.styles.gaugeFront = [[ border-radius: 5px; font-family: "Consolas", "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; ]] Harmony.ui.styles.healthBack = [[ background: #001c07; border: 2px solid black; border-radius: 9px; ]] Harmony.ui.styles.huntingButton = [[ QLabel{ background-color: rgba(6, 70, 0, .7); border: 1px solid rgba(6, 70, 0, .9); font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; } QLabel::hover { background-color: rgba(6, 104, 0, .7); border: 1px solid rgba(6, 104, 0, .9); color: black; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; } ]] Harmony.ui.styles.infoBox = [[ QLabel{ background-color: rgba(0, 0, 0, .7); border: 1px solid rgba(0, 0, 0, .8); font-family: "Consolas", "Courier New", monospace; font-size: 14px; } ]] Harmony.ui.styles.infoBoxFooter = [[ background-color: transparent; border-bottom: 1px solid white; border-right: 1px solid white; font-family: "Consolas", "Courier New", monospace; ]] Harmony.ui.styles.infoBoxHeader = [[ background-color: transparent; border-right: 1px solid white; font-family: "Consolas", "Courier New", monospace; ]] Harmony.ui.styles.leftBox = [[ background-color: rgba(0, 0, 0, 0); border-right: 1px solid #FFFFFF; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-right: 5px; ]] Harmony.ui.styles.manaBack = [[ background: #00075c; border: 2px solid black; border-radius: 9px; ]] Harmony.ui.styles.tacticActive = [[ QLabel{ background-color: rgba(11, 146, 34, .7); border-bottom: 1px solid rgba(0, 0, 0, .8); border-right: 1px solid rgba(0, 0, 0, .8); font-family: "Consolas", "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; } QLabel::hover { background-color: rgba(255, 237, 152, .3); border: 1px solid rgba(255, 237, 152, .5); } ]] Harmony.ui.styles.tacticInactive = [[ QLabel{ background-color: rgba(0, 0, 0, .5); border-bottom: 1px solid rgba(0, 0, 0, .8); border-right: 1px solid rgba(0, 0, 0, .8); font-family: "Consolas", "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; } QLabel::hover { background-color: rgba(255, 237, 152, .3); border: 1px solid rgba(255, 237, 152, .5); color: black; } ]] Harmony.ui.styles.topButton = [[ QLabel{ background-color: #043605; border: 1px solid #135815; border-radius: 3px; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-right: 5px; cursor: pointer; } QLabel::hover { border: 1px solid #66b368; } ]] Harmony.ui.styles.topButtonChild = [[ QLabel { background-color: rgba(0, 0, 0, .8); border: 1px solid #080c2f; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } QLabel::hover { background-color: rgba(0, 0, 0, .8); border: 1px solid #4ab0ce; font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; margin-left: 2px; cursor: pointer; } ]] Harmony.ui.styles.transparent = [[ QLabel{ background-color: rgba(0, 0, 0, 0); } ]]
--[[ This file is to deal with the code to generate the lockout table/vector and to handle the refresh of data and deletion of stale data --]] local addonName, _ = ...; -- libraries local addon = LibStub( "AceAddon-3.0" ):NewAddon( addonName, "AceConsole-3.0", "AceEvent-3.0", "AceBucket-3.0" ); local L = LibStub( "AceLocale-3.0" ):GetLocale( addonName, false ); --_G.LockedOut = addon; -- Upvalues local next, time = next, time; -- cache lua functions local InterfaceOptionsFrame_OpenToCategory, GetCurrencyListSize, GetCurrencyInfo, GetItemInfo, GetMacroIcons, RequestRaidInfo, GetServerExpansionLevel, GetMaxLevelForPlayerExpansion = -- variables InterfaceOptionsFrame_OpenToCategory, C_CurrencyInfo.GetCurrencyListSize, C_CurrencyInfo.GetCurrencyInfo, GetItemInfo, GetMacroIcons, RequestRaidInfo, GetServerExpansionLevel, GetMaxLevelForPlayerExpansion -- lua functions -- this allows me to override the blizzard function in the case of a "pre-patch" event. e.g.: 8.0 (BfA) but Legion still active local function getCurrentExpansionLevel() return GetServerExpansionLevel(); end local function getCurrentMaxLevel() return GetMaxLevelForPlayerExpansion(); end local function getGeneralOptionConfig( self ) local anchorOptions = { ["cell"] = L["At cursor location"], ["parent"] = L["At bottom of frame"] } return { order = 1, type = "group", name = L["Frame Options"], args = { minimapIconList = { order = 1, name = L["Choose Icon (reload ui)"], desc = L["Choose icon for addon - requires ui refresh or login/logout"], type = "select", values = addon:getIconOptions(), set = function(info,val) self.config.profile.minimap.addonIcon = val; end, get = function(info) return self.config.profile.minimap.addonIcon end }, showMinimapIcon = { order = 2, name = L["Hide Icon"], desc = L["Show Minimap Icon"], type = "toggle", set = function(info,val) self.config.profile.minimap.hide = val; if( self.config.profile.minimap.hide ) then self.icon:Hide( addonName ); else self.icon:Show( addonName ); end end, get = function(info) return self.config.profile.minimap.hide end }, configureFrameScale = { order = 3, name = L["Frame Scale"], desc = L["Configure the scale of the window"], type = "range", min = 0.50, max = 1.50, step = 0.05, set = function(info,val) self.config.profile.general.frameScale = val; if( addon.tooltip ) then addon.tooltip:SetScale( val ); end end, get = function(info) return self.config.profile.general.frameScale end }, setAnchorPoint = { order = 4, name = L["Anchor To"], desc = L["Choose where hover tooltip displays"], type = "select", style = "dropdown", values = anchorOptions, set = function(info,val) self.config.profile.general.anchorPoint = val; end, get = function(info) return self.config.profile.general.anchorPoint end }, showResetTime = { order = 5, name = L["Show Reset Time"], desc = L["Show reset time instead of checkbox when completed"], type = "toggle", set = function(info,val) self.config.profile.general.showResetTime = val; end, get = function(info) return self.config.profile.general.showResetTime end }, } }; end local function getCharacterOptionConfig( self ) local characterSortOptions = {} for key, data in next, self:getCharSortOptions() do characterSortOptions[ key ] = data.description; end local showCharList = {}; for key, value in next, addon:getCharacterList() do showCharList[ key ] = value; end return { order = 5, type = "group", name = L["Character Options"], args = { showRealmHeader = { order = 1, name = L["Show Realm"], desc = L["Show the realm header"], type = "toggle", set = function(info,val) self.config.profile.general.showRealmHeader = val; end, get = function(info) return self.config.profile.general.showRealmHeader end }, currentRealmOnly = { order = 2, name = L["Current Realm"], desc = L["Show characters from current realm only"], type = "toggle", set = function(info,val) self.config.profile.general.currentRealm = val; end, get = function(info) return self.config.profile.general.currentRealm end }, showCharFirst = { order = 3, name = L["Show Active First"], desc = L["Show logged in char first"], type = "toggle", set = function(info,val) self.config.profile.general.loggedInFirst = val; end, get = function(info) return self.config.profile.general.loggedInFirst end }, characterSort = { order = 4, name = L["Sort Chars By"], desc = L["Configure how characters are sorted in the list"], type = "select", style = "dropdown", values = characterSortOptions, set = function(info,val) self.config.profile.general.charSortBy = val; end, get = function(info) return self.config.profile.general.charSortBy end }, charTrackWhen = { order = 5, name = L["Start Tracking Level"], desc = L["Start tracking characters greater than or equal to level below"], type = "range", min = 1, max = getCurrentMaxLevel(), step = 1, set = function(info,val) self.config.profile.general.minTrackCharLevel = val; end, get = function(info) return self.config.profile.general.minTrackCharLevel end }, charVisible = { order = 6, name = L["Visible Characters"], desc = L["Which characters should show in menu"], type = "multiselect", values = showCharList, set = function(info,key,val) self.config.profile.general.showCharList[key] = val; end, get = function(info,key) return self.config.profile.general.showCharList[key] end }, } }; end local function getDungeonHeaderConfig( self ) local dungeonDisplayType = { [0] = L["All Characters"], [1] = L["Current realm only"], [2] = L["Current char only"], [3] = L["Hide completely"], }; return { order = 10, name = L["Instance Options"], type = "group", args = { dungeonShow = { order = 21, name = L["Show"], desc = L["Show dungeon information"], type = "toggle", set = function(info,val) self.config.profile.dungeon.show = val; end, get = function(info) return self.config.profile.dungeon.show end }, instanceDisplay = { order = 22, name = L["Locked Instance #"], desc = L["Determine how the locked instances show"], type = "select", style = "dropdown", values = dungeonDisplayType, set = function(info,val) self.config.profile.dungeon.displayType = val; end, get = function(info) return self.config.profile.dungeon.displayType end }, } }; end local function getRaidHeaderConfig( self ) return { order = 20, name = L["Raid Options"], type = "group", args = { raidShow = { order = 31, name = L["Show"], desc = L["Show raid information"], type = "toggle", set = function(info,val) self.config.profile.raid.show = val; end, get = function(info) return self.config.profile.raid.show end }, } } end local function getWorldBossHeaderConfig( self ) return { order = 30, name = L["World Boss Options"], type = "group", args = { worldBossShow = { order = 41, name = L["Show"], desc = L["Show world boss information"], type = "toggle", set = function(info,val) self.config.profile.worldBoss.show = val; end, get = function(info) return self.config.profile.worldBoss.show end }, worldBossOnlyDead = { order = 42, name = L["Show when dead"], desc = L["Show in list only when killed"], type = "toggle", set = function(info,val) self.config.profile.worldBoss.showKilledOnly = val; end, get = function(info) return self.config.profile.worldBoss.showKilledOnly end }, } }; end local function getEmissaryHeaderConfig( self ) return { order = 40, name = L["Emissary Options"], type = "group", args = { emissaryShow = { order = 51, name = L["Show"], desc = L["Show Emissary Information"], type = "toggle", set = function(info,val) self.config.profile.emissary.show = val; end, get = function(info) return self.config.profile.emissary.show end }, emissaryExp = { order = 52, name = L["Emissary groups"], desc = L["Which emissary groups to display"], type = "multiselect", values = addon.EmissaryDisplayGroups, set = function(info,key,val) self.config.profile.emissary.displayGroup[ key ] = val; end, get = function(info,key) return self.config.profile.emissary.displayGroup[ key ] end }, } }; end local function getWeeklyQuestHeaderConfig( self ) return { order = 50, name = L["Repeatable Quest Options"], type = "group", args = { weeklyQuestShow = { order = 61, name = L["Show"], desc = L["Show repeatable quest information"], type = "toggle", set = function(info,val) self.config.profile.weeklyQuest.show = val; end, get = function(info) return self.config.profile.weeklyQuest.show end }, } }; end local function getCurrencyHeaderConfig( self ) local currencyOptions = { ["short"] = L["Short"], ["long"] = L["Long"] }; local currencySortOptions = {}; for key, data in next, self:getCurrencyOptions() do currencySortOptions[ key ] = data.description; end local currencyList = { }; for ndx, currencyData in next, self:getCurrencyList() do if( currencyData.show ) then if( currencyData.icon == nil ) then if( currencyData.type == "C" ) then local currencyInfo = GetCurrencyInfo( currency.ID ); currencyData.icon = currencyInfo.iconFileID; currencyData.name = currencyInfo.name; else _, _, _, _, _, _, _, _, _, currencyData.icon = GetItemInfo( currencyData.ID ); end; end currencyList[ currencyData.ID ] = (currencyData.icon == nil ) and "" or currencyData.icon .. currencyData.name; end end return { order = 60, name = L["Currency Options"], type = "group", args = { currencyShow = { order = 101, name = L["Show"], desc = L["Show currency information"], type = "toggle", set = function(info,val) self.config.profile.currency.show = val; end, get = function(info) return self.config.profile.currency.show end }, currencyShorten = { order = 102, name = L["Currency Display"], desc = L["Configures currency display"], type = "select", style = "dropdown", values = currencyOptions, set = function(info,val) self.config.profile.currency.display = val; end, get = function(info) return self.config.profile.currency.display end }, currencySort = { order = 102, name = L["Sort By"], desc = L["Configure how currency is sorted"], type = "select", style = "dropdown", values = currencySortOptions, set = function(info,val) self.config.profile.currency.sortBy = val; end, get = function(info) return self.config.profile.currency.sortBy end }, displayExpansion = { order = 103, name = L["Display Expansion"], desc = L["Display expansion abbreviation the currency belongs to"], type = "toggle", set = function(info,key,val) self.config.profile.currency.displayExpansion = val; end, get = function(info,key) return self.config.profile.currency.displayExpansion end }, currencyVisible = { order = 104, name = L["Visible Currencies"], desc = L["Select which currencies you'd like to see"], type = "multiselect", values = currencyList, set = function(info,key,val) self.config.profile.currency.displayList[key] = val; end, get = function(info,key) return self.config.profile.currency.displayList[key] end }, } }; end local function getHolidayHeaderConfig( self ) return { order = 40, name = L["Holiday Options"], type = "group", args = { holidayShow = { order = 101, name = L["Show"], desc = L["Show holiday tracing info"], type = "toggle", set = function(info,val) self.config.profile.holidayEvents.show = val; end, get = function(info) return self.config.profile.holidayEvents.show end }, } }; end function addon:getConfigOptions() local configOptions = { type = "group", childGroups = "tab", name = addonName, args = { generalOptGroup = getGeneralOptionConfig( self ), characterOptGroup = getCharacterOptionConfig( self ), dungeonHeader = getDungeonHeaderConfig( self ), raidHeader = getRaidHeaderConfig( self ), worldBossHeader = getWorldBossHeaderConfig( self ), emissaryHeader = getEmissaryHeaderConfig( self ), weeklyQuestHeader = getWeeklyQuestHeaderConfig( self ), currencyHeader = getCurrencyHeaderConfig( self ), holidayHeader = getHolidayHeaderConfig( self ), } }; return configOptions; end function addon:getDefaultOptions() local currencyListDefaults = {}; for _, currencyData in next, self:getCurrencyList() do if( currencyData.show ) then currencyListDefaults[ currencyData.ID ] = (currencyData.expansionLevel == getCurrentExpansionLevel()); else currencyListDefaults[ currencyData.ID ] = nil; -- if improperly flagged, remove from list end end local showCharList = {}; for key, _ in next, addon:getCharacterList() do showCharList[ key ] = true; end local defaultOptions = { global = { enabled = true }, profile = { minimap = { --[[ position can only be >= 0 so use this to fix the position saving issue by forcing it to 0 later on if it == -1 --]] minimapPos = -1, hide = false, addonIcon = "134244", }, general = { currentRealm = false, showRealmHeader = true, loggedInFirst = true, anchorPoint = "cell", showCharList = showCharList, charSortBy = "rc", frameScale = 1.0, minTrackCharLevel = getCurrentMaxLevel(), showResetTime = false }, dungeon = { show = true, displayType = 0 }, raid = { show = true }, worldBoss = { show = true, showKilledOnly = true }, currency = { show = true, display = "long", displayList = currencyListDefaults, sortBy = "en", displayExpansion = true }, emissary = { show = true, displayGroup = addon.EmissaryDisplayGroups }, weeklyQuest = { show = true }, holidayEvents = { show = true }, } } return defaultOptions; end --[[ libdbicon doesn't trigger the update for some reason. so lets force the update outside first since -1 is an invalid value. change it to a correct default of 0 - this fixes the issue with minimap position not saving --]] local function minimapPositionFix( self ) if( self.config.profile.minimap.minimapPos == -1 ) then self.config.profile.minimap.minimapPos = 0; end end function addon:OnEnable() self:RegisterEvent( "PLAYER_ENTERING_WORLD", "EVENT_ResetExpiredData" ); self:RegisterEvent( "ZONE_CHANGED_NEW_AREA", "EVENT_CheckEnteredInstance" ); self:RegisterEvent( "COMBAT_LOG_EVENT_UNFILTERED", "EVENT_CheckEnteredInstance" ); self:RegisterBucketEvent( "UNIT_QUEST_LOG_CHANGED", 1, "EVENT_FullCharacterRefresh" ); self:RegisterEvent( "BAG_UPDATE", "EVENT_FullCharacterRefresh" ); self:RegisterEvent( "TIME_PLAYED_MSG", "EVENT_TimePlayed" ); self:RegisterEvent( "PLAYER_LOGOUT", "EVENT_Logout" ); self:RegisterEvent( "CHALLENGE_MODE_MAPS_UPDATE", "EVENT_SaveToInstance" ); self:RegisterEvent( "CHALLENGE_MODE_LEADERS_UPDATE", "EVENT_SaveToInstance" ); self:RegisterEvent( "CHALLENGE_MODE_MEMBER_INFO_UPDATED", "EVENT_SaveToInstance" ); self:RegisterEvent( "CHALLENGE_MODE_COMPLETED", "EVENT_SaveToInstance" ); self:RegisterEvent( "BOSS_KILL", "EVENT_SaveToInstance" ); self:RegisterBucketEvent( "CURRENCY_DISPLAY_UPDATE", 1, "EVENT_CoinUpdate" ); self:RegisterChatCommand( "lo", "ChatCommand" ); self:RegisterChatCommand( "lockedout", "ChatCommand" ); end function addon:OnDisable() self:UnRegisterEvent( "PLAYER_ENTERING_WORLD" ); self:UnRegisterEvent( "ZONE_CHANGED_NEW_AREA" ); self:UnRegisterEvent( "COMBAT_LOG_EVENT_UNFILTERED" ); self:UnRegisterEvent( "UNIT_QUEST_LOG_CHANGED" ); self:UnRegisterEvent( "BAG_UPDATE" ); self:UnRegisterEvent( "TIME_PLAYED_MSG" ); self:UnRegisterEvent( "PLAYER_LOGOUT" ); self:UnRegisterEvent( "CHALLENGE_MODE_MAPS_UPDATE" ); self:UnRegisterEvent( "CHALLENGE_MODE_LEADERS_UPDATE" ); self:UnRegisterEvent( "CHALLENGE_MODE_MEMBER_INFO_UPDATED" ); self:UnRegisterEvent( "CHALLENGE_MODE_COMPLETED" ); self:UnRegisterEvent( "BOSS_KILL" ); self:UnRegisterEvent( "CURRENCY_DISPLAY_UPDATE" ); self:UnRegisterChatCommand( "lo" ); self:UnRegisterChatCommand( "lockedout" ); end function addon:OnInitialize() local defaultOptions = self:getDefaultOptions(); self.config = LibStub( "AceDB-3.0" ):New( "LockedOutConfig", defaultOptions, true ); self.config:RegisterDefaults( defaultOptions ); local LockedoutMo = LibStub( "LibDataBroker-1.1" ):NewDataObject( "Locked Out", { type = "data source", text = L[ "Locked Out" ], label = "0/0", icon = self.config.profile.minimap.addonIcon, OnClick = function( frame, button ) self:OpenConfigDialog( button ) end, OnEnter = function( frame ) self:ShowInfo( frame ) end, } ); -- local LockedoutMo self.icon = LibStub( "LibDBIcon-1.0" ); minimapPositionFix( self ); self.icon:Register(addonName, LockedoutMo, self.config.profile.minimap) self.optionFrameName = addonName .. "OptionPanel" LibStub( "AceConfigRegistry-3.0" ):RegisterOptionsTable( self.optionFrameName, self:getConfigOptions() ); self.optionFrame = LibStub( "AceConfigDialog-3.0" ):AddToBlizOptions( self.optionFrameName, addonName ); self.optionFrame.default = function() self:ResetDefaults() end; self.toolTipShowing = false; self.loggingOut = false; end BINDING_NAME_LOCKEDOUT = L["Show/Hide the LockedOut tooltip"] BINDING_HEADER_LOCKEDOUT = L["Locked Out"] function LockedOut_ToggleMinimap( ) self = addon; self.toolTipShowing = not self.toolTipShowing; self:ShowInfo( self.icon.objects[addonName], self.toolTipShowing ); end function addon:ChatCommand( ) self:OpenConfigDialog(); end function addon:ResetDefaults() -- reset database here. self.config:ResetProfile(); minimapPositionFix( self ); self.icon:Refresh( addonName, self.config.profile.minimap ); LibStub("AceConfigRegistry-3.0"):NotifyChange( self.optionFrameName ); end function addon:OpenConfigDialog( button ) self.config:RegisterDefaults( self:getDefaultOptions() ); LibStub( "AceConfigRegistry-3.0" ):RegisterOptionsTable( self.optionFrameName, self:getConfigOptions() ); if( button == nil) or ( button == "RightButton" ) then -- this command is buggy, open it twice to fix the bug. InterfaceOptionsFrame_OpenToCategory( self.optionFrame ); -- #1 InterfaceOptionsFrame_OpenToCategory( self.optionFrame ); -- #2 end --[[ this helps to build the currency table local currList = self:getCurrencyList(); for ndx=1, 2000 do local currencyInfo = GetCurrencyInfo( ndx ); if( currencyInfo ~= nil ) then local name = currencyInfo.name; local found = false; for _, data in next, currList do if( data.ID == ndx ) then found = true; break; end end if( found == false ) then --print( '{ ID=' .. ndx .. ', name=nil, icon=nil, expansionLevel=7, type="C", show=true }, -- ' .. name ); print( "{ ID=" .. ndx .. ", name=nil, expansionLevel=" .. getCurrentExpansionLevel() .. ", type="C", show=true }, -- " .. name ); end end end --]] end function addon:EVENT_TimePlayed( event, timePlayed, currentPlayedLevel ) addon:debug( "EVENT_TimePlayed: ", event ); self.lastTimePlayedUpdate = time(); self.playerDb.timePlayed = { total = timePlayed, currentLevel = currentPlayedLevel }; end function addon:EVENT_Logout( event ) addon:debug( "EVENT_Logout: ", event ); self.loggingOut = true; self.playerDb.lastLogin = time(); -- means we fired before, and we can go ahead and force an update if( self.lastTimePlayedUpdate ) then local diff = self.playerDb.lastLogin - self.lastTimePlayedUpdate; self:EVENT_TimePlayed( event, self.playerDb.timePlayed.total + diff, self.playerDb.timePlayed.currentLevel + diff ); end end function addon:EVENT_CoinUpdate( event ) addon:debug( "EVENT_CoinUpdate: ", "CURRENCY_DISPLAY_UPDATE" ); self:EVENT_FullCharacterRefresh( "CURRENCY_DISPLAY_UPDATE" ); end function addon:EVENT_SaveToInstance( event ) addon:debug( "EVENT_SaveToInstance: ", event ); self:RegisterEvent( "UPDATE_INSTANCE_INFO", "EVENT_UpdateInstanceInfo" ); RequestRaidInfo(); end function addon:EVENT_UpdateInstanceInfo() self:UnregisterEvent( "UPDATE_INSTANCE_INFO" ); self:Lockedout_BuildInstanceLockout(); end function addon:EVENT_CheckEnteredInstance( event ) addon:debug( "EVENT_CheckEnteredInstance: ", event ); -- force a refresh every time something dies...in an effort to keep the latest time updating. if( event == "COMBAT_LOG_EVENT_UNFILTERED" ) then local _, eventType = CombatLogGetCurrentEventInfo(); if( eventType ~= "UNIT_DIED" ) then return; end end self:IncrementInstanceLockCount(); end function addon:EVENT_ResetExpiredData( event ) addon:debug( "EVENT_ResetExpiredData: ", event ); self:InitCharDB() self:checkExpiredLockouts( ); self.config:RegisterDefaults( self:getDefaultOptions() ); end function addon:EVENT_FullCharacterRefresh( event ) addon:debug( "EVENT_FullCharacterRefresh: ", event ); self:Lockedout_RebuildAll( ); end
require('hop').setup() vim.api.nvim_set_keymap('n', 'ss', "<cmd>:HopWord<cr>", {}) vim.api.nvim_set_keymap('n', 'sc', "<cmd>:HopChar1<cr>", {}) vim.api.nvim_set_keymap('n', 'sw', "<cmd>:HopChar2<cr>", {})
local json = require("cjson") local bit = require("bit") local exception = require("core.exception") local Util = { table = require("core.util.table"), string = require("core.util.string"), } function Util:isNull(value) return not value or (value == null) or (value == ngx.null) end --- 值是否为表 -- -- @param mixed value 值 -- @return boolean 是否为表 function Util:isTable(value) return type(value) == "table" end --- 值是否为字符串 -- -- @param mixed value 值 -- @return boolean 是否为字符串 function Util:isString(value) return type(value) == "string" end --- 值是否为数字 -- -- @param mixed value 值 -- @return boolean 是否为数字 function Util:isNumber(value) return type(value) == "number" end --- 值是否为布尔值 -- -- @param mixed value 值 -- @return boolean 是否为布尔值 function Util:isBoolean(value) return type(value) == "boolean" end --- 数值是否包含位值 -- -- @param number value 数值 -- @param number flag 位值 -- @return boolean 是否包含 function Util:hasBit(value, flag) return bit.band(value, flag) == flag end --- 数值添加位值 -- -- @param number value 数值 -- @param number flag 位值 -- @return number 添加后的数值 function Util:addBit(value, flag) return bit.bor(value, flag) end --- 数值移除位值 -- -- @param number value 数值 -- @param number flag 位值 -- @return number 移除后的数值 function Util:removeBit(value, flag) return bit.bxor(value, bit.band(value, flag)) end --- 转化任意类型的值为字符串 -- -- @param mixed value 任意类型的值 -- @param boolean forSql 是否需要SQL转义(转义关键字符并在两端加单引号) -- @return string 转化后的字符串 function Util:strval(value, forSql) local str = "" if value ~= nil then str = self:isTable(value) and json.encode(value) or tostring(value) elseif forSql then str = 'NULL' end if value and forSql then if (type(value) ~= 'boolean') and (type(value) ~= 'number') then return ngx.quote_sql_str(str) end end return str end --- 转化任意类型的值为数字 -- -- @param mixed value 任意类型的值 -- @param boolean abs 是否取绝对值 -- @return number 转化后的数字 function Util:numval(value, abs) local num = 0 if value then num = tonumber(value) or 0 end if num ~= 0 and abs then num = math.abs(num) end return num end --- 对数字四舍五入 -- -- @param number num 数字 -- @return number 四舍五入后的数字 function Util:round(num) return math.floor(num + 0.5) end --- 获取数字在限制内的值 -- -- @param number num 数字 -- @param number min 下限 -- @param number max 上限 -- @return number 限制内的数值 function Util:between(num, min, max) return math.max(min, math.min(max, num)) end --- 返回用参数替代格式字符串中占位符后的字符串 -- -- @param string format 格式字符串(占位符为{n}或{key}) -- @param table params 参数表(Hash或Array模式) -- @param boolean forSql 是否需要SQL转义(转义关键字符并在两端加单引号) -- @return string 格式化后的字符串 function Util:format(format, params, forSql) if not self:isTable(params) then return format end return (format:gsub("{(%w+)}", function(key) if key:match("^%d+$") then key = tonumber(key) end return self:strval(params[key], forSql) end)) end --- 获取当前时间 -- -- @param boolean isDate 是否返回日期格式 -- @return string|number 日期(yyyy-mm-dd hh:mm:ss)或时间戳(integer) function Util:now(isDate) return isDate and ngx.localtime() or ngx.time() end --- 解析时间日期格式为时间戳 -- -- @param string datetime 日期时间(yyyy-mm-dd hh:mm:ss) -- @return number 时间戳 function Util:parseDTime(datetime) local year, month, day, hour, min, sec = string.match(datetime, "(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)") return os.time({ sec = sec, min = min, hour = hour, day = day, month = month, year = year }) end --- 解析时间日期格式为时间 table -- -- @param string datetime 日期时间(yyyy-mm-dd hh:mm:ss) -- @return number 时间 table function Util:parseDDate(datetime) return os.date('*t',self:parseDTime(datetime)) end --- 截取日期部分 -- -- @param string datetime 日期时间(yyyy-mm-dd hh:mm:ss) -- @return number 日期 function Util:date(datetime) local result = datetime if not datetime then result = self:now(true) end m = ngx.re.match(result,[[(\d+)-(\d+)-(\d+)]],"o") if m then return m[0] end end --- 得到一天的起始时间 -- -- @param string datetime 日期时间(yyyy-mm-dd hh:mm:ss) -- @return number 日期时间(yyyy-mm-dd hh:mm:ss) function Util:dayBeginTime(datetime) local result = self:date(datetime) if result then return result .. ' 00:00:00' end end --- 得到一天的结束 -- -- @param string datetime 日期时间(yyyy-mm-dd hh:mm:ss) -- @return number 日期时间(yyyy-mm-dd hh:mm:ss) function Util:dayEndTime( datetime ) local result = self:date(datetime) if result then return result .. ' 23:59:59.999' end end function Util:CNHToLocalDate(date) if date then local result = ngx.re.gsub(date,"(年|月)","-") return ngx.re.gsub(result,'日',"") end end --~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- 判断时间差距,time2,time1是时间戳 -- 返回一个序列table,包含: -- {sec=52,min=0,hour=0,day=0,month=0,year=0} -- 致谢RichardWarburton。 -- 07/07/12 19:44:06 --~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function Util:timeDiff(time2,time1) local d1,d2,carry,diff = os.date('*t',time1),os.date('*t',time2),false,{} local colMax = {60,60,24,os.date('*t',os.time{year=d1.year,month=d1.month+1,day=0}).day,12} d2.hour = d2.hour - (d2.isdst and 1 or 0) + (d1.isdst and 1 or 0) -- handle dst for i,v in ipairs({'sec','min','hour','day','month','year'}) do diff[v] = d2[v] - d1[v] + (carry and -1 or 0) carry = diff[v] < 0 if carry then diff[v] = diff[v] + colMax[i] end end return diff end --~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- 判断时间差距,time2,time1是字符时间 -- 返回一个序列table,包含: -- {sec=52,min=0,hour=0,day=0,month=0,year=0} -- 致谢RichardWarburton。 -- 07/07/12 19:44:06 --~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function Util:dtimeDiff(time2,time1) return self:timeDiff(self:parseDTime(time2),self:parseDTime(time1)) end function Util:newDate(dt1,interval ,dateUnit) local ofset=0 if dateUnit =='DAY' then ofset = 60 *60 * 24 * interval elseif dateUnit == 'HOUR' then ofset = 60 *60 * interval elseif dateUnit == 'MINUTE' then ofset = 60 * interval elseif dateUnit == 'SECOND' then ofset = interval end local newTime = os.date("*t", dt1 + tonumber(ofset)) return newTime end --- 获得时区偏移秒数 -- -- @return number function Util:getTimeOffset() local diffTime = tonumber(os.date("%z")) return math.floor(diffTime / 100) * 3600 + (diffTime % 100) * 60 end --- IP是否在IP列表中 -- -- @param string ip IP地址 -- @param table list IP表(Array模式) -- @return boolean 是否在列表中 function Util:inIpList(ip, list) local bRange = ip:gsub("%.%d+%.%d+$", ".*.*") local cRange = ip:gsub("%.%d+$", ".*") for _, v in ipairs(list) do if v == ip or v == bRange or v == cRange then return true end end return false end --- 获取唯一键名 -- -- @param string prefix 前缀 -- @return string 唯一键名 function Util:getUniqKey(prefix) return string.format((prefix or "") .. "%X", ngx.now() * 100 + math.random(0, 99)) end --- 使用密钥对字符串进行加密(解密) -- -- @param string str 原始字符串(加密后的密文) -- @param string key 密钥 -- @return string 加密后的密文(原始字符串) function Util:encrypt(str, key) local strBytes = { str:byte(1, #str) } local keyBytes = { key:byte(1, #key) } local n, keyLen = 1, #keyBytes for i = 1, #strBytes do strBytes[i] = bit.bxor(strBytes[i], keyBytes[n]) n = n + 1 if n > keyLen then n = n - keyLen end end return string.char(unpack(strBytes)) end --- 预处理JSON信息(将空表替换成NULL) -- -- @param mixed data 数据 -- @param number depth 深度 function Util:jsonPrep(data, depth) depth = depth or 3 if self:isTable(data) then for k, v in pairs(data) do if self:isTable(v) then if self.table:isEmpty(v) then data[k] = NULL elseif depth > 0 then self:jsonPrep(v, depth - 1) end end end end end --- 尝试对字符串进行JSON解码 -- -- @param string jsonStr JSON字符串 -- @return mixed 解码数据 function Util:jsonDecode(jsonStr) local ok, data = pcall(json.decode, jsonStr) return ok and data or nil end --- 终止程序运行并返回调试信息 -- -- @param mixed info 调试数据 function Util:debug(info) exception:raise("core.debug", info) end --- 将数据转化为可打印的字符串 -- -- @param table data 数据 -- @param string indentStr 缩进字符 -- @param number indentLevel 缩进级别 -- @return string 可打印的字符串 function Util:toString(data, indentStr, indentLevel) local dataType = type(data) if dataType == "string" then return string.format('%q', data) elseif dataType == "number" or dataType == "boolean" then return tostring(data) elseif dataType == "table" then return self.table:toString(data, indentStr or "\t", indentLevel or 1) else return "<" .. tostring(data) .. ">" end end --- 打印数据到日志文件中 -- -- @param table data 数据 -- @param string prefix 描述前缀 -- @param string logFile 日志文件路径 function Util:logData(data, prefix, logFile) self:writeFile(logFile or "/tmp/lua.log", (prefix or "") .. self:toString(data) .. "\n", true) end --- 文件是否存在 -- -- @param string file 文件路径 -- @return boolen 是否存在 function Util:isFile(file) local fd = io.open(file, "r") if fd then fd:close() return true end return false end --- 将字符串内容写入文件 -- -- @param string file 文件路径 -- @param string content 内容 -- @param string append 追加模式(否则为覆盖模式) function Util:writeFile(file, content, append) local fd = exception:assert("core.cantOpenFile", { file = file }, io.open(file, append and "a+" or "w+")) local result, err = fd:write(content) fd:close() if not result then exception:raise("core.cantWriteFile", { file = file, errmsg = err }) end end --- 读取文件的全部内容 -- -- @param string file 文件路径 -- @return string 文件内容 function Util:readFile(file) local fd = exception:assert("core.cantOpenFile", { file = file }, io.open(file, "r")) local result = fd:read("*a") fd:close() if not result then exception:raise("core.cantReadFile", { file = file }) end return result end --- 执行系统命令并获得返回结果 -- -- @param string command 系统命令 -- @return string 返回结果 function Util:execute(command) local fd = exception:assert("core.cantOpenFile", { command = command }, io.popen(command, 'r')) local result = fd:read("*a") fd:close() if not result then exception:raise("core.cantReadFile", { command = command }) end return result end --- 建立模块与父模块的继承关系 -- -- @param table module 模块 -- @param table parent 父模块 -- @return table 模块(第一个参数) function Util:inherit(module, parent) module.__super = parent return setmetatable(module, { __index = parent }) end --- 访问nginx定义的内部位置,并返回数据结果 -- -- @param string uri 位置路径 -- @param table args GET参数(GET模式) -- @param table|string postData Post数据(Post模式) -- @param boolean stdRet 标准结果({"op":<number>,"data":<table>,"error":<string>},解析成数据并检查错误) -- @return table 结果数据 function Util:proxy(uri, args, postData, stdRet) local params = { args = args } if postData then params.method = ngx.HTTP_POST if self:isTable(postData) then params.body = ngx.encode_args(postData) else params.body = tostring(postData) end end local res = ngx.location.capture(uri, params) if res.status ~= ngx.HTTP_OK then exception:raise("core.proxyFailed", res) end if stdRet then local ok, data = pcall(json.decode, res.body) if not ok then exception:raise("core.proxyFailed", res) end if data.error and data.error ~= ngx.null then exception:raise("core.proxyFailed", data) end return data.data end return res.body end return Util
function start (song) end function update (elapsed) end function beatHit (beat) end function stepHit (beat) end function keyPressed (key) FlxG.camera.shake(0.05, 0.05); end
--[[ Replaces Code nodes with attrs that would be produced by rST reader from the role syntax by a Str AST node containing {role}, followed by a Code node. This is to emulate MyST syntax in Pandoc. (MyST is a CommonMark flavour with rST features mixed in.) Reference: https://myst-parser.readthedocs.io/en/latest/syntax/syntax.html#roles-an-in-line-extension-point ]] function Code(elem) local role = elem.attributes['role'] if elem.classes:includes('interpreted-text') and role ~= nil then elem.classes = elem.classes:filter(function (c) return c ~= 'interpreted-text' end) elem.attributes['role'] = nil return { pandoc.Str('{' .. role .. '}'), elem, } end end
-- indent.lua function edGetIndent() local indent = 0 local pos = getEditorLineStart() while edGetAt(pos) == " " do indent = indent + 1 pos = pos + 1 end return indent end function edGetIndent() local indent = 0 local pos = getEditorLineStart() while (function () local c = edGetAt(pos) if c == "\n" then return false end return c == " " end)() do indent = indent + 1 pos = pos + 1 end return indent end
Config = {} Config.Locale = 'en' -- check in locales folder for all avaiable languages Config.debugMode = false -- print a lot of stuff in console for internal test Config.showMutedOnScreen = true -- render an small text on screen that shows player they are muted Config.disableTalkKeyForMutedPlayers = true -- this will disable talking key (default : N) for players that are muted Config.notificationType = { -- what type of notification should we use ? GTA = true, chat = false } Config.discordLog = { -- discord webhook ( required ) webhook = "https://discord.com/api/webhooks/869448920022020126/hbrt-lGbilLXO6az7grk4uSCZfGXsLlDBxufDCdVRXXt5b4yNqQXNaBtXOasrt-w8yr3", -- discord bot profile ( optional ) botProfilePicture = "" } Config.permissions = { ['steam:100000000000000'] = true, ['license:1500000000000000000'] = true, ['fivem:151222'] = true, ['discord:1512255522223422'] = true } Config.ESX_permissions = { -- you can ignore it if you are not using ESX ['developer'] = true, ['admin'] = true, ['mod'] = false, } Config.QBC_permissions = { -- you can ignore it if you are not using QBCore ['god'] = true, ['admin'] = true, ['user'] = false, }
local a,b,c,d,e; d=b
local DynamicMusic = Class(function(self, inst) self.inst = inst self.inst:StartUpdatingComponent(self) self.enabled = true self.is_busy = false self.busy_timeout = 0 self.playing_danger = false self.season = GetSeasonManager() and GetSeasonManager().current_season or SEASONS.AUTUMN self.inst:ListenForEvent( "gotnewitem", function() self:OnContinueBusy() end ) self.inst:ListenForEvent( "dropitem", function() self:OnContinueBusy() end ) self.inst:ListenForEvent( "attacked", function(inst, dat) if self.enabled and dat.attacker and dat.attacker ~= self.inst and not dat.attacker:HasTag("shadow") and not dat.attacker:HasTag("thorny") and not (dat.attacker.components.burnable and dat.attacker.components.burnable:IsSmoldering()) then self:OnStartDanger() end end ) self.inst:ListenForEvent( "doattack", function(inst, dat) if self.enabled and dat and dat.target and dat.target.components.combat and not dat.target:HasTag("prey") and not dat.target:HasTag("bird") and not dat.target:HasTag("wall") and not dat.target:HasTag("butterfly") and not dat.target:HasTag("shadow") and not dat.target:HasTag("veggie") and not dat.target:HasTag("smashable") then self:OnStartDanger() end end ) self.inst:ListenForEvent( "resurrect", function(inst) self:StopPlayingDanger() end) self.inst:ListenForEvent( "dusktime", function(it, data) if self.enabled and not self.playing_danger and data.newdusk then self:StopPlayingBusy() self.inst.SoundEmitter:PlaySound( "dontstarve/music/music_dusk_stinger") end end, GetWorld()) self.inst:ListenForEvent( "daytime", function(it, data) if self.enabled and data.day > 0 and not self.playing_danger then self:StopPlayingBusy() self.inst.SoundEmitter:PlaySound( "dontstarve/music/music_dawn_stinger") end end, GetWorld()) self.inst:ListenForEvent( "nighttime", function(it, data) end, GetWorld()) inst:ListenForEvent( "builditem", function(it, data) self:OnStartBusy() end) inst:ListenForEvent( "buildstructure", function(it, data) self:OnStartBusy() end) inst:ListenForEvent( "working", function(it, data) self:OnStartBusy() end) end) function DynamicMusic:StartPlayingBusy() if GetWorld():IsRuins() then self.inst.SoundEmitter:PlaySound( "dontstarve/music/music_work_ruins", "busy") elseif GetWorld():IsCave() then self.inst.SoundEmitter:PlaySound( "dontstarve/music/music_work_cave", "busy") elseif GetSeasonManager():IsWinter() then self.season = SEASONS.WINTER self.inst.SoundEmitter:PlaySound( "dontstarve/music/music_work_winter", "busy") elseif GetSeasonManager():IsSpring() then self.season = SEASONS.SPRING self.inst.SoundEmitter:PlaySound( "dontstarve_DLC001/music/music_work_spring", "busy") elseif GetSeasonManager():IsSummer() then self.season = SEASONS.SUMMER self.inst.SoundEmitter:PlaySound( "dontstarve_DLC001/music/music_work_summer", "busy") else self.season = SEASONS.AUTUMN self.inst.SoundEmitter:PlaySound( "dontstarve/music/music_work", "busy") end self.inst.SoundEmitter:SetParameter( "busy", "intensity", 0 ) end function DynamicMusic:Enable() self.enabled = true end function DynamicMusic:Disable() self.enabled = false self:StopPlayingBusy() self:StopPlayingDanger() end function DynamicMusic:StopPlayingBusy() self.inst.SoundEmitter:SetParameter( "busy", "intensity", 0 ) end function DynamicMusic:OnStartBusy() if not self.enabled then return end if not self.busy_started then self.busy_started = true self:StartPlayingBusy() end local day = GetClock():IsDay() if day or GetWorld():IsCave() then self.busy_timeout = 15 if not self.is_busy then self.is_busy = true if not self.playing_danger then self.inst.SoundEmitter:SetParameter( "busy", "intensity", 1 ) end end end end function DynamicMusic:OnStartDanger() if not self.enabled then return end self.danger_timeout = 10 if not self.playing_danger then local epic = GetClosestInstWithTag("epic", self.inst, 30) local soundpath = nil if epic then if GetWorld():IsRuins() then soundpath = "dontstarve/music/music_epicfight_ruins" elseif GetWorld():IsCave() then soundpath = "dontstarve/music/music_epicfight_cave" elseif GetSeasonManager():IsWinter() then soundpath = "dontstarve/music/music_epicfight_winter" elseif GetSeasonManager():IsSpring() then soundpath = "dontstarve_DLC001/music/music_epicfight_spring" elseif GetSeasonManager():IsSummer() then soundpath = "dontstarve_DLC001/music/music_epicfight_summer" else soundpath = "dontstarve/music/music_epicfight" end elseif GetWorld():IsRuins() then soundpath = "dontstarve/music/music_danger_ruins" elseif GetWorld():IsCave() then soundpath = "dontstarve/music/music_danger_cave" elseif GetSeasonManager():IsWinter() then soundpath = "dontstarve/music/music_danger_winter" elseif GetSeasonManager():IsSpring() then soundpath = "dontstarve_DLC001/music/music_danger_spring" elseif GetSeasonManager():IsSummer() then soundpath = "dontstarve_DLC001/music/music_danger_summer" else soundpath = "dontstarve/music/music_danger" end self.inst.SoundEmitter:PlaySound(soundpath, "danger") self:StopPlayingBusy() self.playing_danger = true end end function DynamicMusic:StopPlayingDanger() self.inst.SoundEmitter:KillSound("danger") self.playing_danger = false end function DynamicMusic:OnContinueBusy() if self.is_busy then self.busy_timeout = 10 end end function DynamicMusic:OnUpdate(dt) if self.danger_timeout and self.danger_timeout > 0 then self.danger_timeout = self.danger_timeout - dt if self.danger_timeout <= 0 then self:StopPlayingDanger() end end if self.busy_timeout and self.busy_timeout > 0 then self.busy_timeout = self.busy_timeout - dt if self.busy_timeout <= 0 then self:StopPlayingBusy() self.is_busy = false end end if not self.is_busy then if not GetWorld():IsCave() then if GetSeasonManager().current_season ~= self.season then self.inst.SoundEmitter:KillSound("busy") self.season = GetSeasonManager().current_season if self.season == SEASONS.WINTER then self.inst.SoundEmitter:PlaySound( "dontstarve/music/music_work_winter", "busy") elseif self.season == SEASONS.SPRING then self.inst.SoundEmitter:PlaySound( "dontstarve_DLC001/music/music_work_spring", "busy") elseif self.season == SEASONS.SUMMER then self.inst.SoundEmitter:PlaySound( "dontstarve_DLC001/music/music_work_summer", "busy") else --autumn self.inst.SoundEmitter:PlaySound( "dontstarve/music/music_work", "busy") end end end end end return DynamicMusic
----------------------------------------------- -- torchItem.lua -- The code for the torch, when it is in the player's inventory. -- Created by NimbusBP1729 ----------------------------------------------- return{ name = 'torch', description = 'Torch', type = 'weapon', subtype = 'melee', damage = '2', special_damage = 'fire= 3', info = 'a standard torch', }
function main() m.log(9, "echo 123"); return "Lua script matched."; end
local awful = require 'awful' screen.connect_signal('request::desktop_decoration', function(s) awful.tag({'1', '2', '3', '4', '5'}, s, awful.layout.layouts[1]) end)
object_draft_schematic_furniture_furniture_tapestry_pole = object_draft_schematic_furniture_shared_furniture_tapestry_pole:new { } ObjectTemplates:addTemplate(object_draft_schematic_furniture_furniture_tapestry_pole, "object/draft_schematic/furniture/furniture_tapestry_pole.iff")
function onCreate() makeLuaSprite('cave','cave',-750,-430) addLuaSprite('cave',false) setLuaSpriteScrollFactor('cave', 0.9, 0.9); end
function SetPlayerPos(amx, player, x, y, z) setElementPosition(player, x, y, z) end GetPlayerPos = GetObjectPos function SetPlayerFacingAngle(amx, player, angle) setPedRotation(player, angle) end function GetPlayerFacingAngle(amx, player, refRot) writeMemFloat(amx, refRot, getPedRotation(player)) end function IsPlayerInRangeOfPoint(amx, player, range, pX, pY, pZ) return getDistanceBetweenPoints3D(pX, pY, pZ, getElementPosition(player)) <= range end function GetPlayerDistanceFromPoint(amx, player, pX, pY, pZ) return float2cell(getDistanceBetweenPoints3D(pX, pY, pZ, getElementPosition(player))) end function IsPlayerStreamedIn(amx, otherPlayer, player) return g_Players[getElemID(player)].streamedPlayers[getElemID(otherPlayer)] == true end function SetPlayerInterior(amx, player, interior) local playerId = getElemID(player) if g_Players[playerId].viewingintro then return end local oldInt = getElementInterior(player) setElementInterior(player, interior) procCallOnAll('OnPlayerInteriorChange', playerId, interior, oldInt) clientCall(player, 'AMX_OnPlayerInteriorChange', interior, oldInt) end function GetPlayerInterior(amx, player) return getElementInterior(player) end function SetPlayerHealth(amx, player, health) setElementHealth(player, health) end function GetPlayerHealth(amx, player, refHealth) writeMemFloat(amx, refHealth, getElementHealth(player)) end function SetPlayerArmour(amx, player, armor) setPedArmor(player, armor) end function GetPlayerArmour(amx, player, refArmor) writeMemFloat(amx, refArmor, getPedArmor(player)) end function SetPlayerAmmo(amx, player, slot, ammo) setWeaponAmmo(player, slot, ammo) end function GetPlayerAmmo(amx, player) return getPedTotalAmmo(player) end -- Weapon function GetPlayerWeaponState(amx, player) -- -1 WEAPONSTATE_UNKNOWN -- 0 WEAPONSTATE_NO_BULLETS -- 1 WEAPONSTATE_LAST_BULLET -- 2 WEAPONSTATE_MORE_BULLETS -- 3 WEAPONSTATE_RELOADING local vehicle = getPedOccupiedVehicle(player) if vehicle ~= nil then return -1 end -- TODO: Function don't return 3 because a isPedReloadingWeapon function only client-side local ammo = getPedAmmoInClip(player) if ammo == 0 then return 0 elseif ammo == 1 then return 1 elseif ammo >= 2 then return 2 else return -1 end end -- TODO: GetPlayerTargetPlayer function GetPlayerTargetActor(amx, player) local elem = getPedTarget(player) if getElementType(elem) == 'ped' and getElementData(elem, 'amx.actorped') then return getElemID(elem) end return INVALID_ACTOR_ID end function SetPlayerTeam(amx, player, team) setPlayerTeam(player, team) end function GetPlayerTeam(amx, player) return table.find(g_Teams, getPlayerTeam(player)) end function SetPlayerScore(amx, player, score) setElementData(player, 'Score', score) end function GetPlayerScore(amx, player) return getElementData(player, 'Score') end function GetPlayerDrunkLevel(player) notImplemented('GetPlayerDrunkLevel', 'SCM is not supported.') return 0 end function SetPlayerDrunkLevel(player) notImplemented('SetPlayerDrunkLevel', 'SCM is not supported.') return 0 end function SetPlayerColor(amx, player, r, g, b) setPlayerNametagColor(player, r, g, b) if g_ShowPlayerMarkers then setBlipColor(g_Players[getElemID(player)].blip, r, g, b, 255) end end function GetPlayerColor(amx, player) local r, g, b = getPlayerNametagColor(player) return color2cell(r, g, b) end function SetPlayerSkin(amx, player, skin) setElementModel(player, skinReplace[skin] or skin) end function GetPlayerSkin(amx, player) return getElementModel(player) end function GivePlayerWeapon(amx, player, weaponID, ammo) giveWeapon(player, weaponID, ammo, true) end function ResetPlayerWeapons(amx, player) takeAllWeapons(player) end function SetPlayerArmedWeapon(amx, player, weapon) return setPedWeaponSlot(player, weapon) end function GetPlayerWeaponData(amx, player, slot, refWeapon, refAmmo) local playerdata = g_Players[getElemID(player)] local weapon = playerdata.weapons and playerdata.weapons[slot] if weapon then amx.memDAT[refWeapon], amx.memDAT[refAmmo] = weapon.id, weapon.ammo end end function GivePlayerMoney(amx, player, amount) givePlayerMoney(player, amount) end function ResetPlayerMoney(amx, player) setPlayerMoney(player, 0) end function SetPlayerName(amx, player, name) return setPlayerName(player, name) end function GetPlayerMoney(amx, player) return getPlayerMoney(player) end function GetPlayerState(amx, player) return getPlayerState(player) end function GetPlayerIp(amx, player, refName, len) local ip = getPlayerIP(player) if #ip < len then writeMemString(amx, refName, ip) end end function GetPlayerPing(amx, player) return getPlayerPing(player) end function GetPlayerWeapon(amx, player) return getPedWeapon(player) end function GetPlayerKeys(amx, player, refKeys, refUpDown, refLeftRight) amx.memDAT[refKeys] = buildKeyState(player, g_KeyMapping) amx.memDAT[refUpDown] = buildKeyState(player, g_UpDownMapping) amx.memDAT[refLeftRight] = buildKeyState(player, g_LeftRightMapping) end function GetPlayerName(amx, player, nameBuf, bufSize) local name = getPlayerName(player) if #name <= bufSize then writeMemString(amx, nameBuf, name) end end function SetPlayerTime(amx, player, hours, minutes) clientCall(player, 'setTime', hours, minutes) end function GetPlayerTime(amx, player, refHour, refMinute) amx.memDAT[refHour], amx.memDAT[refMinute] = getTime() end -- TODO: TogglePlayerClock client function SetPlayerWeather(amx, player, weatherID) clientCall(player, 'setWeather', weatherID % 256) end function ForceClassSelection(amx, playerID) if not g_Players[playerID] then return end g_Players[playerID].returntoclasssel = true end function SetPlayerWantedLevel(amx, player, level) setPlayerWantedLevel(player, level) end function GetPlayerWantedLevel(amx, player) return getPlayerWantedLevel(player) end function GetPlayerFightingStyle(amx, player) return getPedFightingStyle(player) end function SetPlayerFightingStyle(amx, player, style) return setPedFightingStyle(player, style) end function SetPlayerVelocity(amx, player, vx, vy, vz) setElementVelocity(player, vx, vy, vz) end function GetPlayerVelocity(amx, player, refVX, refVY, refVZ) local vx, vy, vz = getElementVelocity(player) writeMemFloat(amx, refVX, vx) writeMemFloat(amx, refVY, vy) writeMemFloat(amx, refVZ, vz) end -- dummy function PlayCrimeReportForPlayer(amx, player, suspectid, crimeid) notImplemented('PlayCrimeReportForPlayer') return false end function PlayAudioStreamForPlayer(amx, player, url, posX, posY, posZ, distance, usepos) clientCall(player, 'PlayAudioStreamForPlayer', url, posX, posY, posZ, distance, usepos) end function StopAudioStreamForPlayer(amx, player) clientCall(player, 'StopAudioStreamForPlayer') end function SetPlayerShopName(amx) notImplemented('SetPlayerShopName') return false end function SetPlayerSkillLevel(amx, player, skill, level) return setPedStat(player, skill + 69, level) end function GetPlayerSurfingVehicleID(amx, player) return -1 end function GetPlayerSurfingObjectID(amx) notImplemented('GetPlayerSurfingObjectID') end function RemoveBuildingForPlayer(amx, player, model, x, y, z, radius) clientCall(player, 'RemoveBuildingForPlayer', model, x, y, z, radius) end function GetPlayerLastShotVectors(amx) notImplemented('GetPlayerLastShotVectors') return false end function SetPlayerAttachedObject(amx, player, index, modelid, bone, fOffsetX, fOffsetY, fOffsetZ, fRotX, fRotY, fRotZ, fScaleX, fScaleY, fScaleZ, materialcolor1, materialcolor2) local x, y, z = getElementPosition (player) local mtaBone = g_BoneMapping[bone] local obj = createObject(modelid, x, y, z) if obj ~= false then local playerID = getElemID(player) g_Players[playerID].attachedObjects[index] = obj setElementCollisionsEnabled (obj, false) setObjectScale (obj, fScaleX, fScaleY, fScaleZ) attachElementToBone(obj, player, mtaBone, fOffsetX, fOffsetY, fOffsetZ, fRotX, fRotY, fRotZ) --Todo: Implement material colors else outputDebugString('SetPlayerAttachedObject: Cannot attach object since the model is invalid. Model id was ' .. modelid) return 0 end return 1 end function RemovePlayerAttachedObject(amx, player, index) local playerID = getElemID(player) local obj = g_Players[playerID].attachedObjects[index] --Get the object stored at this slot if obj ~= false then detachElementFromBone( obj ) destroyElement( obj ) g_Players[playerID].attachedObjects[index] = nil return 1 end return 0 end function IsPlayerAttachedObjectSlotUsed(amx) notImplemented('IsPlayerAttachedObjectSlotUsed') return false end function EditAttachedObject(amx) notImplemented('EditAttachedObject') return false end function CreatePlayerTextDraw(amx, player, x, y, text) outputDebugString('CreatePlayerTextDraw called with args ' .. x .. ' ' .. y .. ' ' .. text) if ( not g_PlayerTextDraws[player] ) then --Create dimension if it doesn't exist outputDebugString('Created dimension for g_PlayerTextDraws[player]') g_PlayerTextDraws[player] = {} end local serverTDId = #g_PlayerTextDraws[player]+1 local clientTDId = #g_TextDraws + serverTDId local textdraw = { x = x, y = y, lwidth=0.5, lheight = 0.5, shadow = { visible=0, align=1, text=text, font=1, lwidth=0.5, lheight = 0.5 } } textdraw.clientTDId = clientTDId textdraw.serverTDId = serverTDId textdraw.visible = 0 g_PlayerTextDraws[player][serverTDId] = textdraw setmetatable( textdraw, { __index = textdraw.shadow, __newindex = function(t, k, v) local different if not t.shadow[k] then different = true else if type(v) == 'table' then different = not table.cmp(v, t.shadow[k]) else different = v ~= t.shadow[k] end end if different then --table.dump(v, 1, nil) --Dump the data --outputDebugString(string.format('A property changed for %d string: %s', textdraw.clientTDId, textdraw.text)) clientCall(player, 'TextDrawPropertyChanged', textdraw.clientTDId, k, v) t.shadow[k] = v end end } ) outputDebugString('assigned id s->' .. serverTDId .. ' c->' .. clientTDId .. ' to g_PlayerTextDraws[player]') clientCall(player, 'TextDrawCreate', clientTDId, table.deshadowize(textdraw, true)) return serverTDId end function PlayerTextDrawDestroy(amx, player, textdrawID) if not IsPlayerTextDrawValid(player, textdrawID) then return false end outputDebugString('Sending textdraw id s->' .. g_PlayerTextDraws[player][textdrawID].serverTDId .. ' c->' .. g_PlayerTextDraws[player][textdrawID].clientTDId .. ' for destruction') clientCall(player, 'TextDrawDestroy', g_PlayerTextDraws[player][textdrawID].clientTDId) g_PlayerTextDraws[player][textdrawID] = nil end function PlayerTextDrawLetterSize(amx, player, textdrawID, x, y) if not IsPlayerTextDrawValid(player, textdrawID) then return false end g_PlayerTextDraws[player][textdrawID].lwidth = width g_PlayerTextDraws[player][textdrawID].lheight = height return true end function PlayerTextDrawTextSize(amx, player, textdrawID, x, y) if not IsPlayerTextDrawValid(player, textdrawID) then return false end g_PlayerTextDraws[player][textdrawID].boxsize = { x, y } return true end function PlayerTextDrawAlignment(amx, player, textdrawID, align) if not IsPlayerTextDrawValid(player, textdrawID) then return false end g_PlayerTextDraws[player][textdrawID].align = (align == 0 and 1 or align) return true end function PlayerTextDrawColor(amx, player, textdrawID, r, g, b, a) if not IsPlayerTextDrawValid(player, textdrawID) then return false end g_PlayerTextDraws[player][textdrawID].color = { r, g, b } return true end function PlayerTextDrawUseBox(amx, player, textdrawID, usebox) if not IsPlayerTextDrawValid(player, textdrawID) then outputDebugString('textdraw is invalid, not setting usebox ' .. textdrawID) return false end g_PlayerTextDraws[player][textdrawID].usebox = usebox return true end function PlayerTextDrawBoxColor(amx, player, textdrawID, r, g, b, a) if not IsPlayerTextDrawValid(player, textdrawID) then return false end g_PlayerTextDraws[player][textdrawID].boxcolor = { r, g, b, a } end function PlayerTextDrawSetShadow(amx, player, textdrawID, size) if not IsPlayerTextDrawValid(player, textdrawID) then return false end g_PlayerTextDraws[player][textdrawID].shade = size return true end function PlayerTextDrawSetOutline(amx, player, textdrawID, size) if not IsPlayerTextDrawValid(player, textdrawID) then return false end g_PlayerTextDraws[player][textdrawID].outlinesize = size return true end function PlayerTextDrawSetProportional(amx, player, textdrawID, proportional) notImplemented('PlayerTextDrawSetProportional') --TextDrawSetProportional(amx, textdraw, proportional) end function PlayerTextDrawBackgroundColor(amx, player, textdrawID, r, g, b, a) if not IsPlayerTextDrawValid(player, textdrawID) then return false end g_PlayerTextDraws[player][textdrawID].outlinecolor = { r, g, b, a } return true end function PlayerTextDrawFont(amx, player, textdrawID, font) if not IsPlayerTextDrawValid(player, textdrawID) then return false end g_PlayerTextDraws[player][textdrawID].font = font return true end function PlayerTextDrawSetSelectable(amx) notImplemented('PlayerTextDrawSetSelectable') return false end function PlayerTextDrawShow(amx, player, textdrawID) if not IsPlayerTextDrawValid(player, textdrawID) then outputDebugString('PlayerTextDrawShow: not showing anything, not valid') return false end --if g_PlayerTextDraws[player][textdrawID].visible == 1 then -- return false --end g_PlayerTextDraws[player][textdrawID].visible = true clientCall(player, 'TextDrawShowForPlayer', g_PlayerTextDraws[player][textdrawID].clientTDId) --outputDebugString('PlayerTextDrawShow: proccessed for ' .. textdrawID .. ' with ' .. g_PlayerTextDraws[player][textdrawID].text) return true end function PlayerTextDrawHide(amx, player, textdrawID) if not IsPlayerTextDrawValid(player, textdrawID) then return false end --if g_PlayerTextDraws[player][textdrawID].visible == 0 then -- return false --end g_PlayerTextDraws[player][textdrawID].visible = false clientCall(player, 'TextDrawHideForPlayer', g_PlayerTextDraws[player][textdrawID].clientTDId) --outputDebugString('PlayerTextDrawHide: proccessed for ' .. textdrawID .. ' with ' .. g_PlayerTextDraws[player][textdrawID].text) end function PlayerTextDrawSetString(amx, player, textdrawID, str) if not IsPlayerTextDrawValid(player, textdrawID) then return false end g_PlayerTextDraws[player][textdrawID].text = str return true end function PlayerTextDrawSetPreviewModel(amx) notImplemented('PlayerTextDrawSetPreviewModel') return false end function PlayerTextDrawSetPreviewRot(amx) notImplemented('PlayerTextDrawSetPreviewRot') return false end function PlayerTextDrawSetPreviewVehCol(amx) notImplemented('PlayerTextDrawSetPreviewVehCol') return false end function GetPVarInt(amx, player, varname) local value = g_Players[getElemID(player)].pvars[varname] if not value or value[1] ~= PLAYER_VARTYPE_INT then return 0 end return value[2] end function SetPVarInt(amx, player, varname, value) g_Players[getElemID(player)].pvars[varname] = {PLAYER_VARTYPE_INT, value} return 1 end function GetPVarString(amx, player, varname, outbuf, length) local value = g_Players[getElemID(player)].pvars[varname] if not value or value[1] ~= PLAYER_VARTYPE_STRING then return 0 end if #value[2] < length then writeMemString(amx, outbuf, value[2]) else writeMemString(amx, outbuf, string.sub(value, 0, length - 1)) end return 1 end function SetPVarString(amx, player, varname, value) g_Players[getElemID(player)].pvars[varname] = {PLAYER_VARTYPE_STRING, value} return 1 end function GetPVarFloat(amx, player, varname) local value = g_Players[getElemID(player)].pvars[varname] if not value or value[1] ~= PLAYER_VARTYPE_FLOAT then return 0 end return float2cell(value[2]) end function SetPVarFloat(amx, player, varname, value) g_Players[getElemID(player)].pvars[varname] = {PLAYER_VARTYPE_FLOAT, value} return 1 end function DeletePVar(amx, player, varname) g_Players[getElemID(player)].pvars[varname] = nil return 1 end function GetPVarsUpperIndex(amx) notImplemented('GetPVarsUpperIndex') return false end function GetPVarNameAtIndex(amx) notImplemented('GetPVarNameAtIndex') return false end function GetPVarType(amx, player, varname) local value = g_Players[getElemID(player)].pvars[varname] if value then return value[1] end return PLAYER_VARTYPE_NONE end function SetPlayerChatBubble(amx, player, text, color, dist, exptime) notImplemented('SetPlayerChatBubble') return false end function PutPlayerInVehicle(amx, player, vehicle, seat) warpPedIntoVehicle(player, vehicle, seat) if g_RCVehicles[getElementModel(vehicle)] then setElementAlpha(player, 0) end --setPlayerState(player, seat == 0 and PLAYER_STATE_DRIVER or PLAYER_STATE_PASSENGER) --No need to do this since the vehicle event gets called when we enter a vehicle end function GetPlayerVehicleID(amx, player) local vehicle = getPedOccupiedVehicle(player) if not vehicle then return 0 end return getElemID(vehicle) end function GetPlayerVirtualWorld(amx, player) return getElementDimension(player) end function GetPlayerVehicleSeat(amx, player) return getPedOccupiedVehicleSeat(player) end function RemovePlayerFromVehicle(amx, player) local vehicle = getPedOccupiedVehicle(player) if vehicle then removePedFromVehicle(player) if g_RCVehicles[getElementModel(vehicle)] then clientCall(root, 'setElementAlpha', player, 255) end end setPlayerState(player, PLAYER_STATE_ONFOOT) end function TogglePlayerControllable(amx, player, enable) toggleAllControls(player, enable, true, false) end function PlayerPlaySound(amx, player, soundID, x, y, z) notImplemented('PlayerPlaySound') end function ApplyAnimation(amx, player, animlib, animname, fDelta, loop, lockx, locky, freeze, time, forcesync) --time = Timer in ms. For a never-ending loop it should be 0. if time == 0 then loop = true end setPedAnimation(player, animlib, animname, time, loop, lockx or locky, false, freeze) setPedAnimationSpeed(player, animname, fDelta) end function ClearAnimations(amx, player) setPedAnimation(player, false) g_Players[getElemID(player)].specialaction = SPECIAL_ACTION_NONE end function GetPlayerAnimationIndex(player) notImplemented('GetPlayerAnimationIndex') return 0 end function GetAnimationName(amx) notImplemented('GetAnimationName') return false end function GetPlayerSpecialAction(amx, player) if doesPedHaveJetPack(player) then return SPECIAL_ACTION_USEJETPACK else return g_Players[getElemID(player)].specialaction or SPECIAL_ACTION_NONE end end function SetPlayerSpecialAction(amx, player, actionID) if actionID == SPECIAL_ACTION_NONE then removePedJetPack(player) setPedAnimation(player, false) elseif actionID == SPECIAL_ACTION_USEJETPACK then givePedJetPack(player) elseif g_SpecialActions[actionID] then setPedAnimation(player, unpack(g_SpecialActions[actionID])) end g_Players[getElemID(player)].specialaction = actionID end function DisableRemoteVehicleCollisions(amx) notImplemented('DisableRemoteVehicleCollisions') return false end function SetPlayerCheckpoint(amx, player, x, y, z, size) g_Players[getElemID(player)].checkpoint = { x = x, y = y, z = z, radius = size } clientCall(player, 'SetPlayerCheckpoint', x, y, z, size) end function DisablePlayerCheckpoint(amx, player) g_Players[getElemID(player)].checkpoint = nil clientCall(player, 'DisablePlayerCheckpoint') end function SetPlayerRaceCheckpoint(amx, player, type, x, y, z, nextX, nextY, nextZ, size) g_Players[getElemID(player)].racecheckpoint = { type = type, x = x, y = y, z = z, radius = size } clientCall(player, 'SetPlayerRaceCheckpoint', type, x, y, z, nextX, nextY, nextZ, size) end function DisablePlayerRaceCheckpoint(amx, player) g_Players[getElemID(player)].racecheckpoint = nil clientCall(player, 'DisablePlayerRaceCheckpoint') end -- SetPlayerWorldBounds client -- SetPlayerMarkerForPlayer client function ShowPlayerNameTagForPlayer(amx, player, playerToShow, show) clientCall(player, 'setPlayerNametagShowing', playerToShow, show) end -- SetPlayerMapIcon client -- RemovePlayerMapIcon client function AllowPlayerTeleport(amx, player, allow) deprecated('AllowPlayerTeleport', '0.3d') end function SetPlayerCameraPos(amx, player, x, y, z) fadeCamera(player, true) setCameraMatrix(player, x, y, z) end function SetPlayerCameraLookAt(amx, player, lx, ly, lz) fadeCamera(player, true) local x, y, z = getCameraMatrix(player) setCameraMatrix(player, x, y, z, lx, ly, lz) end function SetCameraBehindPlayer(amx, player) --In samp calling SetCameraBehindPlayer also unsets camera interpolation clientCall(player, 'removeCamHandlers') setCameraTarget(player, player) end function GetPlayerCameraPos(amx, player, refX, refY, refZ) local x, y, z = getCameraMatrix(player) writeMemFloat(amx, refX, x) writeMemFloat(amx, refY, y) writeMemFloat(amx, refZ, z) end function GetPlayerCameraFrontVector(amx, player, refX, refY, refZ) local x, y, z, lx, ly, lz = getCameraMatrix(player) writeMemFloat(amx, refX, lx) writeMemFloat(amx, refY, ly) writeMemFloat(amx, refZ, lz) end function GetPlayerCameraMode(amx) notImplemented('GetPlayerCameraMode') end function EnablePlayerCameraTarget(amx) notImplemented('EnablePlayerCameraTarget') return false end function GetPlayerCameraTargetObject(amx) notImplemented('GetPlayerCameraTargetObject') return false end function GetPlayerCameraTargetVehicle(amx) notImplemented('GetPlayerCameraTargetVehicle') return false end function GetPlayerCameraTargetPlayer(amx) notImplemented('GetPlayerCameraTargetPlayer') return false end function GetPlayerCameraTargetActor(amx) notImplemented('GetPlayerCameraTargetActor') return false end function GetPlayerCameraAspectRatio(amx) notImplemented('GetPlayerCameraAspectRatio') return false end function GetPlayerCameraZoom(amx) notImplemented('GetPlayerCameraZoom') return false end function AttachCameraToObject(amx, player, object) clientCall(player, 'AttachCameraToObject', object) end function AttachCameraToPlayerObject(amx) notImplemented('AttachCameraToPlayerObject') return false end --playerid, Float:FromX, Float:FromY, Float:FromZ, Float:ToX, Float:ToY, Float:ToZ, time, cut = CAMERA_CUT function InterpolateCameraPos(amx, player, FromX, FromY, FromZ, ToX, ToY, ToZ, time, cut) clientCall(player, 'InterpolateCameraPos', FromX, FromY, FromZ, ToX, ToY, ToZ, time, cut) end function InterpolateCameraLookAt(amx, player, FromX, FromY, FromZ, ToX, ToY, ToZ, time, cut) clientCall(player, 'InterpolateCameraLookAt', FromX, FromY, FromZ, ToX, ToY, ToZ, time, cut) end function IsPlayerAdmin(amx, player) return isPlayerInACLGroup(player, 'Admin') or isPlayerInACLGroup(player, 'Console') end function IsPlayerConnected(amx, playerID) return g_Players[playerID] ~= nil end function IsPlayerInAnyVehicle(amx, player) return getPedOccupiedVehicle(player) and true end function IsPlayerInCheckpoint(amx, player) local playerdata = g_Players[getElemID(player)] if not playerdata.checkpoint then return false end local x, y = getElementPosition(player) return math.sqrt((playerdata.checkpoint.x - x)^2 + (playerdata.checkpoint.y - y)^2) <= playerdata.checkpoint.radius end function IsPlayerInRaceCheckpoint(amx, player) local playerdata = g_Players[getElemID(player)] if not playerdata.racecheckpoint then return false end local x, y = getElementPosition(player) return math.sqrt((playerdata.racecheckpoint.x - x)^2 + (playerdata.racecheckpoint.y - y)^2) <= playerdata.racecheckpoint.radius end function IsPlayerInVehicle(amx, player, vehicle) return getPedOccupiedVehicle(player) == vehicle end function SetPlayerVirtualWorld(amx, player, dimension) setElementDimension(player, dimension) end function EnableStuntBonusForAll(amx, enable) notImplemented('EnableStuntBonusForAll') end function EnableStuntBonusForPlayer(amx, player, enable) notImplemented('EnableStuntBonusForPlayer') end function TogglePlayerSpectating(amx, player, enable) if enable then fadeCamera(player, true) setCameraMatrix(player, 75.461357116699, 64.600051879883, 51.685581207275, 149.75857543945, 131.53228759766, 40.597320556641) setPlayerHudComponentVisible(player, 'radar', false) setPlayerState(player, PLAYER_STATE_SPECTATING) else local playerdata = g_Players[getElemID(player)] local spawninfo = playerdata.spawninfo or (g_PlayerClasses and g_PlayerClasses[playerdata.selectedclass]) if not spawninfo then putPlayerInClassSelection(player) return end if isPedDead(player) then spawnPlayerBySelectedClass(player) end --In samp calling TogglePlayerSpectating also unsets camera interpolation clientCall(player, 'removeCamHandlers') setCameraTarget(player, player) clientCall(player, 'setCameraTarget', player) --Clear the one on the client as well, otherwise we can't go back to normal camera after spectating vehicles setPlayerHudComponentVisible(player, 'radar', true) setPlayerState(player, PLAYER_STATE_ONFOOT) end end function PlayerSpectatePlayer(amx, player, playerToSpectate, mode) setCameraTarget(player, playerToSpectate) end function PlayerSpectateVehicle(amx, player, vehicleToSpectate, mode) if getVehicleController(vehicleToSpectate) then setCameraTarget(player, getVehicleController(vehicleToSpectate)) else clientCall(player, 'setCameraTarget', vehicleToSpectate) end end function StartRecordingPlayerData(amx) notImplemented('StartRecordingPlayerData') return false end function StopRecordingPlayerData(amx) notImplemented('StopRecordingPlayerData') return false end function SelectTextDraw(amx) notImplemented('SelectTextDraw') return false end function CancelSelectTextDraw(amx) notImplemented('CancelSelectTextDraw') return false end -- Explosion function CreateExplosionForPlayer(amx, player, x, y, z, type, radius) clientCall(player, 'createExplosion', x, y, z, type, true, -1.0, false) return 1 end
--[[ Desc: Input component Author: SerDing Since: 2018-04-06 16:11:06 Last Modified time: 2018-04-06 16:11:06 Docs: * Receive and cache input messages for entity, implement input handler interface. * When you create an instance for a entity, it will register itself to the input module of engine. * skillInputMap is used to map some skill shortcut messages to concrete skill messages(e.g:"skill_1"->"gorecross") ]] local _Event = require("core.event") local _INPUT = require("engine.input") ---@type Engine.Input local _Base = require("entity.component.base") ---@class Entity.Component.Input : Engine.Input.InputHandler ---@field protected _actionBindings table<string, table<string, Event>> ---@field protected _axisBindings table<string, Event> ---@field protected _actionState table @ map of actions ---@field public skillInputMap table<string, string> local _InputComponent = require("core.class")(_Base) function _InputComponent:Ctor(entity, data) _Base.Ctor(self, entity) self._actionState = {} self._actionBindings = { [EInput.STATE.PRESSED] = {}, [EInput.STATE.DOWN] = {}, [EInput.STATE.RELEASED] = {}, } self._axisBindings = { movex = _Event.New(), } self.skillInputMap = data.skillInputMap or {} _INPUT.Register(self) end function _InputComponent:BindAction(action, state, obj, callback) if not self._actionBindings[state][action] then self._actionBindings[state][action] = _Event.New() end self._actionBindings[state][action]:AddListener(obj, callback) --print("BindAction", action, state, self._actionBindings[state][action]) end ---@param axis string ---@param callback fun(value:number):void function _InputComponent:BindAxis(axis, obj, callback) if not self._axisBindings[axis] then self._axisBindings[axis] = _Event.New() end self._axisBindings[axis]:AddListener(obj, callback) end function _InputComponent:UnBindAction(action, state, obj, callback) local event = self._actionBindings[state][action] if event then event:DelListener(obj, callback) end end function _InputComponent:UnBindAxis(axis, obj, callback) local event = self._axisBindings[axis] if event then event:DelListener(obj, callback) end end function _InputComponent:InputAction(action, state) local event = self._actionBindings[state][action] --print("InputAction: ", action, state, event) if event then event:Notify() end end function _InputComponent:InputAxis(axis, value) local event = self._axisBindings[axis] if event then event:Notify(value) end end function _InputComponent:HandleAction(action, state) if not self._entity.aic.enable then self:InputAction(action, state) end end function _InputComponent:HandleAxis(axis, value) if not self._entity.aic.enable then self:InputAxis(axis, value) end end return _InputComponent
equip_exam = {} equip_exam.name = core.get_current_modname() equip_exam.path = core.get_modpath(equip_exam.name) local files = { "formspec", "node", "crafting", } for _, f in pairs(files) do dofile(equip_exam.path .. "/" .. f .. ".lua") end
local pkgObj = {} local function push(list,value) local node = {next=nil,value=value} if list.head == nil then list.head = node list.tail = node else list.tail.next = node list.tail = node end list.len = list.len + 1 end local function pop(list) local ret=nil if list.head ~= nil then ret = list.head.value list.head= list.head.next list.len = list.len -1 end return ret end function pkgObj.create() local list = {push=push,pop=pop,len=0} return list end return pkgObj
local K, C, L = unpack(select(2, ...)) local Module = K:GetModule("ActionBar") local _G = _G local math_min = _G.math.min local math_ceil = _G.math.ceil local table_insert = _G.table.insert local FilterConfig = C.ActionBars.actionBarCustom local padding, margin = 0, 6 local prevPage = 8 local function ChangeActionPageForDruid() local page = IsPlayerSpell(33891) and 10 or 8 if prevPage ~= page then RegisterStateDriver(_G["KKUI_CustomBar"], "page", page) for i = 1, 12 do local button = _G["KKUI_CustomBarButton"..i] button.id = (page - 1) * 12 + i button:SetAttribute("action", button.id) end prevPage = page end end local function UpdatePageBySpells() if InCombatLockdown() then K:RegisterEvent("PLAYER_REGEN_ENABLED", UpdatePageBySpells) else ChangeActionPageForDruid() K:UnregisterEvent("PLAYER_REGEN_ENABLED", UpdatePageBySpells) end end function Module:SetupCustomBar(anchor) local size = C["ActionBar"].CustomBarButtonSize local num = 12 local name = "KKUI_CustomBar" local page = K.Class == "WARRIOR" and 10 or 8 local frame = CreateFrame("Frame", name, UIParent, "SecureHandlerStateTemplate") frame:SetWidth(num * size + (num - 1) * margin + 2 * padding) frame:SetHeight(size + 2 * padding) frame:SetPoint(unpack(anchor)) frame.mover = K.Mover(frame, L[name], "CustomBar", anchor) frame.buttons = {} -- RegisterStateDriver(frame, "visibility", "[petbattle] hide; show") RegisterStateDriver(frame, "page", page) local buttonList = {} for i = 1, num do local button = CreateFrame("CheckButton", "$parentButton"..i, frame, "ActionBarButtonTemplate") button:SetSize(size, size) button.id = (page - 1) * 12 + i button.isCustomButton = true button.commandName = L[name]..i button:SetAttribute("action", button.id) frame.buttons[i] = button table_insert(buttonList, button) table_insert(Module.buttons, button) end if C["ActionBar"].FadeCustomBar and FilterConfig.fader then Module.CreateButtonFrameFader(frame, buttonList, FilterConfig.fader) end Module:UpdateCustomBar() end function Module:UpdateCustomBar() local frame = _G.KKUI_CustomBar if not frame then return end local size = C["ActionBar"].CustomBarButtonSize local num = C["ActionBar"].CustomBarNumButtons local perRow = C["ActionBar"].CustomBarNumPerRow for i = 1, num do local button = frame.buttons[i] button:SetSize(size, size) button:ClearAllPoints() if i == 1 then button:SetPoint("TOPLEFT", frame, padding, -padding) elseif mod(i - 1, perRow) == 0 then button:SetPoint("TOP", frame.buttons[i - perRow], "BOTTOM", 0, -margin) else button:SetPoint("LEFT", frame.buttons[i - 1], "RIGHT", margin, 0) end button:SetAttribute("statehidden", false) button:Show() end for i = num + 1, 12 do local button = frame.buttons[i] button:SetAttribute("statehidden", true) button:Hide() end local column = math_min(num, perRow) local rows = math_ceil(num / perRow) frame:SetWidth(column * size + (column - 1) * margin + 2 * padding) frame:SetHeight(size * rows + (rows - 1) * margin + 2 * padding) frame.mover:SetSize(frame:GetSize()) end function Module:CreateCustomBar() if not C["ActionBar"].CustomBar then return end Module:SetupCustomBar({"BOTTOM", UIParent, "BOTTOM", 0, 140}) if K.Class == "DRUID" then UpdatePageBySpells() K:RegisterEvent("LEARNED_SPELL_IN_TAB", UpdatePageBySpells) end end
local commands = bot.commands local fw = "𝑨 𝑩 𝑪 𝑫 𝑬 𝑭 𝑮 𝑯 𝑰 𝑱 𝑲 𝑳 𝑴 𝑵 𝑶 𝑷 𝑸 𝑹 𝑺 𝑻 𝑼 𝑽 𝑾 𝑿 𝒀 𝒁" local charMap = {} for i, c in next, fw:split(" ") do charMap[64 + i] = { string.byte(c, 1, 9) } end commands.stand = { callback = function(msg, line) local str = "『 " .. line .. " 』" -- props to string.anime from Metastruct str = str:upper() -- str = str:gsub("%l", function(c) return string.char(239, 189, 130 + (c:byte() - 98)) end) str = str:gsub("%u", function(c) return -- string.char(239, 188, 161 + (c:byte() - 65)) -- OG fullwidth string.char(unpack(charMap[c:byte()])) end) msg.channel:send(str) end, help = { text = "Converts text to something ressembling a Stand name from JoJo.", usage = "`{prefix}{cmd} <any text>`", example = "`{prefix}{cmd} Star Platinum`" }, category = "Fun" }
--[[ Example Service This is an example to demonstrate how to use the BaseService class to implement a game service. **NOTE:** After declaring you service, you have to include your package inside the main.lua file! ]]-- require 'common' require 'services.baseservice' --Declare class DebugTools local DebugTools = Class('DebugTools', BaseService) --[[--------------------------------------------------------------- DebugTools:initialize() DebugTools class constructor ---------------------------------------------------------------]] function DebugTools:initialize() BaseService.initialize(self) PrintInfo('DebugTools:initialize()') end --[[--------------------------------------------------------------- DebugTools:__gc() DebugTools class gc method Essentially called when the garbage collector collects the service. ---------------------------------------------------------------]] function DebugTools:__gc() PrintInfo('*****************DebugTools:__gc()') end --[[--------------------------------------------------------------- DebugTools:OnInit() Called on initialization of the script engine by the game! ---------------------------------------------------------------]] function DebugTools:OnInit() assert(self, 'DebugTools:OnInit() : self is null!') PrintInfo("\n<!> ExampleSvc: Init..") end --[[--------------------------------------------------------------- DebugTools:OnDeinit() Called on de-initialization of the script engine by the game! ---------------------------------------------------------------]] function DebugTools:OnDeinit() assert(self, 'DebugTools:OnDeinit() : self is null!') PrintInfo("\n<!> ExampleSvc: Deinit..") end --[[--------------------------------------------------------------- DebugTools:OnNewGame() When a new save file is loaded this is called! ---------------------------------------------------------------]] function DebugTools:OnNewGame() assert(self, 'DebugTools:OnNewGame() : self is null!') for ii = 1, _DATA.StartChars.Count, 1 do _DATA.Save:RogueUnlockMonster(_DATA.StartChars[ii-1].Item1.Species) end if _DATA.Save.ActiveTeam.Players.Count > 0 then local talk_evt = RogueEssence.Dungeon.BattleScriptEvent("AllyInteract") _DATA.Save.ActiveTeam.Players[0].ActionEvents:Add(talk_evt) _DATA.Save:RegisterMonster(_DATA.Save.ActiveTeam.Players[0].BaseForm.Species) _DATA.Save.ActiveTeam:SetRank(1) if not GAME:InRogueMode() then _DATA.Save.ActiveTeam.Bank = 1000 end SV.General.Starter = _DATA.Save.ActiveTeam.Players[0].BaseForm else PrintInfo("\n<!> ExampleSvc: Preparing debug save file") _DATA.Save.ActiveTeam:SetRank(1) _DATA.Save.ActiveTeam.Name = "Debug" _DATA.Save.ActiveTeam.Money = 1000 _DATA.Save.ActiveTeam.Bank = 1000000 local mon_id = RogueEssence.Dungeon.MonsterID(1, 0, 0, Gender.Male) _DATA.Save.ActiveTeam.Players:Add(_DATA.Save.ActiveTeam:CreatePlayer(_DATA.Save.Rand, mon_id, 50, -1, 0)) mon_id = RogueEssence.Dungeon.MonsterID(4, 0, 0, Gender.Male) _DATA.Save.ActiveTeam.Players:Add(_DATA.Save.ActiveTeam:CreatePlayer(_DATA.Save.Rand, mon_id, 50, -1, 0)) mon_id = RogueEssence.Dungeon.MonsterID(7, 0, 0, Gender.Male) _DATA.Save.ActiveTeam.Players:Add(_DATA.Save.ActiveTeam:CreatePlayer(_DATA.Save.Rand, mon_id, 50, -1, 0)) local talk_evt = RogueEssence.Dungeon.BattleScriptEvent("AllyInteract") _DATA.Save.ActiveTeam.Players[0].ActionEvents:Add(talk_evt) talk_evt = RogueEssence.Dungeon.BattleScriptEvent("AllyInteract") _DATA.Save.ActiveTeam.Players[1].ActionEvents:Add(talk_evt) talk_evt = RogueEssence.Dungeon.BattleScriptEvent("AllyInteract") _DATA.Save.ActiveTeam.Players[2].ActionEvents:Add(talk_evt) _DATA.Save.ActiveTeam.Leader.IsFounder = true _DATA.Save:UpdateTeamProfile(true) for ii = 1, _DATA.DataIndices[RogueEssence.Data.DataManager.DataType.Zone].Count, 1 do GAME:UnlockDungeon(ii-1) end --for ii = 900, 2370, 1 do -- GAME:GivePlayerStorageItem(ii) -- SV.unlocked_trades[ii] = true --end SV.base_camp.ExpositionComplete = true SV.base_camp.IntroComplete = true SV.test_grounds.DemoComplete = true SV.General.Starter = _DATA.Save.ActiveTeam.Players[0].BaseForm end end --[[--------------------------------------------------------------- DebugTools:OnUpgrade() When a save file in an old version is loaded this is called! ---------------------------------------------------------------]] function DebugTools:OnUpgrade() assert(self, 'DebugTools:OnUpgrade() : self is null!') PrintInfo("=>> Loading version") _DATA.Save.NextDest = _DATA.StartMap if SV.test_grounds.DemoComplete == nil then SV.test_grounds = { SpokeToPooch = false, AcceptedPooch = false, Missions = { }, CurrentOutlaws = { }, FinishedMissions = { }, Starter = { Species=25, Form=0, Skin=0, Gender=2 }, Partner = { Species=133, Form=0, Skin=0, Gender=1 }, DemoComplete = false, } end -- end if SV.unlocked_trades ~= nil then else SV.unlocked_trades = {} end if SV.General.Starter == nil then SV.General.Starter = MonsterID(1, 0, 0, Gender.Male) end PrintInfo("=>> Loaded version") end ---Summary -- Subscribe to all channels this service wants callbacks from function DebugTools:Subscribe(med) med:Subscribe("DebugTools", EngineServiceEvents.Init, function() self.OnInit(self) end ) med:Subscribe("DebugTools", EngineServiceEvents.Deinit, function() self.OnDeinit(self) end ) med:Subscribe("DebugTools", EngineServiceEvents.NewGame, function() self.OnNewGame(self) end ) med:Subscribe("DebugTools", EngineServiceEvents.UpgradeSave, function() self.OnUpgrade(self) end ) -- med:Subscribe("DebugTools", EngineServiceEvents.GraphicsUnload, function() self.OnGraphicsUnload(self) end ) -- med:Subscribe("DebugTools", EngineServiceEvents.Restart, function() self.OnRestart(self) end ) end ---Summary -- un-subscribe to all channels this service subscribed to function DebugTools:UnSubscribe(med) end ---Summary -- The update method is run as a coroutine for each services. function DebugTools:Update(gtime) -- while(true) -- coroutine.yield() -- end end --Add our service SCRIPT:AddService("DebugTools", DebugTools:new()) return DebugTools
if json4lua == nil then json4lua = {} end if json4lua.internal == nil then json4lua.internal = {} end if json4lua.config == nil then json4lua.config = {} end -- [[ Default Configuration ]] -- json4lua.config.ignore_unsupported_datatypes = true; json4lua.config.ignore_nonstring_keys = true; json4lua.config.ignore_nontable_inputs = false; -- [[ Internal API: Encode ]] -- json4lua.internal.escape_sequence = { [ "\\" ] = "\\\\", [ "\"" ] = "\\\"", [ "\b" ] = "\\b", [ "\f" ] = "\\f", [ "\n" ] = "\\n", [ "\r" ] = "\\r", [ "\t" ] = "\\t" } json4lua.internal.escape = function(str) local res = str:gsub("[\\\"\b\f\n\r\t]", json4lua.internal.escape_sequence) return res end json4lua.internal.encoder = { ["nil"] = function(val, out) out.write("null") end, ["table"] = function(tab, out, dejavu) if dejavu[tab] then error("Circular reference found") end dejavu[tab] = 0 local i = 0 for _ in pairs(tab) do i = i + 1 if not tab[i] then json4lua.internal.write_object(tab, out, dejavu) return end end json4lua.internal.write_array(tab, out, dejavu) end, ["string"] = function(str, out) table.insert(out, "\"" .. json4lua.internal.escape(str) .. "\"") end, ["number"] = function(num, out) if num ~= num or num <= -math.huge or num >= math.huge then error("NaN or Inf found") end table.insert(out, string.format("%.14g", num)) end, ["boolean"] = function(b, out) table.insert(out, "\"" .. tostring(b) .. "\"") end, } json4lua.internal.write_array = function(arr, out, dejavu) table.insert(out, "[") local first = true for k=1, #arr do local v = arr[k]; encoder = json4lua.internal.encoder[type(v)] if not encoder then if json4lua.config.ignore_unsupported_datatypes == false then error("Unsupported Datatype: " .. type(v)) end goto next end if first == false then table.insert(out, ",") else first = false; end encoder(v, out, dejavu) ::next:: end table.insert(out, "]") end json4lua.internal.write_object = function(obj, out, dejavu) table.insert(out, "{") local first = true for k, v in pairs(obj) do if type(k) ~= "string" then if json4lua.config.ignore_nonstring_keys == false then error("Non-string key found: type = " .. type(v)) end goto next end local encoder = json4lua.internal.encoder[type(v)] if not encoder then if json4lua.config.ignore_unsupported_datatypes == false then error("Unsupported Datatype: " .. type(v)) end goto next end if first == false then table.insert(out, ",") else first = false; end table.insert(out, "\"") table.insert(out, json4lua.internal.escape(k)) table.insert(out, "\":") encoder(v, out, dejavu) ::next:: end table.insert(out, "}") end -- [[ Internal API: Decode ]] -- json4lua.internal.ignored_token = { [" "] = 0, ["\n"] = 0, ["\t"] = 0, ["\r"] = 0, ["\f"] = 0, } json4lua.internal.read_array = function(reader) end json4lua.internal.read_object = function(reader) end -- [[ Public API ]] -- json4lua.encode = function(obj) if type(obj) ~= "table" then if json4lua.config.ignore_nontable_inputs == false then error(string.format("json4lua.encode expected type 'table', found '%s'", type(obj))) end end local out = {""} json4lua.internal.encoder["table"](obj, out, {}) return table.concat(out) end json4lua.decode = function(json) if type(json) ~= "string" then error(string.format("json4lua.decode expected type 'string', found '%s'", type(json))) end local reader = {} reader.pos = 1 reader.next = function() local c = string.sub(json, reader.pos, reader.pos) reader.pos = reader.pos + 1 return c end reader.error = function(msg) error(msg .. " at position" .. reader.pos) end local first; repeat first = reader.next() until not json4lua.internal.ignored_token[first] if first == "{" then return json4lua.internal.read_object(reader) elseif first == "[" then return json4lua.internal.read_array(reader) else reader.error("Unexpected token " + first) end end friend1 = {} friend1.name = "Sam" friend1.age = 13 friend2 = {} friend2.name = "Ben" friend2.age = 12 person = {} person.name = "Tom" person.age = 12 person.friends = {friend1, friend2} print(json4lua.decode('{}'))
-- ======== -- DEFAULTS -- ======== -- Created by datwaft <github.com/datwaft> -- ======== -- Preamble -- ======== local M = {} local fusion = require("bubbly.utils.table").fusion -- ======= -- Palette -- ======= M.palette = { background = "Black", foreground = "White", black = "Black", red = "Red", green = "Green", yellow = "Yellow", blue = "Blue", purple = "Magenta", cyan = "Cyan", white = "White", lightgrey = "LightGrey", darkgrey = "Grey", } -- ========== -- Characters -- ========== M.characters = { left = "", right = "", close = "x", bubble_separator = " ", } -- ======= -- Symbols -- ======= M.symbols = { default = "PANIC!", path = { readonly = "RO", unmodifiable = "", modified = "+", }, signify = { added = "+%s", modified = "~%s", removed = "-%s", }, gitsigns = { added = "+%s", modified = "~%s", removed = "-%s", }, coc = { error = "E%s", warning = "W%s", }, builtinlsp = { diagnostic_count = { error = "E%s", warning = "W%s", }, }, branch = " %s", total_buffer_number = "﬘ %d", lsp_status = { diagnostics = { error = "E%d", warning = "W%d", hint = "H%d", info = "I%d", }, }, } -- ==== -- Tags -- ==== M.tags = { default = "HELP ME PLEASE!", mode = { normal = "NORMAL", insert = "INSERT", visual = "VISUAL", visualblock = "VISUAL-B", command = "COMMAND", terminal = "TERMINAL", replace = "REPLACE", default = "UNKOWN", }, paste = "PASTE", filetype = { noft = "no ft", }, } -- ====== -- Colors -- ====== M.colors = { default = "red", mode = { normal = "green", insert = "blue", visual = "red", visualblock = "red", command = "red", terminal = "blue", replace = "yellow", default = "white", }, path = { readonly = { background = "lightgrey", foreground = "foreground" }, unmodifiable = { background = "darkgrey", foreground = "foreground" }, path = "white", modified = { background = "lightgrey", foreground = "foreground" }, }, branch = "purple", signify = { added = "green", modified = "blue", removed = "red", }, gitsigns = { added = "green", modified = "blue", removed = "red", }, paste = "red", coc = { error = "red", warning = "yellow", status = { background = "lightgrey", foreground = "foreground" }, }, builtinlsp = { diagnostic_count = { error = "red", warning = "yellow", }, current_function = "purple", }, filetype = "blue", progress = { rowandcol = { background = "lightgrey", foreground = "foreground" }, percentage = { background = "darkgrey", foreground = "foreground" }, }, tabline = { active = "blue", inactive = "white", close = "darkgrey", }, total_buffer_number = "cyan", lsp_status = { messages = "white", diagnostics = { error = "red", warning = "yellow", hint = "white", info = "blue", }, }, } M.inactive_color = { background = "lightgrey", foreground = "foreground" } -- ====== -- Styles -- ====== M.styles = { default = "bold", mode = "bold", path = { readonly = "bold", unmodifiable = "", path = "", modified = "", }, branch = "bold", signify = { added = "bold", modified = "bold", removed = "bold", }, gitsigns = { added = "bold", modified = "bold", removed = "bold", }, paste = "bold", coc = { error = "bold", warning = "bold", status = "", }, builtinlsp = { diagnostic_count = { error = "", warning = "", }, current_function = "", }, filetype = "", progress = { rowandcol = "", percentage = "", }, tabline = { active = "bold", inactive = "", }, total_buffer_number = "", lsp_status = { messages = "", diagnostics = { error = "", warning = "", hint = "", info = "", }, }, } M.inactive_style = "" -- ===== -- Width -- ===== M.width = { default = 0, progress = { rowandcol = 8, }, } -- ====== -- Timing -- ====== M.timing = { default = 0, lsp_status = { messages = { update_delay = 500, -- ms }, }, } -- ====== -- Filter -- ====== M.filter = { default = {}, } -- ========== -- Statusline -- ========== M.statusline = { "mode", "truncate", "path", "divisor", "filetype", "progress", } -- ============= -- Option fusion -- ============= M.fusion = function() -- Palette vim.g.bubbly_palette = fusion(M.palette, vim.g.bubbly_palette) -- Characters vim.g.bubbly_characters = fusion(M.characters, vim.g.bubbly_characters) -- Symbols vim.g.bubbly_symbols = fusion(M.symbols, vim.g.bubbly_symbols) -- Tags vim.g.bubbly_tags = fusion(M.tags, vim.g.bubbly_tags) -- Width vim.g.bubbly_width = fusion(M.width, vim.g.bubbly_width) -- Timing vim.g.bubbly_timing = fusion(M.timing, vim.g.bubbly_timing) -- Filter vim.g.bubbly_filter = fusion(M.filter, vim.g.bubbly_filter) -- Colors vim.g.bubbly_colors = fusion(M.colors, vim.g.bubbly_colors) if not vim.g.bubbly_inactive_color then vim.g.bubbly_inactive_color = M.inactive_color end -- Styles vim.g.bubbly_styles = fusion(M.styles, vim.g.bubbly_styles) if not vim.g.bubbly_inactive_style then vim.g.bubbly_inactive_style = M.inactive_style end -- Tabline vim.g.bubbly_tabline = vim.g.bubbly_tabline or 1 -- Statusline if not vim.g.bubbly_statusline or type(vim.g.bubbly_statusline) ~= "table" then vim.g.bubbly_statusline = M.statusline end for _, e in ipairs(vim.g.bubbly_statusline) do if not require("bubbly.utils.checkmodule")(e) then require("bubbly.utils.io").warning( [[Couldn't find the module named ']] .. e:lower() .. [[', it will be ignored.]] ) end end end -- ============ -- Finalization -- ============ return M
local class = require 'middleclass' local lume = require 'lume' local Timer = require 'Timer' -- エイリアス local lg = love.graphics -- 基底クラス local Entity = require 'Entity' -- インゲーム クラス local InGame = class('InGame', Entity) InGame:include(require 'stateful') -- クラス local EntityManager = require 'EntityManager' local Tetrimino = require 'Tetrimino' local Stage = require 'Stage' local function randomSelect(array) return array[love.math.random(#array)] end local function shuffle(t) local rtn = {} for i = 1, #t do local r = love.math.random(i) if r ~= i then rtn[i] = rtn[r] end rtn[r] = t[i] end return rtn end local baseSpeed = 1 local baseScale = 0.25 local nextScale = 0.15 local scoreTable = { 40, 100, 300, 1200, } -- 初期化 function InGame:initialize(t) Entity.initialize(self) self.app = t.app or {} self.width = self.app.width or 800 self.height = self.app.height or 600 self.spriteSheetTiles = self.app.spriteSheetTiles self.spriteSheetParticles = self.app.spriteSheetParticles self.font64 = self.app.font64 self.font32 = self.app.font32 self.font16 = self.app.font16 -- オーディオ self.audio = self.app.audio or {} -- タイマー self.timer = Timer() -- エンティティマネージャ self.manager = EntityManager() -- 初期状態 self.speed = baseSpeed self.counter = self.speed self.level = 0 self.score = 0 self.lines = 0 self.next = {} self.stock = {} self.busy = true -- スタート self:gotoState 'Start' end -- 破棄 function InGame:added(parent) end -- 破棄 function InGame:destroy() self.timer:destroy() self.manager:destroy() self.manager = nil end -- 更新 function InGame:update(dt) end -- 描画 function InGame:draw() end -- キー入力 function InGame:keypressed(key, scancode, isrepeat) end -- ステージの描画 function InGame:setupStage() -- ステージ self.backstage = self.manager:add( Stage { spriteSheet = self.spriteSheetTiles, x = 0, y = 0, scale = baseScale, colorArray = Tetrimino.makeArray(10, 20, 'black'), alpha = 0.25 } ) self.stage = self.manager:add( Stage { spriteSheet = self.spriteSheetTiles, x = 0, y = 0, scale = baseScale, colorArray = Tetrimino.makeArray(10, 20) } ) -- ステージの位置 local w, h = self.stage:getDimensions() self.stage.x = (self.width - w) * 0.5 self.stage.y = (self.height - h) * 0.5 self.backstage.x = self.stage.x self.backstage.y = self.stage.y end -- ステージの描画 function InGame:drawStage() -- ステージ if self.stage == nil then return end -- ステージのライン lg.setColor(0, 0, 0, 0.75) lg.rectangle('fill', self.stage.x, self.stage.y, self.stage:getDimensions()) lg.setColor(1, 1, 1) lg.rectangle('line', self.stage.x, self.stage.y, self.stage:getDimensions()) -- スコア類 lg.printf( 'LEVEL\n' .. self.level .. '\n\nSCORE\n' .. self.score .. '\n\nLINES\n' .. self.lines, self.font16, 0, self.stage.y, self.stage.x - 16, 'right' ) -- 次のテトリミノ local w, h = self.stage:getDimensions() lg.printf('NEXT', self.font16, self.stage.x + w + 16, self.stage.y, self.width, 'left') end -- 現在のテトリミノの更新 function InGame:updateTetrimino(dt) local hit = false -- タイマーのカウントダウン self.counter = self.counter - (dt or self.speed) if self.counter < 0 then -- タイマーのリセット self.counter = self.counter + self.speed -- 下に移動 if self:moveTetrimino(0, 1) then -- 接触したのでステージに積む self:mergeTetrimino() hit = true end end return hit end -- テトリミノのマージ function InGame:mergeTetrimino() self.stage:merge(self.currentTetrimino) local lines = self.stage:score() if lines > 0 then self.lines = self.lines + lines self.score = self.score + scoreTable[lines] * (self.level + 1) self.level = math.floor(self.lines / 10) self.audio:playSound('score') else self.audio:playSound('fall') end self.manager:remove(self.currentTetrimino) self:nextTetrimino() end -- テトリミノの移動 function InGame:moveTetrimino(x, y) local hit = false local t = self.currentTetrimino local tx, ty = t.x, t.y t:move(x, y) if self.stage:hit(t) then t.x, t.y = tx, ty hit = true end return hit end -- テトリミノの移動 function InGame:fallTetrimino() while not self:updateTetrimino() do end self:resetCounter() end -- 次の配列名を返す function InGame:nextArrayName() if #self.stock == 0 then self.stock = shuffle(lume.clone(Tetrimino.arrayNames)) end return table.remove(self.stock) end -- テトリミノの生成 function InGame:generateNextTetriminos(n) local w, h = self.stage:getDimensions() local count = (n or 6) - #self.next for i = 1, count do table.insert( self.next, self.manager:add( Tetrimino { spriteSheet = self.spriteSheetTiles, x = self.stage.x + w + 16, y = 0, scale = nextScale, array = self:nextArrayName() } ) ) end local fh = self.font16:getHeight() * 2 for i, t in ipairs(self.next) do local x, y = t:toPixelDimensions(0, 4) t.y = self.stage.y + (i - 1) * y + fh end end -- テトリミノの生成 function InGame:nextTetrimino() if #self.next == 0 then self:generateNextTetriminos() end local x, y = self.stage:toPixelDimensions(3, 0) x = x + self.stage.x y = y + self.stage.y self.currentTetrimino = lume.first(self.next) self.currentTetrimino.x, self.currentTetrimino.y = x, y self.currentTetrimino.scale = baseScale self.next = lume.slice(self.next, 2) self:generateNextTetriminos() end local fitcheck = { { 0, 1 }, { 1, 1 }, { -1, 1 }, --{ 0, -1 }, --{ 1, -1 }, --{ -1, -1 }, } -- テトリミノの生成 function InGame:fitTetrimino() local valid = true local t = self.currentTetrimino local hitresult = self.stage:hit(t) while hitresult do if lume.find(hitresult, 'left') then t:move(1) elseif lume.find(hitresult, 'right') then t:move(-1) elseif lume.find(hitresult, 'bottom') then t:move(0, -1) elseif lume.find(hitresult, 'hit') then local ok = false for _, pos in ipairs(fitcheck) do if not self:moveTetrimino(unpack(pos)) then ok = true break end end if not ok then valid = false break end else break end hitresult = self.stage:hit(t) end return valid end function InGame:resetSpeed(level) level = level or self.level self.speed = baseSpeed / (level + 1) self:resetCounter() end function InGame:resetCounter(counter) self.counter = counter or self.speed end -- スタート ステート local Start = InGame:addState 'Start' -- ステート開始 function Start:enteredState() -- 初期化 self.timer:destroy() self.manager:clear() self:setupStage() -- リセット self.level = 0 self.score = 0 self.lines = 0 self.next = {} self.stock = {} self.busy = true self:resetSpeed() self.fade = { .42, .75, .89, 1 } -- BGM self.audio:playMusic('ingame') -- 開始演出 self.timer:tween( 1, self, { fade = { [4] = 0 } }, 'in-out-cubic', function () -- 操作可能 self:gotoState 'Play' end ) end -- ステート終了 function Start:exitedState() self.timer:destroy() end -- 更新 function Start:update(dt) self.timer:update(dt) self.manager:update(dt) end -- 描画 function Start:draw() -- クリア love.graphics.clear(.42, .75, .89) -- ステージ描画 self:drawStage() -- エンティティの描画 self.manager:draw() -- タイトル --lg.setColor(1, 1, 1) --lg.printf('CHOOSE LEVEL', self.font64, 0, self.height * 0.3 - self.font64:getHeight() * 0.5, self.width, 'center') -- フェード if self.fade[4] > 0 then lg.setColor(unpack(self.fade)) lg.rectangle('fill', 0, 0, self.width, self.height) end end -- キー入力 function Start:keypressed(key, scancode, isrepeat) if not self.busy then self:gotoState 'Play' end end -- プレイ ステート local Play = InGame:addState 'Play' -- ステート開始 function Play:enteredState() -- 新規テトリミノ self:nextTetrimino() end -- ステート終了 function Play:exitedState() self.audio:stopMusic() end -- 更新 function Play:update(dt) self.manager:update(dt) if self:updateTetrimino(dt) and self.stage:hit(self.currentTetrimino) then self:gotoState 'Gameover' end end -- 描画 function Play:draw() -- クリア love.graphics.clear(.42, .75, .89) -- ステージ描画 self:drawStage() -- エンティティの描画 self.manager:draw() end -- キー入力 function Play:keypressed(key, scancode, isrepeat) if key == 'space' or key == 'a' then self.currentTetrimino:rotate(-1) if not self:fitTetrimino() then self.currentTetrimino:rotate() else self.audio:playSound('move') end elseif key == 'd' then self.audio:playSound('move') self.currentTetrimino:rotate() if not self:fitTetrimino() then self.currentTetrimino:rotate(-1) else self.audio:playSound('move') end elseif key == 'left' then if not self:moveTetrimino(-1) then self.audio:playSound('move') end elseif key == 'right' then if not self:moveTetrimino(1) then self.audio:playSound('move') end elseif key == 'down' then self.audio:playSound('move') if not self:moveTetrimino(0, 1) then self.audio:playSound('move') self:resetCounter() end elseif key == 'up' then self:fallTetrimino() if self.stage:hit(self.currentTetrimino) then self:gotoState 'Gameover' end elseif not self.app.debugMode then -- 以下、デバッグモードのみ elseif key == 'z' then self.lines = self.lines + 10 self.level = self.level + 1 self:resetSpeed() elseif key == 'x' then self.lines = 0 self.level = 0 self:resetSpeed() end end -- ゲームオーバー ステート local Gameover = InGame:addState 'Gameover' -- ステート開始 function Gameover:enteredState() -- 初期化 self.timer:destroy() self.fade = { .42, .75, .89, 0 } self.alpha = 0 self.busy = true self.offset = self.height self.visiblePressAnyKey = true -- SE self.audio:playSound('gameover') -- 開始演出 self.timer:tween( 1, self, { alpha = .5, offset = 0 }, 'in-out-cubic', function () -- キー入力表示の点滅 self.timer:every( 0.5, function () self.visiblePressAnyKey = not self.visiblePressAnyKey end ) -- 操作可能 self.busy = false end ) end -- ステート終了 function Gameover:exitedState() self.timer:destroy() self.audio:stopSound('gameover') self.audio:seekMusic('ingame') end -- 更新 function Gameover:update(dt) self.timer:update(dt) self.manager:update(dt) end -- 描画 function Gameover:draw() -- クリア lg.clear(.42, .75, .89) -- ステージ描画 self:drawStage() -- エンティティの描画 self.manager:draw() -- フェード if self.alpha > 0 then lg.setColor(.42, .75, .89, self.alpha) lg.rectangle('fill', 0, 0, self.width, self.height) end -- タイトル lg.setColor(1, 1, 1) lg.printf('GAMEOVER', self.font64, 0, self.height * 0.3 - self.font64:getHeight() * 0.5 - self.offset, self.width, 'center') -- キー入力表示 if not self.busy and self.visiblePressAnyKey then lg.printf('PRESS ANY KEY TO CONTINUE', self.font32, 0, self.height * 0.7 - self.font32:getHeight() * 0.5, self.width, 'center') end -- フェード if self.fade[4] > 0 then lg.setColor(self.fade) lg.rectangle('fill', 0, 0, self.width, self.height) end end -- キー入力 function Gameover:keypressed(key, scancode, isrepeat) if not self.busy then self.audio:playSound('ok') self.busy = true self.timer:tween( 1, self, { fade = { [4] = 1 }, offset = 0 }, 'in-out-cubic', function () self:gotoState 'Start' end ) end end return InGame
--[[ audioJack.lua Copyright (C) 2016 Kano Computing Ltd. License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2 This is the dialogue you can have with Mr Info in Overworld on the Beach. ]]-- return { type = "repeat", dialogues = { --- 1) Welcome dialogue ------------------------------------------------------------- { type = "copy", copy = { "audioJack" }, arguments = {}, options = {{ portetherMayorName = 2 }, { cSoundWaveTitle = 3 } }, }, --- 2) Mayor ------------------------------------------------------------- { type = "copy", copy = { "audioJack2" }, arguments = {}, options = {}, }, --- 3) Codex ------------------------------------------------------------- { type = "copy", copy = { "audioJack3" }, arguments = {}, options = {}, }, --- the end --- } }
hkArmyScreenPlay = ScreenPlay:new { numberOfActs = 1, screenplayName = "hkArmyScreenPlay", } registerScreenPlay("hkArmyScreenPlay", true) function hkArmyScreenPlay:start() if (isZoneEnabled("mustafar")) then self:spawnMobiles() end end function hkArmyScreenPlay:spawnMobiles() --[[ spawnMobile("mustafar", "hk47", 3600, 3455, 74.8, 1004.9, -166, 0) spawnMobile("mustafar", "hk77", 3600, 3410, 74.8, 820, 90, 0) spawnMobile("mustafar", "hk77", 3600, 3410, 74.8, 825, 90, 0) spawnMobile("mustafar", "hk77", 3600, 3410, 74.8, 830, 90, 0) spawnMobile("mustafar", "hk77", 3600, 3410, 74.8, 835, 90, 0) spawnMobile("mustafar", "hk77", 3600, 3410, 74.8, 840, 90, 0) spawnMobile("mustafar", "hk77", 3600, 3415, 74.8, 820, 90, 0) spawnMobile("mustafar", "hk77", 3600, 3415, 74.8, 825, 90, 0) spawnMobile("mustafar", "hk77", 3600, 3415, 74.8, 830, 90, 0) spawnMobile("mustafar", "hk77", 3600, 3415, 74.8, 835, 90, 0) spawnMobile("mustafar", "hk77", 3600, 3415, 74.8, 840, 90, 0) spawnMobile("mustafar", "magnaguard", 3600, 3501.1, 74.8, 693.6, 5, 0) spawnMobile("mustafar", "magnaguard", 3600, 3485, 74.8, 716, 5, 0) spawnMobile("mustafar", "magnaguard", 3600, 3510, 74.8, 730, 166, 0) spawnMobile("mustafar", "magnaguard", 3600, 3520, 74.8, 696, 18, 0) ]]-- end
object_tangible_furniture_decorative_carved_bowl = object_tangible_furniture_decorative_shared_carved_bowl:new { } ObjectTemplates:addTemplate(object_tangible_furniture_decorative_carved_bowl, "object/tangible/furniture/decorative/carved_bowl.iff")
return {{[1] = [[2.0]],[2] = [[2.0.1]],[3] = [[2.0.2]],[4] = [[2.0.3]],[5] = [[2.0.4]],[6] = [[2.0.5]], [7] = [[2.0.6]], [8] = [[2.0.7]], [9] = [[2.0.8]], [10] = [[2.0.9]], [11] = [[2.0.10]], [12] = [[2.0.11]], [13] = [[2.0.12]], [14] = [[2.0.13]], [15] = [[2.0.14]], [16] = [[2.0.15]], [17] = [[2.0.16]]}, }
return {--[[ #PVF_File ]] ["[player number]"]={2,8}, ["[pvp start area]"]={0,0,0,0,0,0,0,0,0,0,0,0}, ["[dungeon]"]={3,}, ["[type]"]="[normal]", ["[greed]"]="DD BB", ["[tile]"]={"Tile/ForestOver.til","Tile/ForestOver.til","Tile/ForestOver.til","Tile/ForestOverUnder.til","Tile/ForestUnder.til","Tile/ForestUnder.til",}, ["[far sight scroll]"]=56, ["[middle sight scroll]"]=90, ["[near sight scroll]"]=110, ["[background animation]"]={ ["[ani info]"]={ ["[filename]"]="Animation/far0.ani", ["[layer]"]="[distantback]", ["[order]"]="[below]",}, ["[ani info2]"]={ ["[filename]"]="Animation/mid1.ani", ["[layer]"]="[middleback]", ["[order]"]="[below]",},}, ["[pathgate pos]"]={12,252,1332,260,280,142,672,348}, ["[sound]"]={"M_MIRKWOOD","AMB_RAIN_01",}, ["[animation]"]={"Animation/Flower1.ani","[normal]",960,322,0,"Animation/Flower0.ani","[normal]",487,296,0,"Animation/Flower0.ani","[normal]",914,257,0,"Animation/Grass2.ani","[bottom]",413,241,0,"Animation/Stone0.ani","[bottom]",567,281,0,"Animation/Grass2.ani","[bottom]",1033,307,0,"Animation/Stone1.ani","[bottom]",844,235,0,}, ["[passive object]"]={ 3,200,260,400, 4,200,260,0, 227,629,152,0, 226,1030,178,0, 221,541,248,0, 221,967,274,0, 221,534,294,0, 221,1007,327,0, }, ["[monster]"]={ -- 2,0,4,646,220,0,1,1,"[fixed]","[normal]", -- 3,0,5,483,222,0,1,1,"[fixed]","[normal]", -- 1,0,4,824,223,0,1,1,"[fixed]","[normal]", -- 4,0,5,407,302,0,1,1,"[fixed]","[normal]", -- 2,0,4,622,313,0,1,1,"[fixed]","[normal]", -- 1,0,4,785,322,0,1,1,"[fixed]","[normal]", -- 3,0,4,859,301,0,1,1,"[fixed]","[normal]", -- 3,0,4,668,326,0,1,1,"[fixed]","[normal]", -- 2,0,4,622,313,0,1,1,"[fixed]","[normal]", -- 2,0,4,528,325,0,1,1,"[fixed]","[normal]", -- 4,0,5,418,232,0,1,1,"[fixed]","[normal]", -- 3,0,5,465,314,0,1,1,"[fixed]","[normal]", -- 2,0,4,605,248,0,1,1,"[fixed]","[normal]", -- 3,0,4,895,320,0,1,1,"[fixed]","[normal]", -- 2,0,4,349,311,0,1,1,"[fixed]","[normal]", -- 2,0,4,327,245,0,1,1,"[fixed]","[normal]", -- 2,0,4,385,193,0,1,1,"[fixed]","[normal]", -- 2,0,4,266,326,0,1,1,"[fixed]","[normal]", -- 11,0,4,688,226,0,1,1,"[fixed]","[normal]", -- 11,0,4,556,343,0,1,1,"[fixed]","[normal]", }, ["[monster specific AI]"]={"[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]","[normal]",}, ["[special passive object]"]={226,479,150,0,1,"[item]",0,2,-1,-1,-1,227,849,166,0,1,"[item]",0,2,-1,-1,-1,221,778,255,0,1,"[monster]",1,3,3,10,-1,221,847,256,0,1,"[monster]",1,3,3,10,-1,221,699,291,0,1,"[item]",3,-1,1,-1,-1,221,760,301,0,1,"[monster]",2,3,3,10,-1,}, ["[event monster position]"]={425,215,0,470,295,0,602,240,0,714,189,0,}, ["[map name]"]="PVP无名", }
local class = require("pl.class") ---@class Party local M = class() local tablex = require("pl.tablex") function M:_init(leader) self.invited = {} self.leader = leader self.members = {} self.members[leader] = true end function M:delete(member) self.members[member] = nil member.party = nil end function M:add(memeber) self.members[memeber] = true memeber.party = self self.invited[memeber] = nil end function M:disband() for member, _ in pairs(self.members) do self.members[member] = nil end end function M:invite(target) self.invited[target] = true end function M:isInvited(target) return self.invited[target] end function M:removeInvite(target) self.invited[target] = nil end function M:getBroadcastTargets() return tablex.keys(self.members) end return M
require('spec/setup/busted')() local Color = require('stdlib/utils/color') describe('Color', function () local say = require('say') local WHITE = {r = 1, g = 1, b = 1, a = 1} local WHITE_HALF = {r = 1, g = 1, b = 1, a = 0.5} local BLACK = {r = 0, g = 0, b = 0, a = 1} local BLACK_HALF = {r = 0, g = 0, b = 0, a = 0.5} local spies = { new = spy.on(Color, 'new'), white = spy.on(Color, 'white'), from_string = spy.on(Color, 'from_string'), from_hex = spy.on(Color, 'from_hex'), from_array = spy.on(Color, 'from_array'), from_table = spy.on(Color, 'from_table'), from_params = spy.on(Color, 'from_params'), copy = spy.on(Color, 'copy') } local function clear_spies(tab) for _, v in pairs(tab) do v:clear() end end local function is_near(_, arguments) if #arguments~=3 then return false end local epsilon = arguments[1] local given = arguments[2] local expected = arguments[3] for k,v in pairs(expected) do if not given[k] then return false end if math.abs(given[k] - v) > epsilon/2 then return false end end return true end say:set("assertion.is_near.positive", "Expected objects to be similar with epsilon %s.\nPassed in:\n%s\nCompared to:\n%s") say:set("assertion.is_near.negative", "Expected objects to not be similar with epsilon %s.\nPassed in:\n%s\nCompared to:\n%s") assert:register("assertion", "is_near", is_near, "assertion.is_near.positive", "assertion.is_near.negative") describe('Constructors', function() it('should return a white color if nothing is passed', function() local c = Color.new() assert.spy(spies.white).was_called(1) assert.same(WHITE_HALF, c) end) it('should create from Hex', function() local c = Color.new('#FFFFFF') assert.spy(spies.from_hex).was_called(1) assert.same(WHITE_HALF, c) local c2 = Color.new('#FFFFFFFF') assert.spy(spies.from_hex).was_called(2) assert.same(WHITE, c2) local c3 = Color.new('#FFFFFF', 0.5) assert.same(WHITE_HALF, c3) assert.spy(spies.from_hex).was_called(3) end) it('should create from string color name', function() local c = Color.new('black') assert.spy(spies.from_string).was_called(1) assert.same(BLACK, c) assert.same(WHITE, Color.new('white')) assert.spy(spies.from_string).was_called(2) assert.same(WHITE_HALF, Color.new('white', 0.5)) assert.spy(spies.from_string).was_called(3) end) it('should create from RGB Paramaters', function() assert.same(WHITE_HALF, Color.new(1)) assert.same(WHITE_HALF, Color.new(1,1)) assert.same(WHITE_HALF, Color.new(1, 1, 1)) assert.same(WHITE, Color.new(1,1,1,1)) assert.spy(spies.from_params).was_called(4) assert.same(BLACK_HALF, Color.new(0)) assert.same(BLACK, Color.new(0,0,0,1)) assert.spy(spies.from_params).was_called(6) end) it('should create from an array of rgb paramaters', function() assert.same(WHITE_HALF, Color.new{1,1,1}) assert.same(WHITE, Color.new{1,1,1,1}) assert.spy(spies.from_array).was_called(2) assert.same(BLACK_HALF, Color.new{0,0,0}) assert.same(BLACK, Color.new{0,0,0,1}) assert.spy(spies.from_array).was_called(4) end) it('should create from a color dictionary', function() local a = Color.new{r = 1, b = 1, g = 1, a = 1} assert.same(WHITE, a) assert.same(WHITE_HALF, Color.new{r = 1, b = 1, g = 1}) assert.spy(spies.from_table).was_called(2) assert.same(BLACK, Color.new{r = 0, b = 0, g = 0, a = 1}) assert.same(BLACK_HALF, Color.new{r = 0, b = 0, g = 0}) assert.spy(spies.from_table).was_called(4) end) it('should copy from a Color or color', function() clear_spies(spies) assert.same(WHITE_HALF, Color.new(Color.white())) assert.spy(spies.copy).was_called(1) assert.same(WHITE_HALF, Color.copy(Color.white())) assert.spy(spies.copy).was_called(2) assert.same(WHITE_HALF, Color.copy(Color:white(), 0.5)) assert.spy(spies.copy).was_called(3) assert.same(WHITE_HALF, Color()(0.5)) local array_color = {1, 1, 1, 1} assert.same(WHITE_HALF, Color.copy(array_color, 0.5)) assert.spy(spies.from_array).was_called(1) local dict_color = {r = 1, b = 1, g = 1, a = 1} assert.same(WHITE_HALF, Color.copy(dict_color, 0.5)) assert.spy(spies.from_table).was_called(1) end) end) describe('from_hex', function() it('should require hex for converting', function () assert.has_error(Color.from_hex, "missing color hex value") end) it('should require hex string for converting', function () for _,v in pairs({nil, 0, {}, {r=0.5,g=0,b=0.5}}) do assert.has_error(function() Color.from_hex(v) end) end end) it('should accept 6-length hex strings only', function () for _,v in pairs({"fff", "#fff"}) do assert.has_error(function() Color.from_hex(v) end) end end) it('should return 1 as the default alpha', function () local white = Color.from_hex("#ffffff") assert.is_equal(white.a, 0.5) end) it('should use alpha if defined', function () assert.same(0.5, Color.from_hex('#ffffff', 0.5).a) end) end) describe('concat', function() local c = Color() assert.same('The color is {r = 1, g = 1, b = 1, a = 0.5}', 'The color is ' .. c) end) end)
local entity = {} entity["level"] = [[42]] entity["spellDeck"] = {} entity["spellDeck"][1] = [[Mabufula]] entity["spellDeck"][2] = [[]] entity["spellDeck"][3] = [[Marakukaja]] entity["spellDeck"][4] = [[]] entity["spellDeck"][5] = [[]] entity["spellDeck"][6] = [[]] entity["heritage"] = {} entity["heritage"][1] = [[Ice]] entity["heritage"][2] = [[]] entity["resistance"] = {} entity["resistance"][1] = [[Normal]] entity["resistance"][2] = [[Normal]] entity["resistance"][3] = [[Normal]] entity["resistance"][4] = [[Normal]] entity["resistance"][5] = [[Repel]] entity["resistance"][6] = [[Normal]] entity["resistance"][7] = [[Normal]] entity["resistance"][8] = [[Weak]] entity["resistance"][9] = [[Normal]] entity["desc"] = [[There are two parts to the Tiamat mythos. In the first, she is a creator goddess, peacefully creating the cosmos through successive generations. In the second, she is considered the monstrous embodiment of primordial chaos.]] --a function: evolveName entity["arcana"] = [[Devil]] entity["stats"] = {} entity["stats"][1] = [[24]] entity["stats"][2] = [[35]] entity["stats"][3] = [[27]] entity["stats"][4] = [[30]] entity["stats"][5] = [[27]] entity["name"] = [[Tiamat]] entity["spellLearn"] = {} entity["spellLearn"]["Cool Breeze"] = [[48]] entity["spellLearn"]["Evil Smile"] = [[45]] entity["spellLearn"]["Bufudyne"] = [[44]] entity["spellLearn"]["Ailment Boost"] = [[47]] return entity
-- -- c_main.lua -- objectPreview = {} objectPreview_mt = { __index = objectPreview } local isMRTShaderSupported = nil local glRenderTarget = nil refOPTable = {} local scx, scy = guiGetScreenSize () local fov = ({getCameraMatrix()})[8] function objectPreview:create(element,rotX,rotY,rotZ,projPosX,projPosY,projSizeX,projSizeY,isRelative,postGui,isSRT) local posX,posY,posZ = getCameraMatrix() if isRelative == false then projPosX, projPosY, projSizeX, projSizeY = projPosX / scx, projPosY / scy, projSizeX / scx, projSizeY / scy end local elementType = getElementType(element) outputDebugString('objPrev: Identified element as: '..tostring(elementType)) if elementType =="ped" or elementType =="player" then elementType = "ped" end local new = { element = element, elementType = elementType, alpha = 255, elementRadius = 0, elementPosition = {posX, posY, posZ}, elementRotation = {rotX, rotY, rotZ}, elementRotationOffsets = {0, 0, 0}, elementPositionOffsets = {0, 0, 0}, zDistanceSpread = 0, projection = {projPosX, projPosY, projSizeX, projSizeY, postGui, isRelative}, shader = nil, isSecondRT = isSRT, isUpdate = false, renID = findEmptyEntry(refOPTable) } setElementAlpha(new.element, 254) setElementStreamable(new.element, false) setElementFrozen(new.element, true) setElementCollisionsEnabled (new.element, false) if elementType =="vehicle" then new.zDistanceSpread = -3.9 for i=0,5 do setVehicleDoorState ( new.element, i, 0 ) end elseif elementType =="ped" then new.zDistanceSpread = -1.0 else new.zDistanceSpread = 3.0 end new.elementRadius = math.max(returnMaxValue({getElementBoundingBox(new.element)}), 1) local tempRadius = getElementRadius(new.element) if tempRadius > new.elementRadius then new.elementRadius = tempRadius end if new.isSecondRT then if not isMRTShaderSupported then outputDebugString('objPrev: Can not create a preview. MRT in shaders not supported') return false end outputDebugString('objPrev: Creating fx_pre_'..elementType..'.fx') new.shader = dxCreateShader("fx/fx_pre_"..elementType..".fx", 0, 0, false, "all") if not glRenderTarget then glRenderTarget = dxCreateRenderTarget( scx, scy, true ) outputDebugString('objPrev : MRT objects visible - created RT') end else outputDebugString('objPrev: Creating fx_pre_'..elementType..'_noMRT.fx') new.shader = dxCreateShader("fx/fx_pre_"..elementType.."_noMRT.fx", 0, 0, false, "all") end if not new.shader then return false end if isMRTShaderSupported and glRenderTarget and new.isSecondRT then dxSetShaderValue (new.shader, "secondRT", glRenderTarget) end dxSetShaderValue(new.shader, "sFov", math.rad(fov)) dxSetShaderValue(new.shader, "sAspect", (scy / scx)) engineApplyShaderToWorldTexture (new.shader, "*", new.element) refOPTable[new.renID] = {} refOPTable[new.renID].enabled = true refOPTable[new.renID].isSecondRT = isSRT refOPTable[new.renID].instance = new new.onPreRender = function() new:update() end addEventHandler( "onClientPreRender", root, new.onPreRender, true, "low-5" ) setmetatable(new, objectPreview_mt) outputDebugString('objPrev: Created ID: '..new.renID..' for: '..tostring(elementType)) return new end function objectPreview:getID() return self.renID end function objectPreview:setAlpha(alphaValue) self.alpha = alphaValue self.isUpdate = false return setElementAlpha(self.element, self.alpha) end function objectPreview:destroy() if self.onPreRender then removeEventHandler( "onClientPreRender", root, self.onPreRender) self.onPreRender = nil end self.onPreRender = nil local renID = self.renID refOPTable[renID].enabled = false refOPTable[renID].isSecondRT = false refOPTable[renID].instance = nil if self.shader then engineRemoveShaderFromWorldTexture(self.shader, "*", self.element) destroyElement(self.shader) self.shader = nil end outputDebugString('objPrev: Destroyed ID: '..renID) self.element = nil end function objectPreview:update() -- Check if element exists if not isElement(self.element) then return false end -- Calculate position and size of the projector local projPosX, projPosY, projSizeX, projSizeY, postGui, isRelative = unpack(self.projection) projSizeX, projSizeY = projSizeX / 2, projSizeY / 2 projPosX, projPosY = projPosX + projSizeX - 0.5, -(projPosY + projSizeY - 0.5) projPosX, projPosY = 2 * projPosX, 2 * projPosY -- Calculate position and rotation of the element local cameraMatrix = getElementMatrix(getCamera()) local rotationMatrix = createElementMatrix({0,0,0}, self.elementRotation) local positionMatrix = createElementMatrix(self.elementRotationOffsets, {0,0,0}) local transformMatrix = matrixMultiply(positionMatrix, rotationMatrix) local multipliedMatrix = matrixMultiply(transformMatrix, cameraMatrix) local distTemp = self.zDistanceSpread local posTemp = self.elementPositionOffsets local posX, posY, posZ = getPositionFromMatrixOffset(cameraMatrix, {posTemp[1], 1.6 * self.elementRadius + distTemp + posTemp[2], posTemp[3]}) local rotX, rotY, rotZ = getEulerAnglesFromMatrix(multipliedMatrix) local velX, velY, velZ = getCamVelocity() local vecLen = math.sqrt(math.pow(velX, 2) + math.pow(velY, 2) + math.pow(velZ, 2)) local camCom = {cameraMatrix[2][1] * vecLen, cameraMatrix[2][2] * vecLen, cameraMatrix[2][3] * vecLen} velX, velY, velZ = (velX + camCom[1]), (velY + camCom[2]), (velZ + camCom[3]) setElementPosition(self.element, posX + velX, posY + velY, posZ + velZ) setElementRotation(self.element, rotX, rotY, rotZ, "ZXY") -- Set shader values if self.shader then dxSetShaderValue(self.shader, "sCameraPosition", cameraMatrix[4]) dxSetShaderValue(self.shader, "sCameraForward", cameraMatrix[2]) dxSetShaderValue(self.shader, "sCameraUp", cameraMatrix[3]) dxSetShaderValue(self.shader, "sElementOffset", 0, -distTemp, 0) dxSetShaderValue(self.shader, "sWorldOffset", -velX, -velY, -velZ) dxSetShaderValue(self.shader, "sMoveObject2D", projPosX, projPosY) dxSetShaderValue(self.shader, "sScaleObject2D", 2 * math.min(projSizeX, projSizeY), 2 * math.min(projSizeX, projSizeY)) dxSetShaderValue(self.shader, "sProjZMult", 2) self.isUpdate = true end end local getLastTick = getTickCount() local lastCamVelocity = {0, 0, 0} local currentCamPos = {0, 0, 0} local lastCamPos = {0, 0, 0} function getCamVelocity() if getTickCount() - getLastTick < 100 then return lastCamVelocity[1], lastCamVelocity[2], lastCamVelocity[3] end local currentCamPos = {getElementPosition(getCamera())} lastCamVelocity = {currentCamPos[1] - lastCamPos[1], currentCamPos[2] - lastCamPos[2], currentCamPos[3] - lastCamPos[3]} lastCamPos = {currentCamPos[1], currentCamPos[2], currentCamPos[3]} return lastCamVelocity[1], lastCamVelocity[2], lastCamVelocity[3] end function objectPreview:saveToFile(filePath) if not isMRTShaderSupported or not self.isSecondRT or not isElement(self.element) then outputDebugString('objPrev : saveRTToFile fail (non MRT object or MRT not supported) !') return false end if glRenderTarget then local projPosX, projPosY, projSizeX, projSizeY, postGui, isRelaftive = unpack(self.projection) projPosX, projPosY, projSizeX, projSizeY = toint(projPosX * scx), toint(projPosY * scy), toint(projSizeX * scx), toint(projSizeY * scy) local rtPixels = dxGetTexturePixels ( glRenderTarget, projPosX, projPosY, projSizeX + projPosX, projSizeY + projPosY) if not rtPixels then outputDebugString('objPrev : saveRTToFile fail (could not get texture pixels) !') return false end rtPixels = dxConvertPixels(rtPixels, 'png') isValid = rtPixels and true local file = fileCreate(filePath) isValid = fileWrite(file, rtPixels) and isValid isValid = fileClose(file) and isValid if not isValid then outputDebugString('objPrev : saveRTToFile fail (could not save pixels to file) !') return false end outputDebugString('objPrev : saveRTToFile to: '..filePath) return isValid else outputDebugString('objPrev : saveRTToFile fail (render target error) !') return false end return false end function objectPreview:drawRenderTarget() if not isMRTShaderSupported or not self.isSecondRT then return false end if glRenderTarget then local projPosX, projPosY, projSizeX, projSizeY, postGui, isRelative = unpack(self.projection) projPosX, projPosY, projSizeX, projSizeY = projPosX * scx, projPosY * scy, projSizeX * scx, projSizeY * scy visible = getElementData(self.element, "alpha") or 255 return dxDrawImageSection(projPosX, projPosY, projSizeX, projSizeY, projPosX, projPosY, projSizeX, projSizeY, glRenderTarget, 0, 0, 0, tocolor(255, 255, 255, visible), true ) end return false end function objectPreview:setProjection(projPosX, projPosY, projSizeX, projSizeY, postGui, isRelative) if self.projection then if isRelative == false then projPosX, projPosY, projSizeX, projSizeY = projPosX / scx, projPosY / scy, projSizeX / scx, projSizeY / scy end self.isUpdate = false self.projection = {projPosX, projPosY, projSizeX, projSizeY, postGui, isRelative} end end function objectPreview:setPostGui(postGui) if not self.isSecondRT then return false end if self.projection then self.isUpdate = false self.projection[5] = postGui end end function objectPreview:setRotation(rotX, rotY, rotZ) if self.elementRotation then self.isUpdate = false self.elementRotation = {rotX, rotY, rotZ} end end function objectPreview:setRotationOffsets(offsX, offsY, offsZ) if self.elementRotationOffsets then self.isUpdate = false self.elementRotationOffsets = {offsX, offsY, offsZ} end end function objectPreview:setDistanceSpread(zSpread) if self.zDistanceSpread then self.isUpdate = false self.zDistanceSpread = zSpread end end function objectPreview:setPositionOffsets(offsX, offsY, offsZ) if self.elementPositionOffsets then self.isUpdate = false self.elementPositionOffsets = {offsX, offsY, offsZ} end end function getRTarget() if not isMRTShaderSupported then return false end if glRenderTarget then return glRenderTarget else outputDebugString('objPrev : getRenderTarget fail (no render target) !') return false end end -- onClientPreRender addEventHandler( "onClientPreRender", root, function() if not isMRTShaderSupported or (#refOPTable == 0) then return end if glRenderTarget then dxSetRenderTarget( glRenderTarget, true ) dxSetRenderTarget() end end, true, "low-5" ) -- onClientHUDRender addEventHandler( "onClientHUDRender", root, function() isMRTUsed = false if not isMRTShaderSupported or (#refOPTable == 0) then return end for index, this in ipairs( refOPTable ) do -- Draw secondary render target if refOPTable[index] then if refOPTable[index].isSecondRT then isMRTUsed = true end if refOPTable[index].enabled then local instance = this.instance if instance then instance:drawRenderTarget() end end end end if (isMRTUsed == false) and glRenderTarget then destroyElement( glRenderTarget ) glRenderTarget = nil outputDebugString('objPrev : no MRT objects visible - destroyed RT') end end, true, "low-10" ) -- OnClientResourceStart addEventHandler("onClientResourceStart", getResourceRootElement( getThisResource()), function() if not isMTAUpToDate("07331") then outputChatBox('Object preview: Update your MTA 1.5 client. Download at nightly.mtasa.com',255,0,0) return end isMRTShaderSupported = vCardNumRenderTargets() > 1 if not isMRTShaderSupported then outputChatBox('Object preview: Multiple RT in shader not supported',255,0,0) return end end)
ancientigguardian = Creature:new { customName = "Ancient IG-88 Guardian", socialGroup = "mercenary", faction = "", level = 300, chanceHit = 25.00, damageMin = 300, damageMax = 400, baseXp = 500000, baseHAM = 500000, baseHAMmax = 510000, armor = 0, resists = {80,80,80,80,80,80,80,80,80}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + STALKER, optionsBitmask = AIENABLED, diet = HERBIVORE, templates = {"object/mobile/dressed_death_watch_grey.iff"}, lootGroups = { }, weapons = {"tusken_weapons"}, reactionStf = "@npc_reaction/slang", attacks = merge(commandomaster,marksmanmaster,tkamaster,brawlermaster,fencermaster,swordsmanmaster,pikemanmaster,riflemanmaster,pistoleermaster) } CreatureTemplates:addCreatureTemplate(ancientigguardian, "ancientigguardian")
RegisterServerEvent('keys:send') AddEventHandler('keys:send', function(player, data) TriggerClientEvent('keys:received', player, data) end) RegisterServerEvent('enteredMyVehicle') AddEventHandler('enteredMyVehicle', function(plate) local source = tonumber(source) local user = exports["npc-core"]:getModule("Player"):GetUser(source) local char = user:getCurrentCharacter() exports.ghmattimysql:execute("SELECT * FROM characters_cars WHERE cid = @cid AND license_plate = @license_plate", { ['@cid'] = char.id, ['@license_plate'] = plate }, function(data) if data[1] ~= nil then TriggerClientEvent('veh.checkOwner',source,true) else TriggerClientEvent('veh.checkOwner',source,false) TriggerClientEvent('veh.getDegredation',source,plate) end end) end)
-- Copyright 2021 Sonu Kumar -- -- 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 -- -- https://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and limitations under the License. -- local srcValues = redis.call('ZRANGE', KEYS[1], 0, ARGV[1]) if #srcValues > 0 then local delta = tonumber(ARGV[2]) local op = tonumber(ARGV[3]) for existing_score, v in ipairs(srcValues) do local score = delta if op == 0 then score = score + existing_score end redis.call('ZADD', KEYS[2], score, v) end redis.call('ZREM', KEYS[1], unpack(srcValues)) end ; local size = redis.call('ZCARD', KEYS[1]) return size
trans = nil local timer = 0.2 function Constructor() trans = owner:GetLayer():GetObject("pig"):GetComponent("Transform") end function OnUpdate(dt) p = trans:GetWorldPosition() p = p + trans:RightVector()*dt*40 if(timer < 0) then timer = 0.2 s = trans:GetWorldRotation() s.y = s:y()+7 if(s:y() > 360) then s.y = s:y()-359 end trans:SetWorldRotation(s) end trans:SetWorldPosition(p) timer= timer - dt end
--local minetest.colorize saves time Colorize = minetest.colorize --Making the priv minetest.register_privilege("wings_god", { description = "Can change the wings settings of players", give_to_singleplayer = true }) --Command to add fly privs player! minetest.register_chatcommand("wings_effect", { description = "/wings_effect playername on / off (off = wings have an effect to you, on = they do not (This is good for keeping fly privs)", privs = {wings_god=true}, func = function(name, param) local pname = param:split(' ')[1] local peffect = param:split(' ')[2] local player = minetest.get_player_by_name(pname) if player == nil then minetest.chat_send_player(name, Colorize("#ff0000", "Error Player has to be online!")) return end if peffect == "on" then minetest.chat_send_player(name, Colorize("#ff8800", "Successfully changed wings settings from player "..pname.." to on")) minetest.chat_send_player(name, Colorize("#ff8800", "Your wings settings got changed to on")) player:set_attribute("No_wing_effect", "True") elseif peffect == "off" then --Simple but works minetest.chat_send_player(name, Colorize("#ff8800", "Successfully changed wings settings from player "..pname.." to off")) minetest.chat_send_player(name, Colorize("#ff8800", "Your wings settings got changed to off")) player:set_attribute("No_wing_effect", "False") else minetest.chat_send_player(name, Colorize("#ff0000", "Error you can only set it to on or off")) end end }) --let admins / mods not effect by the wings but anyone else who glitchs minetest.register_on_joinplayer(function(player) --check player privs local name = player and player:get_player_name() if player:get_attribute("No_wing_effect") == nil then player:set_attribute("No_wing_effect", "False") end if player:get_attribute("No_wing_effect") == "True" then return end if player:get_attribute("No_wing_effect") == "False" then local privs = minetest.get_player_privs(name) --indeed important check else server would crash do NEVER REMOVE THIS CODE PART if not minetest.check_player_privs(name, { fly=true }) then return end -------------------------------------------------------------- priv_to_get_revoked = "fly" for priviliges, _ in pairs(privs) do privs[priv_to_get_revoked] = nil end minetest.set_player_privs(name, privs) end end) --the actual wings code minetest.register_craftitem("wings:wings", { description = Colorize("#f3e15c", "Wings (hold it in your hands to fly)"), inventory_image = "wings.png", }) local timer = 0 minetest.register_globalstep(function(dtime) timer = timer + dtime if timer >= 0.3 then for _, player in ipairs(minetest.get_connected_players()) do local name = player and player:get_player_name() --simple check nothing spezial to see here if name == nil then return end local wielditem = player:get_wielded_item() if wielditem:get_name() == "wings:wings" then if player:get_attribute("No_wing_effect") == "True" then --minetest.chat_send_all("Worked") timer = 0 return end local privs = minetest.get_player_privs(name) local name = player:get_player_name() privs.fly = true minetest.set_player_privs(name, privs) timer = 0 else if player:get_attribute("No_wing_effect") == "True" then --minetest.chat_send_all("Worked") timer = 0 return end local privs = minetest.get_player_privs(name) local name = player:get_player_name() --indeed important check else server would crash do NEVER REMOVE THIS CODE PART if not minetest.check_player_privs(name, { fly=true }) then timer = 0 return end -------------------------------------------------------------- priv_to_get_revoked = "fly" for priviliges, _ in pairs(privs) do privs[priv_to_get_revoked] = nil end minetest.set_player_privs(name, privs) timer = 0 end end end end)
SRL={{["Angles"]=Angle(0,175.56608581543,0),["Position"]=Vector(1511.0524902344,-364.5080871582,64.03125),["Class"]="info_player_start"},{["Angles"]=Angle(0,175.56608581543,0),["Position"]=Vector(1707.3967285156,-379.73303222656,64.03125),["Class"]="info_player_start"},{["Angles"]=Angle(0,175.56608581543,0),["Position"]=Vector(1523.3400878906,-26.393058776855,64.03125),["Class"]="info_player_start"},{["Angles"]=Angle(0,175.56608581543,-0),["Position"]=Vector(1303.5194091797,106.90692901611,64.03125),["Class"]="info_player_start"},{["Angles"]=Angle(0,175.56608581543,0),["Position"]=Vector(1200.8824462891,427.17333984375,64.03125),["Class"]="info_player_start"},{["Angles"]=Angle(0,175.56608581543,0),["Position"]=Vector(1565.2960205078,588.58905029297,64.03125),["Class"]="info_player_start"},{["Angles"]=Angle(0,1.1061450242996,0),["Position"]=Vector(-1247.0478515625,137.53453063965,64.028930664063),["Class"]="pb_spawn"},{["Angles"]=Angle(0,0,0),["Position"]=Vector(1961.7934570313,98.335105895996,256.03125),["Class"]="prop_blocker_ceiling"}}
SceneManager = require("SceneManager") BattleScene_Normal = {} BattleScene_Normal.name = "BattleScene_Normal" local _window_width, _window_height = GetWindowSize() local _FONT_HP_ = nil local _FONT_TIP_ = nil local _COLOR_CLEAR_ = {r = 0, g = 0, b = 0, a = 75} local _COLORLIST_ENEMY_ = { {r = 162, g = 215, b = 221, a = 255}, {r = 242, g = 242, b = 176, a = 255}, {r = 246, g = 191, b = 188, a = 255}, {r = 104, g = 190, b = 141, a = 255}, {r = 133, g = 104, b = 89, a = 255} } local _RECT_PLAYER_HP_BAR_ = {x = 50, y = 35, w = 250, h = 30} local _RECT_RIDER_HP_BAR_ = {x = _window_width - 300, y = 35, w = 250, h = 30} local _ENEMY_SIZE_ = 13 local _ENEMY_GENERATE_DELAY_ = 40 local _RIDER_HP_DECREASE_DELAY_ = 45 local _PLAYER_HP_DECREASE_DELAY_ = 35 local _hp = 100 local _speed = 10 local _colors_player = {{r = 197, g = 61, b = 67, a = 255}, {r = 2, g = 135, b = 96, a = 255}} local _rider_hp = 100 local _timer_enemy_generate = 0 local _timer_rider_hp_decrease = 0 local _timer_player_hp_decrease = 0 local _player_x, _player_y = _window_width / 2, _window_height / 2 local _move_up, _move_down, _move_left, _move_right = false, false, false, false local _isReserveMode = false local _tips_text = {"接受正义的审判吧!", "你似乎熟悉了我的攻击方式,真是有趣的事情呢!", "反转一切!", "卑微的下民,你的行动怎么慢下来了!", "看样子你已经撑不住了!"} local _tips_text_index = 1 local _enemy_list = {} local _music_Background = nil local function _FadeOut() SetDrawColor({r = 0, g = 0, b = 0, a = 15}) for i = 1, 100 do FillRectangle({x = 0, y = 0, w = _window_width, h = _window_height}) UpdateWindow() Sleep(10) end end local function _DrawPlayer() if _isReserveMode then SetDrawColor(_colors_player[2]) else SetDrawColor(_colors_player[1]) end FillTriangle({x = _player_x, y = _player_y}, {x = _player_x, y = _player_y - 20}, {x = _player_x - 10, y = _player_y + 10}) FillTriangle({x = _player_x, y = _player_y}, {x = _player_x, y = _player_y - 20}, {x = _player_x + 10, y = _player_y + 10}) end local function _DrawPlayerHpField() -- 绘制白色HP条外边框 SetDrawColor({r = 255, g = 255, b = 255, a = 255}) FillRectangle(_RECT_PLAYER_HP_BAR_) SetDrawColor({r = 0, g = 0, b = 0, a = 255}) FillRectangle({x = _RECT_PLAYER_HP_BAR_.x + 3, y = _RECT_PLAYER_HP_BAR_.y + 3, w = _RECT_PLAYER_HP_BAR_.w - 6, h = _RECT_PLAYER_HP_BAR_.h - 6}) -- 绘制当前血量条 if _isReserveMode then SetDrawColor(_colors_player[2]) else SetDrawColor(_colors_player[1]) end if _hp > 0 then FillRectangle({x = _RECT_PLAYER_HP_BAR_.x + 3, y = _RECT_PLAYER_HP_BAR_.y + 3, w = (_RECT_PLAYER_HP_BAR_.w - 6) * (_hp / 100), h = _RECT_PLAYER_HP_BAR_.h - 6}) end -- 绘制血量值数值 local _image_HpValueText if _hp > 0 then _image_HpValueText = CreateUTF8TextImageBlended(_FONT_HP_, _hp, {r = 255, g = 255, b = 255, a = 255}) else _image_HpValueText = CreateUTF8TextImageBlended(_FONT_HP_, 0, {r = 255, g = 255, b = 255, a = 255}) end local _texture_HpValueText = CreateTexture(_image_HpValueText) local _width_image_HpValueText, _height_image_HpValueText = GetImageSize(_image_HpValueText) CopyTexture(_texture_HpValueText, {x = _RECT_PLAYER_HP_BAR_.x + _RECT_PLAYER_HP_BAR_.w + 20, y = _RECT_PLAYER_HP_BAR_.y, w = _width_image_HpValueText, h = _height_image_HpValueText}) DestroyTexture(_texture_HpValueText) UnloadImage(_image_HpValueText) end local function _DrawRiderHpField() -- 绘制白色HP外边框 SetDrawColor({r = 255, g = 255, b = 255, a = 255}) FillRectangle(_RECT_RIDER_HP_BAR_) SetDrawColor({r = 0, g = 0, b = 0, a = 255}) FillRectangle({x = _RECT_RIDER_HP_BAR_.x + 3, y = _RECT_RIDER_HP_BAR_.y + 3, w = _RECT_RIDER_HP_BAR_.w - 6, h = _RECT_RIDER_HP_BAR_.h - 6}) -- 绘制蓝色当前血量条 SetDrawColor({r = 39, g = 146, b = 145, a = 255}) if _rider_hp > 0 then FillRectangle({x = _RECT_RIDER_HP_BAR_.x + 3, y = _RECT_RIDER_HP_BAR_.y + 3, w = (_RECT_RIDER_HP_BAR_.w - 6) * (_rider_hp / 100), h = _RECT_RIDER_HP_BAR_.h - 6}) end -- 绘制骑士名字 local _image_HpValueText = CreateUTF8TextImageBlended(_FONT_HP_, "骑士", {r = 255, g = 255, b = 255, a = 255}) local _texture_HpValueText = CreateTexture(_image_HpValueText) local _width_image_HpValueText, _height_image_HpValueText = GetImageSize(_image_HpValueText) CopyTexture(_texture_HpValueText, {x = _RECT_RIDER_HP_BAR_.x - _width_image_HpValueText - 20, y = _RECT_RIDER_HP_BAR_.y, w = _width_image_HpValueText, h = _height_image_HpValueText}) DestroyTexture(_texture_HpValueText) UnloadImage(_image_HpValueText) end local function _DrawTipText() local _image_TipText = CreateUTF8TextImageBlended(_FONT_TIP_, _tips_text[_tips_text_index], {r = 255, g = 255, b = 255, a = 255}) local _texture_TipText = CreateTexture(_image_TipText) local _width_image_TipText, _height_image_TipText = GetImageSize(_image_TipText) local _rect_TipText = { x = _window_width / 2 - _width_image_TipText / 2, y = _window_height - _height_image_TipText - 50, w = _width_image_TipText, h = _height_image_TipText } -- 绘制白色提示框 SetDrawColor({r = 255, g = 255, b = 255, a = 255}) FillRectangle({x = _rect_TipText.x - 100, y = _rect_TipText.y - 10, w = _rect_TipText.w + 200, h = _rect_TipText.h + 20}) SetDrawColor({r = 0, g = 0, b = 0, a = 255}) FillRectangle({x = _rect_TipText.x - 97, y = _rect_TipText.y - 7, w = _rect_TipText.w + 194, h = _rect_TipText.h + 14}) CopyTexture(_texture_TipText, _rect_TipText) DestroyTexture(_texture_TipText) UnloadImage(_image_TipText) end local function _ClearWindow() SetDrawColor(_COLOR_CLEAR_) FillRectangle({x = 0, y = 0, w = _window_width, h = _window_height}) end local function _GenerateEnemies() local _point_center_x, _point_center_y = math.random(100, _window_width - 100), math.random(100, _window_height - 100) local _meta_speeds = { {x = 1, y = 0}, {x = 0.707, y = -0.707}, {x = 0, y = -1}, {x = -0.707, y = -0.707}, {x = -1, y = 0}, {x = -0.707, y = 0.707}, {x = 0, y = 1}, {x = 0.707, y = 0.707} } local _speed = math.random(2, 10) local _color = _COLORLIST_ENEMY_[math.random(1, #_COLORLIST_ENEMY_)] for _, _meta_speed in ipairs(_meta_speeds) do table.insert(_enemy_list, { color = _color, speed = {x = _meta_speed.x * _speed, y = _meta_speed.y * _speed}, position = {x = _point_center_x, y = _point_center_y} }) end end local function _UpdateEnemies() for index, enemy in pairs(_enemy_list) do if enemy.position.x > 0 and enemy.position.x < _window_width and enemy.position.y > 0 and enemy.position.y < _window_height then if math.sqrt((enemy.position.x - _player_x) ^ 2 + (enemy.position.y - _player_y) ^ 2) <= _ENEMY_SIZE_ then if _isReserveMode then -- 反转模式下碰触回血 if _hp < 100 then _hp = _hp + 6 end else if _hp > 0 then _hp = _hp - 10 end end table.remove(_enemy_list, index) end enemy.position.x = enemy.position.x + enemy.speed.x enemy.position.y = enemy.position.y + enemy.speed.y else table.remove(_enemy_list, index) end end end local function _DrawEnemies() for _, enemy in pairs(_enemy_list) do SetDrawColor(enemy.color) FillCircle({x = enemy.position.x, y = enemy.position.y}, _ENEMY_SIZE_) end end function BattleScene_Normal.Init() SceneManager.ClearWindowWhenUpdate = false _FONT_HP_ = LoadFont("./Resource/Font/SIMYOU.TTF", 25) _FONT_TIP_ = LoadFont("./Resource/Font/SIMYOU.TTF", 35) _music_Background = LoadMusic("./Resource/Audio/bgm_2.ogg") FadeInMusic(_music_Background, -1, 1000) SetMusicVolume(50) end function BattleScene_Normal.Update() _ClearWindow() if UpdateEvent() then local _event = GetEventType() if _event == EVENT_QUIT then SceneManager.Quit() return elseif _event == EVENT_KEYDOWN_UP then _move_up = true elseif _event == EVENT_KEYUP_UP then _move_up = false elseif _event == EVENT_KEYDOWN_DOWN then _move_down = true elseif _event == EVENT_KEYUP_DOWN then _move_down = false elseif _event == EVENT_KEYDOWN_LEFT then _move_left = true elseif _event == EVENT_KEYUP_LEFT then _move_left = false elseif _event == EVENT_KEYDOWN_RIGHT then _move_right = true elseif _event == EVENT_KEYUP_RIGHT then _move_right = false elseif _event == EVENT_KEYDOWN_1 then _hp = _hp - 1 end end if _move_up then if _player_y > _speed then _player_y = _player_y - _speed end end if _move_down then if _player_y < _window_height - _speed then _player_y = _player_y + _speed end end if _move_left then if _player_x > _speed then _player_x = _player_x - _speed end end if _move_right then if _player_x < _window_width - _speed then _player_x = _player_x + _speed end end if _timer_enemy_generate >= _ENEMY_GENERATE_DELAY_ then _GenerateEnemies() _timer_enemy_generate = 0 else _timer_enemy_generate = _timer_enemy_generate + 1 end if _timer_rider_hp_decrease >= _RIDER_HP_DECREASE_DELAY_ then if _rider_hp > 0 then _rider_hp = _rider_hp - 1 end _timer_rider_hp_decrease = 0 else _timer_rider_hp_decrease = _timer_rider_hp_decrease + 1 end if _isReserveMode and _timer_player_hp_decrease >= _PLAYER_HP_DECREASE_DELAY_ then if _hp >= 2 then _hp = _hp - 2 end _timer_player_hp_decrease = 0 else _timer_player_hp_decrease = _timer_player_hp_decrease + 1 end if _rider_hp <= 50 and _rider_hp > 40 then -- 骑士血量在40~50期间,更换标语 _tips_text_index = 2 elseif _rider_hp <= 43 and _rider_hp > 0 then -- 骑士血量在0~43期间,更换标语并启动反转模式 _tips_text_index = 3 _isReserveMode = true elseif _rider_hp <= 0 then -- 骑士血量归零,切换到成功场景 FadeOutMusic(1000) _FadeOut() SceneManager.LoadScene("VictoryScene") return end if _hp <= 80 and _hp > 60 then -- 玩家血量在60~80期间,第一次减速,更换标语 _speed = 6 if _tips_text_index ~= 2 and _tips_text_index ~= 3 then _tips_text_index = 4 end elseif _hp <= 50 and _hp > 40 then -- 玩家血量在40~50期间,第二次减速 _speed = 5 elseif _hp <= 40 and _hp > 0 then -- 玩家血量在0~40期间,第三次减速,更换标语 _speed = 4 if _tips_text_index ~= 2 and _tips_text_index ~= 3 then _tips_text_index = 5 end elseif _hp <= 0 then -- 玩家血量归零,切换到失败场景 FadeOutMusic(1000) _FadeOut() SceneManager.LoadScene("FailureScene") return end _UpdateEnemies() _DrawEnemies() _DrawPlayer() _DrawPlayerHpField() _DrawRiderHpField() _DrawTipText() end function BattleScene_Normal.Unload() UnloadFont(_FONT_HP_) UnloadFont(_FONT_TIP_) UnloadMusic(_music_Background) end return BattleScene_Normal
print("how Deep") nDeeep=io.read() nDeeep=tonumber(nDeeep) <<<<<<< HEAD print("I'm digging a mine") ======= print("me mine get cookeis") >>>>>>> caf03f92df0c0114aa2733b6bedea25c7e720858 for j=1,20 do for i=1,nDeeep do turtle.digDown() turtle.down() end for i=1,nDeeep do turtle.up() end turtle.forward() end
local CurrentVersion = '2.0.0' local GithubResourceName = 'RadarWhileDriving' PerformHttpRequest('https://raw.githubusercontent.com/Flatracer/FiveM_Resources/master/' .. GithubResourceName .. '/VERSION', function(Error, NewestVersion, Header) PerformHttpRequest('https://raw.githubusercontent.com/Flatracer/FiveM_Resources/master/' .. GithubResourceName .. '/CHANGES', function(Error, Changes, Header) print('\n') print('##############') print('## ' .. GetCurrentResourceName()) print('##') print('## Current Version: ' .. CurrentVersion) print('## Newest Version: ' .. NewestVersion) print('##') if CurrentVersion ~= NewestVersion then print('## Outdated') print('## Check the Topic') print('## For the newest Version!') print('##############') print('CHANGES:\n' .. Changes) else print('## Up to date!') print('##############') end print('\n') end) end)
-- Copyright (c) 2018 Phil Leblanc -- see LICENSE file ------------------------------------------------------------------------ --[[ test plterm - Pure Lua ANSI Terminal functions - unix only ]] -- some local definitions local strf = string.format local byte, char, rep = string.byte, string.char, string.rep local app, concat = table.insert, table.concat local repr = function(x) return strf("%q", tostring(x)) end ------------------------------------------------------------------------ local term = require "plterm" local out, outf = term.out, term.outf local golc = term.golc local color = term.color local colors = term.colors ------------------------------------------------------------------------ local function test_ansi() local l, c, mode term.clear() term.golc(1,1) outf("[1,1]") -- colors term.golc(2,1); color(colors.red, colors.bgyellow) outf "red on yellow" term.golc(3,1); color(colors.green, colors.bgblack) outf "green on black" term.golc(4,1); color(0); color(colors.red, colors.bgcyan, colors.reverse) outf "red on cyan, reverse" color(0) -- save, restore golc(5, 10) term.save() golc(1, 15); outf"[1,15]" term.restore() outf"[5,10]restored" -- getcurpos mode = term.savemode() term.setrawmode() -- required to enable getcurpos() golc(12, 30) l, c = term.getcurpos() golc(11,30); outf"getcurpos(): next line should be [12,30]" golc(12,30); outf(strf("[%d,%d]" , l, c)) -- golc beyond limits golc(999,999) -- ok with vte l, c = term.getcurpos() golc(13, 30) outf(strf("bottom right is [%d,%d]", l, c)) golc(14, 30) l, c = term.getscrlc() outf(strf("getscrlc(): number of lines, col [%d,%d]", l, c)) golc(14, 1); term.right(29) term.down(999) outf"down to last line" term.up(); term.left(17) outf"up 1 and left 17" -- done golc(18,1) outf "test_ansi() OK. " --~ term.setsanemode() term.restoremode(mode) end --test_ansi local function test_input() mode = term.savemode() term.setrawmode() -- required to enable getcurpos() local readkey = term.input() while true do golc(16,1); outf"type a key ('q' to quit): " local code = readkey() golc(16, 30); term.cleareol() outf("key is " .. term.keyname(code)) if code == byte'q' then break end end golc(19,1) outf "test_input() OK. " term.restoremode(mode) end --test_input test_ansi() test_input()
local vim = vim local api = vim.api local globals = require 'vimwiki_server/globals' local g = require 'vimwiki_server/lib/graphql' local u = require 'vimwiki_server/lib/utils' local M = {} -- Synchronous function to select an element under cursor function M.an_element() local bridge = globals.bridge local tmp = globals.tmp local path = tmp:get_current_buffer_tmp_path() local reload = true local offset = u.cursor_offset() local query = g.query([[ { page(path: "$path", reload: $reload) { nodeAtOffset(offset: $offset) { region { offset len } } } } ]], {path=path, reload=reload, offset=offset}) local res = bridge:send_wait_ok(query) if res then local region = u.get(res, 'data.page.nodeAtOffset.region') if region then u.select_in_buffer(region.offset, region.len) elseif res.errors then for i, e in ipairs(res.errors) do vim.api.nvim_command('echoerr '..e.message) end end end end -- Synchronous function to select root of an element under cursor function M.root_element() local bridge = globals.bridge local tmp = globals.tmp local path = tmp:get_current_buffer_tmp_path() local reload = true local offset = u.cursor_offset() local query = g.query([[ { page(path: "$path", reload: $reload) { nodeAtOffset(offset: $offset) { root { region { offset len } } } } } ]], {path=path, reload=reload, offset=offset}) local res = bridge:send_wait_ok(query) if res then local region = u.get(res, 'data.page.nodeAtOffset.root.region') if region then u.select_in_buffer(region.offset, region.len) elseif res.errors then for i, e in ipairs(res.errors) do vim.api.nvim_command('echoerr '..e.message) end end end end -- Synchronous function to select parent of an element under cursor function M.parent_element() local bridge = globals.bridge local tmp = globals.tmp local path = tmp:get_current_buffer_tmp_path() local reload = true local offset = u.cursor_offset() local query = g.query([[ { page(path: "$path", reload: $reload) { nodeAtOffset(offset: $offset) { parent { region { offset len } } } } } ]], {path=path, reload=reload, offset=offset}) local res = bridge:send_wait_ok(query) if res then local region = u.get(res, 'data.page.nodeAtOffset.parent.region') if region then u.select_in_buffer(region.offset, region.len) elseif res.errors then for i, e in ipairs(res.errors) do vim.api.nvim_command('echoerr '..e.message) end end end end -- Synchronous function to select the child element(s) of the element under -- cursor, or the element under cursor itself if it has no children function M.inner_element() local bridge = globals.bridge local tmp = globals.tmp local path = tmp:get_current_buffer_tmp_path() local reload = true local offset = u.cursor_offset() local query = g.query([[ { page(path: "$path", reload: $reload) { nodeAtOffset(offset: $offset) { isLeaf children { region { offset len } } region { offset len } } } } ]], {path=path, reload=reload, offset=offset}) local res = bridge:send_wait_ok(query) if res then local node = u.get(res, 'data.page.nodeAtOffset') if node then local region = nil -- If element under cursor is a leaf node, we use its region if node.isLeaf then region = node.region -- Otherwise, we calculate the start and len from the children else local offset = u.min(u.filter_map(node.children, (function(c) return c.region.offset end))) local len = u.max(u.filter_map(node.children, (function(c) return c.region.offset + c.region.len end))) - offset region = { offset = offset, len = len, } end if region then u.select_in_buffer(region.offset, region.len) end elseif res.errors then for i, e in ipairs(res.errors) do vim.api.nvim_command('echoerr '..e.message) end end end end return M
--[[-------------------------------------------------------- -- Database Schema - A SQL Table Schema Tool for Lua -- -- Copyright (c) 2014-2015 TsT worldmaster.fr -- --]]-------------------------------------------------------- ------------------------------------------------------------------------------ -- hoPairs -- ------------- -- --local hoPairs = assert( require("orderedpairs").hoPairs ) -- -- -- original source : http://lua-users.org/wiki/SortedIteration -- -- Ordered table iterator, allow to iterate on the natural order of the keys -- of a table. local function cmp_multitype(op1, op2) local type1, type2 = type(op1), type(op2) if type1 ~= type2 then --cmp by type return type1 < type2 elseif type1 == "number" and type2 == "number" or type1 == "string" and type2 == "string" then return op1 < op2 --comp by default elseif type1 == "boolean" and type2 == "boolean" then return op1 == true else return tostring(op1) < tostring(op2) --cmp by address end end local function __genHybrideOrderedIndex( t ) local orderedIndex = {} local rev = {} for key,val in pairs(t) do if type(key) == "string" then table.insert( orderedIndex, key ) else rev[val] = key -- rev['id'] = n end end local function cmp_keyorder(op1, op2) -- type are all strings here local r1,r2 = rev[op1], rev[op2] local type1, type2 = type(r1), type(r2) if type1 ~= type2 then -- string VS number (or n VS s) return type1 == "number" -- forced first end if not r1 and not r2 then -- no forced order : alphabetical order return tostring(op1) < tostring(op2) end return r1 < r2 end table.sort( orderedIndex, cmp_keyorder ) return orderedIndex end local function genericNext(t, state, genindex) local genindex = genindex or __genOrderedIndex local key --print("orderedNext: state = "..tostring(state) ) if state == nil then -- the first time, generate the index t.__orderedIndex = genindex( t ) key = t.__orderedIndex[1] return key, t[key] end -- fetch the next value key = nil for i = 1,#t.__orderedIndex do if t.__orderedIndex[i] == state then key = t.__orderedIndex[i+1] end end if key then return key, t[key] end -- no more value to return, cleanup t.__orderedIndex = nil return end local function hoNext(t, state) return genericNext(t, state, __genHybrideOrderedIndex) end local function hoPairs(t) return hoNext, t, nil end -- ------------------------------------------------------------------------------ --local dbtype = 'mysql' --local dbtype = 'sqlite' local datatypes = { ['serial'] = { -- stub }, ['int'] = { ['mysql'] = 'int', ['sqlite'] = 'INTEGER', }, ['float'] = { -- stub }, ['numeric'] = { -- stub }, ['varchar'] = { ['mysql'] = 'varchar', ['sqlite'] = 'VARCHAR', }, ['char'] = { -- stub }, ['text'] = { ['sqlite'] = 'TEXT', -- stub }, ['blob'] = { -- stub }, ['datetime'] = { ['sqlite'] = 'datetime', -- stub } } -- getDbFieldType( string abstractType ) -- Input: (String) string Generic Type of DB Field - see datatypes table -- Output: (String) Returns Type specific to database implementation (mysql, sqlite) -- local function getDbFieldType(abstractType, dbtype) return assert(dbtype, "missing dbtype") and datatypes and datatypes[abstractType] and datatypes[abstractType][dbtype] end local function renderLine(linetab) if type(linetab) == "string" then return linetab end local sep = linetab.sep or '' -- separator local bol = linetab.bol or '' -- begin of line local eol = linetab.eol or '' -- end of line for i,v in ipairs(linetab) do local tv = type(v) if tv == "table" then local rendered = renderLine(v) linetab[i] = rendered tv=type(rendered) assert(tv=="string", "rendered element must be a string") end assert(tv=="string", "element must be a string") end return bol..table.concat(linetab, sep)..eol end assert("(AA, B B, C C C);" == renderLine({ sep=', ', bol='(', eol=');',"AA", "B B", "C C C"}), "renderLine() selftest 1") assert("(AA,\"1/22/333\",C C C);" == renderLine({ sep=',', bol='(', eol=');', "AA", { sep='/', bol='"', eol='"', "1", "22", "333", }, "C C C", }), "renderLine() selftest 2") local function _f_char_text(t2, len) if(len) then return '('..len..')' end end local function _f_varchar(t2, len) --assert(not len, 'Database Error: varchar type must have length property') if not len then print('Database Error: varchar type must have length property') end return _f_char_text(t2, len) end -- generateAttributes( table tableAttributes, string dbtype, boolean isprimarykey) ) -- Input: (Table) Table with attributes ; (String) 'sqlite' or 'mysql' ; (Boolean) True if the current field is a primary key -- Output: (Table) SQL Field Attributes -- local function generateAttributes(tableAttributes, dbtype, isprimarykey) assert(dbtype) assert( type(tableAttributes) == "table", "tableAttributes must be a table :"..type(tableAttributes)) local len = tableAttributes['length'] local t2 = tableAttributes['type'] local t_attributes = {sep=' ', bol=nil, eol=nil} t_attributes[#t_attributes+1] = getDbFieldType(t2, dbtype) or t2 if(t2 == 'varchar') then local r = _f_varchar(t2, len) if r then t_attributes[#t_attributes+1] = r end elseif(t2 == 'char' or t2 == 'text') then local r = _f_char_text(t2, len) if r then t_attributes[#t_attributes+1] = r end end if not (dbtype == 'sqlite' and isprimarykey) then if(tableAttributes['unsigned'] == true) then t_attributes[#t_attributes+1] = 'UNSIGNED' end end if(tableAttributes['default']) then t_attributes[#t_attributes+1] = 'DEFAULT '..'\''..tableAttributes['default']..'\'' end if(tableAttributes['not null'] == true) then t_attributes[#t_attributes+1] = 'NOT NULL' end if(tableAttributes['auto increment'] == true) then if(dbtype == 'mysql') then t_attributes[#t_attributes+1] = 'AUTO_INCREMENT' elseif(dbtype == 'sqlite') then if isprimarykey then t_attributes[#t_attributes+1] = 'PRIMARY KEY AUTOINCREMENT' else print("WARNING: 'auto increment' should be apply if field is not a primary key") -- -- autoincrement only allowed on primary key end end end if(tableAttributes['description'] and dbtype == 'mysql') then t_attributes[#t_attributes+1] = 'COMMENT \''..tableAttributes['description']..'\'' end return t_attributes end local function schemaIsValid(schema) assert(type(schema) == "table", "Schema must be a table") if schema.schema then return false, "Found a schema.schema. The real schema is maybe inside the schema.schema." end for tableName,columns in pairs(schema) do if columns.description and type(columns.description) ~= "string" then return false, ("Invalid element in the table '%s' definition, description must be a string"):format(tableName) end if type(columns.fields) ~= "table" then return false, ("Invalid element in the table '%s' definition, fields must be a table"):format(tableName) end end return true end local function schema_orderedfieldnames(fields) if #fields == 0 then -- no number, use keys return false end local ifields = {} for k,v in pairs(fields) do if type(k) == "number" then ifields[#ifields+1] = v end end -- table.sort(ifields, function(a,b) return fields[a] > fields[b] end) table.sort(ifields) return ifields end -- schemaToSql( table schema, string dbtype ) -- Input: (Table) Containing DB Schema elements -- (String) Target Database Engine to format SQL : 'mysql'|'sqlite' -- Output: (Table) SQL for creating Database Tables -- local function schemaToSql(schema, dbtype) assert(dbtype and (dbtype == 'mysql' or dbtype == 'sqlite'), "You must specify the database type (mysql or sqlite)") local sqlQueryQueue = {} local newline = '\n' local prefix = '\t' local fkey_enabled = false -- Enable FOREIGN KEY SUPPORT only once -- CREATE Tables for tableName,columns in pairs(schema) do local foreignkeys = columns['foreign key'] if foreignkeys and dbtype == 'sqlite' then if not fkey_enabled then sqlQueryQueue[#sqlQueryQueue+1] = "PRAGMA foreign_keys=ON;"..newline fkey_enabled=true end end local primarykey = columns['primary key'] local description = columns['description'] -- CREATE Tables local sqlOut2 = { bol='CREATE TABLE '..tableName..' ', eol=';'..newline, sep='' } if description and (dbtype == 'sqlite' or dbtype == 'mysql') then sqlQueryQueue[#sqlQueryQueue+1] = "-- COMMENT '"..description.."'" end local sqlOut = { bol='('..newline, eol=newline..')', sep=','..newline, } local stuff = function(columnName, attributes) local isprimarykey = not not (columnName == primarykey) local ta2 = generateAttributes(attributes, assert(dbtype), isprimarykey) local attr = renderLine(ta2) local columnName = ("%-20s"):format( columnName ) sqlOut[#sqlOut+1] = prefix..columnName..' '..attr end for columnName, attributes in hoPairs(columns['fields']) do if type(columnName) ~= "number" then -- print("hoPairs():", columnName, attributes) stuff(columnName, attributes) end end -- After the Last Column if primarykey then if dbtype == 'mysql' or dbtype == 'sqlite' then if not (dbtype == 'sqlite' and columns['fields'][primarykey]['auto increment'] ) then sqlOut[#sqlOut+1] = prefix..'PRIMARY KEY ('..primarykey..')' end end end if foreignkeys then if dbtype == 'sqlite' then for key,foreignkey in pairs(foreignkeys) do sqlOut[#sqlOut+1] = prefix..'FOREIGN KEY ('..key..') REFERENCES '..foreignkey..' ON UPDATE CASCADE ON DELETE CASCADE' end end end if(description and dbtype == 'mysql') then sqlOut[#sqlOut+1] = "ENGINE=InnoDB COMMENT '"..description.."'" end sqlOut2[#sqlOut2+1] = sqlOut sqlQueryQueue[#sqlQueryQueue+1] = renderLine(sqlOut2) end -- ALTER CREATED TABLES TO PROVIDE FOREIGN KEY SUPPORT for tableName,columns in pairs(schema) do local foreignkeys = columns['foreign key'] if foreignkeys and dbtype ~= 'sqlite' then local sqlOut2 = { bol='ALTER TABLE '..tableName..' '..newline..prefix, eol=';'..newline, sep=', '..newline..prefix, } for key, foreignkey in pairs(foreignkeys) do sqlOut2[#sqlOut2+1] = 'ADD CONSTRAINT fk_'..tableName..'_'..key..' FOREIGN KEY ('..key..') REFERENCES '..foreignkey..' ON UPDATE CASCADE ON DELETE CASCADE' end sqlQueryQueue[#sqlQueryQueue+1] = renderLine(sqlOut2) end end return sqlQueryQueue end local function schemaTables(schema) local tables = {} for tablename in pairs(schema) do if type(tablename) == "string" then tables[#tables+1] = tablename end end return tables end local _M = {} _M.schemaToSql = assert(schemaToSql) _M.schemaIsValid = assert(schemaIsValid) _M.schemaTables = assert(schemaTables) return _M -- usefull links : -- http://www.w3schools.com/sql/default.asp
local update = false local t = Def.ActorFrame{ InitCommand = function(self) self:xy(0,-100):diffusealpha(0):visible(false) end; BeginCommand = function(self) self:queuecommand("Set") end; OffCommand = function(self) self:finishtweening() self:bouncy(0.3) self:xy(0,-100):diffusealpha(0) end; OnCommand = function(self) self:bouncy(0.3) self:xy(0,0):diffusealpha(1) end; SetCommand = function(self) self:finishtweening() if getTabIndex() == 2 then self:queuecommand("On"); self:visible(true) update = true else self:queuecommand("Off"); update = false end; end; TabChangedMessageCommand = function(self) self:queuecommand("Set") end; PlayerJoinedMessageCommand = function(self) self:queuecommand("Set") end; }; local frameX = 18 local frameY = 30 local frameWidth = capWideScale(get43size(390),390) local frameHeight = 320 local fontScale = 0.4 local distY = 15 local offsetX = 10 local offsetY = 20 local pn = GAMESTATE:GetEnabledPlayers()[1] local song local steps t[#t+1] = Def.Actor{ CurrentSongChangedMessageCommand = function(self) song = GAMESTATE:GetCurrentSong() steps = GAMESTATE:GetCurrentSteps(pn) end; CurrentStepsP1ChangedMessageCommand = function(self) steps = GAMESTATE:GetCurrentSteps(pn) end; CurrentStepsP2ChangedMessageCommand = function(self) steps = GAMESTATE:GetCurrentSteps(pn) end; } t[#t+1] = Def.Quad{ InitCommand = cmd(xy,frameX,frameY+offsetY;zoomto,frameWidth,frameHeight-offsetY;halign,0;valign,0;diffuse,getMainColor("frame");diffusealpha,0.6); } t[#t+1] = Def.Quad{ InitCommand = cmd(xy,frameX,frameY;zoomto,frameWidth,offsetY;halign,0;valign,0;diffuse,getMainColor("frame");diffusealpha,0.8); } t[#t+1] = LoadFont("Common Normal")..{ InitCommand = cmd(xy,frameX+5,frameY+offsetY-9;zoom,0.45;halign,0;diffuse,getMainColor('highlight')); BeginCommand = cmd(settext,THEME:GetString("ScreenSelectMusic","SimfileInfoHeader")) } t[#t+1] = Def.Quad{ InitCommand = function(self) self:y(frameY+5+offsetY+150*3/8) self:x(frameX+75+5) self:diffuse(color("#000000")):diffusealpha(0.6) self:zoomto(150,150*3/4) end } t[#t+1] = Def.Sprite { Name = "BG"; SetCommand = function(self) if update then self:finishtweening() self:sleep(0.25) if song then if song:HasJacket() then self:visible(true); self:Load(song:GetJacketPath()) elseif song:HasBackground() then self:visible(true) self:Load(song:GetBackgroundPath()) else self:visible(false) end else self:visible(false) end; self:scaletofit(frameX+5,frameY+5+offsetY,frameX+150+5,frameY+150*3/4+offsetY+5) self:y(frameY+5+offsetY+150*3/8) self:x(frameX+75+5) self:smooth(0.5) self:diffusealpha(0.8) end end; BeginCommand = function(self) self:queuecommand("Set") end; CurrentSongChangedMessageCommand = function(self) self:finishtweening() self:smooth(0.5):diffusealpha(0):sleep(0.35) self:queuecommand("Set") end } t[#t+1] = LoadFont("Common Normal")..{ Name = "StepsAndMeter"; InitCommand = cmd(xy,frameX+frameWidth-offsetX,frameY+offsetY+10;zoom,0.5;halign,1;); SetCommand = function(self) if steps and update then local diff = getDifficulty(steps:GetDifficulty()) local stype = ToEnumShortString(steps:GetStepsType()):gsub("%_"," ") local meter = steps:GetMeter() if IsUsingWideScreen() then self:settext(stype.." "..diff.." "..meter) else self:settext(diff.." "..meter) end self:diffuse(getDifficultyColor(GetCustomDifficulty(steps:GetStepsType(),steps:GetDifficulty()))) end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; CurrentStepsP1ChangedMessageCommand = function(self) self:queuecommand("Set") end; CurrentStepsP2ChangedMessageCommand = function(self) self:queuecommand("Set") end; } t[#t+1] = LoadFont("Common Normal")..{ Name = "StepsAndMeter"; InitCommand = cmd(xy,frameX+frameWidth-offsetX,frameY+offsetY+23;zoom,0.4;halign,1;); SetCommand = function(self) local notecount = 0 local length = 1 if steps and song and update then length = song:GetStepsSeconds() notecount = steps:GetRadarValues(pn):GetValue("RadarCategory_Notes") self:settext(string.format("%0.2f %s",notecount/length,THEME:GetString("ScreenSelectMusic","SimfileInfoAvgNPS"))) self:diffuse(Saturation(getDifficultyColor(GetCustomDifficulty(steps:GetStepsType(),steps:GetDifficulty())),0.3)) else self:settext("0.00 Average NPS") end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; CurrentStepsP1ChangedMessageCommand = function(self) self:queuecommand("Set") end; CurrentStepsP2ChangedMessageCommand = function(self) self:queuecommand("Set") end; } t[#t+1] = LoadFont("Common Normal")..{ Name = "Song Title"; InitCommand = cmd(xy,frameX+offsetX+150,frameY+offsetY+45;zoom,0.6;halign,0;maxwidth,((frameWidth-offsetX*2-150)/0.6)-40); SetCommand = function(self) if update and song then self:settext(song:GetDisplayMainTitle()) self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) else self:settext("Not Available") self:diffuse(getMainColor("disabled")) end self:GetParent():GetChild("Song Length"):x(frameX+offsetX+155+(math.min(self:GetWidth()*0.60,frameWidth-195))) end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; } t[#t+1] = LoadFont("Common Normal")..{ Name = "Song Length"; InitCommand = cmd(xy,frameX+offsetX+150,frameY+offsetY+44;zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.6); SetCommand = function(self) local length = 0 if update and song then length = song:GetStepsSeconds() self:visible(true) end self:settext(string.format("%s",SecondsToMSS(length))) self:diffuse(getSongLengthColor(length)) end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; } t[#t+1] = LoadFont("Common Normal")..{ Name = "Song SubTitle"; InitCommand = cmd(xy,frameX+offsetX+150,frameY+offsetY+60;zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4); SetCommand = function(self) if update and song then self:visible(true) self:settext(song:GetDisplaySubTitle()) self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) else self:visible(false) end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; } t[#t+1] = LoadFont("Common Normal")..{ Name = "Song Artist"; InitCommand = cmd(xy,frameX+offsetX+150,frameY+offsetY+73;zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4); SetCommand = function(self) if update and song then self:visible(true) self:settext(song:GetDisplayArtist()) self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) if #song:GetDisplaySubTitle() == 0 then self:y(frameY+offsetY+60) else self:y(frameY+offsetY+73) end else self:y(frameY+offsetY+60) self:settext("Not Available") self:diffuse(getMainColor("disabled")) end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; } t[#t+1] = LoadFont("Common Normal")..{ Name = "Song BPM"; InitCommand = cmd(xy,frameX+offsetX+150,frameY+offsetY+130;zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4); SetCommand = function(self) local bpms = {0,0} if update and song then bpms = song:GetTimingData():GetActualBPM() for k,v in pairs(bpms) do bpms[k] = math.round(bpms[k]) end self:visible(true) if bpms[1] == bpms[2] and bpms[1]~= nil then self:settext(string.format("BPM: %d",bpms[1])) else self:settext(string.format("BPM: %d-%d (%d)",bpms[1],bpms[2],getCommonBPM(song:GetTimingData():GetBPMsAndTimes(true),song:GetLastBeat()))) end self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) else self:settext("Not Available") self:diffuse(getMainColor("disabled")) end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; } t[#t+1] = LoadFont("Common Normal")..{ Name = "BPM Change Count"; InitCommand = cmd(xy,frameX+offsetX+150,frameY+offsetY+145;zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4); SetCommand = function(self) local bpms = {0,0} if update and song then self:settext(string.format("BPM Changes: %d",getBPMChangeCount(song:GetTimingData():GetBPMsAndTimes(true)))) self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) else self:settext("Not Available") self:diffuse(getMainColor("disabled")) end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; } t[#t+1] = LoadFont("Common Normal")..{ Name = "Stop Count"; InitCommand = cmd(xy,frameX+offsetX+150,frameY+offsetY+160;zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4); SetCommand = function(self) if update and song then self:settext(string.format("Stops: %d",#song:GetTimingData():GetStops(true))) self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) else self:settext("Not Available") self:diffuse(getMainColor("disabled")) end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; } local radarValues = { {'RadarCategory_Notes','Notes'}, {'RadarCategory_TapsAndHolds','Taps'}, {'RadarCategory_Holds','Holds'}, {'RadarCategory_Rolls','Rolls'}, {'RadarCategory_Mines','Mines'}, {'RadarCategory_Lifts','Lifts'}, {'RadarCategory_Fakes','Fakes'}, } for k,v in ipairs(radarValues) do t[#t+1] = LoadFont("Common Normal")..{ InitCommand = cmd(xy,frameX+offsetX,frameY+offsetY+130+(15*(k-1));zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4); OnCommand = function(self) self:settext(v[2]..": ") self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) end; } t[#t+1] = LoadFont("Common Normal")..{ Name = "RadarValue"..v[1]; InitCommand = cmd(xy,frameX+offsetX+40,frameY+offsetY+130+(15*(k-1));zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4); SetCommand = function(self) local count = 0 if song and steps and update then count = steps:GetRadarValues(pn):GetValue(v[1]) self:settext(count) self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) else self:settext(0) self:diffuse(getMainColor("disabled")) end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; CurrentStepsP1ChangedMessageCommand = function(self) self:queuecommand("Set") end; CurrentStepsP2ChangedMessageCommand = function(self) self:queuecommand("Set") end; } end t[#t+1] = LoadFont("Common Normal")..{ InitCommand = cmd(xy,frameX+offsetX,frameY+frameHeight-10-distY*2;zoom,fontScale;halign,0;); BeginCommand = function(self) self:settext("Path:") self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) end } t[#t+1] = LoadFont("Common Normal")..{ InitCommand = cmd(xy,frameX+offsetX+35,frameY+frameHeight-10-distY*2;zoom,fontScale;halign,0;maxwidth,(frameWidth-35-offsetX-10)/fontScale); BeginCommand = function(self) self:queuecommand("Set") end; SetCommand = function(self) if update and song then self:settext(song:GetSongDir()) self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) else self:settext("Not Available") self:diffuse(getMainColor("disabled")) end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; } t[#t+1] = LoadFont("Common Normal")..{ InitCommand = cmd(xy,frameX+offsetX,frameY+frameHeight-10-distY;zoom,fontScale;halign,0;); BeginCommand = function(self) self:settext("SHA-1:") self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) end } t[#t+1] = LoadFont("Common Normal")..{ InitCommand = cmd(xy,frameX+offsetX+35,frameY+frameHeight-10-distY;zoom,fontScale;halign,0;maxwidth,(frameWidth-35)/fontScale); BeginCommand = function(self) self:queuecommand("Set") end; SetCommand = function(self) if update and steps then self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) self:settext(SHA1FileHex(steps:GetFilename())) else self:settext("Not Available") self:diffuse(getMainColor("disabled")) end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; } t[#t+1] = LoadFont("Common Normal")..{ InitCommand = cmd(xy,frameX+offsetX,frameY+frameHeight-10;zoom,fontScale;halign,0;); BeginCommand = function(self) self:settext("MD5:") self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) end } t[#t+1] = LoadFont("Common Normal")..{ InitCommand = cmd(xy,frameX+offsetX+35,frameY+frameHeight-10;zoom,fontScale;halign,0;maxwidth,(frameWidth-35)/fontScale); BeginCommand = function(self) self:queuecommand("Set") end; SetCommand = function(self) if update and steps then self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)) self:settext(MD5FileHex(steps:GetFilename())) else self:settext("Not Available") self:diffuse(getMainColor("disabled")) end end; CurrentSongChangedMessageCommand = function(self) self:queuecommand("Set") end; } return t
local GameConstants = require("game/GameConstants") local menu = require("game/MainMenu") local Level = require("game/Level") local LevelSelect = require("game/LevelSelect") local GameEnd = require("game/GameEnd") local StateManager = {currentState = nil, _state = GameConstants.State.MENU} function StateManager.init() StateManager.currentState = menu StateManager.currentState:load() end -- I should really optimize these state thingies but -- I didn't add a way to switch back from game to menu -- or level select to menu. So the load gets called -- only once. TODO: update later. function StateManager.switchState(state, arg) StateManager._state = state if state == GameConstants.State.PLAYING then StateManager.currentState = Level:new(arg) StateManager.currentState:load() elseif state == GameConstants.State.LVL_SELECT then StateManager.currentState = LevelSelect StateManager.currentState:load() else StateManager.currentState = GameEnd StateManager.currentState:load() end end function StateManager.handleKeyPress(key) if StateManager.currentState.handleKeyPress then StateManager.currentState:handleKeyPress(key) end end function StateManager.updateState(dt) StateManager.currentState:update(dt) end function StateManager.drawState() StateManager.currentState:show() end return StateManager
local M, module = {}, ... _G[module] = M function M.run() -- make this a volatile module: package.loaded[module] = nil print("Running component gradient...") disp:setColor(0, 0, 255, 0) disp:setColor(1, 255, 0, 0) disp:setColor(2, 255, 0, 255) disp:setColor(3, 0, 255, 255) disp:drawGradientBox(0, 0, disp:getWidth(), disp:getHeight()) disp:setColor(255, 255, 255) disp:setPrintPos(2,18) disp:setPrintDir(0) disp:print("GradientBox") disp:setColor(0, 0, 255, 0) disp:drawBox(2, 25, 8, 8) disp:setColor(0, 255, 0, 0) disp:drawBox(2+10, 25, 8, 8) disp:setColor(0, 255, 0, 255) disp:drawBox(2, 25+10, 8, 8) disp:setColor(0, 0, 255, 255) disp:drawBox(2+10, 25+10, 8, 8) print("...done") end return M
-- API.lua -- Implements the functions that are considered "External API" callable by other plugins --- Locks an area specified by the coords -- Returns true on success, false and error ID and error message on failure -- a_LockedByName is the name of the player locking the area (for information purposes only) function LockAreaByCoords(a_WorldName, a_BlockX, a_BlockZ, a_LockedByName) -- Check params: a_BlockX = tonumber(a_BlockX) a_BlockZ = tonumber(a_BlockZ) if ( (type(a_WorldName) ~= "string") or (type(a_BlockX) ~= "number") or (type(a_BlockZ) ~= "number") or (type(a_LockedByName) ~= "string") ) then return false, "ParamError", "Invalid parameters. Expected string, number, number and string." end -- Find the appropriate area: local Area = g_DB:LoadAreaByPos(a_WorldName, a_BlockX, a_BlockZ) if (Area == nil) then return false, "NoAreaHere", "There is no gallery area here" end -- If the area is already locked, bail out: if (Area.IsLocked) then return false, "AlreadyLocked", "This area has already been locked by " .. Area.LockedBy .. " on " .. Area.DateLocked end -- Lock the area: g_DB:LockArea(Area, a_LockedByName) ReplaceAreaForAllPlayers(Area) return true end --- Locks an area specified by its ID -- Returns true on success, false and error ID and error message on failure -- a_LockedByName is the name of the player locking the area (for information purposes only) function LockAreaByID(a_AreaID, a_LockedByName) -- Check params: a_AreaID = tonumber(a_AreaID) if ( (type(a_AreaID) ~= "number") or (type(a_LockedByName) ~= "string") ) then return false, "ParamError", "Invalid parameters. Expected number and string." end -- Find the appropriate area: local Area = g_DB:LoadAreaByID(a_AreaID) if (Area == nil) then return false, "NoSuchArea", "There is no such area" end -- If the area is already locked, bail out: if (Area.IsLocked) then return false, "AlreadyLocked", "This area has already been locked by " .. Area.LockedBy .. " on " .. Area.DateLocked end -- Lock the area: g_DB:LockArea(Area, a_LockedByName) ReplaceAreaForAllPlayers(Area) return true end --- Unlocks an area specified by the coords -- Returns true on success, false and error ID and error message on failure -- a_UnlockedByName is the name of the player unlocking the area (for information purposes only) function UnlockAreaByCoords(a_WorldName, a_BlockX, a_BlockZ, a_UnlockedByName) -- Check params: a_BlockX = tonumber(a_BlockX) a_BlockZ = tonumber(a_BlockZ) if ( (type(a_WorldName) ~= "string") or (type(a_BlockX) ~= "number") or (type(a_BlockZ) ~= "number") or (type(a_UnlockedByName) ~= "string") ) then return false, "ParamError", "Invalid parameters. Expected string, number, number and string." end -- Find the appropriate area: local Area = g_DB:LoadAreaByPos(a_WorldName, a_BlockX, a_BlockZ) if (Area == nil) then return false, "NoAreaHere", "There is no gallery area here" end -- If the area isn't locked, bail out: if not(Area.IsLocked) then return false, "NotLocked", "This area hasn't been locked." end -- Lock the area: g_DB:UnlockArea(Area, a_UnlockedByName) ReplaceAreaForAllPlayers(Area) return true end --- Unlocks an area specified by its ID -- Returns true on success, false and error ID and error message on failure -- a_LockedByName is the name of the player locking the area (for information purposes only) function UnlockAreaByID(a_AreaID, a_UnlockedByName) -- Check params: a_AreaID = tonumber(a_AreaID) if ( (type(a_AreaID) ~= "number") or (type(a_UnlockedByName) ~= "string") ) then return false, "ParamError", "Invalid parameters. Expected number and string." end -- Find the appropriate area: local Area = g_DB:LoadAreaByID(a_AreaID) if (Area == nil) then return false, "NoSuchArea", "There is no such area" end -- If the area is already unlocked, bail out: if not(Area.IsLocked) then return false, "NotLocked", "This area has already been unlocked by " .. Area.LockedBy .. " on " .. Area.DateLocked end -- Unlock the area: g_DB:UnlockArea(Area, a_UnlockedByName) ReplaceAreaForAllPlayers(Area) return true end
object_tangible_furniture_all_frn_all_data_terminal_wall_s1 = object_tangible_furniture_all_shared_frn_all_data_terminal_wall_s1:new { } ObjectTemplates:addTemplate(object_tangible_furniture_all_frn_all_data_terminal_wall_s1, "object/tangible/furniture/all/frn_all_data_terminal_wall_s1.iff")
--local null_ls = require("null-ls") -- register any number of sources simultaneously --local sources = { -- --null_ls.builtins.formatting.prettier, -- --null_ls.builtins.diagnostics.write_good, -- --null_ls.builtins.code_actions.gitsigns, -- null_ls.builtins.diagnostics.vale.with({ -- filetypes = { "markdown", "tex", "txt" }, -- -- command = "vale", -- -- args = { "--no-exit", "--output=JSON", "$FILENAME" }, -- }) --} --null_ls.setup({ sources = sources })
return { install_script = [[ wget -O vscode.tar.gz https://update.code.visualstudio.com/latest/linux-x64/stable rm -rf vscode mkdir vscode tar -xzf vscode.tar.gz -C vscode --strip-components 1 rm vscode.tar.gz rm -rf vscode-html mkdir vscode-html cp -r vscode/resources/app/extensions/node_modules vscode-html cp -r vscode/resources/app/extensions/html-language-features vscode-html rm -rf vscode ]], default_config = { cmd = { "node", "./vscode-html/html-language-features/server/dist/node/htmlServerMain.js", "--stdio" }, filetypes = { -- html 'aspnetcorerazor', 'blade', 'django-html', 'edge', 'ejs', 'erb', 'gohtml', 'haml', 'handlebars', 'hbs', 'html', 'html-eex', 'jade', 'leaf', 'liquid', 'markdown', 'mdx', 'mustache', 'njk', 'nunjucks', 'php', 'razor', 'slim', 'twig', -- mixed 'vue', 'svelte', }, root_dir = require'lspconfig'.util.root_pattern(".git", vim.fn.getcwd()), init_options = { provideFormatter = true, }, } }
-- copy from https://github.com/ejoy/avalon/blob/master/lualib/staticfile.lua local conf = require "conf" local io = io local root = conf.static_path local cache = setmetatable({}, { __mode = "kv" }) local function cachefile(_, filename) local v = cache[filename] if v then return v[1] end local f = io.open (root .. filename) if f then local content = f:read "a" f:close() cache[filename] = { content } return content else cache[filename] = {} end end local staticfile = setmetatable({}, {__index = cachefile }) return staticfile
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ # Heka JSON Message Decoder Module https://wiki.mozilla.org/Firefox/Services/Logging The above link describes the Heka message format with a JSON schema. The JSON will be decoded and passed directly to inject_message so it needs to decode into a Heka message table described here: https://mozilla-services.github.io/lua_sandbox/heka/message.html ## Decoder Configuration Table * none ## Functions ### decode Decode and inject the resulting message *Arguments* - data (string) - JSON message with a Heka schema *Return* - nil - throws an error on an invalid data type, JSON parse error, inject_message failure etc. --]] -- Imports local cjson = require "cjson" local inject_message = inject_message local M = {} setfenv(1, M) -- Remove external access to contain everything in the module function decode(data) inject_message(cjson.decode(data)) end return M
-- vim: ft=lua ts=2 return { area = true, base = true, br = true, col = true, command = true, embed = true, hr = true, img = true, input = true, keygen = true, link = true, meta = true, param = true, source = true, track = true, wbr = true }
module(..., package.seeall) local tinsert, tremove = table.insert, table.remove local format = string.format local db = BAMBOO_DB ------------------------public ------------ local function getClassName(self) return self.__name end -- return the key of some string like 'User:__index' -- local function getIndexKey(self) return getClassName(self) + ':__index' end function getFieldHashKey(self, field) return getClassName(self) .. ":" .. field.. ':__hash' end function getFieldZSetKey(self,field) return getClassName(self)..":"..field..":__zset"; end function getFieldValSetKey(self, field, value) return getClassName(self) .. ":" .. field..":".. value .. ':__set' end function getAllIds(self) local indexKey = getIndexKey(self); return db:zrange(indexKey, 0,-1); end --[[function getFieldZSet(self,sKey,eKey) local indexKey = getFieldZSetKey(self); return db:zrange(indexKey,0,-1); end]] function getFieldHashFields(self,field) local indexKey = getFieldHashKey(self,field); return db:hkeys(indexKey); end ---------------------------make index ------------ --remove the string index of the field of the object function indexFieldStrRemove(self, field) local indexKey = getFieldHashKey(self,field); local id = db:hget(indexKey, self[field]); if id==nil then --do nothing elseif tonumber(id) then--this field only has a id if tonumber(id) == tonumber(self.id) then db:hdel(indexKey, self[field]); end else --this field has a id set local indexSetKey = id; db:srem(indexSetKey, self.id); local num = db:scard(indexSetKey) ; if num == 1 then local ids = db:smembers(indexSetKey); db:del(indexSetKey); db:hset(indexKey,self[field],ids[1]); end end end --create the string index of the field of the object function indexFieldStr(self,field) --add the new local indexKey = getFieldHashKey(self,field); local id = db:hget(indexKey, self[field]); if id==nil then db:hset(indexKey, self[field], self.id); elseif tonumber(id) then--this field already has a id local indexSetKey = getFieldValSetKey(self, field, self[field]); db:sadd(indexSetKey, id); db:sadd(indexSetKey, self.id); db:hset(indexKey, self[field], indexSetKey); else -- this field has a id set, the id is the set name db:sadd(id, self.id); end end -- create or update the index of the object field function indexField(self, field, ctype, oldObj) local value = self[field]; if oldObj and oldObj[field] == value then return; end if ctype == 'number' then local indexKey = getFieldZSetKey(self,field); db:zadd(indexKey, value, self.id); elseif ctype == 'string' then if oldObj then indexFieldStrRemove(oldObj,field);--remove the old end if self[field] then indexFieldStr(self,field); --add the new end else end end -- create or update the index of the object or the object field -- if create, must be called after save() and the newIndex must be true -- if update, must be called before save() and the newIndex must be false -- NOTE: 1.the application developer should not call this function, becuase -- it autolly be called in the Model:save(), Model:del(), and so on. function index(self,newIndex,field) I_AM_INSTANCE(self) if field then checkType(field, 'string') end -- start index if newIndex then -- when new ,it can not create index for the field only, --[[if field then -- index for field index_type = self.__fields[field].index_type; if index_type then indexField(self, field, index_type, nil) end else--]] -- index for object for field, def in pairs(self.__fields) do if def.hash_index then indexField(self, field, def.type, nil); end end -- end else if field then -- index for field local oldObj = self:getClass():getById(self.id); ctype = self.__fields[field].type; if ctype then indexField(self, field, ctype, oldObj) end else -- index for object local oldObj = self:getClass():getById(self.id); for field, def in pairs(self.__fields) do if def.hash_index then indexField(self, field, def.type, oldObj); end end end end end; --index field del function indexFieldDel(self, field, ctype) if ctype == 'number' then local indexKey = getFieldZSetKey(self,field); db:zrem(indexKey, self.id); elseif ctype == 'string' then indexFieldStrRemove(self,field);--remove the old else end end function indexDel(self) for field, def in pairs(self.__fields) do if def.hash_index then indexFieldDel(self, field, def.type); end end end ---------------- use index --------------------------- --[[function filterQueryArgs(self,query_args) if query_args and query_args['id'] then -- remove 'id' query argument print("[Warning] Filter doesn't support search by id.") query_args['id'] = nil end local logic = 'and' -- normalize the 'and' and 'or' logic if query_args[1] then assert(query_args[1] == 'or' or query_args[1] == 'and', "[Error] The logic should be 'and' or 'or', rather than: " .. tostring(query_args[1])) if query_args[1] == 'or' then logic = 'or' end query_args[1] = nil end return logic, query_args; end -- walkcheck can process full object and partial object function walkcheck(self,objs,query_args,logic_choice) local query_set = QuerySet() for i = 1, #objs do local obj = objs[i] --DEBUG(obj) -- check the object's legalery, only act on valid object --if isValidInstance(obj) then local flag = checkLogicRelation(self, obj, query_args, logic_choice) -- if walk to this line, means find one if flag then tinsert(query_set, obj) end --end end return query_set; end function filterQuerySet(self, query_args, start, stop, is_rev, is_get) -- if query table is empty, return slice instances if isFalse(query_args) then local start = start or 1 local stop = stop or -1 local nums = self:numbers() return self:slice(start, stop, is_rev); end local all_ids = self -- nothing in id list, return empty table if #all_ids == 0 then return List() end -- create a query set local query_set = nil; local logic_choice = (logic == 'and') local partially_got = false query_set = walkcheck(objs); -- here, _t_query_set is the all instance fit to query_args now local _t_query_set = query_set if #query_set == 0 then return query_set end if is_get == 'get' then query_set = (is_rev == 'rev') and List {_t_query_set[#_t_query_set]} or List {_t_query_set[1]} else -- now id_list is a list containing all id of instances fit to this query_args rule, so need to slice query_set = _t_query_set:slice(start, stop, is_rev) end return query_set end ptable(all_ids) --]] function filterEqString(self, field, value) local indexKey = getFieldHashKey(self,field); local id = db:hget(indexKey, value); if id == nil then return List(); elseif tonumber(id) then return {id}; else local ids = db:smembers(id); return ids; end end function filterBtNumber(self,field,min,max) local indexKey = getFieldZSetKey(self,field); return db:zrangebyscore(indexKey,min,max) end function filterNumber(self,field,name,args) local all_ids = {}; if name == 'eq' then-- equal all_ids = filterBtNumber(self,field,args,args); elseif name == 'uneq' then --unequal local lefts = filterBtNumber(self,field,-math.huge,"("..tostring(args)); local rights = filterBtNumber(self,field,"("..tostring(args),math.huge); all_ids = lefts; for i,v in ipairs(rights) do table.insert(all_ids,v); end elseif name == 'lt' then -- less then all_ids = filterBtNumber(self,field,-math.huge,"("..args); elseif name == 'gt' then -- great then all_ids = filterBtNumber(self,field,"("..args,math.huge); elseif name == 'le' then -- less and equal then all_ids = filterBtNumber(self,field,-math.huge,args); elseif name == 'ge' then -- great and equal then all_ids = filterBtNumber(self,field,args,math.huge); elseif name == 'bt' then all_ids = filterBtNumber(self,field,"("..args[1],"("..args[2]); elseif name == 'be' then all_ids = filterBtNumber(self,field,args[1],args[2]); elseif name == 'outside' then all_ids = filterBtNumber(self,field,-math.huge,"("..args[1]); local t = filterBtNumber(self,field,"("..args[2], math.huge); for i,v in ipairs(t) do table.insert(all_ids,v); end elseif name == 'inset' then for i,v in ipairs(args) do local ids = filterBtNumber(self,field,v,v); for __,id in ipairs(ids) do table.insert(all_ids, id); end end elseif name == 'uninset' then local all = Set(getAllIds(self)); for i,v in ipairs(args) do local ids = filterBtNumber(self,field,v,v); for __,id in ipairs(ids) do all[id] = nil; end end for k,v in pairs(all) do table.insert(all_ids,k) end else end return all_ids; end function filterString(self,field,name,args) local all_ids = {}; if name == 'eq' then-- equal all_ids = filterEqString(self,field,args); elseif name == 'uneq' then --unequal local all = Set(getAllIds(self)); local ids = filterEqString(self,field,args); for __,id in ipairs(ids) do all[id] = nil; end for k,v in pairs(all) do table.insert(all_ids,k) end elseif name == 'lt' then -- less then local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do if key<args then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end else --break; end end elseif name == 'gt' then -- great then local keys = getFieldHashFields(self,field); for i=#keys,1,-1 do if keys[i]>args then local ids = filterEqString(self,field,keys[i]); for _,id in ipairs(ids) do table.insert(all_ids,id); end else --break; end end elseif name == 'le' then -- less and equal then local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do if key<=args then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end else --break; end end elseif name == 'ge' then -- great and equal then local keys = getFieldHashFields(self,field); for i=#keys,1,-1 do if keys[i]>=args then local ids = filterEqString(self,field,keys[i]); for _,id in ipairs(ids) do table.insert(all_ids,id); end else --break; end end elseif name == 'bt' then -- between local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do if key<args[2] and key >args[1] then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end elseif key >= args[2] then --break; else end end elseif name == 'be' then -- between and equal local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do if key<=args[2] and key >=args[1] then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end elseif key>args[2] then --break; else end end elseif name == 'outside' then local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do if key<args[1] or key>args[2] then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end else --break; end end --[[ for i=#keys,1,-1 do if keys[i] > args then local ids = filterEqString(self,field,keys[i]); for _,id in ipairs(ids) do table.insert(all_ids,id); end else break; end] end--]] elseif name == 'contains' then local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do if string.find(key,args) then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end end end elseif name == 'uncontains' then local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do if not string.find(key,args) then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end end end elseif name == 'startsWith' then local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do local start = string.find(key,args); if start and start == 1 then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end end end elseif name == 'unstartsWith' then local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do local start = string.find(key,args); if (not start) or( start >1) then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end end end elseif name == 'endsWith' then local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do local _,ends = string.find(key,args); if ends and ends == string.len(key) then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end end end elseif name == 'unendsWith' then local keys = getFieldHashFields(self,field); for i,key in pairs(keys) do local _,ends = string.find(key,args); if (not ends) or ( ends<string.len(key)) then local ids = filterEqString(self,field,key); for _,id in ipairs(ids) do table.insert(all_ids,id); end end end elseif name == 'inset' then for i,v in ipairs(args) do local t = filterEqString(self,field,v); for _,id in ipairs(t) do table.insert(all_ids,id); end end elseif name == 'uninset' then local all = Set(getAllIds(self)); for i,v in ipairs(args) do local t = filterEqString(self,field,v); for _,id in ipairs(t) do all[id] = nil; end end for k,v in pairs(all) do table.insert(all_ids,k) end end return all_ids; end function filterLogic( logic, all_ids) if logic == "and" then local ids = {}; local tset = {}; for i=2, #all_ids do tset[i-1] = Set(all_ids[i]); end for i,v in ipairs(all_ids[1]) do local flag = true; for __,set in ipairs(tset) do if set[v] == nil then flag = false; break; end end if flag then table.insert(ids,v); end end return ids; elseif logic == 'or' then local t = Set(all_ids[1]); for i=2,#all_ids do for __,v in ipairs(all_ids[i]) do t[v] = true; end end local ids = {}; for k,v in pairs(t) do table.insert(ids,k); end return ids; else print("[Warning] unknown logic :" .. logic); return {}; end end --- fitler some instances belong to this model -- @param query_args: query arguments in a table function filter(self, query_args, logic) --[[I_AM_CLASS_OR_QUERY_SET(self) assert(type(query_args) == 'table' or type(query_args) == 'function', '[Error] the query_args passed to filter must be table or function.') if start then assert(type(start) == 'number', '[Error] @filter - start must be number.') end if stop then assert(type(stop) == 'number', '[Error] @filter - stop must be number.') end if is_rev then assert(type(is_rev) == 'string', '[Error] @filter - is_rev must be string.') end --]] local is_query_table = (type(query_args) == 'table') --[[ deal args local query_str_iden if is_query_table then logic, query_args = filterQueryArgs(self,query_args); end--]] local all_ids = {}; local i = 0; if type(query_args) == 'table' then for field,value in pairs(query_args) do i = i + 1; if not self.__fields[field] then return List(); end if type(value) == 'function' then local flag,name,args = value('___hashindex^*_#@[]-+~~!$$$$');--get the args if self.__fields[field].type == 'number' then all_ids[i] = filterNumber(self,field,name,args); elseif self.__fields[field].type == 'string' then all_ids[i] = filterString(self,field,name,args); else all_ids[i] = {}; end else if self.__fields[field].type == 'number' then all_ids[i] = filterBtNumber(self,field,value,value); elseif self.__fields[field].type == 'string' then all_ids[i] = filterEqString(self,field,value); else all_ids[i] = {}; end end end else print("rule index not surport"); end if #all_ids == 1 then return all_ids[1]; end return filterLogic(logic, all_ids); end;
-- simulate flux hs.location.start() hs.timer.doAfter(1, function() loc = hs.location.get() hs.location.stop() -- NY time -- local times = {sunrise = "07:00", sunset = "20:00"} -- UTC + NY time local times = {sunrise = "14:00", sunset = "03:00"} -- UTC + SF time -- local times = {sunrise = "11:00", sunset = "00:00"} if loc then local tzOffset = tonumber(string.sub(os.date("%z"), 1, -3)) for i,v in pairs({"sunrise", "sunset"}) do times[v] = os.date("%H:%M", hs.location[v](loc.latitude, loc.longitude, tzOffset)) end end hs.redshift.start(3600, times.sunset, times.sunrise) end)
-- Easy installer. Bootstrapped by http://pastebin.com/p8PJVxC4 local repo, tree = select(1,...) if not tree then -- assume tree as the preferred argument. tree = repo or 'master' end if not repo then repo = 'eric-wieser/computercraft-github' end local REPO_BASE = ('https://raw.githubusercontent.com/%s/%s/'):format(repo, tree) local FILES = { 'apis/dkjson', 'apis/github', 'programs/github', 'github' } local function request(url_path) local request = http.get(REPO_BASE..url_path) local status = request.getResponseCode() local response = request.readAll() request.close() return status, response end local function makeFile(file_path, data) local path = 'github.rom/'..file_path local dir = path:match('(.*/)') fs.makeDir(dir) local file = fs.open(path,'w') file.write(data) file.close() end local function rewriteDofiles() for _, file in pairs(FILES) do local filename = ('github.rom/%s'):format(file) local r = fs.open(filename, 'r') local data = r.readAll() r.close() local w = fs.open(filename, 'w') data = data:gsub('dofile%("', 'dofile("github.rom/') w.write(data) w.close() end end -- install github for key, path in pairs(FILES) do local try = 0 local status, response = request(path) while status ~= 200 and try <= 3 do status, response = request(path) try = try + 1 end if status then makeFile(path, response) else printError(('Unable to download %s'):format(path)) fs.delete('github.rom') fs.delete('github') break end end rewriteDofiles() fs.move('github.rom/github', 'github') print("github by Eric Wieser installed!") dofile('github')
--New object_static_installation_shared_mockup_clothing_factory_style_1 = SharedStaticObjectTemplate:new { clientTemplateFileName = "object/static/installation/shared_mockup_clothing_factory_style_1.iff" } ObjectTemplates:addClientTemplate(object_static_installation_shared_mockup_clothing_factory_style_1, "object/static/installation/shared_mockup_clothing_factory_style_1.iff") --**********************************************************************************************************************************
local Players = game:GetService("Players") local CorePackages = game:GetService("CorePackages") local InGameMenuDependencies = require(CorePackages.InGameMenuDependencies) local Roact = InGameMenuDependencies.Roact local t = InGameMenuDependencies.t local InGameMenu = script.Parent.Parent local Promise = require(InGameMenu.Utility.Promise) local withLocalization = require(InGameMenu.Localization.withLocalization) local Page = require(InGameMenu.Components.Page) local ThemedTextLabel = require(InGameMenu.Components.ThemedTextLabel) local PageNavigationWatcher = require(InGameMenu.Components.PageNavigationWatcher) local InviteFriendsList = require(script.InviteFriendsList) local AddFriendsNow = require(script.AddFriendsNow) local LoadingFriendsError = require(script.LoadingFriendsError) local InviteFriendsPage = Roact.PureComponent:extend("InviteFriendsPage") InviteFriendsPage.validateProps = t.strictInterface({ pageTitle = t.string, }) function InviteFriendsPage:init() self.state = { loadingFriends = true, loadingFriendsError = false, friends = {}, } end function InviteFriendsPage:renderLoadingPage() return withLocalization({ loading = "CoreScripts.InGameMenu.InviteFriends.Loading", })(function(localized) return Roact.createElement(ThemedTextLabel, { Size = UDim2.new(1, 0, 1, 0), Text = localized.loading, fontKey = "Header1", themeKey = "TextEmphasis", }) end) end function InviteFriendsPage:renderError() return Roact.createElement(LoadingFriendsError, { onRetry = function() self:setState({ loadingFriends = true, loadingFriendsError = false, }) self:loadFriends() end }) end function InviteFriendsPage:renderNoFriends() return Roact.createElement(AddFriendsNow) end function InviteFriendsPage:renderFriends() return Roact.createElement(InviteFriendsList, { players = self.state.friends, }) end function InviteFriendsPage:render() local state = self.state local children = { Watcher = Roact.createElement(PageNavigationWatcher, { desiredPage = "InviteFriends", onNavigateTo = function() self:loadFriends() end, }) } if state.loadingFriends then children.Loading = self:renderLoadingPage() elseif state.loadingFriendsError then children.ErrorLoading = self:renderError() elseif #state.friends == 0 then children.NoFriends = self:renderNoFriends() else children.FriendsList = self:renderFriends() end return Roact.createElement(Page, { pageTitle = self.props.pageTitle, }, children) end function InviteFriendsPage:didMount() self.mounted = true self:loadFriends() end function InviteFriendsPage:loadFriends() Promise.new(function(resolve, reject) coroutine.wrap(function() local localPlayer = Players.LocalPlayer local success, friendsPages = pcall(function() return Players:GetFriendsAsync(localPlayer.UserId) end) if not success then reject("Error loading friends") return end local friends = {} while true do for _, item in ipairs(friendsPages:GetCurrentPage()) do friends[#friends+1] = { IsOnline = item.IsOnline, Id = item.Id, Username = item.Username, DisplayName = item.DisplayName, } end if not friendsPages.IsFinished then success = pcall(function() friendsPages:AdvanceToNextPageAsync() end) if not success then reject("Error loading friends") return end else break end end resolve(friends) end)() end):andThen(function(friends) if self.mounted then self:setState({ loadingFriends = false, friends = friends }) end end):catch(function() if self.mounted then self:setState({ loadingFriends = false, loadingFriendsError = true, }) end end) end function InviteFriendsPage:willUnmount() self.mounted = false end return InviteFriendsPage
--------------------------------------------------------------------- -- SF Compiler. -- Compiles code into an uninitialized Instance. --------------------------------------------------------------------- SF.Compiler = {} --- Preprocesses and Compiles code and returns an Instance -- @param code Either a string of code, or a {path=source} table -- @param context The context to use in the resulting Instance -- @param mainfile If code is a table, this specifies the first file to parse. -- @param player The "owner" of the instance -- @param data The table to set instance.data to. Default is a new table. -- @param dontpreprocess Set to true to skip preprocessing -- @return True if no errors, false if errors occured. -- @return The compiled instance, or the error message. function SF.Compiler.Compile ( code, context, mainfile, player, data, dontpreprocess ) if type( code ) == "string" then mainfile = mainfile or "generic" code = { mainfile = code } end local instance = setmetatable( {}, SF.Instance ) data = data or {} instance.player = player instance.env = setmetatable( {}, context.env ) instance.env._G = instance.env instance.data = data instance.ppdata = {} instance.ops = 0 instance.hooks = {} instance.scripts = {} instance.source = code instance.initialized = false instance.context = context instance.mainfile = mainfile -- Add local libraries for k, v in pairs( context.libs ) do instance.env[ k ] = setmetatable( {}, v ) end -- Call onLoad functions for k, v in pairs( context.env.__index ) do if type( v ) == "table" then local meta = debug.getmetatable( v ) if meta.onLoad then meta.onLoad( instance ) end end end for k, v in pairs( context.libs ) do if type( v ) == "table" then if v.onLoad then v.onLoad( instance ) end end end for filename, source in pairs( code ) do if not dontpreprocess then SF.Preprocessor.ParseDirectives( filename, source, context.directives, instance.ppdata, instance ) else print( "No preprocess" ) end if string.match( source, "^[%s\n]*$" ) then -- Lua doesn't have empty statements, so an empty file gives a syntax error instance.scripts[ filename ] = function () end else local func = CompileString( source, "SF:"..filename, false ) if type( func ) == "string" then return false, func end debug.setfenv( func, instance.env ) instance.scripts[ filename ] = func end end return true, instance end
--[[ Enumerated state of the purchase prompt ]] local createEnum = require(script.Parent.createEnum) local PromptState = createEnum("PromptState", { "None", "PremiumUpsell", "RobuxUpsell", "PromptPurchase", "PurchaseInProgress", "UpsellInProgress", "AdultConfirmation", "U13PaymentModal", "U13MonthlyThreshold1Modal", "RequireEmailVerification", "U13MonthlyThreshold2Modal", "PurchaseComplete", "Error", }) return PromptState
-- Copyright (c) 2021 榆柳松 -- https://github.com/wzhengsen/LuaOOP -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local Config = require("OOP.Config"); local require = require; local rawset = rawset; local type = type; local select = select; local warn = warn or print; local mType = Config.LuaVersion > 5.2 and math.type or type; local integer = Config.LuaVersion > 5.2 and "integer" or "number"; local i18n = require("OOP.i18n"); local EnumBehavior = Config.EnumBehavior; local DefaultEnumIndex = Config.DefaultEnumIndex; local AllEnumerations = require("OOP.Variant.Internal").AllEnumerations; local enum = nil; local auto = DefaultEnumIndex - 1; if Config.Debug then function enum(first,...) if nil == first then auto = auto + 1; return auto; end local isInteger = mType(first) == integer; if isInteger then auto = first; return auto; end auto = DefaultEnumIndex - 1; local fT = type(first); local isString = fT == "string"; assert(isString or fT == "table",i18n"Only integers or strings or tables can be used to generate a enumeration.") if not isString then assert(select("#",...) == 0,i18n"Excess parameters."); end local e = isString and {} or first; if isString then for k,v in ipairs({first,...}) do e[v] = k; end end if EnumBehavior == 2 then AllEnumerations[e] = true; return e; end local _enum = {}; AllEnumerations[_enum] = true; return setmetatable(_enum,{ __index = e, __newindex = function () if EnumBehavior == 0 then warn("You can't edit a enumeration."); elseif EnumBehavior == 1 then error(i18n"You can't edit a enumeration."); end end, __pairs = function()return pairs(e);end }); end else function enum(first,...) if nil == first then auto = auto + 1; return auto; end local isInteger = mType(first) == integer; if isInteger then auto = first; return auto; end auto = DefaultEnumIndex - 1; local isString = type(first) == "string" local e = isString and {} or first; if isString then for k,v in ipairs({first,...}) do e[v] = k; end end AllEnumerations[e] = true; return e; end end rawset(_G,Config.enum,enum);
assert = _G.assert collectgarbage = _G.collectgarbage dofile = _G.dofile error = _G.error getfenv = _G.getfenv getmetatable = _G.getmetatable ipairs = _G.ipairs load = _G.load loadfile = _G.loadfile loadstring = _G.loadstring next = _G.next pairs = _G.pairs pcall = _G.pcall print = _G.print rawequal = _G.rawequal rawget = _G.rawget rawset = _G.rawset select = _G.select setfenv = _G.setfenv setmetatable = _G.setmetatable tonumber = _G.tonumber tostring = _G.tostring type = _G.type unpack = _G.unpack xpcall = _G.xpcall module = _G.module require = _G.require _VERSION = "string" _M = {}
data:extend({ { type = "recipe", name = "ground-telescope", category = "satellite-crafting", enabled = false, ingredients = { {"steel-plate", 2000}, {"concrete", 1000}, {"pipe", 1000}, {"processing-unit", 500}, {"electric-engine-unit", 1000}, {"telescope-components", 1}, }, energy_required = 180, result = "ground-telescope", }, })
hook.Add( "PopulateEntities", "AddEntityContent", function( pnlContent, tree, node ) local Categorised = {} -- Add this list into the tormoil local SpawnableEntities = list.Get( "SpawnableEntities" ) if ( SpawnableEntities ) then for k, v in pairs( SpawnableEntities ) do v.Category = v.Category or "Other" Categorised[ v.Category ] = Categorised[ v.Category ] or {} table.insert( Categorised[ v.Category ], v ) end end -- -- Add a tree node for each category -- for CategoryName, v in SortedPairs( Categorised ) do -- Add a node to the tree local node = tree:AddNode( CategoryName, "icon16/bricks.png" ); -- When we click on the node - populate it using this function node.DoPopulate = function( self ) -- If we've already populated it - forget it. if ( self.PropPanel ) then return end -- Create the container panel self.PropPanel = vgui.Create( "ContentContainer", pnlContent ) self.PropPanel:SetVisible( false ) self.PropPanel:SetTriggerSpawnlistChange( false ) for k, ent in SortedPairsByMemberValue( v, "PrintName" ) do spawnmenu.CreateContentIcon( ent.ScriptedEntityType or "entity", self.PropPanel, { nicename = ent.PrintName or ent.ClassName, spawnname = ent.ClassName, material = "entities/"..ent.ClassName..".png", admin = ent.AdminOnly }) end end -- If we click on the node populate it and switch to it. node.DoClick = function( self ) self:DoPopulate() pnlContent:SwitchPanel( self.PropPanel ); end end -- Select the first node local FirstNode = tree:Root():GetChildNode( 0 ) if ( IsValid( FirstNode ) ) then FirstNode:InternalDoClick() end end ) spawnmenu.AddCreationTab( "#spawnmenu.category.entities", function() local ctrl = vgui.Create( "SpawnmenuContentPanel" ) ctrl:CallPopulateHook( "PopulateEntities" ); return ctrl end, "icon16/bricks.png", 20 )
local Ans = select(2, ...); local TUJDB = Ans.Database.TUJ; local TSMDB = Ans.Database.TSM; local Sources = Ans.Sources; local Utils = Ans.Utils; local Data = Ans.Data; local Filter = Ans.Filter; local AHTabs = {}; local AHTabIndexToTab = {}; AnsCore = {}; AnsCore.__index = AnsCore; Ans.Filters = {}; AnsCore.API = Ans; local AH_TAB_CLICK = nil; StaticPopupDialogs["ANS_NO_PRICING"] = { text = "Looks like, you have no data pricing source! TheUndermineJournal, TSM, AnsAuctionData, and Auctionator are currently supported.", button1 = "OKAY", OnAccept = function() end, timeout = 0, whileDead = false, hideOnEscape = true, preferredIndex = 3 }; --local function AHTabClick(self, button, down) -- AH_TAB_CLICK(self, button, down); -- AnsCore:AHTabClick(self, button, down); --end local TUJOnlyPercentFn = "tujmarket"; local TSMOnlyPercentFn = "dbmarket"; local TUJAndTSMPercentFn = "min(dbmarket,tujmarket)"; local ATRPercentFn = "atrvalue"; local ATRTSMPercentFn = "min(atrvalue,dbmarket)"; local ATRTUJPercentFn = "min(atrvalue,tujmarket)"; local AnsOnlyPercentFn = "ansmarket"; function AnsCore:AddAHTab(name, displayMode) local n = #AuctionHouseFrame.Tabs + 1; local lastTab = AuctionHouseFrame.Tabs[n - 1]; local framename = "AuctionHouseFrameTab"..n; local frame = CreateFrame("BUTTON", framename, AuctionHouseFrame, "AuctionHouseFrameDisplayModeTabTemplate"); frame:SetID(n); frame:SetText(name); frame:SetNormalFontObject(_G["AnsFontOrange"]); frame:SetPoint("LEFT", lastTab, "RIGHT", -15, 0); frame.displayMode = displayMode; frame:HookScript("OnClick", function() AuctionHouseFrame:SetTitle(name) end); tinsert(AuctionHouseFrame.Tabs, frame); AuctionHouseFrame.tabsForDisplayMode[displayMode] = n; PanelTemplates_SetNumTabs(AuctionHouseFrame, n); end function AnsCore:RegisterEvents(frame) frame:RegisterEvent("VARIABLES_LOADED"); end function AnsCore:EventHandler(frame, event, ...) if (event == "VARIABLES_LOADED") then self:OnLoad(); end; end function AnsCore:OnLoad() self:MigrateGlobalSettings(); self:CreateDefaultFilters(); self:MigrateCustomFilters(); self:RegisterPriceSources(); self:LoadFilters(); self:LoadCustomVars(); end function AnsCore:RegisterPriceSources() local tsmEnabled = false; local tujEnabled = false; local ansEnabled = false; local auctionatorEnabled = false; if (Utils:IsAddonEnabled("Auctionator") and Atr_GetAuctionBuyout) then auctionatorEnabled = true; end if (TSM_API or TSMAPI) then tsmEnabled = true; end if (AnsAuctionData) then ansEnabled = true; end if (TUJMarketInfo) then tujEnabled = true; end if (tujEnabled and tsmEnabled and ANS_GLOBAL_SETTINGS.percentFn:len() == 0) then print("AnS: setting default tuj and tsm percent fn"); ANS_GLOBAL_SETTINGS.percentFn = TUJAndTSMPercentFn; elseif (tujEnabled and not tsmEnabled and not auctionatorEnabled and ANS_GLOBAL_SETTINGS.percentFn:len() == 0) then print("AnS: setting default tuj percent fn"); ANS_GLOBAL_SETTINGS.percentFn = TUJOnlyPercentFn; elseif (tsmEnabled and not tujEnabled and not auctionatorEnabled and ANS_GLOBAL_SETTINGS.percentFn:len() == 0) then print("AnS: setting default tsm percent fn"); ANS_GLOBAL_SETTINGS.percentFn = TSMOnlyPercentFn; elseif (auctionatorEnabled and not tsmEnabled and not tujEnabled and ANS_GLOBAL_SETTINGS.percentFn:len() == 0) then print("AnS: setting default auctionator percent fn"); ANS_GLOBAL_SETTINGS.percentFn = ATRPercentFn; elseif (auctionatorEnabled and tujEnabled and not tsmEnabled and ANS_GLOBAL_SETTINGS.percentFn:len() == 0) then print("AnS: setting default auctionator and tuj percent fn"); ANS_GLOBAL_SETTINGS.percentFn = ATRTUJPercentFn; elseif (auctionatorEnabled and tsmEnabled and not tujEnabled and ANS_GLOBAL_SETTINGS.percentFn:len() == 0) then print("AnS: setting default auctionator and tsm percent fn"); ANS_GLOBAL_SETTINGS.percentFn = ATRTSMPercentFn; elseif (ansEnabled and ANS_GLOBAL_SETTINGS.percentFn:len() == 0) then print("AnS: setting default AnsAuctionData percent fn"); ANS_GLOBAL_SETTINGS.percentFn = AnsOnlyPercentFn; end if (not tsmEnabled and not tujEnabled and not auctionatorEnabled and not ansEnabled) then StaticPopup_Show("ANS_NO_PRICING"); end if (tsmEnabled) then print("AnS: found TSM pricing source"); Sources:Register("DBMarket", TSMDB.GetPrice, "marketValue"); Sources:Register("DBMinBuyout", TSMDB.GetPrice, "minBuyout"); Sources:Register("DBHistorical", TSMDB.GetPrice, "historical"); Sources:Register("DBRegionMinBuyoutAvg", TSMDB.GetPrice, "regionMinBuyout"); Sources:Register("DBRegionMarketAvg", TSMDB.GetPrice, "regionMarketValue"); Sources:Register("DBRegionHistorical", TSMDB.GetPrice, "regionHistorical"); Sources:Register("DBRegionSaleAvg", TSMDB.GetPrice, "regionSale"); Sources:Register("DBRegionSaleRate", TSMDB.GetSaleInfo, "regionSalePercent"); Sources:Register("DBRegionSoldPerDay", TSMDB.GetSaleInfo, "regionSoldPerDay"); Sources:Register("DBGlobalMinBuyoutAvg", TSMDB.GetPrice, "globalMinBuyout"); Sources:Register("DBGlobalMarketAvg", TSMDB.GetPrice, "globalMarketValue"); Sources:Register("DBGlobalHistorical", TSMDB.GetPrice, "globalHistorical"); Sources:Register("DBGlobalSaleAvg", TSMDB.GetPrice, "globalSale"); Sources:Register("DBGlobalSaleRate", TSMDB.GetSaleInfo, "globalSalePercent"); Sources:Register("DBGlobalSoldPerDay", TSMDB.GetSaleInfo, "globalSoldPerDay"); end if (tujEnabled) then print("AnS: found TUJ pricing source"); Sources:Register("TUJMarket", TUJDB.GetPrice, "market"); Sources:Register("TUJRecent", TUJDB.GetPrice, "recent"); Sources:Register("TUJGlobalMedian", TUJDB.GetPrice, "globalMedian"); Sources:Register("TUJGlobalMean", TUJDB.GetPrice, "globalMean"); Sources:Register("TUJAge", TUJDB.GetPrice, "age"); Sources:Register("TUJDays", TUJDB.GetPrice, "days"); Sources:Register("TUJStdDev", TUJDB.GetPrice, "stddev"); Sources:Register("TUJGlobalStdDev", TUJDB.GetPrice, "globalStdDev"); end if (ansEnabled) then print("AnS: found AnS pricing source"); Sources:Register("ANSRecent", AnsAuctionData.GetRealmValue, "recent"); Sources:Register("ANSMarket", AnsAuctionData.GetRealmValue, "market"); Sources:Register("ANSMin", AnsAuctionData.GetRealmValue, "min"); Sources:Register("ANS3Day", AnsAuctionData.GetRealmValue, "3day"); --Sources:Register("ANSRegionRecent", AnsAuctionData.GetRegionValue, "recent"); --Sources:Register("ANSRegionMarket", AnsAuctionData.GetRegionValue, "market"); --Sources:Register("ANSRegionMin", AnsAuctionData.GetRegionValue, "min"); --Sources:Register("ANSRegion3Day", AnsAuctionData.GetRegionValue, "3day"); end if (auctionatorEnabled) then print("AnS: found Auctionator pricing source"); Sources:Register("AtrValue", Atr_GetAuctionBuyout, nil); end end function AnsCore:LoadCustomVars() ANS_CUSTOM_VARS = ANS_CUSTOM_VARS or {}; Sources:ClearCache(); Sources:LoadCustomVars(); end function AnsCore:LoadFilters() wipe(Ans.Filters); for i, f in ipairs(ANS_FILTERS) do local filter = Filter:New(f.name); filter.priceFn = f.priceFn; filter.useGlobalMaxBuyout = f.useMaxPPU; filter.useGlobalMinILevel = f.useMinLevel; filter.useGlobalMinQuality = f.useQuality; filter.useGlobalPercent = f.usePercent; if (f.exactMatch == nil) then filter.exactMatch = true; else filter.exactMatch = f.exactMatch; end filter:ParseTSM(f.ids); if (#f.children > 0) then self:LoadSubFilters(f.children, filter); end tinsert(Ans.Filters, filter); end end function AnsCore:LoadSubFilters(filters, parent) for i, f in ipairs(filters) do local filter = Filter:New(f.name); filter.priceFn = f.priceFn; filter.useGlobalMaxBuyout = f.useMaxPPU; filter.useGlobalMinILevel = f.useMinLevel; filter.useGlobalMinQuality = f.useQuality; filter.useGlobalPercent = f.usePercent; if (f.exactMatch == nil) then filter.exactMatch = true; else filter.exactMatch = f.exactMatch; end filter:ParseTSM(f.ids); parent:AddChild(filter); -- probably should do this as a stack -- but for now will do recursive if (#f.children > 0) then self:LoadSubFilters(f.children, filter); end end end function AnsCore:MigrateGlobalSettings() if (ANS_GLOBAL_SETTINGS.rescanTime == nil) then ANS_GLOBAL_SETTINGS.rescanTime = 0; end if (ANS_GLOBAL_SETTINGS.showDressing == nil) then ANS_GLOBAL_SETTINGS.showDressing = false; end if (ANS_GLOBAL_SETTINGS.dingSound == nil) then ANS_GLOBAL_SETTINGS.dingSound = true; end if (ANS_GLOBAL_SETTINGS.scanDelayTime == nil) then ANS_GLOBAL_SETTINGS.scanDelayTime = 5; end if (ANS_GLOBAL_SETTINGS.characterBlacklist == nil) then ANS_GLOBAL_SETTINGS.characterBlacklist = ""; end if (ANS_GLOBAL_SETTINGS.useCoinIcons == nil) then ANS_GLOBAL_SETTINGS.useCoinIcons = false; end if (ANS_GLOBAL_SETTINGS.itemsPerUpdate == nil) then ANS_GLOBAL_SETTINGS.itemsPerUpdate = 20; end if (ANS_GLOBAL_SETTINGS.itemBlacklist == nil) then ANS_GLOBAL_SETTINGS.itemBlacklist = {}; end if (ANS_GLOBAL_SETTINGS.useCommodityConfirm == nil) then ANS_GLOBAL_SETTINGS.useCommodityConfirm = false; end if (ANS_GLOBAL_SETTINGS.tooltipRealm3Day == nil) then ANS_GLOBAL_SETTINGS.tooltipRealm3Day = true; end if (ANS_GLOBAL_SETTINGS.tooltipRealmMarket == nil) then ANS_GLOBAL_SETTINGS.tooltipRealmMarket = true; end if (ANS_GLOBAL_SETTINGS.tooltipRealmRecent == nil) then ANS_GLOBAL_SETTINGS.tooltipRealmRecent = true; end if (ANS_GLOBAL_SETTINGS.tooltipRealmMin == nil) then ANS_GLOBAL_SETTINGS.tooltipRealmMin = true; end end function AnsCore:MigrateCustomFilters() ANS_CUSTOM_FILTERS = ANS_CUSTOM_FILTERS or {}; if (#ANS_CUSTOM_FILTERS > 0) then for i, v in ipairs(ANS_CUSTOM_FILTERS) do local t = { name = v.name, ids = v.ids, children = {}, useMaxPPU = false, useMinLevel = false, useQuality = false, usePercent = true, exactMatch = true, priceFn = v.priceFn }; tinsert(ANS_FILTERS, t); end end -- migrating away from custom filters -- and combined them with all filters ANS_CUSTOM_FILTERS = {}; end function AnsCore:RestoreDefaultFilters() self:RestoreFilter(Data, ANS_FILTERS); end function AnsCore:RestoreFilter(children, parent) for i,v in ipairs(children) do local restored = false; for i2, v2 in ipairs(parent) do if (v2.name == v.name) then v2.ids = v.ids; v2.useMaxPPU = v.useMaxPPU; v2.useMinLevel = v.useMinLevel; v2.useQuality = v.useQuality; v2.usePercent = v.usePercent; v2.priceFn = v.priceFn; v2.exactMatch = v.exactMatch; if (v.children and #v.children > 0) then self:RestoreFilter(v.children, v2.children); end restored = true; break; end end if (not restored) then self:PopulateFilter(v, parent); end end end function AnsCore:CreateDefaultFilters() if (not ANS_BASE_SELECTION) then ANS_BASE_SELECTION = {}; end if (not ANS_FILTERS or #ANS_FILTERS == 0) then ANS_FILTERS = {}; -- reset filter selection as a new method will now -- be used ANS_FILTER_SELECTION = {}; self:RestoreFilter(Data, ANS_FILTERS); end end function AnsCore:PopulateFilter(v, parent) local t = { name = v.name, ids = v.ids, children = {}, useMaxPPU = v.useMaxPPU, useMinLevel = v.useMinLevel, useQuality = v.useQuality, usePercent = v.usePercent, exactMatch = v.exactMatch, priceFn = v.priceFn }; if (v.children and #v.children > 0) then for i2, v2 in ipairs(v.children) do self:PopulateFilter(v2, t.children); end end tinsert(parent, t); end
-- Grab all of the functions and classes from our GUI library local info = debug.getinfo(1,'S'); script_path = info.source:match[[^@?(.*[\/])[^\/]-$]] GUI = dofile(script_path .. "ultraschall_gui_lib.lua") gfx_path=script_path.."/Ultraschall_Gfx/ColorPicker/" -- All functions in the GUI library are now contained in the GUI table, -- so they can be accessed via: GUI.function(params) ---- Window settings and user functions ---- GUI.name = "Ultraschall Color Picker" GUI.x, GUI.y, GUI.w, GUI.h = 100, 200, 235, 175 ----------------------- -- Step 1 : get started ----------------------- max_color = 20 -- Number of colors to cycle curtheme = reaper.GetLastColorThemeFile() os = reaper.GetOS() --------------------------------------------------------- -- Step 2 : build table with color values from theme file --------------------------------------------------------- t = {} -- initiate table file = io.open(curtheme, "r"); for line in file:lines() do index = string.match(line, "group_(%d+)") -- use "Group" section index = tonumber(index) if index then if index < max_color then color_int = string.match(line, "=(%d+)") -- get the color value if string.match(os, "OS") then r, g, b = reaper.ColorFromNative(color_int) color_int = reaper.ColorToNative(b, g, r) -- swap r and b for Mac end t[index] = tonumber(color_int) -- put color into table end end end -- for key,value in pairs(t) do Msg(value) end function gentle_rainboom(url) local id = reaper.NamedCommandLookup("_Ultraschall_Set_Colors_To_Sonic_Rainboom") reaper.Main_OnCommand(id,0) end function spread_rainboom(url) local id = reaper.NamedCommandLookup("_Ultraschall_Set_Colors_To_Sonic_Rainboom_Spread") reaper.Main_OnCommand(id,0) end function debug() gfx.set(1, 0.5, 0.5, 1) gfx.circle(10, 10, 20, 1) end -- body ---- GUI Elements ---- GUI.elms = { -- name = element type x y w h caption ...other params... colors = GUI.ColorPic:new( 4, 4, 170, 170, t), col1 = GUI.Pic:new( 190,4, 42, 83, 1, gfx_path.."us_col1.png", gentle_rainboom, ""), col2 = GUI.Pic:new( 190,88, 42, 83, 1, gfx_path.."us_col2.png", spread_rainboom, ""), -- label = GUI.Lbl:new( 0, 160, "Ultraschall was sucsessfully installed.", 0), -- label2 = GUI.Lbl:new( 135, 200, "Visit the Podcast menu to explore the user interface and features.", 0), -- label3 = GUI.Lbl:new( 210, 220, "Use Project templates for a quick setup.", 0), -- label4 = GUI.Lbl:new( 265, 290, "If you need assistance:", 0), -- label3 = GUI.Lbl:new( 455, 290, "Visit our support forum:", 0), -- pan_sldr = GUI.Sldr:new( 360, 280, 128, "Pan:", -100, 100, 200, 4), -- pan_knb = GUI.Knob:new( 530, 100, 48, "Awesomeness", 0, 9, 11, 5, 1), -- label2 = GUI.Lbl:new( 508, 42, "Awesomeness", 0), -- options = GUI.OptLst:new( 50, 100, 150, 150, "Color notes by:", "Channel,Pitch,Velocity,Penis Size", 4), -- blah = GUI.OptLst:new( 50, 260, 250, 200, "I have a crush on:", "Justin F,schwa,X-Raym,Jason Brian Merrill,pipelineaudio,Xenakios", 2, 0), -- newlist = GUI.ChkLst:new( 210, 100, 120, 150, "I like to eat:", "Fruit,Veggies,Meat,Dairy", 4), -- checkers = GUI.Checklist:new( 20, 380, 240, 30, "", "Show this Screen on Start", 4), -- tutorials = GUI.Btn:new( 30, 320, 190, 40, "Tutorials", open_url, "http://ultraschall.fm/tutorials/"), -- twitter = GUI.Btn:new( 242, 320, 190, 40, "Twitter", open_url, "https://twitter.com/ultraschall_fm"), -- forum = GUI.Btn:new( 455, 320, 190, 40, "Userforum", open_url, "https://sendegate.de/c/ultraschall"), -- label4 = GUI.Lbl:new( 300, 400, "Have fun!", 0), --testbtn2 = GUI.Btn:new( 450, 100, 100, 50, "CLICK", userfunc, "This|#Is|A|!Menu"), -- newtext = GUI.TxtBox:new( 340, 210, 200, 30, "Favorite music player:", 4), } ---- Put all of your own functions and whatever here ---- --Msg("hallo") --GUI.func = drawcolors(t) -- GUI.func = debug() -- GUI.freq = 0 ---- Main loop ---- --[[ If you want to run a function during the update loop, use the variable GUI.func prior to starting GUI.Main() loop: GUI.func = my_function GUI.freq = 5 <-- How often in seconds to run the function, so we can avoid clogging up the CPU. - Will run once a second if no value is given. - Integers only, 0 will run every time. GUI.Init() GUI.Main() ]]-- -- local startscreen = GUI.val("checkers") -- local startscreen = GUI.elms.checkers[GUI.Val()] -- Open Colorpicker, when it hasn't been opened yet if reaper.GetExtState("Ultraschall_Windows", GUI.name) == "" then windowcounter=0 -- Check if window was ever opened yet(and external state for it exists already). -- If yes, use temporarily 0 as opened windows-counter;will be changed by ultraschall_gui_lib.lua later else windowcounter=tonumber(reaper.GetExtState("Ultraschall_Windows", GUI.name)) end -- get number of opened windows if windowcounter<1 then -- you can choose how many GUI.name-windows are allowed to be opened at the same time. -- 1 means 1 window, 2 means 2 windows, 3 means 3 etc GUI.Init() GUI.Main() end function atexit() reaper.SetExtState("Ultraschall_Windows", GUI.name, 0, false) end reaper.atexit(atexit)
data:extend({ { type = "bool-setting", name = "autocolor_on", setting_type = "runtime-per-user", default_value = false, order = "a" }, { type = "double-setting", name = "autocolor_r", setting_type = "runtime-per-user", minimum_value = 0, maximum_value = 255, default_value = 0, -- As is the default color order = "b" }, { type = "double-setting", name = "autocolor_g", setting_type = "runtime-per-user", minimum_value = 0, maximum_value = 255, default_value = 0, -- As is the default color order = "c" }, { type = "double-setting", name = "autocolor_b", setting_type = "runtime-per-user", minimum_value = 0, maximum_value = 255, default_value = 0, -- As is the default color order = "d" }, { type = "double-setting", name = "autocolor_a", setting_type = "runtime-per-user", minimum_value = 0, maximum_value = 255, default_value = 127, -- As is the default color order = "e" }, })
gfx.initialize = function() gfx.create_context({alpha = true}) gfx.clear_color(0.0, 0.0, 0.0, 1.0) vertices = gfx.array.new(gfx.FLOAT, 0.0, 0.5, 0.0, -0.5, -0.5, 0.0, 0.5, -0.5, 0.0) vertexPosObject = gfx.gen_buffers(1) gfx.bind_buffer(gfx.ARRAY_BUFFER, vertexPosObject) gfx.buffer_data(gfx.ARRAY_BUFFER, 9*4, vertices, gfx.STATIC_DRAW) vss = "attribute vec4 vPosition; void main() { gl_Position = vPosition; }" vs = gfx.create_shader(gfx.VERTEX_SHADER, vss) fss = "precision mediump float; void main() { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }" fs = gfx.create_shader(gfx.FRAGMENT_SHADER, fss) program = gfx.create_program(vs, fs) w, h = gfx.canvas_size() gfx.viewport(0, 0, w, h) gfx.clear(gfx.COLOR_BUFFER_BIT) gfx.use_program(program) gfx.bind_buffer(gfx.ARRAY_BUFFER, vertexPosObject) gfx.vertex_attrib_pointer(0, 3, gfx.FLOAT, 0, 0, 0) gfx.enable_vertex_attrib_array(0) gfx.draw_arrays(gfx.TRIANGLES, 0, 3) end
-- AICharacter: TankClose -------------------------------------------------------------------------- -- Crytek Source File. -- Copyright (C), Crytek Studios, 2001-2004. -------------------------------------------------------------------------- -- $Id$ -- $DateTime$ -- Description: Character SCRIPT for Tank -- -------------------------------------------------------------------------- -- History: -- - 06/02/2005 : Created by Kirill Bulatsev -- - 10/07/2006 : Dulplicated for the special tank by Tetsuji -- -------------------------------------------------------------------------- AICharacter.TankClose = { Constructor = function(self,entity) -- entity.AI.DesiredFireDistance[1] = 30; -- main gun -- entity.AI.DesiredFireDistance[2] = 6; -- secondary machine gun entity.AI.weaponIdx = 1; --temp: select main gun by default end, AnyBehavior = { STOP_VEHICLE = "TankCloseIdle", }, TankCloseIdle = { ----------------------------------- ACT_GOTO = "TankCloseGoto", STOP_VEHICLE = "", VEHICLE_GOTO_DONE = "", TO_TANKCLOSE_ATTACK = "TankCloseAttack", TO_TANKCLOSE_GOTOPATH = "TankCloseGotoPath", TO_TANKCLOSE_SWITCHPATH = "TankCloseSwitchPath", TO_TANKCLOSE_RUNAWAY = "TankCloseRunAway", TO_TANKCLOSE_IDLE = "", OnEnemySeen = "", }, TankCloseGoto = { ----------------------------------- ACT_GOTO = "", STOP_VEHICLE = "TankCloseIdle", VEHICLE_GOTO_DONE = "TankCloseIdle", TO_TANKCLOSE_ATTACK = "", TO_TANKCLOSE_GOTOPATH = "", TO_TANKCLOSE_SWITCHPATH = "TankCloseSwitchPath", TO_TANKCLOSE_RUNAWAY = "TankCloseRunAway", TO_TANKCLOSE_IDLE = "", OnEnemySeen = "TankCloseAttack", }, TankCloseAttack = { ----------------------------------- ACT_GOTO = "", STOP_VEHICLE = "TankCloseIdle", VEHICLE_GOTO_DONE = "TankCloseIdle", TO_TANKCLOSE_ATTACK = "", TO_TANKCLOSE_GOTOPATH = "", TO_TANKCLOSE_SWITCHPATH = "TankCloseSwitchPath", TO_TANKCLOSE_RUNAWAY = "TankCloseRunAway", TO_TANKCLOSE_IDLE = "", OnEnemySeen = "", }, TankCloseGotoPath = { ----------------------------------- ACT_GOTO = "", STOP_VEHICLE = "TankCloseIdle", VEHICLE_GOTO_DONE = "TankCloseIdle", TO_TANKCLOSE_ATTACK = "", TO_TANKCLOSE_GOTOPATH = "", TO_TANKCLOSE_SWITCHPATH = "TankCloseSwitchPath", TO_TANKCLOSE_RUNAWAY = "TankCloseRunAway", TO_TANKCLOSE_IDLE = "TankCloseIdle", OnEnemySeen = "TankCloseAttack", }, TankCloseSwitchPath = { ----------------------------------- ACT_GOTO = "", STOP_VEHICLE = "TankCloseIdle", VEHICLE_GOTO_DONE = "TankCloseIdle", TO_TANKCLOSE_ATTACK = "TankCloseAttack", TO_TANKCLOSE_GOTOPATH = "", TO_TANKCLOSE_SWITCHPATH = "", TO_TANKCLOSE_RUNAWAY = "TankCloseRunAway", TO_TANKCLOSE_IDLE = "TankCloseIdle", OnEnemySeen = "", }, TankCloseRunAway = { ----------------------------------- ACT_GOTO = "", STOP_VEHICLE = "TankCloseIdle", VEHICLE_GOTO_DONE = "TankCloseIdle", TO_TANKCLOSE_ATTACK = "", TO_TANKCLOSE_GOTOPATH = "", TO_TANKCLOSE_SWITCHPATH = "", TO_TANKCLOSE_RUNAWAY = "", TO_TANKCLOSE_IDLE = "TankCloseIdle", OnEnemySeen = "", }, }
------------------------------------------- ------------ Global Permissions ----------- ------------------------------------------- -- sh_permissions.lua SHARED -- -- -- -- Set up permissions for multiple Gmod -- -- moderation systems. -- ------------------------------------------- -- Get the most up-to-date version from GitHub: -- https://github.com/MyHatStinks/gmod-global-permissions ---------- You shouldn't need to edit below this line ---------- -- Anything you add below here might not be loaded! -- This number will be incremented when a new permissions system is added -- Should help keep compatibility with other addons using this code -- Format YYYYMMDD.revision local version = 20201123.1 if GlobalPermissions and GlobalPermissions.Version>=version then return end -- Only overwrite if this is newer GlobalPermissions = GlobalPermissions or {} GlobalPermissions.Version = version -- Permission groups GlobalPermissions.GROUP_SUPERADMIN = 0 GlobalPermissions.GROUP_ADMIN = 1 GlobalPermissions.GROUP_ALL = 2 ------------------------ -- Set up permissions -- ------------------------ function GlobalPermissions.SetupPermission( Permission, DefaultGroup, Help, Cat ) hook.Run( "Permission.SetUp", Permission, DefaultGroup, Help, Cat ) -- ULX if ULib and ULib.ucl then if ULib.ucl.registerAccess then local grp = GlobalPermissions.GetULXPermissionGroup(DefaultGroup) or ULib.ACCESS_SUPERADMIN return ULib.ucl.registerAccess( Permission, grp, Help, Cat ) end end -- Evolve if evolve and evolve.privileges then table.Add( evolve.privileges, {Permission} ) table.sort( evolve.privileges ) return end -- Exsto if exsto then exsto.CreateFlag( Permission:lower(), Help ) return end -- Serverguard if serverguard and serverguard.permission then serverguard.permission:Add(Permission) return end -- SAM if sam and sam.permissions and sam.permissions.add then sam.permissions.add( Permission, Cat, GlobalPermissions.GetSAMPermissionGroup(DefaultGroup) ) return end end ----------------------- -- Check permissions -- ----------------------- function GlobalPermissions.HasPermission( ply, Permission, Default ) if not IsValid(ply) then return Default end local hasPermission = hook.Run( "Permission.HasPermission", ply, Permission, Default ) if hasPermission~=nil then return hasPermission end -- ULX if ULib then return ULib.ucl.query( ply, Permission, true ) end -- Evolve if ply.EV_HasPrivilege then return ply:EV_HasPrivilege( Permission ) end -- Exsto if exsto then return ply:IsAllowed( Permission:lower() ) end -- Serverguard if serverguard and serverguard.player then return serverguard.player:HasPermission(ply, Permission) end -- SAM if sam and ply.HasPermission then return ply:HasPermission( Permission ) end return Default end ---------------------- -- Check User Group -- ---------------------- function GlobalPermissions.GetRank( ply ) if not IsValid(ply) then return end local customRank = hook.Run( "Permission.GetRank", ply ) if customRank~=nil then return customRank end -- ULX/SAM if ulx or (sam and sam.permissions) then return ply:GetUserGroup() end -- Exsto if exsto and ply.GetRank then return ply:GetRank() end -- Evolve if ply.EV_GetRank then return ply:EV_GetRank() end -- Serverguard if serverguard and serverguard.player then return serverguard.player:GetRank(ply).name end -- SAM if SAM then end -- Failed: Give a best guess return ply:GetUserGroup() or "user" end ------------------------------- -- Default permission groups -- ------------------------------- local GroupToULX function GlobalPermissions.GetULXPermissionGroup( perm ) if not perm then return ULib.ACCESS_SUPERADMIN end if not GroupToULX then -- Table setup is delayed so ULib can load GroupToULX = { [GlobalPermissions.GROUP_SUPERADMIN] = ULib and ULib.ACCESS_SUPERADMIN, [GlobalPermissions.GROUP_ADMIN] = ULib and ULib.ACCESS_ADMIN, [GlobalPermissions.GROUP_ALL] = ULib and ULib.ACCESS_ALL, } end return GroupToULX[perm] or ULib.ACCESS_SUPERADMIN end local GroupToSAM = { [GlobalPermissions.GROUP_SUPERADMIN] = "superadmin", [GlobalPermissions.GROUP_ADMIN] = "admin", [GlobalPermissions.GROUP_ALL] = "user", } function GlobalPermissions.GetSAMPermissionGroup( perm ) return GroupToSAM[ perm or "" ] or nil end --------------- -- On Loaded -- --------------- hook.Add( "Initialize", "Permission.OnLoad", function() --Short delay, to load after admin mods if not (GlobalPermissions and GlobalPermissions.SetupPermission) then return end --Just in case hook.Run( "Permission.OnLoad" ) end)
--[=[ Utility functions involving field of view. @class FieldOfViewUtility ]=] local ReplicatedStorage = game:GetService("ReplicatedStorage") local Math = require(ReplicatedStorage.Knit.Util.Additions.Math.Math) local FieldOfViewUtility = {} --[=[ Converts field of view to height @param fov number @return number ]=] function FieldOfViewUtility.FovToHeight(fov) return 2*math.tan(math.rad(fov)/2) end --[=[ Converts height to field of view @param height number @return number ]=] function FieldOfViewUtility.HeightToFov(height) return 2*math.deg(math.atan(height/2)) end --[=[ Linear way to log a value so we don't get floating point errors or infinite values @param height number @param linearAt number @return number ]=] function FieldOfViewUtility.SafeLog(height, linearAt) if height < linearAt then local slope = 1/linearAt return slope*(height - linearAt) + math.log(linearAt) else return math.log(height) end end --[=[ Linear way to exponentiate field of view so we don't get floating point errors or infinite values. @param logHeight number @param linearAt number @return number ]=] function FieldOfViewUtility.SafeExp(logHeight, linearAt) local transitionAt = math.log(linearAt) if logHeight <= transitionAt then return linearAt*(logHeight - transitionAt) + linearAt else return math.exp(logHeight) end end local linearAt = FieldOfViewUtility.FovToHeight(1) --[=[ Interpolates field of view in height space, instead of degrees. @param fov0 number @param fov1 number @param percent number @return number -- Fov in degrees ]=] function FieldOfViewUtility.LerpInHeightSpace(fov0, fov1, percent) local height0 = FieldOfViewUtility.FovToHeight(fov0) local height1 = FieldOfViewUtility.FovToHeight(fov1) local logHeight0 = FieldOfViewUtility.SafeLog(height0, linearAt) local logHeight1 = FieldOfViewUtility.SafeLog(height1, linearAt) local newLogHeight = Math.Lerp(logHeight0, logHeight1, percent) return FieldOfViewUtility.HeightToFov(FieldOfViewUtility.SafeExp(newLogHeight, linearAt)) end table.freeze(FieldOfViewUtility) return FieldOfViewUtility
--- -- usage.lua -- Usage and uses -- -- Example -- ------- -- -- usage "vendor" -- defines "USING_VENDOR" -- includedirs "include/vendor" -- links "lib/vendor" -- -- project "core" -- kind "SharedLib" -- uses "vendor" -- uses "core" -- -- usage "core" -- links "openssh" -- includedirs "include/core" -- -- project "app" -- kind "ConsoleApp" -- uses "core" -- -- "core" will link vendor and openssh and define 'USING_VENDOR' -- "app" will link 'core' and define 'USING_VENDOR' -- If "core" was a StaticLib, the link dependencies would pass through. -- "core" will define 'USING_VENDOR' -- "app" would link 'vendor', 'core', and 'openssh' and still define -- 'USING_VENDOR' -- -- Notes -- ----- -- -- 'uses' are recursive. -- -- If a project and usage exist, the project is used first, then the usage. -- -- If a project uses itself, any link dependencies in the usage will be -- consumed by the project as needed. Otherwise those link dependencies -- will pass onto to the user. -- -- Using a project will link the project and resolves nested uses, -- in addition to any declared usage. -- -- "uses" do not respect configurations/filters due to havy optimizations -- "usage" can contain configuration filters require 'stack' local p = premake local oven = p.oven local context = p.context local keyLinks = "links" local field = p.field local fieldLinks = field.get(keyLinks) newoption { trigger = "usage-optimization-off", description = "Turn off optimization for usage module. Useful for debuging dependencies (50% slower generation)." } local optimization = (_OPTIONS["usage-optimization-off"] == nil) --- -- Two stacks which stores actual order of projects and usages -- Projects stack and uses stack are aligned -- local usesStack = Stack:Create() local sourcesStack = Stack:Create() -- -- 'uses' api -- p.api.register { name = "uses", scope = { "config" }, kind = "list:string", } -- -- 'usage' container -- -- TODO: maybe lock down what can be specified in usage further? p.usage = p.api.container("usage", p.workspace, { "config" }) function p.usage.new(mode) return p.container.new(p.usage, mode) end -- -- Extend workspace with findusage -- function p.workspace.findusage(wks, name) name = name:lower() for _, usage in ipairs(wks.usages) do if name == usage.name:lower() then return usage end end return nil end --- -- Push usage and source project name on stack -- * if "usage" is already on stack it mean that "usage" in this configuration was in use, -- local printUsesStack local function pushUsage( usageName, sourceName ) -- search for uses local usesStackIndex = usesStack:find_value(usageName) if usesStackIndex == nil then verbosef("{PUSH} USES_STACK [%s]: %s", sourceName, usageName) -- push on stack usesStack:push(usageName) sourcesStack:push(sourceName) else verbosef("{EXIST} USES_STACK [%s]: %s", sourceName, usageName) end end --- -- Pop usage and source name form stack -- local function popUsage( count ) local count = count or 1 for i = 1, count do -- pop form stack local sourceName = sourcesStack:pop() local usageName = usesStack:pop() verbosef("{POP} USES_STACK [%s]: %s", sourceName, usageName) end end -- -- During baking we can start new bake so we have to stash current stack -- local stackStash = Stack:Create() --- -- During "bake" process it is posible to call another "bake", -- to starts new bake we have to stash current uses stack and create new empty --- local function stashStack() if _OPTIONS["verbose"] then for i , sourceName in ipairs(sourcesStack._et) do verbosef("{STASH} USES_STACK [%s]: %s", sourceName, usesStack:get(i)) end end stackStash:push( {["sourcesStack"] = sourcesStack, ["usesStack"] = usesStack} ) sourcesStack = Stack:Create() usesStack = Stack:Create() end --- -- After "bake" previous uses stack have to be recreated --- local function unstashStack() local stash = stackStash:pop() sourcesStack = stash.sourcesStack usesStack = stash.usesStack if _OPTIONS["verbose"] then for i , sourceName in ipairs(sourcesStack._et) do verbosef("{UNSTASH} USES_STACK [%s]: %s", sourceName, usesStack:get(i)) end end end -- -- Print stack -- printUsesStack = function() -- reconstructed full stack from stashed and current stacks local fullStack = {} -- for formating we need max length of sourceName, it will be first column local maxSourceNameLen = 1 -- get full stack form stashed stacks. form oldest to newest for _, stacks in ipairs(stackStash._et) do if stacks.sourcesStack:getn() > 0 then for i, sourceName in ipairs(stacks.sourcesStack._et) do local len = sourceName:len() if len > maxSourceNameLen then maxSourceNameLen = len end table.insert(fullStack, { ["sourceName"] = sourceName, ["usageName"] = stacks.usesStack:get(i) } ) end end end -- get stack form currect "bake" for i, sourceName in ipairs(sourcesStack._et) do local len = sourceName:len() if len > maxSourceNameLen then maxSourceNameLen = len end table.insert(fullStack, { ["sourceName"] = sourceName, ["usageName"] = usesStack:get(i) } ) end -- print full stack in three columns -- SOURCE: ACRION: USAGE: -- -- Actions: -- BAKES - mean that usage requred "bake" project -- USES - use project or usage print("\nUses stack:\n") local line = string.format("%-" .. maxSourceNameLen .. "s ACRION: USAGE: \n", "SOURCE:") print(line) for _, entry in ipairs(fullStack) do if not entry.sourceName:find('"bake"') then if entry.usageName:find('"bake"') then line = string.format("%-" .. maxSourceNameLen .. "s BAKES %s", entry.sourceName, entry.usageName:gsub('"bake" ', "")) else line = string.format("%-" .. maxSourceNameLen .. "s USES %s", entry.sourceName, entry.usageName) end print(line) end end end --- -- Resolve usage of targetProject.targetBlock -- local function resolveUsage( targetProject, targetBlock, usage ) verbosef("\nProject %s is using usage %s\n", targetProject.name, usage.name) -- Clone each block in the usage and insert it into the target project for _,usageBlock in ipairs(usage.blocks) do -- Merge the criteria for the usage and target -- detach fat references before deepcopy usageOrigin = usageBlock._origin usageBlock._origin = nil local newBlock = table.deepcopy(usageBlock) -- attach fat references after deepcopy newBlock._origin = usageOrigin usageBlock._origin = usageOrigin newBlock._criteria.patterns = table.join( newBlock._criteria.patterns, targetBlock._criteria.patterns ) newBlock._criteria.data = p.criteria._compile(newBlock._criteria.patterns) -- todo: would be nice not to do this. -- needs to be in sync with internal block logic. if newBlock.filename then newBlock.filename = nil newBlock._basedir = newBlock.basedir newBlock.basedir = nil end -- Insert the new block into the target project. -- TODO: We need to insert as if at the call site, -- and it need to deal with with 'removes' -- merging between the two blocks. table.insert( targetProject.blocks, newBlock ) -- Recursion in usage is to fuzzy if newBlock.uses then error("Usage '" .. usage.name .. "'. Uses in usage is forbidden, move 'uses' to project.") end end end --- -- Insert usageName to outTable and push usageName on stack, -- if srcProjectName and usageName are equal push is not performed. -- This is common case and it should be in separeted function -- local function insertUsage( usesTable, usageName, sourceName ) local usagePushed = 0 -- project can use own usage and it is valid use -- without this check we will get error about double push on stack if usageName ~= sourceName then pushUsage( usageName, sourceName ) usagePushed = 1 end table.insert( usesTable, usageName ) return usagePushed end --- -- Manually run "bake" process on source project if need, -- if "bake" on sourceProject is under way this mean that we have circular dependence -- local function bakeProject( sourceProject, targetProject ) -- _isUsageBaking - is flag on project which informs that premake alredy starts "bake" process -- such situation occure with circular dependence if sourceProject._isUsageBaking then printUsesStack() error("Use of " .. "'" .. sourceProject.name .. "' in '" .. targetProject.name .. "'" .." circular dependence!!!" ) else if not sourceProject._usageBaked then verbosef("\nUsage starts baking %s\n", sourceProject.name ) sourceProject._isUsageBaking = true pushUsage( '"bake" ' .. sourceProject.name, targetProject.name ) -- source mark "bake" process on stack if optimization then bakeProjectUsage( sourceProject ) else sourceProject.ctx = p.container.bake(sourceProject) -- bake context is temporary in current version of premake5, we have to store it sourceProject._isBaked = false -- premake5 thinks that object was not baked end popUsage() sourceProject._isUsageBaking = false sourceProject._usageBaked = true verbosef("\nUsage ends baking %s\n", sourceProject.name ) end end end --- -- Resolve a sourceProject 'uses' into a target block of a target project -- local resolveUse local function resolveUses( sourceProject, targetProject, targetBlock ) if optimization then local targetProjectResolvedUses = targetProject.resolvedUses -- get table of already resolved uses for this projects local sourceProjectResolvedUses = sourceProject.resolvedUses local sourceProjectName = sourceProject.name local targetBlockResolvedUsesLinks = targetBlock.resolvedUsesLinks -- Iterate over the source project uses for usageName,usageInfo in pairs(sourceProjectResolvedUses) do -- project can use own usage and it is valid use -- without this check we will get error about double push on stack if usageName ~= usageInfo.parent then pushUsage( '"bake" ' .. usageInfo.parent, '???' ) pushUsage( usageName, usageInfo.parent ) popUsage(2) end if not targetProjectResolvedUses[usageName] then usage = usageInfo.block -- sourceProject include own usage if usage then resolveUsage( targetProject, targetBlock, usage ) end if usageInfo.type == "project" then -- When referring to a project, 'uses' acts like 'links' too. table.insert(targetBlockResolvedUsesLinks, usageName ) end targetProjectResolvedUses[usageName] = usageInfo end end else local pushCount = 0 -- Store feched uses for future usage if sourceProject.ctx.usesValues == nil then sourceProject.ctx.usesValues = context.fetchvalue( sourceProject.ctx, 'uses' ) end local usesToResolve = {} -- push all uses on stack before resolve, it guranty that all uses on current level are before uses are resolved -- this is essential for duplicated uses detection for k,v in ipairs(sourceProject.ctx.usesValues ) do if type(v) == "table" then for _, vName in ipairs(v) do pushCount = pushCount + insertUsage( usesToResolve, vName, sourceProject.name ) end else pushCount = pushCount + insertUsage( usesToResolve, v, sourceProject.name ) end end -- Iterate over the source project uses' for _,v in ipairs(usesToResolve) do if v == sourceProject.name then if not usage then error( "Project " .. sourceProject.name .. " used itself but declares no usage") end else resolveUse( targetProject, targetBlock, v ) end end if pushCount > 0 then popUsage(pushCount) end end end --- -- Resolve a single 'use' into a target block of a target project -- resolveUse = function( targetProject, targetBlock, usageName ) -- get table of already resolved uses for this projects local resolvedUses = targetProject.resolvedUses local usageType = "project" local usageScriptPath = "" -- if use already resolved SKIP it if not resolvedUses[usageName] then local targetWorkspace = targetProject.solution local sourceProject = p.workspace.findproject( targetWorkspace, usageName ) local usage = p.workspace.findusage( targetWorkspace, usageName ) if sourceProject ~= nil and sourceProject.name ~= targetProject.name then verbosef("\nProject %s is using project %s\n", targetProject.name, sourceProject.name ) -- The source project might not be baked yet, bake it now. -- We need this for the context. bakeProject( sourceProject, targetProject ) resolveUses( sourceProject, targetProject, targetBlock ) -- sourceProject include own usage if usage then resolveUsage( targetProject, targetBlock, usage ) end -- When referring to a project, 'uses' acts like 'links' too. table.insert(targetBlock.resolvedUsesLinks, usageName ) usageType = "project" usageScriptPath = sourceProject.script elseif usage ~= nil then resolveUsage( targetProject, targetBlock, usage ) usageType = "usage" usageScriptPath = usage.script elseif sourceProject ~= nil then error( "Project " .. sourceProject.name .. " used itself but declares no usage") else -- throw an error on Windows and keep going on Linux local isLinux = ( package.config:sub(1,1) == '/' ) local messageText = "Use of " .. "'" .. usageName.. "'" .. ", is not defined as a usage or project in workspace " .. "'" .. targetWorkspace.name .. "'" .. " for " .. targetProject.name if isLinux then print( messageText ) return else error( messageText ) end end resolvedUses[usageName] = { ["type"] = usageType, ["script"] = usageScriptPath, ["block"] = usage, ["parent"] = targetProject.name } end end --- -- Resolve all uses from a target block in a target project -- local function resolveAllUsesInBlock( targetProject, targetBlock ) local pushCount = 0 usesToResolve = {} for _, usageKey in ipairs(targetBlock.uses) do if type(usageKey) == "table" then for _, usageName in ipairs(usageKey) do pushCount = pushCount + insertUsage( usesToResolve, usageName, targetProject.name ) end else pushCount = pushCount + insertUsage( usesToResolve, usageKey, targetProject.name ) end end for _, usageName in ipairs(usesToResolve) do resolveUse( targetProject, targetBlock, usageName ) end if pushCount > 0 then popUsage(pushCount) end end -- -- Before baking a project, resolve all the 'uses' -- function bakeProjectUsage( prj ) -- do not resolve "uses" twice if prj.resolvedUses == nil then -- create table of already resolved uses for this projects prj.resolvedUses = {} stashStack() local blocks = {} for k, v in pairs(prj.blocks) do blocks[k] = v end pushUsage( prj.name, '"bake"' ) for _, block in pairs(blocks) do if block.uses then block.resolvedUsesLinks = {} resolveAllUsesInBlock(prj, block) -- When referring to a project, 'uses' acts like 'links' too. block[keyLinks] = field.store( fieldLinks, block[keyLinks], fixOrder( block.resolvedUsesLinks ) ) end end popUsage() unstashStack() end end -- -- Put the linked projects in the right order -- function fixOrder( resolvedUsesLinks ) if next(resolvedUsesLinks) ~= nil then local fixedResolvedUsesLinks = {} for i = #resolvedUsesLinks, 1, -1 do table.insert( fixedResolvedUsesLinks, resolvedUsesLinks[ i ] ) end return fixedResolvedUsesLinks end return resolvedUsesLinks end -- -- Register override -- premake.override(p.project, "bake", function(base, self) bakeProjectUsage(self) return base(self) end)
-- This file is subject to copyright - contact swampservers@gmail.com for more information. -- INSTALL: CINEMA local SERVICE = {} SERVICE.Name = "DLive" SERVICE.NeedsCodecs = true function SERVICE:GetKey(url) if url.host and string.match(url.host, "dlive.tv") and string.match(url.path, "^/([%w_]+)[/]?$") then return url.encoded end return false end if CLIENT then function SERVICE:LoadVideo(Video, panel) local url = "http://swampservers.net/cinema/hls.html" panel:EnsureURL(url) --using a 2 second delay is the fastest way to load the video, sending th_video any quicker is much much slower for whatever reason timer.Simple(2, function() if IsValid(panel) then local str = string.format("th_video('%s',false);", string.JavascriptSafe(Video:Data())) panel:QueueJavascript(str) end end) end end theater.RegisterService('dlive', SERVICE)
local Container = {} Container.__VERSION = "Container 2.0" Container.__AUTHOR = "lettuce-magician" local mt = { __index = Container, __metatable = false } local _cst = {} local function iter_table(tbl, Index) if type(Index) ~= "number" then Index = 0 end Index = Index + 1 local Value = tbl[Index] if Value then return Index, Value end end -- A bit shit but ill fix it later local function MakeMethods(Name) local Methods = _cst[Name]["Methods"] local Storage = _cst[Name]["Storage"] function Methods:Set(Index, Value) assert(type(Index) == "string" or type(Index) == "number", "bad argument #1 to 'Set': string or number expected, got "..type(Index)) assert(Value ~= nil, "cant set nil values") Storage[Index] = Value return Storage[Index] end function Methods:Append(Value) assert(Value ~= nil, "cant append nil values") Storage[#Storage + 1] = Value return Storage[#Storage] end function Methods:Get(Index) assert(type(Index) == "string" or type(Index) == "number", "bad argument #1 to 'Get': string expected, got "..type(Index)) if Storage[Index] ~= nil then return Storage[Index] end end function Methods:Call(Index, ...) assert(type(Index) == "string" or type(Index) == "number", "bad argument #1 to 'Call': string or number expected, got "..type(Index)) assert(type(Storage[Index]) == "function", Index.." is not a function.") return Storage[Index](...) end function Methods:Remove(Index) assert(type(Index) == "string" or type(Index) == "number", "bad argument #1 to 'Remove': string or number expected, got "..type(Index)) assert(self[Index] ~= nil, "attempt to remove a nil index") Storage[Index] = nil end function Methods:Exists(Index) assert(type(Index) == "string" or type(Index) == "number", "bad argument #1 to 'Exists': string or number expected, got "..type(Index)) if Storage[Index] ~= nil then return true else return false end end function Methods:Bulk(Mode, ...) local ToSet = {...} if Mode == "a" then for i, v in pairs(ToSet) do table.insert(Storage, i, v) end elseif Mode == "s" then for i, v in pairs(ToSet) do Storage[i] = v end elseif Mode == "r" then for i in pairs(ToSet) do if Storage[i] ~= nil then Storage[i] = nil else error("attempt to remove a nil index") end end else error("invalid mode; mode can only be 'a' (append), 'r' (remove) or 's' (set)") end end function Methods:Pairs() return next, Storage, nil end function Methods:Iter(Index) if type(Index) ~= "number" then Index = 0 end Index = Index + 1 local Value = Storage[Index] if Value then return Index, Value end end function Methods:IPairs() return iter_table, Storage, 0 end function Methods:Size() return #Storage end function Methods:First() return Storage[1] end function Methods:Last() return Storage[#Storage] end function Methods:Clear() Storage = {} end setmetatable(Methods, { __index = Methods, __newindex = function (t, k, v) if rawget(Storage, k) then rawset(Storage, k, v) else error("attempt to edit Methods table") end end, __metatable = {} }) return Methods end --- Creates a new container to the Container Storage --- --- If ``Name`` is nil, the container name is set to 'default' --- --- If ``Name`` already exists, rises an error ---@param Name string ---@return table function Container.Create(Name) if Name == nil then Name = "default" end assert(_cst[Name] == nil, "container "..Name.." already exists.") _cst[Name] = { ["Methods"] = {}, ["Storage"] = {} } return MakeMethods(Name) end --- Removes a container of the Container Storage -- -- If containter dosent exists, rises an error. ---@param Name string function Container.Delete(Name) assert(type(Name) == "string", "bad argument #1 to 'Remove': string expected, got "..type(Name)) assert(_cst[Name] ~= nil, "attempt to remove a nil container") _cst[Name] = nil end --- Clones a container. --- --- If ``NewName`` is not a string then it will be set to be the ``Name`` + list pos. --- --- If a conteiner with ``NewName`` already exists or the container dosent exists, rises an error. ---@param Name string ---@param NewName string ---@return table function Container.Clone(Name, NewName) assert(type(Name) == "string", "bad argument #1 to 'Clone': string expected, got "..type(Name)) if NewName == nil then NewName = Name..(#_cst + 1) end assert(_cst[Name] ~= nil, "attempt to clone a nil container") assert(_cst[NewName] == nil, NewName.." already exists.") _cst[NewName] = { ["Methods"] = {}, ["Storage"] = {}, } for i, v in pairs(_cst[Name]["Storage"]) do _cst[NewName]["Storage"][i] = v end return MakeMethods(NewName) end --- Clear the Container Storage function Container.Clear() _cst = {} end return setmetatable(Container, mt)
-- load the base plugin object and create a subclass local plugin = require("kong.plugins.base_plugin"):extend() -- local debug = require "kong.plugins.newrelic-insights.debug" local http = require "resty.http" local JSON = require "kong.plugins.newrelic-insights.json" local basic_serializer = require "kong.plugins.log-serializers.basic" local body_data; local authenticated_consumer; -- constructor function plugin:new() plugin.super.new(self, "newrelic-insights") end ---[[ runs in the 'access_by_lua_block' function plugin:access(plugin_conf) plugin.super.access(self) ngx.req.read_body(); -- Populate get_body_data() -- Fetch body data while API cosockets are enabled plugin.body_data = ngx.req.get_body_data(); if ngx.ctx.authenticated_consumer == nil then plugin.authenticated_consumer = "NOT AUTHENTICATED"; else plugin.authenticated_consumer = ngx.ctx.authenticated_consumer.username; end end local function recordEvent(premature, plugin_conf, requestEnvelop) if premature then return end local client = http.new() local params = { eventType = "kong_api_gateway_request", headers_host = requestEnvelop.request.headers.host, headers_contentLength = requestEnvelop.request.headers["content-length"], headers_userAgent = requestEnvelop.request.headers["user-agent"], headers_accept = requestEnvelop.request.headers["accept"], headers_contentType = requestEnvelop.request.headers["content-type"], request_method = requestEnvelop.request.method, request_route = requestEnvelop.request["request_uri"], request_size = requestEnvelop.request["size"], client_ip = requestEnvelop["client_ip"], config_api_name = requestEnvelop.api["name"], config_api_https_only = requestEnvelop.api["https_only"], config_api_preserve_host = requestEnvelop.api["preserve_host"], config_api_upstream_connect_timeout = requestEnvelop.api["upstream_connect_timeout"], config_api_upstream_read_timeout = requestEnvelop.api["api_upstream_read_timeout"], config_api_upstream_send_timeout = requestEnvelop.api["api_upstream_send_timeout"], config_api_strip_uri = requestEnvelop.api["strip_uri"], config_api_upstream_url = requestEnvelop.api["upstream_url"], latencies_request = requestEnvelop.latencies["request"], latencies_kong = requestEnvelop.latencies["kong"], latencies_proxy = requestEnvelop.latencies["proxy"], response_status = requestEnvelop.response["status"], response_size = requestEnvelop.response["size"], started_at = requestEnvelop["started_at"], body_data = plugin.body_data, authenticated_consumer = plugin.authenticated_consumer }; -- Add querystring variables as data column for key,value in pairs(requestEnvelop.request.querystring) do -- Don't record the api_key in newrelic_insights if(key ~= 'api_key') then params[key] = value; end end if plugin_conf.environment_name ~= nil then params['environment_name'] = plugin_conf.environment_name end -- debug.log_r("=============================================================="); -- debug.log_r(params); -- debug.log_r("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); if plugin_conf.account_id ~= nil and plugin_conf.api_key ~= nil then client:set_timeout(30000) local ok, err = client:connect("insights-collector.newrelic.com", 443); if not ok then ngx.log(ngx.STDERR, "Could not connect to newrelic insights API", err); else local ok, err = client:ssl_handshake(false, "insights-collector.newrelic.com", false) if not ok then ngx.log(ngx.STDERR, "Could not perform SSL handshake with Newrelic Insight", err); return end local res, err = client:request { method = "POST", path = "/v1/accounts/" .. plugin_conf.account_id .. "/events", body = JSON.stringify(params), headers = { ["Content-Type"] = "application/json", ["X-Insert-Key"] = plugin_conf.api_key } } if not res then ngx.log(ngx.STDERR, "Could not send http logs to Newrelic Insights", err); end end end end function plugin:log(plugin_conf) plugin.super.log(self) local requestEnvelop = basic_serializer.serialize(ngx); -- trigger logging method with ngx_timer, a workaround to enable API local ok, err = ngx.timer.at(0, recordEvent, plugin_conf, requestEnvelop) if not ok then ngx.log(ngx.STDERR, "Fail to create timer", err); end end -- set the plugin priority, which determines plugin execution order plugin.PRIORITY = 1000 -- return our plugin object return plugin
local M = {} local excludeDirsFunc = function(opts) local excludeDirs = {} local dir = "" repeat dir = vim.fn.input("Exclude Dir (be sure to add trailing '/') > ", "", "file") if dir ~= nil and dir ~= "" then table.insert(excludeDirs, "--glob=!" .. dir) end until dir == "" for index, direc in ipairs(excludeDirs) do print(direc) end return excludeDirs end M.CustomLiveGrep = function() local includeDirs = {} local dir = "" repeat dir = vim.fn.input("Include Dir > ", "", "file") if dir ~= nil and dir ~= "" then table.insert(includeDirs, dir) end until dir == "" require("telescope.builtin").live_grep({search_dirs = includeDirs, additional_args = excludeDirsFunc}) end return M
local turretUtils = {} require "util" local function foreach(table_, fun_) for k, tab in pairs(table_) do fun_(tab) end return table_ end local indicator_pictures = { north = { filename = "__base__/graphics/entity/flamethrower-turret/flamethrower-turret-led-indicator-north.png", line_length = 2, width = 4, height = 10, frame_count = 2, axially_symmetrical = false, direction_count = 1, shift = util.by_pixel(8, 20), hr_version = { filename = "__base__/graphics/entity/flamethrower-turret/hr-flamethrower-turret-led-indicator-north.png", line_length = 2, width = 10, height = 18, frame_count = 2, axially_symmetrical = false, direction_count = 1, shift = util.by_pixel(7, 20), scale = 0.5 } }, east = { filename = "__base__/graphics/entity/flamethrower-turret/flamethrower-turret-led-indicator-east.png", line_length = 2, width = 12, height = 6, frame_count = 2, axially_symmetrical = false, direction_count = 1, shift = util.by_pixel(-34, -6), hr_version = { filename = "__base__/graphics/entity/flamethrower-turret/hr-flamethrower-turret-led-indicator-east.png", line_length = 2, width = 18, height = 8, frame_count = 2, axially_symmetrical = false, direction_count = 1, shift = util.by_pixel(-33, -5), scale = 0.5 } }, south = { filename = "__base__/graphics/entity/flamethrower-turret/flamethrower-turret-led-indicator-south.png", line_length = 2, width = 4, height = 12, frame_count = 2, axially_symmetrical = false, direction_count = 1, shift = util.by_pixel(-8, -46), hr_version = { filename = "__base__/graphics/entity/flamethrower-turret/hr-flamethrower-turret-led-indicator-south.png", line_length = 2, width = 8, height = 18, frame_count = 2, axially_symmetrical = false, direction_count = 1, shift = util.by_pixel(-8, -45), scale = 0.5 } }, west = { filename = "__base__/graphics/entity/flamethrower-turret/flamethrower-turret-led-indicator-west.png", line_length = 2, width = 10, height = 10, frame_count = 2, axially_symmetrical = false, direction_count = 1, shift = util.by_pixel(32, -22), hr_version = { filename = "__base__/graphics/entity/flamethrower-turret/hr-flamethrower-turret-led-indicator-west.png", line_length = 2, width = 20, height = 10, frame_count = 2, axially_symmetrical = false, direction_count = 1, shift = util.by_pixel(32, -20), scale = 0.5 } } } local function set_shift(shift, tab) tab.shift = shift if tab.hr_version then tab.hr_version.shift = shift end return tab end local function flamethrower_turret_pipepictures() local pipe_sprites = pipepictures() return { north = set_shift({0, 1}, util.table.deepcopy(pipe_sprites.straight_vertical)), south = set_shift({0, -1}, util.table.deepcopy(pipe_sprites.straight_vertical)), east = set_shift({-1, 0}, util.table.deepcopy(pipe_sprites.straight_horizontal)), west = set_shift({1, 0}, util.table.deepcopy(pipe_sprites.straight_horizontal)) } end function turretUtils.makeAmmoTurret(attributes, attack) local name = attributes.name .. "-ammo-turret-rampant-arsenal" local itemName = attributes.name .. "-item-rampant-arsenal" data:extend({ { type = "item", name = itemName, icon = attributes.icon or "__base__/graphics/icons/gun-turret.png", icon_size = 32, flags = attributes.itemFlags or {}, subgroup = attributes.subgroup or "defensive-structure", order = attributes.order or "b[turret]-a[gun-turret]", place_result = name, stack_size = attributes.stackSize or 50 }, { type = "ammo-turret", name = name, icon = attributes.icon or "__base__/graphics/icons/gun-turret.png", icon_size = 32, flags = attributes.flags or {"placeable-player", "player-creation"}, -- healing_per_tick = -0.04, minable = {mining_time = attributes.miningTime or 0.5, result = itemName}, max_health = attributes.health or 400, corpse = "medium-remnants", collision_box = attributes.collisionBox or {{-0.7, -0.7 }, {0.7, 0.7}}, selection_box = attributes.selectionBox or {{-1, -1 }, {1, 1}}, rotation_speed = attributes.rotationSpeed or 0.007, preparing_speed = attributes.preparingSpeed or 0.08, folding_speed = attributes.foldingSpeed or 0.08, dying_explosion = "medium-explosion", inventory_size = attributes.inventorySize or 1, automated_ammo_count = attributes.autoAmmoCount or 10, attacking_speed = attributes.attackingSpeed or 0.5, alert_when_attacking = true, open_sound = { filename = "__base__/sound/machine-open.ogg", volume = 0.85 }, close_sound = { filename = "__base__/sound/machine-close.ogg", volume = 0.75 }, folded_animation = attributes.foldedAnimation, preparing_animation = attributes.preparingAnimation, prepared_animation = attributes.preparedAnimation, folding_animation = attributes.foldingAnimation, energy_source = attributes.energySource, attacking_animation = attributes.attackingAnimation, turret_base_has_direction = attributes.hasBaseDirection, resistances = attributes.resistances, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }, attack_parameters = attack or { type = "projectile", ammo_category = "bullet", cooldown = 6, projectile_creation_distance = 1.39375, projectile_center = {0, -0.0875}, -- same as gun_turret_attack shift shell_particle = { name = "shell-particle", direction_deviation = 0.1, speed = 0.1, speed_deviation = 0.03, center = {-0.0625, 0}, creation_distance = -1.925, starting_frame_speed = 0.2, starting_frame_speed_deviation = 0.1 }, range = 18, sound = make_heavy_gunshot_sounds(), }, call_for_help_radius = 40, order = attributes.order } }) return name, itemName end function turretUtils.makeFluidTurret(attributes, attack) local name = attributes.name .. "-fluid-turret-rampant-arsenal" local itemName = attributes.name .. "-item-rampant-arsenal" data:extend({ { type = "item", name = itemName, icon = attributes.icon or "__base__/graphics/icons/gun-turret.png", icon_size = 32, flags = attributes.itemFlags or {}, subgroup = attributes.subgroup or "defensive-structure", order = attributes.order or "b[turret]-a[gun-turret]", place_result = name, stack_size = attributes.stackSize or 50 }, { type = "fluid-turret", name = name, icon = attributes.icon or "__base__/graphics/icons/flamethrower-turret.png", icon_size = 32, flags = {"placeable-player", "player-creation"}, minable = {mining_time = attributes.miningTime or 0.5, result = itemName}, max_health = attributes.health or 1400, corpse = "medium-remnants", collision_box = attributes.collisionBox or {{-1.7, -2.2 }, {1.7, 2.2}}, selection_box = attributes.selectionBox or {{-2, -2.5 }, {2, 2.5}}, rotation_speed = attributes.rotationSpeed or 0.015, preparing_speed = attributes.preparingSpeed or 0.08, folding_speed = attributes.foldingSpeed or 0.08, attacking_speed = attributes.attackingSpeed or 1, ending_attack_speed = attributes.attackingEndSpeed or 0.2, dying_explosion = "medium-explosion", inventory_size = 1, automated_ammo_count = 10, attacking_animation_fade_out = 10, turret_base_has_direction = true, resistances = attributes.resistances or { { type = "fire", percent = 100, }, }, fluid_box = { pipe_picture = flamethrower_turret_pipepictures(), render_layer = "lower-object", secondary_draw_order = 0, pipe_covers = pipecoverspictures(), base_area = 1, pipe_connections = attributes.pipeConnections or { { position = {-2.5, 2.0} }, { position = {2.5, 2.0} } } }, fluid_buffer_size = attributes.fluidBuffer or 100, fluid_buffer_input_flow = attributes.fluidBufferFlow or 250 / 60 / 5, -- 5s to fill the buffer activation_buffer_ratio = attributes.fluidBufferRation or 0.25, folded_animation = attributes.foldedAnimation, preparing_animation = attributes.preparingAnimation, prepared_animation = attributes.preparedAnimation, folding_animation = attributes.foldingAnimation, not_enough_fuel_indicator_picture = indicator_pictures, enough_fuel_indicator_picture = foreach(util.table.deepcopy(indicator_pictures), function (tab) tab.x = tab.width end), indicator_light = { intensity = 0.8, size = 0.9 }, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }, prepare_range = attributes.prepareRange or 55, shoot_in_prepare_state = false, attack_parameters = attack or { type = "stream", ammo_category = "flamethrower", cooldown = 4, range = 45, min_range = 6, turn_range = 1.0/3.0, fire_penalty = 30, fluids = { {type = "crude-oil"}, {type = "heavy-oil", damage_modifier = 1.05}, {type = "light-oil", damage_modifier = 1.1} }, fluid_consumption = 0.2, gun_center_shift = { north = {0, -0.65}, east = {0, 0}, south = {0, 0}, west = {0, 0} }, gun_barrel_length = 0.4, ammo_type = { category = "flamethrower", action = { type = "line", range = 45, force = "enemy", width = 20, action_delivery = { type = "stream", stream = "flamethrower-fire-stream2", duration = 10, source_offset = {0.15, -0.5}, } } }, cyclic_sound = { begin_sound = { { filename = "__base__/sound/fight/flamethrower-start.ogg", volume = 0.7 } }, middle_sound = { { filename = "__base__/sound/fight/flamethrower-mid.ogg", volume = 0.7 } }, end_sound = { { filename = "__base__/sound/fight/flamethrower-end.ogg", volume = 0.7 } } } }, -- {0, 0.625} call_for_help_radius = 40, order = attributes.order } }) return name, itemName end function turretUtils.makeElectricTurret(attributes, attack) local name = attributes.name .. "-electric-turret-rampant-arsenal" local itemName = attributes.name .. "-item-rampant-arsenal" data:extend({ { type = "item", name = itemName, icon = attributes.icon or "__base__/graphics/icons/gun-turret.png", icon_size = 32, flags = attributes.itemFlags or {}, subgroup = attributes.subgroup or "defensive-structure", order = attributes.order or "b[turret]-a[gun-turret]", place_result = name, stack_size = attributes.stackSize or 50 }, { type = "electric-turret", name = name, icon = attributes.icon or "__base__/graphics/icons/laser-turret.png", icon_size = 32, flags = attributes.flags or { "placeable-player", "placeable-enemy", "player-creation"}, minable = { mining_time = attributes.miningTime or 0.5, result = itemName }, max_health = attributes.health or 1000, corpse = "medium-remnants", collision_box = attributes.collisionBox or {{ -0.7, -0.7}, {0.7, 0.7}}, selection_box = attributes.selectionBox or {{ -1, -1}, {1, 1}}, rotation_speed = attributes.rotationSpeed or 0.01, preparing_speed = attributes.preparingSpeed or 0.05, dying_explosion = "medium-explosion", turret_base_has_direction = attributes.hasBaseDirection, folding_speed = attributes.foldingSpeed or 0.05, energy_source = attributes.energySource or { type = "electric", buffer_capacity = "801kJ", input_flow_limit = "9600kW", drain = "24kW", usage_priority = "primary-input" }, resistances = attributes.resistances, folded_animation = attributes.foldedAnimation, preparing_animation = attributes.preparingAnimation, prepared_animation = attributes.preparedAnimation, folding_animation = attributes.foldingAnimation, base_picture = attributes.basePicture, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }, attack_parameters = attack or { type = "projectile", ammo_category = "electric", cooldown = 20, projectile_center = {-0.09375, -0.2}, turn_range = 1.0/3.0, projectile_creation_distance = 1.4, range = 24, damage_modifier = 4, ammo_type = { type = "projectile", category = "laser-turret", energy_consumption = "800kJ", action = { { type = "direct", action_delivery = { { type = "projectile", projectile = "laser", starting_speed = 0.35 } } } } }, sound = make_laser_sounds() }, call_for_help_radius = 40, order = attributes.order } }) return name, itemName end return turretUtils
-- s-300v 9s32 tr GT = {}; GT_t.ws = 0; set_recursive_metatable(GT, GT_t.generic_stationary); set_recursive_metatable(GT.chassis, GT_t.CH_t.STATIC); GT.chassis.life = 4; GT.visual.shape = "9s32"; GT.visual.shape_dstr = "9s32_d"; GT.visual.fire_pos[2] = 1; GT.snd.radarRotation = "RadarRotation"; GT.sensor = {}; GT.sensor.max_range_finding_target = 150000; GT.sensor.min_range_finding_target = 200; GT.sensor.max_alt_finding_target = 150000; GT.sensor.height = 8.0; --Burning after hit GT.visual.fire_size = 0.5; --relative burning size GT.visual.fire_pos[1] = 0; -- center of burn at long axis shift(meters) GT.visual.fire_pos[2] = 0; -- center of burn shift at vertical shift(meters) GT.visual.fire_pos[3] = 0; -- center of burn at transverse axis shift(meters) GT.visual.fire_time = 900; --burning time (seconds) GT.CustomAimPoint = {0,1.5,0} -- weapon system GT.WS = {}; GT.WS.maxTargetDetectionRange = 150000; GT.WS.radar_type = 102; -- 6 trackers, first tracker is main, other 5 are limited within 120 degree -- 0 tracker, dummy local ws = GT_t.inc_ws(); GT.WS[ws] = {}; GT.WS[ws].pos = {0,27,0}; GT.WS[ws].angles = { {math.rad(180), math.rad(-180), math.rad(-10), math.rad(80)}, }; GT.WS[ws].drawArgument1 = 11; GT.WS[ws].omegaY = 0.174533; GT.WS[ws].omegaZ = 0.174533; GT.WS[ws].pidY = { p = 10, i = 0.1, d = 4}; GT.WS[ws].pidZ = { p = 10, i = 0.1, d = 4}; GT.WS[ws].LN = {}; GT.WS[ws].LN[1] = {}; GT.WS[ws].LN[1].depends_on_unit = {{{"S-300V 9S457 cp"}}}; GT.WS[ws].LN[1].reactionTime = 1; GT.WS[ws].LN[1].max_number_of_missiles_channels = 2; GT.WS[ws].LN[1].type = 102; GT.WS[ws].LN[1].distanceMin = 2000; GT.WS[ws].LN[1].distanceMax = 150000; GT.WS[ws].LN[1].reflection_limit = 0.02; GT.WS[ws].LN[1].ECM_K = 0.4; GT.WS[ws].LN[1].min_trg_alt = 15; GT.WS[ws].LN[1].max_trg_alt = 150000; GT.WS[ws].LN[1].beamWidth = math.rad(90); for i = 1,5 do -- 5 tracker's ws = GT_t.inc_ws(); GT.WS[ws] = {} GT.WS[ws].base = 1 GT.WS[ws].pos = {0,0,0} GT.WS[ws].angles = { {math.rad(45), math.rad(-45), math.rad(-10), math.rad(80)}, }; GT.WS[ws].omegaY = 3 GT.WS[ws].omegaZ = 3 GT.WS[ws].LN = {} GT.WS[ws].LN[1] = {} set_recursive_metatable(GT.WS[ws].LN[1], GT.WS[1].LN[1]) end --for GT.Name = "S-300V 9S32 tr"; GT.DisplayName = _("SAM SA-12 S-300V Grill Pan TR"); GT.DisplayNameShort = _("SA-12 TR"); GT.Rate = 20; GT.Sensors = { RADAR = GT.Name }; GT.DetectionRange = GT.sensor.max_range_finding_target; GT.ThreatRange = 0; GT.mapclasskey = "P0091000083"; GT.attribute = {wsType_Ground,wsType_SAM,wsType_Radar,RLS_9C32_1, "LR SAM", "SAM TR", "RADAR_BAND1_FOR_ARM", "CustomAimPoint", }; GT.category = "Air Defence"; GT.tags = {"Air Defence", "Tracking Radar"}; GT.Countries = {"Ukraine", "Russia"}