content
stringlengths
5
1.05M
function Grenade:GetIsAffectedByWeaponUpgrades() return true end
require 'lpeg' --[[ compile(string <text_grammar_definition>, string <S0 state name>, boolean <optional debug>) returns lpeg_pattern ]]-- local function compile(g, S0name, quantifier, _debug) local P = lpeg.P local C = lpeg.C local Ct = lpeg.Ct local V = lpeg.V local S = lpeg.S local delim = P[[/]] local nl = P"\n" local _space = S" \t" local space0 = _space^0 local space1 = _space^1 local nspace = (1 - (_space+delim+nl))^1 local quot1 = P[[']] local quot2 = P[["]] local escape = P[[\]] local quot = P{ #quot1*V(2) + #quot2*V(3), quot1 * C( ( (escape*quot1) + (1-quot1) )^0) * quot1, quot2 * C( ( (escape*quot2) + (1-quot2) )^0) * quot2, } local lines = Ct( lpeg.P{ "line", line = (( Ct( ( space0 * C(nspace) * space0 * "<-" * space0 * V('def_list') * space0 )^1 ) + nl ))^0, def_list = Ct( ( (V('def') * space0 * delim * space0) + (V('def') * space0) )^1 ), def = ( ( Ct( quot * Ct( ( space1 * C( nspace ))^1 ) ) ) + ( Ct(quot) ) ), } ) local TI = table.insert local empty = lpeg.P(0) local t = {} local wr = function(...) if _debug then io.write(string.format(...)) end end TI(t, S0name) for i,line in ipairs(lines:match(g)) do t[line[1]] = (function() wr("%q = ", tostring(line[1])) local def_list for _, _def in ipairs(line[2]) do wr("(") local _def_list = (function() local def = _def[1] wr("%q", _def[1]) if type(_def[2])=="table" then for j, state in ipairs(_def[2]) do wr(" %s", state) def = def * V(state) end end return def end)() if type(def_list)=="nil" then def_list = _def_list else def_list = def_list + _def_list end wr(")") end return def_list end)() wr("\n") end if quantifier then return P(t) * quantifier else return P(t) end end return { compile = compile }
object_tangible_quest_som_vault_dial = object_tangible_quest_shared_som_vault_dial:new { } ObjectTemplates:addTemplate(object_tangible_quest_som_vault_dial, "object/tangible/quest/som_vault_dial.iff")
--[[---------------------------------------------------------------------------- MIT License Copyright (c) 2018 David F. Burns This file is part of LrSlide. 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. ------------------------------------------------------------------------------]] require 'strict' local Debug = require 'Debug'.init() local LrDialogs = import 'LrDialogs' local LrView = import 'LrView' local LrFunctionContext = import 'LrFunctionContext' local LrFileUtils = import 'LrFileUtils' local LrColor = import 'LrColor' local LrHttp = import 'LrHttp' local LrPrefs = import 'LrPrefs' local Util = require 'Util' require 'FontFinder' local function showTextInADialog( title, text ) LrFunctionContext.callWithContext( "showTextInADialog", Debug.showErrors( function( _ ) local f = LrView.osFactory() local _, numLines = text:gsub( '\n', '\n' ) local c local thresholdForScrollable = 30 -- Create the contents for the dialog. -- if it's a short license, just show a static control. Else, put the static control in a scrollable view. if numLines <= thresholdForScrollable then c = f:row { f:static_text { selectable = true, title = text, size = 'small', height_in_lines = -1, width = 550, } } else c = f:row { f:scrolled_view { horizontal_scroller = false, width = 600, height = thresholdForScrollable * 14, f:static_text { selectable = true, title = text, size = 'small', height_in_lines = -1, width = 550, } } } end LrDialogs.presentModalDialog { title = title, contents = c, cancelVerb = '< exclude >', } end ) ) end local function startDialog( propertyTable ) local prefs = LrPrefs.prefsForPlugin() Util.log( 0, 'PLUGIN MANAGER: startDialog' ) Util.logpp( 0, prefs ) propertyTable.chromePath = prefs.chromePath or '' propertyTable.slideWidth = prefs.slideWidth or 1024 propertyTable.slideHeight = prefs.slideHeight or 768 end local function endDialog( propertyTable ) local prefs = LrPrefs.prefsForPlugin() Util.log( 0, 'PLUGIN MANAGER: endDialog' ) prefs.chromePath = propertyTable.chromePath prefs.slideWidth = propertyTable.slideWidth prefs.slideHeight = propertyTable.slideHeight Util.logpp( 0, prefs ) end local function validateChromeExecutable( _, path ) local exists, errorMessage path = Util.trim( path ) -- special case: valid if the path is empty if #path == 0 then return true, path end exists = LrFileUtils.exists( path ) if exists and exists == 'file' then return true, path end errorMessage = 'Could not find Chrome at the path given:\n\n' .. path .. '\n\nPlease provide a correct path or leave the path blank.' Util.log( 0, errorMessage ) return false, '', errorMessage end -- Section for the top of the dialog. local function sectionsForTopOfDialog( f, propertyTable ) local bind = LrView.bind local share = LrView.share local ChromeMessage local test, _, msg = validateChromeExecutable( nil, propertyTable.chromePath ) if not test then ChromeMessage = msg end Util.log( 0, 'PLUGIN MANAGER: sectionsForTopOfDialog' ) -- Util.logpp( 0, propertyTable ) return { { title = 'License Info', synopsis = 'Expand for license info', f:row { f:push_button { title = "Show license...", action = Debug.showErrors(function( _ ) showTextInADialog( 'License for LrSlide', Util.readFileIntoString( _PLUGIN.path .. '/licenses/LICENSE' ) ) end ), }, }, f:row { f:separator { fill_horizontal = 1, }, }, f:row { f:static_text { title = 'This plugin makes use of code from 3rd parties:', }, }, f:row { f:static_text { title = 'markdown.lua', text_color = LrColor( 'blue' ), mouse_down = function() LrHttp.openUrlInBrowser( 'https://github.com/mpeterv/markdown' ) end }, f:push_button { title = "Show license...", action = Debug.showErrors( function( _ ) showTextInADialog( 'License for markdown.lua', Util.readFileIntoString( _PLUGIN.path .. '/licenses/LICENSE.markdown' ) ) end ), }, }, f:row { f:static_text { title = 'UTF 8 Lua Library', }, f:push_button { title = "Show license...", action = Debug.showErrors( function( _ ) showTextInADialog( 'License for Lua UTF-8 Library', Util.readFileIntoString( _PLUGIN.path .. '/licenses/LICENSE.utf8' ) ) end ), }, }, f:row { f:static_text { title = 'Simple JSON Encode/Decode from Jeffrey Friedl', text_color = LrColor( 'blue' ), mouse_down = function() LrHttp.openUrlInBrowser( 'http://regex.info/blog/lua/json' ) end }, f:push_button { title = "Show license...", action = function() LrHttp.openUrlInBrowser( 'https://creativecommons.org/licenses/by/3.0/legalcode' ) end, }, }, }, { title = 'Advanced Settings', synopsis = function() local s = '' if #propertyTable.chromePath > 0 then s = s .. 'Custom Chrome' else s = s .. 'Default Chrome' end return s end, f:row { f:column { spacing = f:control_spacing(), fill = 1, f:static_text { title = "By default, LrSlide will automatically find Chrome. If for some reason it can't, or if you need to override this, you can enter the location here. Most users will leave this blank.", fill_horizontal = 1, width_in_chars = 55, height_in_lines = 2, size = 'small', }, ChromeMessage and f:static_text { title = ChromeMessage, fill_horizontal = 1, width_in_chars = 55, height_in_lines = 5, size = 'small', text_color = import 'LrColor'( 1, 0, 0 ), } or 'skipped item', f:row { spacing = f:label_spacing(), f:static_text { title="Path to Chrome:", alignment = 'right', width = share 'title_width', }, f:edit_field { value = bind { key = 'chromePath', object = propertyTable }, fill_horizontal = 1, width_in_chars = 25, validate = validateChromeExecutable, }, f:push_button { title = "Browse...", action = Debug.showErrors( function( _ ) local options = { title = 'Find the Chrome program:', prompt = 'Select', canChooseFiles = true, canChooseDirectories = false, canCreateDirectories = false, allowsMultipleSelection = false, } if ( WIN_ENV == true ) then options.fileTypes = 'exe' else options.fileTypes = '' end local result result = LrDialogs.runOpenPanel( options ) if ( result ) then propertyTable.chromePath = Util.trim( result[ 1 ] ) end end ) }, }, }, }, f:separator { fill_horizontal = 1, }, f:row { f:column { spacing = f:control_spacing(), fill = 1, f:static_text { title = "For performance reasons, LrSlide only scans for your system's fonts once per week. If you need to force it to rescan now, click the button below.", fill_horizontal = 1, width_in_chars = 55, height_in_lines = 3, size = 'small', }, f:row { spacing = f:label_spacing(), f:push_button { title = "Delete font cache", action = Debug.showErrors( function( _ ) local fontFinder = newFontFinder() fontFinder.deleteFontCache() LrDialogs.message( 'The font cache was deleted.' ) end ), }, }, }, }, }, { title = 'Size of Slides', synopsis = function() return propertyTable.slideWidth .. ' x ' .. propertyTable.slideHeight .. ' pixels' end, f:column { spacing = f:control_spacing(), fill = 1, f:static_text { title = 'Set the size for new slides here. If you want to change the size of existing slides, set the size here, press Done, then select the slides and choose Library -> Plug-in Extras -> LrSlide -> Re-render selected slides.', fill_horizontal = 1, width_in_chars = 55, height_in_lines = 2, size = 'small', }, f:row { spacing = f:label_spacing(), f:static_text { title = 'Width:', alignment = 'right', }, f:edit_field { value = bind { key = 'slideWidth', object = propertyTable }, width_in_chars = 10, validate = function( _, value ) local number = tonumber( Util.trim( value ) ) if not number then return false, '', "The slide width must be made of only digits." end local int = math.floor( number ) if int < 1 or int > 5000 then return false, '', "The slide width must be between 1 and 5000." end return true, value end }, f:static_text { title = 'Height:', alignment = 'right', }, f:edit_field { value = bind { key = 'slideHeight', object = propertyTable }, width_in_chars = 10, validate = function( _, value ) local number = tonumber( Util.trim( value ) ) if not number then return false, '', 'The slide height must be made of only digits.' end local int = math.floor( number ) if int < 1 or int > 5000 then return false, '', 'The slide width must be between 1 and 5000.' end return true, value end }, }, }, } } end return { sectionsForTopOfDialog = sectionsForTopOfDialog, startDialog = startDialog, endDialog = endDialog, }
--[=[ Handles reset requests since Roblox's reset system doesn't handle ragdolls correctly @server @class ResetService ]=] local require = require(script.Parent.loader).load(script) local GetRemoteEvent = require("GetRemoteEvent") local ResetServiceConstants = require("ResetServiceConstants") local ResetService = {} --[=[ Initializes the reset service. Should be done via a [ServiceBag]. ]=] function ResetService:Init() assert(not self._remoteEvent, "Already initialized") self._remoteEvent = GetRemoteEvent(ResetServiceConstants.REMOTE_EVENT_NAME) self._remoteEvent.OnServerEvent:Connect(function(player) self:_resetCharacter(player) end) end function ResetService:_resetCharacter(player) player:LoadCharacter() end return ResetService
local _={} _[1]={"error","function \"function args arity check fail.f\" expected 2 arguments but received 1; at test/tests/function args arity check fail.ans:4"} return {_[1]} --[[ { "error", 'function "function args arity check fail.f" expected 2 arguments but received 1; at test/tests/function args arity check fail.ans:4' } ]]--
CustomizableWeaponry:addFireSound("KSKS.Fire", {"Weapons/SKS_BF4/fire1.wav","Weapons/SKS_BF4/fire2.wav","Weapons/SKS_BF4/fire3.wav"}, 1, 125, CHAN_STATIC) CustomizableWeaponry:addFireSound("KSKS.SupFire", {"Weapons/SKS_BF4/firesil1.wav","Weapons/SKS_BF4/firesil2.wav","Weapons/SKS_BF4/firesil3.wav"}, 1, 60, CHAN_STATIC) CustomizableWeaponry:addReloadSound("KSKS.Deploy", "Weapons/SKS_BF4/deploy.wav") CustomizableWeaponry:addReloadSound("KSKS.Cloth", "Weapons/SKS_BF4/cloth.wav") CustomizableWeaponry:addReloadSound("KSKS.Clipout", "Weapons/SKS_BF4/clipout.wav") CustomizableWeaponry:addReloadSound("KSKS.Clipin", "Weapons/SKS_BF4/clipin.wav") CustomizableWeaponry:addReloadSound("KSKS.Boltback", "Weapons/SKS_BF4/boltback.wav") CustomizableWeaponry:addReloadSound("KSKS.Boltforward", "Weapons/SKS_BF4/boltrelease.wav")
--[[ TheNexusAvenger Tests the GitStatusRequest class. --]] local NexusUnitTesting = require("NexusUnitTesting") local NexusGit = require(game:GetService("ServerStorage"):WaitForChild("NexusGit")) local GetGitStatusRequest = NexusGit:GetResource("NexusGitRequest.GetRequest.GetGitStatusRequest") local NexusEnums = NexusGit:GetResource("NexusPluginFramework.Data.Enum.NexusEnumCollection").GetBuiltInEnums() --Mock the request. local MockGitStatusRequest = GetGitStatusRequest:Extend() function MockGitStatusRequest:SendRequest() return { GetResponse = function() return "[\"Current branch:\"," .."\"master\"," .."\"Remote branch:\"," .."\"origin/master\"," .."\"Ahead by:\"," .."\"2\"," .."\"Changes to be committed:\"," .."\"Modified: TestFile1.lua\"," .."\"New file: TestFile2.lua\"," .."\"Modified: Directory1/TestFile3.lua\"," .."\"New file: Directory1/TestFile4.lua\"," .."\"Modified: Directory1/Directory2/TestFile5.lua\"," .."\"Renamed: Directory1/Directory2/TestFile10.lua -> Directory1/Directory2/TestFile6.lua\"," .."\"Deleted: Directory1/Directory2/TestFile7.lua\"," .."\"Untracked files:\"," .."\"TestFile8.lua\"," .."\"Directory1/TestFile9.lua\"]" end } end --[[ Tests that the constructor works without failing. --]] NexusUnitTesting:RegisterUnitTest("Constructor",function(UnitTest) local CuT = GetGitStatusRequest.new("http://localhost:0000") UnitTest:AssertEquals(CuT.ClassName,"GetGitStatusRequest","Class name is incorrect.") end) --[[ Tests the StringsToFiles method. --]] NexusUnitTesting:RegisterUnitTest("StringsToFiles",function(UnitTest) --Create a table of tracked objects. local FileStrings = { Modified = { "TestFile1.lua", "Directory1/TestFile3.lua", "Directory1/Directory2/TestFile5.lua", }, Created = { "TestFile2.lua", "Directory1/TestFile4.lua", }, Renamed = { "Directory1/Directory2/TestFile6.lua", }, Deleted = { "Directory1/Directory2/TestFile7.lua", }, Untracked = { "TestFile8.lua", "Directory1/TestFile9.lua", }, } --Convert the strings to a list of files. local CuT = GetGitStatusRequest.new("http://localhost:0000") local Files = CuT:StringsToFiles(FileStrings) UnitTest:AssertEquals(#Files,4,"Incorrect amount of files.") --[[ Returns the file for the given name. --]] local function GetFile(FileName) for _,File in pairs(Files) do if File:GetFileName() == FileName then return File end end end --Assert the modified files are correct. UnitTest:AssertTrue(NexusEnums.FileStatus.Modified:Equals(GetFile("TestFile1.lua"):GetStatus()),"File status is incorrect.") UnitTest:AssertTrue(NexusEnums.FileStatus.Modified:Equals(GetFile("Directory1"):GetFile("TestFile3.lua"):GetStatus()),"File status is incorrect.") UnitTest:AssertTrue(NexusEnums.FileStatus.Modified:Equals(GetFile("Directory1"):GetFile("Directory2"):GetFile("TestFile5.lua"):GetStatus()),"File status is incorrect.") --Assert the created files are correct. UnitTest:AssertTrue(NexusEnums.FileStatus.Created:Equals(GetFile("TestFile2.lua"):GetStatus()),"File status is incorrect.") UnitTest:AssertTrue(NexusEnums.FileStatus.Created:Equals(GetFile("Directory1"):GetFile("TestFile4.lua"):GetStatus()),"File status is incorrect.") --Assert the renamed files are correct. UnitTest:AssertTrue(NexusEnums.FileStatus.Renamed:Equals(GetFile("Directory1"):GetFile("Directory2"):GetFile("TestFile6.lua"):GetStatus()),"File status is incorrect.") --Assert the deleted files are correct. UnitTest:AssertTrue(NexusEnums.FileStatus.Deleted:Equals(GetFile("Directory1"):GetFile("Directory2"):GetFile("TestFile7.lua"):GetStatus()),"File status is incorrect.") --Assert the untracked files are correct. UnitTest:AssertTrue(NexusEnums.FileStatus.Untracked:Equals(GetFile("TestFile8.lua"):GetStatus()),"File status is incorrect.") UnitTest:AssertTrue(NexusEnums.FileStatus.Untracked:Equals(GetFile("Directory1"):GetFile("TestFile9.lua"):GetStatus()),"File status is incorrect.") end) --[[ Tests the GetStatus method. --]] NexusUnitTesting:RegisterUnitTest("GetStatus",function(UnitTest) --Create the mocked component under testing. local CuT = MockGitStatusRequest.new("http://localhost:0000") local StatusData = CuT:GetStatus() --Assert the base response info is correct. UnitTest:AssertEquals(StatusData.CurrentBranch,"master","Current branch is incorrect.") UnitTest:AssertEquals(StatusData.RemoteBranch,"origin/master","Remote branch is incorrect.") UnitTest:AssertEquals(StatusData.AheadBy,2,"Ahead by count is incorrect.") --[[ Returns the file for the given name. --]] local function GetFile(FileName) for _,File in pairs(StatusData.Files) do if File:GetFileName() == FileName then return File end end end --Assert the modified files are correct. UnitTest:AssertTrue(NexusEnums.FileStatus.Modified:Equals(GetFile("TestFile1.lua"):GetStatus()),"File status is incorrect.") UnitTest:AssertTrue(NexusEnums.FileStatus.Modified:Equals(GetFile("Directory1"):GetFile("TestFile3.lua"):GetStatus()),"File status is incorrect.") UnitTest:AssertTrue(NexusEnums.FileStatus.Modified:Equals(GetFile("Directory1"):GetFile("Directory2"):GetFile("TestFile5.lua"):GetStatus()),"File status is incorrect.") --Assert the created files are correct. UnitTest:AssertTrue(NexusEnums.FileStatus.Created:Equals(GetFile("TestFile2.lua"):GetStatus()),"File status is incorrect.") UnitTest:AssertTrue(NexusEnums.FileStatus.Created:Equals(GetFile("Directory1"):GetFile("TestFile4.lua"):GetStatus()),"File status is incorrect.") --Assert the renamed files are correct. UnitTest:AssertTrue(NexusEnums.FileStatus.Renamed:Equals(GetFile("Directory1"):GetFile("Directory2"):GetFile("TestFile6.lua"):GetStatus()),"File status is incorrect.") --Assert the deleted files are correct. UnitTest:AssertTrue(NexusEnums.FileStatus.Deleted:Equals(GetFile("Directory1"):GetFile("Directory2"):GetFile("TestFile7.lua"):GetStatus()),"File status is incorrect.") UnitTest:AssertTrue(NexusEnums.FileStatus.Deleted:Equals(GetFile("Directory1"):GetFile("Directory2"):GetFile("TestFile10.lua"):GetStatus()),"File status is incorrect.") --Assert the untracked files are correct. UnitTest:AssertTrue(NexusEnums.FileStatus.Untracked:Equals(GetFile("TestFile8.lua"):GetStatus()),"File status is incorrect.") UnitTest:AssertTrue(NexusEnums.FileStatus.Untracked:Equals(GetFile("Directory1"):GetFile("TestFile9.lua"):GetStatus()),"File status is incorrect.") end) return true
-------------------------------- -- @module AbstractCheckButton -- @extend Widget -- @parent_module ccui -------------------------------- -- -- @function [parent=#AbstractCheckButton] getCrossDisabledFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- -- @function [parent=#AbstractCheckButton] getBackDisabledFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- Load background selected state texture for check button.<br> -- param backGroundSelected The background selected state image name.<br> -- param texType @see `Widget::TextureResType` -- @function [parent=#AbstractCheckButton] loadTextureBackGroundSelected -- @param self -- @param #string backGroundSelected -- @param #int texType -- @return AbstractCheckButton#AbstractCheckButton self (return value: ccui.AbstractCheckButton) -------------------------------- -- Load background disabled state texture for checkbox.<br> -- param backGroundDisabled The background disabled state texture name.<br> -- param texType @see `Widget::TextureResType` -- @function [parent=#AbstractCheckButton] loadTextureBackGroundDisabled -- @param self -- @param #string backGroundDisabled -- @param #int texType -- @return AbstractCheckButton#AbstractCheckButton self (return value: ccui.AbstractCheckButton) -------------------------------- -- -- @function [parent=#AbstractCheckButton] getCrossNormalFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- Change CheckBox state.<br> -- Set to true will cause the CheckBox's state to "selected", false otherwise.<br> -- param selected Set to true will change CheckBox to selected state, false otherwise. -- @function [parent=#AbstractCheckButton] setSelected -- @param self -- @param #bool selected -- @return AbstractCheckButton#AbstractCheckButton self (return value: ccui.AbstractCheckButton) -------------------------------- -- -- @function [parent=#AbstractCheckButton] getBackPressedFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- brief Return the sprite instance of front cross when disabled<br> -- return the sprite instance of front cross when disabled -- @function [parent=#AbstractCheckButton] getRendererFrontCrossDisabled -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- brief Return the sprite instance of background<br> -- return the sprite instance of background. -- @function [parent=#AbstractCheckButton] getRendererBackground -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- Load cross texture for check button.<br> -- param crossTextureName The cross texture name.<br> -- param texType @see `Widget::TextureResType` -- @function [parent=#AbstractCheckButton] loadTextureFrontCross -- @param self -- @param #string crossTextureName -- @param #int texType -- @return AbstractCheckButton#AbstractCheckButton self (return value: ccui.AbstractCheckButton) -------------------------------- -- brief Return the sprite instance of background when disabled<br> -- return the sprite instance of background when disabled -- @function [parent=#AbstractCheckButton] getRendererBackgroundDisabled -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- Query whether CheckBox is selected or not.<br> -- return true means "selected", false otherwise. -- @function [parent=#AbstractCheckButton] isSelected -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#AbstractCheckButton] init -- @param self -- @param #string backGround -- @param #string backGroundSeleted -- @param #string cross -- @param #string backGroundDisabled -- @param #string frontCrossDisabled -- @param #int texType -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#AbstractCheckButton] getBackNormalFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- Load all textures for initializing a check button.<br> -- param background The background image name.<br> -- param backgroundSelected The background selected image name.<br> -- param cross The cross image name.<br> -- param backgroundDisabled The background disabled state texture.<br> -- param frontCrossDisabled The front cross disabled state image name.<br> -- param texType @see `Widget::TextureResType` -- @function [parent=#AbstractCheckButton] loadTextures -- @param self -- @param #string background -- @param #string backgroundSelected -- @param #string cross -- @param #string backgroundDisabled -- @param #string frontCrossDisabled -- @param #int texType -- @return AbstractCheckButton#AbstractCheckButton self (return value: ccui.AbstractCheckButton) -------------------------------- -- brief Return a zoom scale<br> -- return A zoom scale of Checkbox.<br> -- since v3.3 -- @function [parent=#AbstractCheckButton] getZoomScale -- @param self -- @return float#float ret (return value: float) -------------------------------- -- brief Return the sprite instance of front cross<br> -- return the sprite instance of front cross -- @function [parent=#AbstractCheckButton] getRendererFrontCross -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- brief Return the sprite instance of background when selected<br> -- return the sprite instance of background when selected -- @function [parent=#AbstractCheckButton] getRendererBackgroundSelected -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- Load background texture for check button.<br> -- param backGround The background image name.<br> -- param type @see `Widget::TextureResType` -- @function [parent=#AbstractCheckButton] loadTextureBackGround -- @param self -- @param #string backGround -- @param #int type -- @return AbstractCheckButton#AbstractCheckButton self (return value: ccui.AbstractCheckButton) -------------------------------- -- When user pressed the CheckBox, the button will zoom to a scale.<br> -- The final scale of the CheckBox equals (CheckBox original scale + _zoomScale)<br> -- since v3.3 -- @function [parent=#AbstractCheckButton] setZoomScale -- @param self -- @param #float scale -- @return AbstractCheckButton#AbstractCheckButton self (return value: ccui.AbstractCheckButton) -------------------------------- -- Load frontcross disabled texture for checkbox.<br> -- param frontCrossDisabled The front cross disabled state texture name.<br> -- param texType @see `Widget::TextureResType` -- @function [parent=#AbstractCheckButton] loadTextureFrontCrossDisabled -- @param self -- @param #string frontCrossDisabled -- @param #int texType -- @return AbstractCheckButton#AbstractCheckButton self (return value: ccui.AbstractCheckButton) -------------------------------- -- -- @function [parent=#AbstractCheckButton] getVirtualRenderer -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- -- @function [parent=#AbstractCheckButton] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#AbstractCheckButton] getVirtualRendererSize -- @param self -- @return size_table#size_table ret (return value: size_table) return nil
term.clear() term.setCursorPos(1,1) print("Thank you for using jOS") print("Loading...") sleep(1) textutils.slowPrint("#############") sleep(1) shell.run("disk/.menu")
--黯影魔 毁灭 local m=14060013 local cm=_G["c"..m] function cm.initial_effect(c) --fusion material c:EnableReviveLimit() aux.AddFusionProcCodeFun(c,cm.fusfilter1,cm.fusfilter,1,true,true) --pendulum summon aux.EnablePendulumAttribute(c,false) --base attack local e0=Effect.CreateEffect(c) e0:SetType(EFFECT_TYPE_SINGLE) e0:SetCode(EFFECT_SET_BASE_ATTACK) e0:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e0:SetRange(LOCATION_MZONE) e0:SetValue(cm.atkval) c:RegisterEffect(e0) --spsummon condition local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(cm.splimit) c:RegisterEffect(e1) --special summon rule local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_SPSUMMON_PROC) e2:SetProperty(EFFECT_FLAG_UNCOPYABLE) e2:SetRange(LOCATION_EXTRA) e2:SetCondition(cm.sprcon) e2:SetOperation(cm.sprop) c:RegisterEffect(e2) --to extra local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(m,0)) e3:SetCategory(CATEGORY_TOEXTRA) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e3:SetCode(EVENT_TO_GRAVE) e3:SetTarget(cm.rettg) e3:SetOperation(cm.retop) c:RegisterEffect(e3) --TurnSet local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(m,1)) e4:SetCategory(CATEGORY_POSITION) e4:SetProperty(EFFECT_FLAG_NO_TURN_RESET) e4:SetType(EFFECT_TYPE_QUICK_O) e4:SetCode(EVENT_FREE_CHAIN) e4:SetRange(LOCATION_EXTRA) e4:SetHintTiming(0,0x1e0) e4:SetCountLimit(1) e4:SetCondition(cm.tscon) e4:SetTarget(cm.tstg) e4:SetOperation(cm.tsop) c:RegisterEffect(e4) --immune local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetCode(EFFECT_IMMUNE_EFFECT) e5:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e5:SetRange(LOCATION_MZONE) e5:SetValue(cm.efilter) c:RegisterEffect(e5) end function cm.fusfilter(c,e,tp) return (c:IsFacedown() or (c:IsRace(RACE_ZOMBIE) and c:IsAttribute(ATTRIBUTE_DARK))) and c:IsType(TYPE_MONSTER) end function cm.fusfilter1(c,e,tp) return c:IsFusionSetCard(0x1406) and c:IsType(TYPE_MONSTER) end function cm.splimit(e,se,sp,st) return e:GetHandler():GetLocation()~=LOCATION_EXTRA end function cm.cfilter(c,tp) return ((c:IsFusionSetCard(0x1406) or c:IsFacedown() or (c:IsRace(RACE_ZOMBIE) and c:IsAttribute(ATTRIBUTE_DARK))) and c:IsType(TYPE_MONSTER)) and c:IsCanBeFusionMaterial() end function cm.fcheck(c,sg) return c:IsFusionSetCard(0x1406) and c:IsType(TYPE_MONSTER) and sg:FilterCount(cm.fcheck2,c)+1==sg:GetCount() end function cm.fcheck2(c) return (c:IsFacedown() or (c:IsRace(RACE_ZOMBIE) and c:IsAttribute(ATTRIBUTE_DARK))) and c:IsType(TYPE_MONSTER) end function cm.fgoal(c,tp,sg) return sg:GetCount()>1 and Duel.GetLocationCountFromEx(tp,tp,sg)>0 and sg:IsExists(cm.fcheck,1,nil,sg) end function cm.fselect(c,tp,mg,sg) sg:AddCard(c) local res=cm.fgoal(c,tp,sg) or mg:IsExists(cm.fselect,1,sg,tp,mg,sg) sg:RemoveCard(c) return res end function cm.sprcon(e,c) if c==nil then return true end local tp=c:GetControler() local mg=Duel.GetReleaseGroup(tp):Filter(cm.cfilter,nil,c) local mg1=Duel.GetReleaseGroup(1-tp):Filter(cm.cfilter,nil,c) mg:Merge(mg1) local sg=Group.CreateGroup() return mg:IsExists(cm.fselect,1,nil,tp,mg,sg) end function cm.sprop(e,tp,eg,ep,ev,re,r,rp,c) local mg=Duel.GetReleaseGroup(tp):Filter(cm.cfilter,nil,c) local mg1=Duel.GetReleaseGroup(1-tp):Filter(cm.cfilter,nil,c) mg:Merge(mg1) local sg=Group.CreateGroup() while true do local cg=mg:Filter(cm.fselect,sg,tp,mg,sg) if cg:GetCount()==0 or (cm.fgoal(c,tp,sg) and not Duel.SelectYesNo(tp,210)) then break end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE) local g=cg:Select(tp,1,1,nil) sg:Merge(g) end Duel.Release(sg,REASON_COST+REASON_FUSION+REASON_MATERIAL) end function cm.atkfilter(c,e,tp) return c:IsSetCard(0x1406) and c:IsFaceup() end function cm.atkval(e,c) return Duel.GetMatchingGroupCount(cm.atkfilter,c:GetControler(),LOCATION_EXTRA,0,nil)*400 end function cm.rettg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return not c:IsForbidden() end Duel.SetOperationInfo(0,CATEGORY_TOEXTRA,c,1,0,0) end function cm.retop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SendtoExtraP(c,tp,REASON_EFFECT) end end function cm.tscon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsFaceup() end function cm.tstg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=Duel.GetMatchingGroup(Card.IsCanTurnSet,tp,0,LOCATION_MZONE,nil) Duel.SetOperationInfo(0,CATEGORY_POSITION,g,g:GetCount(),0,0) end function cm.tsop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(Card.IsCanTurnSet,tp,LOCATION_MZONE,LOCATION_MZONE,nil) if g:GetCount()>0 then Duel.ChangePosition(g,POS_FACEDOWN_DEFENSE) end end function cm.efilter(e,re) return (re:IsActiveType(TYPE_SPELL) or re:IsActiveType(TYPE_TRAP)) and re:GetOwner()~=e:GetOwner() end
local imgEngine = {} image = {} function imgEngine.autoload(pFolder) if not pFolder then pFolder = "img" end -- if not image then image = {} end -- image.current = 1 -- local filesTable = love.filesystem.getDirectoryItems("img") -- for k,file in ipairs(filesTable) do -- print("le dossier module contient l'element n°"..k.." : "..file) if string.find(file,".jpg") or string.find(file,".png") then -- local new = newImg() new.type = "image" new.typeLoad = "imgEngine Autoload" new.name = string.gsub(file,".jpg","") or string.gsub(file,".png","") new.file = pFolder.."/"..tostring(file) new.img = love.graphics.newImage("img/"..file) new.x = 0 new.y = 0 -- new.w_def = new.img:getWidth() new.h_def = new.img:getHeight() new.w = new.w_def new.h = new.h_def new.ox = new.w * 0.5 new.oy = new.h * 0.5 -- new.rotate = 0 new.sx = 1 new.sy = 1 -- table.insert(image, new) -- add file to table for require if debug.img then print("img detected and loaded to table img["..#image.."] : "..new.name.."\n") end else print("ceci n'est pas une image valide : "..file.."\n") -- if not .lua file, then print this in output end end end -- function imgEngine.newImg() local f = newImg() -- TODO: a faire, Si on veux aujouter une image qui n'est pas dans le repertoire img (un dossier par scene par exemple... et qu'on ne veux pas charger ttes les images) return f end -- function newImg() local f = cl.newPlan() f:setPlan(1) -- function f:init() -- list of variables f.type = "" f.typeLoad = "imgEngine.newImg()" f.name = "" f.file = "" f.img = "" f.isVisible = true -- f.x = 0 f.y = 0 -- f.w_def = 0 f.h_def = 0 f.w = 0 f.h = 0 f.ox = 0 f.oy = 0 -- f.rotate = 0 f.sx = 1 f.sy = 1 -- f.center = false -- f.debug = false -- f.color = {1,1,1,1} -- end -- function f:isVisible(pBool) if pBool == nil then self.isVisible = true return end self.isVisible = pBool end -- function f:setPos(pX, pY) if not pX or not pY then self.x, self.y = 0, 0 return end -- if self.center then self.x = pX - self.ox self.y = pY - self.oy else self.x = pX self.y = pY end -- end -- function f:setScale(pSX, pSY) if pSX == nil or pSY == nil then self.sx, self.sy = 1, 1 return end self.sx = pSX self.sy = pSY -- self.w = self.w_def * pSX self.h = self.h_def * pSY end -- function f:setSizes(pW, pH) if pW == nil or pH == nil then print("error ! setSizes need Widht and Heigh to change size !") return end self.w = pW self.h = pH -- self.sx = pW / self.w_def self.sy = pH / self.h_def end -- function f:setColor(pColor) if pColor == nil then self.color = {1,1,1,1} return end self.color = pColor end -- function f:setCenter(pBool) if pBool == nil then self.center = true return end self.center = pBool end -- -- ANIMATIONS -- function f:setLoop(pLoop) if pLoop == nil then self.frame.loop = true return end self.frame.loop = pLoop end -- -- DEBUG -- function f:setDebug(pBool) if pBool == nil then self.debug = true return end self.debug = pBool end -- function f:update(dt) if self.anim then self.anim:update(dt) end end -- function f:draw() if f.isVisible then -- cl.setColor(self.color) -- love.graphics.draw(self.img, self.x, self.y, self.rotate, self.sx, self.sy) -- if self.debug then cl.setColor(cl.color.green) love.graphics.rectangle("line",self.x, self.y, self.w, self.h) end -- cl.setColor() end end -- -- f:init() -- return f end -- function imgEngine.update(dt) if #image >= 1 then for i = #image, 1, -1 do local img = image[i] img:update(dt) end end end -- return imgEngine
local UIStretch = class("UIStretch") function UIStretch:ctor() cc.GameObject.extend(self):addComponent("components.ui.LayoutProtocol"):exportMethods() self:setLayoutSizePolicy(display.AUTO_SIZE, display.AUTO_SIZE) self.position_ = {x = 0, y = 0} self.anchorPoint_ = display.ANCHOR_POINTS[display.CENTER] end function UIStretch:getPosition() return self.position_.x, self.position_.y end function UIStretch:getPositionX() return self.position_.x end function UIStretch:getPositionY() return self.position_.y end function UIStretch:setPosition(x, y) self.position_.x, self.position_.y = x, y end function UIStretch:setPositionX(x) self.position_.x = x end function UIStretch:setPositionY(y) self.position_.y = y end function UIStretch:getAnchorPoint() return self.anchorPoint_ end function UIStretch:setAnchorPoint(ap) self.anchorPoint_ = ap end return UIStretch
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937' description 'ESX Whitelist' version '1.1.0' server_scripts { '@mysql-async/lib/MySQL.lua', '@es_extended/locale.lua', 'config.lua', 'locales/en.lua', 'locales/fr.lua', 'locales/sv.lua', 'server/main.lua', 'server/commands.lua' }
local Response = require('http').Response local Log = require('./log') Response.auto_server = 'U-Gotta-Luvit' function Response:send(code, data, headers, close) --debug('REQ', self.req.url, code) --if code == 500 then p('ERR', data) end self:writeHead(code, headers or { }) if data then self:write(data) end if close or close == nil then self:finish() end end function Response:fail(reason) self:send(500, reason, { ['Content-Type'] = 'text/plain; charset=UTF-8', ['Content-Length'] = #reason }) end function Response:serve_not_found() self:send(404) end function Response:serve_not_modified(headers) self:send(304, nil, headers) end function Response:serve_invalid_range(size) self:send(416, nil, { ['Content-Range'] = 'bytes=*/' .. size }) end
--[[ © 2015 CloudSixteen.com do not share, re-distribute or modify without permission of its author ([email protected]). Clockwork was created by Conna Wiles (also known as kurozael.) http://cloudsixteen.com/license/clockwork.html --]] Clockwork.kernel:AddFile("materials/gmod/scope-refract.vtf"); Clockwork.kernel:AddFile("materials/gmod/scope-refract.vmt"); Clockwork.kernel:AddFile("materials/gmod/scope.vtf"); Clockwork.kernel:AddFile("materials/gmod/scope.vmt");
-- Copyright (c) 2015 Phil Leblanc -- see LICENSE file ------------------------------------------------------------ -- sha2 tests local sha2 = require "plc.sha2" local bin = require "plc.bin" -- for hex conversion local stx, xts = bin.stohex, bin.hextos local function test_sha2() -- checked with sha2 on https://quickhash.com/ assert(sha2.sha256("") == xts[[ e3b0c44298fc1c149afbf4c8996fb924 27ae41e4649b934ca495991b7852b855 ]] ) assert(sha2.sha256("abc") == xts[[ ba7816bf8f01cfea414140de5dae2223 b00361a396177a9cb410ff61f20015ad ]] ) assert(sha2.sha256(('1'):rep(128)) == xts[[ 4ff5ac52aa16dbe3db447ea12d090c5b b6f1325aaaca5ee059b248a89f673972 ]] ) -- tests for sha512 assert(sha2.sha512("") == xts[[ cf83e1357eefb8bdf1542850d66d8007 d620e4050b5715dc83f4a921d36ce9ce 47d0d13c5d85f2b0ff8318d2877eec2f 63b931bd47417a81a538327af927da3e ]] ) assert(sha2.sha512("abc") == xts[[ ddaf35a193617abacc417349ae204131 12e6fa4e89a97ea20a9eeee64b55d39a 2192992a274fc1a836ba3c23a3feebbd 454d4423643ce80e2a9ac94fa54ca49f ]] ) assert(sha2.sha512(('1'):rep(128)) == xts[[ 610e0f364ac647d7a78be9e1e4b1f423 132a5cb2fa94b0d8baa8d21d42639a77 da897f3d8b3aec464b44d170eb9cf802 0b6e4a377672bce649746be941a1d47d ]] ) --[[ more from FIPS 180-4 (added to test padding) https://csrc.nist.gov/CSRC/media/Projects/ \ Cryptographic-Algorithm-Validation-Program/documents/ \ shs/shabytetestvectors.zip ]] -- 63 bytes assert(sha2.sha512(xts[[ ebb3e2ad7803508ba46e81e220b1cff33ea8381504110e9f8092ef085afef84d b0d436931d085d0e1b06bd218cf571c79338da31a83b4cb1ec6c06d6b98768 ]]) == xts[[ f33428d8fc67aa2cc1adcb2822f37f29cbd72abff68190483e415824f0bcecd4 47cb4f05a9c47031b9c50e0411c552f31cd04c30cea2bc64bcf825a5f8a66028 ]] ) -- 64 bytes assert(sha2.sha512(xts[[ c1ca70ae1279ba0b918157558b4920d6b7fba8a06be515170f202fafd36fb7f7 9d69fad745dba6150568db1e2b728504113eeac34f527fc82f2200b462ecbf5d ]]) == xts[[ 046e46623912b3932b8d662ab42583423843206301b58bf20ab6d76fd47f1cbb cf421df536ecd7e56db5354e7e0f98822d2129c197f6f0f222b8ec5231f3967d ]] ) -- 65 bytes assert(sha2.sha512(xts[[ d3ddddf805b1678a02e39200f6440047acbb062e4a2f046a3ca7f1dd6eb03a18 be00cd1eb158706a64af5834c68cf7f105b415194605222c99a2cbf72c50cb14 bf ]]) == xts[[ bae7c5d590bf25a493d8f48b8b4638ccb10541c67996e47287b984322009d27d 1348f3ef2999f5ee0d38e112cd5a807a57830cdc318a1181e6c4653cdb8cf122 ]] ) -- 127 bytes assert(sha2.sha512(xts[[ c13e6ca3abb893aa5f82c4a8ef754460628af6b75af02168f45b72f8f09e45ed 127c203bc7bb80ff0c7bd96f8cc6d8110868eb2cfc01037d8058992a6cf2effc bfe498c842e53a2e68a793867968ba18efc4a78b21cdf6a11e5de821dcabab14 921ddb33625d48a13baffad6fe8272dbdf4433bd0f7b813c981269c388f001 ]]) == xts[[ 6e56f77f6883d0bd4face8b8d557f144661989f66d51b1fe4b8fc7124d66d9d2 0218616fea1bcf86c08d63bf8f2f21845a3e519083b937e70aa7c358310b5a7c ]] ) ---------------------------------------------------------------- end test_sha2() print("test_sha2: ok")
require('refactoring').setup({}) local utils = require("utils") utils.map("v", "<leader>re", [[ <Esc><Cmd>lua require('refactoring').refactor('Extract Function')<CR>]], {silent = true, expr = false}) utils.map("v", "<leader>rf", [[ <Esc><Cmd>lua require('refactoring').refactor('Extract Function To File')<CR>]], {silent = true, expr = false}) utils.map("v", "<leader>rv", [[ <Esc><Cmd>lua require('refactoring').refactor('Extract Variable')<CR>]], {silent = true, expr = false}) utils.map("v", "<leader>ri", [[ <Esc><Cmd>lua require('refactoring').refactor('Inline Variable')<CR>]], {silent = true, expr = false}) -- Extract block doesn't need visual mode utils.map("n", "<leader>rb", [[ <Cmd>lua require('refactoring').refactor('Extract Block')<CR>]], {silent = true, expr = false}) utils.map("n", "<leader>rbf", [[ <Cmd>lua require('refactoring').refactor('Extract Block To File')<CR>]], {silent = true, expr = false}) -- Inline variable can also pick up the identifier currently under the cursor without visual mode utils.map("n", "<leader>ri", [[ <Cmd>lua require('refactoring').refactor('Inline Variable')<CR>]], {silent = true, expr = false})
--*********************************************************** --** ROBERT JOHNSON ** --*********************************************************** require "TimedActions/ISBaseTimedAction" ---@class ISReadABook : ISBaseTimedAction ISReadABook = ISBaseTimedAction:derive("ISReadABook"); function ISReadABook:isValid() local vehicle = self.character:getVehicle() if vehicle and vehicle:isDriver(self.character) then return not vehicle:isEngineRunning() end return self.character:getInventory():contains(self.item) and ((self.item:getNumberOfPages() > 0 and self.item:getAlreadyReadPages() <= self.item:getNumberOfPages()) or self.item:getNumberOfPages() < 0); end function ISReadABook:update() self.pageTimer = self.pageTimer + getGameTime():getMultiplier(); self.item:setJobDelta(self:getJobDelta()); if self.item:getNumberOfPages() > 0 then local pagesDifference = self.item:getNumberOfPages() - self.startPage local pagesRead = math.floor(pagesDifference * self:getJobDelta()) self.item:setAlreadyReadPages(self.startPage + pagesRead); if self.item:getAlreadyReadPages() > self.item:getNumberOfPages() then self.item:setAlreadyReadPages(self.item:getNumberOfPages()); end self.character:setAlreadyReadPages(self.item:getFullType(), self.item:getAlreadyReadPages()) end if SkillBook[self.item:getSkillTrained()] then if self.item:getLvlSkillTrained() > self.character:getPerkLevel(SkillBook[self.item:getSkillTrained()].perk) + 1 or self.character:HasTrait("Illiterate") then if self.pageTimer >= 200 then self.pageTimer = 0; local txtRandom = ZombRand(3); if txtRandom == 0 then self.character:Say(getText("IGUI_PlayerText_DontGet")); elseif txtRandom == 1 then self.character:Say(getText("IGUI_PlayerText_TooComplicated")); else self.character:Say(getText("IGUI_PlayerText_DontUnderstand")); end if self.item:getNumberOfPages() > 0 then self.character:setAlreadyReadPages(self.item:getFullType(), 0) self:forceStop() end end elseif self.item:getMaxLevelTrained() < self.character:getPerkLevel(SkillBook[self.item:getSkillTrained()].perk) + 1 then if self.pageTimer >= 200 then self.pageTimer = 0; local txtRandom = ZombRand(2); if txtRandom == 0 then self.character:Say(getText("IGUI_PlayerText_KnowSkill")); else self.character:Say(getText("IGUI_PlayerText_BookObsolete")); end end else ISReadABook.checkMultiplier(self); end end -- Playing with longer day length reduces the effectiveness of morale-boosting -- literature, like Comic Book. local bodyDamage = self.character:getBodyDamage() local stats = self.character:getStats() if self.stats and (self.item:getBoredomChange() < 0.0) then if bodyDamage:getBoredomLevel() > self.stats.boredom then bodyDamage:setBoredomLevel(self.stats.boredom) end end if self.stats and (self.item:getUnhappyChange() < 0.0) then if bodyDamage:getUnhappynessLevel() > self.stats.unhappyness then bodyDamage:setUnhappynessLevel(self.stats.unhappyness) end end if self.stats and (self.item:getStressChange() < 0.0) then if stats:getStress() > self.stats.stress then stats:setStress(self.stats.stress) end end end -- get how much % of the book we already read, then we apply a multiplier depending on the book read progress ISReadABook.checkMultiplier = function(self) -- get all our info in the map local trainedStuff = SkillBook[self.item:getSkillTrained()]; if trainedStuff then -- every 10% we add 10% of the max multiplier local readPercent = (self.item:getAlreadyReadPages() / self.item:getNumberOfPages()) * 100; if readPercent > 100 then readPercent = 100; end -- apply the multiplier to the skill local multiplier = (math.floor(readPercent/10) * (self.maxMultiplier/10)); if multiplier > self.character:getXp():getMultiplier(trainedStuff.perk) then self.character:getXp():addXpMultiplier(trainedStuff.perk, multiplier, self.item:getLvlSkillTrained(), self.item:getMaxLevelTrained()); end end end function ISReadABook.checkLevel(character, item) if item:getNumberOfPages() <= 0 then return end local skillBook = SkillBook[item:getSkillTrained()] if not skillBook then return end local level = character:getPerkLevel(skillBook.perk) if (item:getLvlSkillTrained() > level + 1) or character:HasTrait("Illiterate") then item:setAlreadyReadPages(0) character:setAlreadyReadPages(item:getFullType(), 0) end end function ISReadABook:start() self.item:setJobType(getText("ContextMenu_Read") ..' '.. self.item:getName()); self.item:setJobDelta(0.0); self.startTimeHours = getGameTime():getTimeOfDay() --self.character:SetPerformingAction(GameCharacterActions.Reading, nil, self.item) if (self.item:getType() == "Newspaper") then self:setAnimVariable("ReadType", "newspaper") else self:setAnimVariable("ReadType", "book") end self:setActionAnim(CharacterActionAnims.Read); self:setOverrideHandModels(nil, self.item); self.character:setReading(true) self.character:reportEvent("EventRead"); if not SkillBook[self.item:getSkillTrained()] then self.stats = {} self.stats.boredom = self.character:getBodyDamage():getBoredomLevel() self.stats.unhappyness = self.character:getBodyDamage():getUnhappynessLevel() self.stats.stress = self.character:getStats():getStress() end end function ISReadABook:stop() if self.item:getNumberOfPages() > 0 and self.item:getAlreadyReadPages() >= self.item:getNumberOfPages() then self.item:setAlreadyReadPages(self.item:getNumberOfPages()); end self.character:setReading(false); self.item:setJobDelta(0.0); ISBaseTimedAction.stop(self); end function ISReadABook:perform() self.character:setReading(false); self.item:getContainer():setDrawDirty(true); self.item:setJobDelta(0.0); if not SkillBook[self.item:getSkillTrained()] then self.character:ReadLiterature(self.item); elseif self.item:getAlreadyReadPages() >= self.item:getNumberOfPages() then -- self.character:ReadLiterature(self.item); self.item:setAlreadyReadPages(0); end -- if self.item:getTeachedRecipes() and not self.item:getTeachedRecipes():isEmpty() then -- for i=0, self.item:getTeachedRecipes():size() - 1 do -- if not self.character:getKnownRecipes():contains(self.item:getTeachedRecipes():get(i)) then -- self.character:getKnownRecipes():add(self.item:getTeachedRecipes():get(i)); -- else -- self.character:Say(getText("IGUI_PlayerText_KnowSkill")); -- end -- end -- end -- needed to remove from queue / start next. ISBaseTimedAction.perform(self); end function ISReadABook:new(character, item, time) local o = {} setmetatable(o, self) self.__index = self o.character = character; o.item = item; o.stopOnWalk = true; o.stopOnRun = true; local numPages if item:getNumberOfPages() > 0 then ISReadABook.checkLevel(character, item) item:setAlreadyReadPages(character:getAlreadyReadPages(item:getFullType())) o.startPage = item:getAlreadyReadPages() numPages = item:getNumberOfPages() - item:getAlreadyReadPages() else numPages = 5 end if isClient() then o.minutesPerPage = getServerOptions():getFloat("MinutesPerPage") or 1.0 if o.minutesPerPage < 0.0 then o.minutesPerPage = 1.0 end else o.minutesPerPage = 2.0 end local f = 1 / getGameTime():getMinutesPerDay() / 2 time = numPages * o.minutesPerPage / f if(character:HasTrait("FastReader")) then time = time * 0.7; end if(character:HasTrait("SlowReader")) then time = time * 1.3; end if SkillBook[item:getSkillTrained()] then if item:getLvlSkillTrained() == 1 then o.maxMultiplier = SkillBook[item:getSkillTrained()].maxMultiplier1; elseif item:getLvlSkillTrained() == 3 then o.maxMultiplier = SkillBook[item:getSkillTrained()].maxMultiplier2; elseif item:getLvlSkillTrained() == 5 then o.maxMultiplier = SkillBook[item:getSkillTrained()].maxMultiplier3; elseif item:getLvlSkillTrained() == 7 then o.maxMultiplier = SkillBook[item:getSkillTrained()].maxMultiplier4; elseif item:getLvlSkillTrained() == 9 then o.maxMultiplier = SkillBook[item:getSkillTrained()].maxMultiplier5; else o.maxMultiplier = 1 print('ERROR: book has unhandled skill level ' .. item:getLvlSkillTrained()) end end o.ignoreHandsWounds = true; o.maxTime = time; o.caloriesModifier = 0.5; o.pageTimer = 0; o.forceProgressBar = true; if character:isTimedActionInstant() then o.maxTime = 1; end return o; end
---------------------- -------------------- -- String Functions ---------------- -------------- ------------ ---------- -------- ------ ---- -- ------------------ -- Private Functions -------- ------ ---- -- ------------------ -- Public Functions -------- ------ ---- -- -- _:camelCase(str) -- Converts `str` to [Camel Case](https://en.wikipedia.org/wiki/Camel_case). -- -- @param string(str) -- @return string function _:camelCase(str) str = _:assertArgument('str', str, 'string') -- local words = _:words(_.__lower(str)) local out = '' for idx, word in pairs(words) do out = out .. (idx == 1 and word or _:capitalize(word)) end return out end -- _:capitalize(str) -- Capitalizes first character of `str` -- and lower cases the rest. -- -- @param string(str) -- @return string function _:capitalize(str) str = _:assertArgument('str', str, 'string') -- str = _.__lower(str) -- lower case entire string str = _.__gsub(str, '%f[%a]%a', _.__upper) -- perform capitalize return str end -- _:endsWith(str, target, [position=_:size(str)]) -- Determines if `str` ends with `target` up until -- the end `position`. -- -- @param string(str) -- @return boolean function _:endsWith(str, target, position) str = _:assertArgument('str', str, 'string') target = _:assertArgument('target', target, 'string') position = _:assertArgument('position', position, 'number', _:size(str)) -- local substr = _.__sub(str, 0, position) return _.__find(substr, target) == _:size(substr) end -- _:kebabCase(str) -- Converts `str` to [Kebab Case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). -- -- @param string(str) -- @return string function _:kebabCase(str) str = _:assertArgument('str', str, 'string') -- str = _.__gsub(str, '%f[%u]', ' ') -- separate uppercase transitions str = _.__lower(str) -- lower case entire string return _:join(_:words(str), '-') -- join `words` with `-` end -- _:lowerCase(str) -- Converts `str` to lower-case, space-separated words. -- -- @param string(str) -- @return string function _:lowerCase(str) str = _:assertArgument('str', str, 'string') -- str = _.__gsub(str, '%f[%u]', ' ') -- separate uppercase transitions str = _.__lower(str) -- lower case entire string return _:join(_:words(str), ' ') -- join `words` with `-` end -- _:lowerFirst(str) -- Lower-cases first character in `str`. -- -- @param string(str) -- @return string function _:lowerFirst(str) str = _:assertArgument('str', str, 'string') -- return _.__gsub(str, '^%a', _.__lower) end -- _:pad(str, [length=0], [chars=" "]) -- Pads both sides of `str` with `chars`, -- only if `str` is smaller than `length`. -- -- @param string(str) -- @param number(length) -- @param string(chars) -- @return string function _:pad(str, length, chars) str = _:assertArgument('str', str, 'string') length = _:assertArgument('length', length, 'number', 0) chars = _:assertArgument('chars', chars, 'string', ' ') -- local padSize = length - _.__len(str) local halfSize = padSize / 2 local left = "" local right = "" -- if we need to pad, split pad size 1/2 if padSize > 0 then chars = _.__rep(chars, padSize) left = _.__sub(chars, 1, _.__floor(halfSize)) right = _.__sub(chars, 1, _.__ceil(halfSize)) end return left .. str .. right end -- _:padEnd(str, [length=0], [chars=" "]) -- Pads end of `str` with `chars`, only if -- `str` is smaller than `length`. -- -- @param string(str) -- @param number(length) -- @param string(chars) -- @return string function _:padEnd(str, length, chars) str = _:assertArgument('str', str, 'string') length = _:assertArgument('length', length, 'number', 0) chars = _:assertArgument('chars', chars, 'string', ' ') -- chars = _.__rep(chars, length) chars = _.__sub(chars, 1, length - _.__len(str)) return str .. chars end -- _:padStart(str, [length=0], [chars=" "]) -- Pads beginning of `str` with `chars`, only -- if `str` is smaller than `length`. -- -- @param string(str) -- @param number(length) -- @param string(chars) -- @return string function _:padStart(str, length, chars) str = _:assertArgument('str', str, 'string') length = _:assertArgument('length', length, 'number', 0) chars = _:assertArgument('chars', chars, 'string', ' ') -- chars = _.__rep(chars, length) chars = _.__sub(chars, 1, length - _.__len(str)) return chars .. str end -- _:rep(str, [n=1]) -- Repeats given `str` `n` number of times. -- -- @param string(str) -- @return string function _:rep(str, n) str = _:assertArgument('str', str, 'string') n = _:assertArgument('n', n, 'number', 1) -- return _.__rep(str, n) end -- _:replace(str, pattern, [repl=""], [n]) -- Replaces matches from `pattern` in `str` -- with `repl` string. -- -- @param string(str) -- @param string(pattern) -- @param string(repl) - replacement string -- @param number(n) - n-th capture in pattern -- @return string function _:replace(str, pattern, repl, n) str = _:assertArgument('str', str, 'string') pattern = _:assertArgument('pattern', pattern, 'string') repl = _:assertArgument('repl', repl, 'string', '') -- return _.__gsub(str, pattern, repl, n) end -- _:snakeCase(str) -- Converts `str` to [Snake Case](https://en.wikipedia.org/wiki/Snake_case). -- -- @param string(str) -- @return string function _:snakeCase(str) str = _:assertArgument('str', str, 'string') -- -- maybe inefficient, but easy to follow.. str = _.__gsub(str, '(.%f[%u])', '%0_') -- convert uppercase transitions to `_` str = _.__gsub(str, '[%p%s]+', '_') -- convert punctuations to `_` str = _:trim(str, '_') -- trim leading/trailing `_` chars return _.__lower(str) -- lower-case string end -- _:split(str, [separator='[^-]'], [limit=_:size(str)]) -- Splits `str` by `separator`, truncated by `limit`. -- -- @param string(str) -- @return table function _:split(str, separator, limit) str = _:assertArgument('str', str, 'string') separator = _:assertArgument('separator', separator, 'string', '%s+') -- local elements = _:words(str, '[^' .. separator .. ']') local length = _:size(elements) -- limit = _:assertArgument('limit', limit, 'number', length) -- return _:drop(elements, length - limit) end -- _:startCase(str) -- Converts `str` to [Start Case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). -- -- @param string(str) -- @return string function _:startCase(str, target, position) str = _:assertArgument('str', str, 'string') -- str = _.__gsub(str, '%f[%u]', ' ') -- separate uppercase transitions local words = _:words(str) local out = '' for idx, word in pairs(words) do if idx == 1 then out = out .. _:upperFirst(word) else out = out .. ' ' .. _:upperFirst(word) end end return out end -- _:startsWith(str, target, [position=1]) -- Determine if `str` starts with `target`, -- starting at `position`. -- -- @param string(str) -- @param string(target) -- @param number(position) -- @return string function _:startsWith(str, target, position) str = _:assertArgument('str', str, 'string') target = _:assertArgument('target', target, 'string') position = _:assertArgument('position', position, 'number', 1) -- return _.__find(_.__sub(str, position), target) == 1 end -- _:toLower(str) -- Converts entire `str` to lower case. -- -- @param string(str) -- @return string function _:toLower(str) str = _:assertArgument('str', str, 'string') -- return _.__lower(str) end -- _:toUpper(str) -- Converts entire `str` to upper case. -- -- @param string(str) -- @return string function _:toUpper(str) str = _:assertArgument('str', str, 'string') -- return _.__upper(str) end -- _:trim(str, [pattern='%s+']) -- Removes leading and trailing `pattern` of `str`. -- -- @param string(str) -- @param string(pattern) -- @return string function _:trim(str, pattern) str = _:trimStart(str, pattern) str = _:trimEnd(str, pattern) return str end -- _:trimEnd(str, [pattern='%s+']) -- Removes trailing `pattern` of `str`. -- -- @param string(str) -- @param string(pattern) -- @return string function _:trimEnd(str, pattern) str = _:assertArgument('str', str, 'string') pattern = _:assertArgument('pattern', pattern, 'string', '%s+') -- if _:isRegexPattern(pattern) then return _:replace(str, pattern .. '$', '') else return _:replace(str, '[' .. pattern .. ']+$', '') end end -- _:trimStart(str, [pattern='%s+']) -- Removes leading `pattern` or `str`. -- -- @param string(str) -- @param string(pattern) -- @return string function _:trimStart(str, pattern) str = _:assertArgument('str', str, 'string') pattern = _:assertArgument('pattern', pattern, 'string', '%s+') -- if _:isRegexPattern(pattern) then return _:replace(str, '^' .. pattern, '') else return _:replace(str, '^[' .. pattern .. ']+', '') end end -- _:truncate(str, [options]) -- Truncates `str` with `options`. -- -- options: -- - number(length=30) -- truncate length -- - string(separator) -- pattern to truncate to -- - string(omission='...') -- omitted text symbol -- -- @param string(str) -- @return string function _:truncate(str, options) str = _:assertArgument('str', str, 'string') -- options = { length = _:assertArgument('length', (options and options['length'] or nil), 'number', 30), separator = _:assertArgument('separator', (options and options['separator'] or nil), 'string', ''), omission = _:assertArgument('omission', (options and options['omission'] or nil), 'string', '...') } -- local separator = options.separator local omission = options.omission local length = options.length - _.__len(omission) if not _:isEmpty(separator) then local len len = _.__find(str, separator) -- find first occurrence of `separator` len = len - 1 -- offset length to exclude match str = _.__sub(str, 1, len) -- drop end of string after and including pattern length = _.__min(length, len) end str = _.__sub(str, 1, length) str = str .. omission return str end -- _:upperCase(str) -- Converts `str` to space-separated, upper case string. -- -- @param string(str) -- @return string function _:upperCase(str) str = _:assertArgument('str', str, 'string') -- str = _.__gsub(str, '%f[%u]', ' ') -- separate uppercase transitions local words = _:words(str) return _:join(_:map(words, _.__upper), ' ') end -- _:upperFirst(str) -- Converts first character in `str` to upper -- case, leaving the rest untouched. -- -- @param string(str) -- @return string function _:upperFirst(str) str = _:assertArgument('str', str, 'string') -- return _.__gsub(str, '^%a', _.__upper) end -- _:words(str, [pattern='%a+']) -- Converts `str` into table of words, using -- `pattern` as separator. -- -- @param string(str) -- @param string(pattern) -- @return table function _:words(str, pattern) str = _:assertArgument('str', str, 'string') pattern = _:assertArgument('pattern', pattern, 'string', '%a+') _:assertIsRegexPattern('pattern', pattern) -- local words = {} for match in _.__gmatch(str, pattern) do _.__insert(words, match) end return words end
return {'vocaal','vocabulaire','vocabularium','vocalise','vocaliseren','vocalist','vocaliste','vocalistenconcours','vocatie','vocatief','vocht','vochtafscheiding','vochtbalans','vochtblaas','vochtblaasje','vochten','vochtgehalte','vochthoudend','vochthuishouding','vochtig','vochtigheid','vochtigheidsgraad','vochtigheidsmeter','vochtmaat','vochtmeter','vochtminnend','vochtniveau','vochtophoping','vochtplek','vochtresistent','vochtverlies','vochtvlek','vochtvrij','vochtweger','vochtwerend','vochtwering','vochtkring','vochtvoorziening','vochtafdrijvend','vochtprobleem','vochtinbrengend','vochtopname','vochttekort','vochtafvoer','vochtbeperking','vochtigheidsgehalte','vochtinname','vochtmeting','vochtpercentage','vochtschade','vochttoediening','vochttoestand','vochttransport','vochtvoorraad','vochtbehoefte','vochtgevoelig','vochtinwerking','vochtgebrek','vochtvreter','vochtbestrijding','vocking','vocabulaires','vocale','vocalen','vocaliseer','vocaliseerde','vocaliseerden','vocaliseert','vocalises','vocalisten','vocaties','vocatieven','vochtblaasjes','vochtige','vochtiger','vochtigere','vochtigheidsmeters','vochtigst','vochtigste','vochtplekken','vochtresistente','vochtte','vochtten','vochtvrije','vochtwegers','vochtwerende','vochthoudende','vochtmeters','vochtminnende','vochtvlekken','vocabularia','vocabulariums','vochtgehalten','vochtgehaltes','vochtkringen','vochtproblemen','vochtinbrengende','vochtophopingen','vochtvreters','vochttekorten'}
local S = technic.getter technic.register_recipe_type("alloy", { description = S("Alloying"), input_size = 2, }) function technic.register_alloy_recipe(data) data.time = data.time or 6 technic.register_recipe("alloy", data) end local recipes = { {"technic:copper_dust 3", "technic:tin_dust", "technic:bronze_dust 4"}, {"default:copper_ingot 3", "moreores:tin_ingot", "default:bronze_ingot 4"}, {"technic:wrought_iron_dust", "technic:coal_dust", "technic:carbon_steel_dust", 3}, {"technic:wrought_iron_ingot", "technic:coal_dust", "technic:carbon_steel_ingot", 3}, {"technic:carbon_steel_dust", "technic:coal_dust", "technic:cast_iron_dust", 3}, {"technic:carbon_steel_ingot", "technic:coal_dust", "technic:cast_iron_ingot", 3}, {"technic:carbon_steel_dust 3", "technic:chromium_dust", "technic:stainless_steel_dust 4"}, {"technic:carbon_steel_ingot 3", "technic:chromium_ingot", "technic:stainless_steel_ingot 4"}, {"technic:copper_dust 2", "technic:zinc_dust", "technic:brass_dust 3"}, {"default:copper_ingot 2", "technic:zinc_ingot", "technic:brass_ingot 3"}, {"default:sand 2", "technic:coal_dust 2", "technic:silicon_wafer"}, {"technic:silicon_wafer", "technic:gold_dust", "technic:doped_silicon_wafer"}, {"tutorial:uranium1", "technic:bucket_corium", "tutorial:plutonium_ingot"}, {"tutorial:plutonium_ingot", "technic:bucket_corium", "tutorial:uranium1"}, {"tutorial:uranium2", "technic:bucket_corium", "tutorial:blei_ingot"}, {"tutorial:blei_ingot", "technic:bucket_corium", "tutorial:uranium2"}, } for _, data in pairs(recipes) do technic.register_alloy_recipe({input = {data[1], data[2]}, output = data[3], time = data[4]}) end
-- TODO: Managerklasse Schreiben! InfoPickups = {} CInfoPickup = {} function CInfoPickup:constructor(ID,X,Y,Z,Int,Dim,Text) self.ID = ID self.X = X self.Y = Y self.Z = Z self.Int = Int self.Dim = Dim self.Text = Text self.eHit = bind(CInfoPickup.onHit, self) addEventHandler("onPickupHit", self, self.eHit) InfoPickups[self.ID] = self end function CInfoPickup:onHit(thePlayer) if(thePlayer) and (isElement(thePlayer)) and (getElementType(thePlayer) == "player") then thePlayer:showInfoBox("question", self.Text) end end
return require "lzmq.impl.loop"("lzmq.ffi")
local cfg = module("cfg/aptitudes") -- exp notes: -- levels are defined by the amount of xp -- with a step of 5: 5|15|30|50|75 -- total exp for a specific level, exp = step*lvl*(lvl+1)/2 -- level for a specific exp amount, lvl = (sqrt(1+8*exp/step)-1)/2 local exp_step = 5 local gaptitudes = {} function vRP.defAptitudeGroup(group, title) gaptitudes[group] = {_title = title} end -- max_exp: -1 => infinite function vRP.defAptitude(group, aptitude, title, init_exp, max_exp) local vgroup = gaptitudes[group] if vgroup ~= nil then vgroup[aptitude] = {title,init_exp,max_exp} end end function vRP.getAptitudeDefinition(group, aptitude) local vgroup = gaptitudes[group] if vgroup ~= nil and aptitude ~= "_title" then return vgroup[aptitude] end return nil end function vRP.getAptitudeGroupTitle(group) if gaptitudes[group] ~= nil then return gaptitudes[group]._title end return "" end function vRP.getUserAptitudes(user_id) local data = vRP.getUserDataTable(user_id) if data == nil then return nil end if data.gaptitudes == nil then data.gaptitudes = {} end for k,v in pairs(gaptitudes) do if data.gaptitudes[k] == nil then data.gaptitudes[k] = {} end local group = data.gaptitudes[k] for l,w in pairs(v) do if l ~= "_title" and group[l] == nil then group[l] = w[2] end end end return data.gaptitudes end function vRP.varyExp(user_id, group, aptitude, amount) local def = vRP.getAptitudeDefinition(group, aptitude) local uaptitudes = vRP.getUserAptitudes(user_id) if def ~= nil and uaptitudes ~= nil then local exp = uaptitudes[group][aptitude] local level = math.floor(vRP.expToLevel(exp)) exp = exp+amount if exp < 0 then exp = 0 elseif def[3] >= 0 and exp > def[3] then exp = def[3] end uaptitudes[group][aptitude] = exp local player = vRP.getUserSource(user_id) if player ~= nil then local group_title = vRP.getAptitudeGroupTitle(group) local aptitude_title = def[1] if amount < 0 then vRPclient._notify(player,'error',5,aptitude_title,'Você Perdeu Experiencia: -('.. -1*amount ..')') elseif amount > 0 then vRPclient._notify(player,'info',5,aptitude_title,'Você Ganhou Experiencia: +('.. -1*amount ..')') end --- level up/down local new_level = math.floor(vRP.expToLevel(exp)) local diff = new_level-level if diff < 0 then vRPclient._notify(player,'error',5,aptitude_title,'Você Perdeu Nivel de '..group_title..'/'..aptitude_title..': ('.. new_level ..')') elseif diff > 0 then vRPclient._notify(player,'info',5,aptitude_title,'Você Ganhou Nivel de '..group_title..'/'..aptitude_title..': ('.. new_level ..')') end end end end function vRP.levelUp(user_id, group, aptitude) local exp = vRP.getExp(user_id,group,aptitude) local next_level = math.floor(vRP.expToLevel(exp))+1 local next_exp = vRP.levelToExp(next_level) local add_exp = next_exp-exp vRP.varyExp(user_id, group, aptitude, add_exp) end function vRP.levelDown(user_id, group, aptitude) local exp = vRP.getExp(user_id,group,aptitude) local prev_level = math.floor(vRP.expToLevel(exp))-1 local prev_exp = vRP.levelToExp(prev_level) local add_exp = prev_exp-exp vRP.varyExp(user_id, group, aptitude, add_exp) end function vRP.getExp(user_id, group, aptitude) local uaptitudes = vRP.getUserAptitudes(user_id) if not uaptitudes then return 0 end local vgroup = uaptitudes[group] if not vgroup then return end return vgroup[aptitude] or 0 end function vRP.setExp(user_id, group, aptitude, amount) local exp = vRP.getExp(user_id, group, aptitude) vRP.varyExp(user_id, group, aptitude, amount-exp) end function vRP.expToLevel(exp) return (math.sqrt(1+8*exp/exp_step)-1)/2 end function vRP.levelToExp(lvl) return math.floor((exp_step*lvl*(lvl+1))/2) end for k,v in pairs(cfg.gaptitudes) do vRP.defAptitudeGroup(k,v._title or "") for l,w in pairs(v) do if l ~= "_title" then vRP.defAptitude(k,l,w[1],w[2],w[3]) end end end
local function StagesRemaining() if not FlowDJ.fake_play then FlowDJ.stage = GAMESTATE:GetCurrentStageIndex() end local stages = FlowDJGetSetting("NumberOfStages") return FlowDJ.stage < stages end local BaseSelectMusicOrCourse = SelectMusicOrCourse function SelectMusicOrCourse() if IsNetSMOnline() then return BaseSelectMusicOrCourse() elseif GAMESTATE:IsCourseMode() then return BaseSelectMusicOrCourse() else if StagesRemaining() then return "ScreenFlowDJPick" else return GameOverOrContinue() end end end local BasePlayerOptions = Branch.PlayerOptions Branch.PlayerOptions = function() song = GAMESTATE:GetCurrentSong() table.insert(FlowDJ.manual_songs, song:GetMusicPath()) return "ScreenFlowDJPick" end local BaseAfterGameplay = Branch.AfterGameplay Branch.AfterGameplay = function() if StagesRemaining() then return "ScreenProfileSave" else return Branch.EvaluationScreen() end end local BaseAfterProfileSave = Branch.AfterProfileSave Branch.AfterProfileSave = function() if StagesRemaining() then return "ScreenFlowDJPick" else return "ScreenEvaluationSummary" end end local BaseAfterSelectProfile = Branch.AfterSelectProfile Branch.AfterSelectProfile = function() GAMESTATE:SetCurrentPlayMode('PlayMode_Regular') FlowDJ.stage = 0 FlowDJ.manual_songs = {} return SelectMusicOrCourse() end local BaseAfterProfileLoad = Branch.AfterProfileLoad Branch.AfterProfileLoad = function() GAMESTATE:SetCurrentPlayMode('PlayMode_Regular') FlowDJ.stage = 0 FlowDJ.manual_songs = {} return SelectMusicOrCourse() end local BaseAfterScreenSelectColor = Branch.AfterScreenSelectColor Branch.AfterScreenSelectColor = function() GAMESTATE:SetCurrentPlayMode('PlayMode_Regular') FlowDJ.stage = 0 FlowDJ.manual_songs = {} BaseAfterScreenSelectColor() return "ScreenFlowDJPick" end
--- Adds simple Get/Set accessor functions on the specified table. --- Can also force the value to be set to a number, bool or string. --- @param tab table @The table to add the accessor functions too. --- @param key any @The key of the table to be get/set. --- @param name string @The name of the functions (will be prefixed with Get and Set). --- @param force number @The type the setter should force to (uses Enums/FORCE). function _G.AccessorFunc(tab, key, name, force) end --- Marks a Lua file to be sent to clients when they join the server. Doesn't do anything on the client - this means you can use it in a shared file without problems. --- ⚠ **WARNING**: If the file trying to be added is empty, an error will occur, and the file will not be sent to the client. --- ℹ **NOTE**: This function is not needed for scripts located in **lua/autorun/** and **lua/autorun/client/**: they are automatically sent to clients. --- ℹ **NOTE**: You can add up to 8192 files. --- @param file string @The name/path to the Lua file that should be sent, relative to the garrysmod/lua folder function _G.AddCSLuaFile(file) end --- Adds the specified vector to the PVS which is currently building. This allows all objects in visleafs visible from that vector to be drawn. --- @param position GVector @The origin to add. function _G.AddOriginToPVS(position) end --- This function creates a World Tip, similar to the one shown when aiming at a Thruster where it shows you its force. --- This function will make a World Tip that will only last 50 milliseconds (1/20th of a second), so you must call it continuously as long as you want the World Tip to be shown. It is common to call it inside a Think hook. --- Contrary to what the function's name implies, it is impossible to create more than one World Tip at the same time. A new World Tip will overwrite the old one, so only use this function when you know nothing else will also be using it. --- See SANDBOX:PaintWorldTips for more information. --- ℹ **NOTE**: This function is only available in Sandbox and its derivatives --- @param entindex number @**This argument is no longer used**; it has no effect on anything --- @param text string @The text for the world tip to display. --- @param dieTime number @**This argument is no longer used**; when you add a World Tip it will always last only 0.05 seconds --- @param pos GVector @Where in the world you want the World Tip to be drawn --- @param ent GEntity @Which entity you want to associate with the World Tip function _G.AddWorldTip(entindex, text, dieTime, pos, ent) end --- Defines a global entity class variable with an automatic value in order to prevent collisions with other Enums/CLASS. You should prefix your variable with CLASS_ for consistency. --- @param name string @The name of the new enum/global variable. function _G.Add_NPC_Class(name) end --- Loads the specified image from the /cache folder, used in combination steamworks.Download. --- Most addons will provide a 512x512 png image. --- @param name string @The name of the file. --- @return GIMaterial @The material, returns nil if the cached file is not an image. function _G.AddonMaterial(name) end --- Creates an Angle object. --- @param pitch number @The pitch value of the angle --- @param yaw number @The yaw value of the angle. --- @param roll number @The roll value of the angle. --- @return GAngle @Created angle function _G.Angle(pitch, yaw, roll) end --- Returns an angle with a randomized pitch, yaw, and roll between min(inclusive), max(exclusive). --- @param min number @Min bound inclusive. --- @param max number @Max bound exclusive. --- @return GAngle @The randomly generated angle. function _G.AngleRand(min, max) end --- Sends the specified Lua code to all connected clients and executes it. --- ℹ **NOTE**: If you need to use this function more than once consider using net library. Send net message and make the entire code you want to execute in net.Receive on client. --- @param code string @The code to be executed function _G.BroadcastLua(code) end --- Dumps the networked variables of all entities into one table and returns it. --- @return table @Format: function _G.BuildNetworkedVarsTable() end --- Automatically called by the engine when a panel is hovered over with the mouse --- @param panel GPanel @Panel that has been hovered over function _G.ChangeTooltip(panel) end --- Creates a non physical entity that only exists on the client. See also ents.CreateClientProp. --- 🦟 **BUG**: [Parented clientside models will become detached if the parent entity leaves the PVS.](https://github.com/Facepunch/garrysmod-issues/issues/861) --- 🦟 **BUG**: [Clientside entities are not garbage-collected, thus you must store a reference to the object and call CSEnt:Remove manually.](https://github.com/Facepunch/garrysmod-issues/issues/1387) --- 🦟 **BUG**: [Clientside models will occasionally delete themselves during high server lag.](https://github.com/Facepunch/garrysmod-issues/issues/3184) --- @param model string @The file path to the model --- @param renderGroup number @The render group of the entity for the clientside leaf system, see Enums/RENDERGROUP. --- @return GCSEnt @Created client-side model function _G.ClientsideModel(model, renderGroup) end --- Creates a fully clientside ragdoll. --- ℹ **NOTE**: The ragdoll initially starts as hidden and with shadows disabled, see the example for how to enable it. --- There's no need to call Entity:Spawn on this entity. --- The physics won't initialize at all if the model hasn't been precached serverside first. --- 🦟 **BUG**: [Clientside entities are not garbage-collected, thus you must store a reference to the object and call CSEnt:Remove manually.](https://github.com/Facepunch/garrysmod-issues/issues/1387) --- @param model string @The file path to the model --- @param renderGroup number @The Enums/RENDERGROUP to assign. --- @return GCSEnt @The newly created client-side ragdoll function _G.ClientsideRagdoll(model, renderGroup) end --- Creates a scene entity based on the scene name and the entity. --- @param name string @The name of the scene. --- @param targetEnt GEntity @The entity to play the scene on. --- @return GCSEnt @C_SceneEntity function _G.ClientsideScene(name, targetEnt) end --- Closes all Derma menus that have been passed to Global.RegisterDermaMenuForClose and calls GM:CloseDermaMenus function _G.CloseDermaMenus() end --- Creates a Color. --- @param r number @An integer from 0-255 describing the red value of the color. --- @param g number @An integer from 0-255 describing the green value of the color. --- @param b number @An integer from 0-255 describing the blue value of the color. --- @param a number @An integer from 0-255 describing the alpha (transparency) of the color. --- @return table @The created Color. function _G.Color(r, g, b, a) end --- Returns a new Color with the RGB components of the given Color and the alpha value specified. --- @param color table @The Color from which to take RGB values --- @param alpha number @The new alpha value, a number between 0 and 255 --- @return table @The new Color with the modified alpha value function _G.ColorAlpha(color, alpha) end --- Creates a Color with randomized red, green, and blue components. If the alpha argument is true, alpha will also be randomized. --- @param a boolean @Should alpha be randomized. --- @return table @The created Color. function _G.ColorRand(a) end --- Converts a Color into HSL color space. --- @param color table @The Color. --- @return number @The hue in degrees [0, 360). --- @return number @The saturation in the range [0, 1]. --- @return number @The lightness in the range [0, 1]. function _G.ColorToHSL(color) end --- Converts a Color into HSV color space. --- @param color table @The Color. --- @return number @The hue in degrees [0, 360). --- @return number @The saturation in the range [0, 1]. --- @return number @The value in the range [0, 1]. function _G.ColorToHSV(color) end --- Attempts to compile the given file. If successful, returns a function that can be called to perform the actual execution of the script. --- @param path string @Path to the file, relative to the garrysmod/lua/ directory. --- @return function @The function which executes the script. function _G.CompileFile(path) end --- This function will compile the code argument as lua code and return a function that will execute that code. --- Please note that this function will not automatically execute the given code after compiling it. --- @param code string @The code to compile. --- @param identifier string @An identifier in case an error is thrown --- @param HandleError boolean @If false this function will return an error string instead of throwing an error. --- @return function @A function that, when called, will execute the given code function _G.CompileString(code, identifier, HandleError) end --- Returns whether a ConVar with the given name exists or not --- @param name string @Name of the ConVar. --- @return boolean @True if the ConVar exists, false otherwise. function _G.ConVarExists(name) end --- Makes a clientside-only console variable --- ℹ **NOTE**: This function is a wrapper of Global.CreateConVar, with the difference being that FCVAR_ARCHIVE and FCVAR_USERINFO are added automatically when **shouldsave** and **userinfo** are true, respectively. --- Although this function is shared, it should only be used clientside. --- @param name string @Name of the ConVar to be created and able to be accessed --- @param default string @Default value of the ConVar. --- @param shouldsave boolean @Should the ConVar be saved across sessions --- @param userinfo boolean @Should the ConVar and its containing data be sent to the server when it has changed --- @param helptext string @Help text to display in the console. --- @param min number @If set, the convar cannot be changed to a number lower than this value. --- @param max number @If set, the convar cannot be changed to a number higher than this value. --- @return GConVar @Created convar. function _G.CreateClientConVar(name, default, shouldsave, userinfo, helptext, min, max) end --- Creates a console variable (ConVar), in general these are for things like gamemode/server settings. --- 🦟 **BUG**: [FCVAR_ARCHIVE causes default value replication issues on clientside FCVAR_REPLICATED convars and should be omitted clientside as a workaround](https://github.com/Facepunch/garrysmod-issues/issues/3323) --- @param name string @Name of the ConVar --- @param value string @Default value of the convar --- @param flags number @Flags of the convar, see Enums/FCVAR, either as bitflag or as table. --- @param helptext string @The help text to show in the console. --- @param min number @If set, the ConVar cannot be changed to a number lower than this value. --- @param max number @If set, the ConVar cannot be changed to a number higher than this value. --- @return GConVar @The convar created. function _G.CreateConVar(name, value, flags, helptext, min, max) end --- Creates a new material with the specified name and shader. --- ℹ **NOTE**: Materials created with this function can be used in Entity:SetMaterial and Entity:SetSubMaterial by prepending a "!" to their material name argument. --- 🦟 **BUG**: [.pngs must be loaded with Global.Material before being used with this function.](https://github.com/Facepunch/garrysmod-issues/issues/1531) --- 🦟 **BUG**: [This does not work with [patch materials](https://developer.valvesoftware.com/wiki/Patch).](https://github.com/Facepunch/garrysmod-issues/issues/2511) --- 🦟 **BUG**: [This will not create a new material if another material object with the same name already exists.](https://github.com/Facepunch/garrysmod-issues/issues/3103) --- @param name string @The material name --- @param shaderName string @The shader name --- @param materialData table @Key-value table that contains shader parameters and proxies --- @return GIMaterial @Created material function _G.CreateMaterial(name, shaderName, materialData) end --- Creates a new particle system. --- ℹ **NOTE**: The particle effect must be precached with Global.PrecacheParticleSystem and the file its from must be added via game.AddParticles before it can be used! --- @param ent GEntity @The entity to attach the control point to. --- @param effect string @The name of the effect to create --- @param partAttachment number @See Enums/PATTACH. --- @param entAttachment number @The attachment ID on the entity to attach the particle system to --- @param offset GVector @The offset from the Entity:GetPos of the entity we are attaching this CP to. --- @return GCNewParticleEffect @The created particle system. function _G.CreateParticleSystem(ent, effect, partAttachment, entAttachment, offset) end --- Creates a new PhysCollide from the given bounds. --- 🦟 **BUG**: [This fails to create planes or points - no components of the mins or maxs can be the same.](https://github.com/Facepunch/garrysmod-issues/issues/3568) --- @param mins GVector @Min corner of the box --- @param maxs GVector @Max corner of the box --- @return GPhysCollide @The new PhysCollide function _G.CreatePhysCollideBox(mins, maxs) end --- Creates PhysCollide objects for every physics object the model has. The model must be precached with util.PrecacheModel before being used with this function. --- @param modelName string @Model path to get the collision objects of. --- @return table @Table of PhysCollide objects function _G.CreatePhysCollidesFromModel(modelName) end --- Returns a sound parented to the specified entity. --- ℹ **NOTE**: You can only create one CSoundPatch per audio file, per entity at the same time. --- @param targetEnt GEntity @The target entity. --- @param soundName string @The sound to play. --- @param filter GCRecipientFilter @A CRecipientFilter of the players that will have this sound networked to them --- @return GCSoundPatch @The sound object function _G.CreateSound(targetEnt, soundName, filter) end --- Creates and returns a new DSprite element with the supplied material. --- @param material GIMaterial @Material the sprite should draw. --- @return GPanel @The new DSprite element. function _G.CreateSprite(material) end --- Returns the uptime of the server in seconds (to at least 4 decimal places) --- This is a synchronised value and affected by various factors such as host_timescale (or game.GetTimeScale) and the server being paused - either by sv_pausable or all players disconnecting. --- You should use this function for timing in-game events but not for real-world events. --- See also: Global.RealTime, Global.SysTime --- ℹ **NOTE**: This is internally defined as a float, and as such it will be affected by precision loss if your server uptime is more than 6 hours, which will cause jittery movement of players and props and inaccuracy of timers, it is highly encouraged to refresh or change the map when that happens (a server restart is not necessary). --- This is **NOT** easy as it sounds to fix in the engine, so please refrain from posting issues about this --- 🦟 **BUG**: [This returns 0 in GM:PlayerAuthed.](https://github.com/Facepunch/garrysmod-issues/issues/3026) --- @return number @Time synced with the game server. function _G.CurTime() end --- This is not a function. This is a preprocessor keyword that translates to: --- ``` --- local BaseClass = baseclass.Get("my_weapon") --- ``` --- If you type `DEFINE_BASECLASS("my_weapon")` in your script. --- See baseclass.Get for more information. --- @param value string @Baseclass name function _G.DEFINE_BASECLASS(value) end --- Cancels current DOF post-process effect started with Global.DOF_Start function _G.DOF_Kill() end --- Cancels any existing DOF post-process effects. --- Begins the DOF post-process effect. function _G.DOF_Start() end --- Returns an CTakeDamageInfo object. --- 🦟 **BUG**: [This does not create a unique object, but instead returns a shared reference. That means you cannot use two or more of these objects at once.](https://github.com/Facepunch/garrysmod-issues/issues/2771) --- @return GCTakeDamageInfo @The CTakeDamageInfo object. function _G.DamageInfo() end --- Writes text to the right hand side of the screen, like the old error system. Messages disappear after a couple of seconds. --- @param slot number @The location on the right hand screen to write the debug info to --- @param info string @The debugging information to be written to the screen function _G.DebugInfo(slot, info) end --- Loads and registers the specified gamemode, setting the GM table's DerivedFrom field to the value provided, if the table exists. The DerivedFrom field is used post-gamemode-load as the "derived" parameter for gamemode.Register. --- @param base string @Gamemode name to derive from. function _G.DeriveGamemode(base) end --- Creates a DMenu and closes any current menus. --- @param parent GPanel @The panel to parent the created menu to. --- @return GPanel @The created DMenu function _G.DermaMenu(parent) end --- Creates a new derma animation. --- @param name string @Name of the animation to create --- @param panel GPanel @Panel to run the animation on --- @param func function @Function to call to process the animation --- @return table @A lua metatable containing four methods: function _G.Derma_Anim(name, panel, func) end --- Draws background blur around the given panel. --- @param panel GPanel @Panel to draw the background blur around --- @param startTime number @Time that the blur began being painted function _G.Derma_DrawBackgroundBlur(panel, startTime) end --- Creates panel method that calls the supplied Derma skin hook via derma.SkinHook --- @param panel GPanel @Panel to add the hook to --- @param functionName string @Name of panel function to create --- @param hookName string @Name of Derma skin hook to call within the function --- @param typeName string @Type of element to call Derma skin hook for function _G.Derma_Hook(panel, functionName, hookName, typeName) end --- Makes the panel (usually an input of sorts) respond to changes in console variables by adding next functions to the panel: --- * Panel:SetConVar --- * Panel:ConVarChanged --- * Panel:ConVarStringThink --- * Panel:ConVarNumberThink --- The console variable value is saved in the `m_strConVar` property of the panel. --- The panel should call --- Panel:ConVarStringThink or --- Panel:ConVarNumberThink --- in its PANEL:Think hook and should call Panel:ConVarChanged when the panel's value has changed. --- @param target GPanel @The panel the functions should be added to. function _G.Derma_Install_Convar_Functions(target) end --- Creates a derma window to display information --- @param Text string @The text within the created panel. --- @param Title string @The title of the created panel. --- @param Button string @The text of the button to close the panel. --- @return GPanel @The created DFrame function _G.Derma_Message(Text, Title, Button) end --- Shows a message box in the middle of the screen, with up to 4 buttons they can press. --- @param text string @The message to display. --- @param title string @The title to give the message box. --- @param btn1text string @The text to display on the first button. --- @param btn1func function @The function to run if the user clicks the first button. --- @param btn2text string @The text to display on the second button. --- @param btn2func function @The function to run if the user clicks the second button. --- @param btn3text string @The text to display on the third button --- @param btn3func function @The function to run if the user clicks the third button. --- @param btn4text string @The text to display on the third button --- @param btn4func function @The function to run if the user clicks the fourth button. --- @return GPanel @The Panel object of the created window. function _G.Derma_Query(text, title, btn1text, btn1func, btn2text, btn2func, btn3text, btn3func, btn4text, btn4func) end --- Creates a derma window asking players to input a string. --- @param title string @The title of the created panel. --- @param subtitle string @The text above the input box --- @param default string @The default text for the input box. --- @param confirm function @The function to be called once the user has confirmed their input. --- @param cancel function @The function to be called once the user has cancelled their input --- @param confirmText string @Allows you to override text of the "OK" button --- @param cancelText string @Allows you to override text of the "Cancel" button --- @return GPanel @The created DFrame function _G.Derma_StringRequest(title, subtitle, default, confirm, cancel, confirmText, cancelText) end --- Sets whether rendering should be limited to being inside a panel or not. --- See also Panel:NoClipping. --- @param disable boolean @Whether or not clipping should be disabled --- @return boolean @Whether the clipping was enabled or not before this function call function _G.DisableClipping(disable) end --- Draws the bloom shader, which creates a glowing effect from bright objects. --- @param Darken number @Determines how much to darken the effect --- @param Multiply number @Will affect how bright the glowing spots are --- @param SizeX number @The size of the bloom effect along the horizontal axis. --- @param SizeY number @The size of the bloom effect along the vertical axis. --- @param Passes number @Determines how much to exaggerate the effect. --- @param ColorMultiply number @Will multiply the colors of the glowing spots, making them more vivid. --- @param Red number @How much red to multiply with the glowing color --- @param Green number @How much green to multiply with the glowing color --- @param Blue number @How much blue to multiply with the glowing color function _G.DrawBloom(Darken, Multiply, SizeX, SizeY, Passes, ColorMultiply, Red, Green, Blue) end --- Draws the Color Modify shader, which can be used to adjust colors on screen. --- @param modifyParameters table @Color modification parameters function _G.DrawColorModify(modifyParameters) end --- Draws a material overlay on the screen. --- @param Material string @This will be the material that is drawn onto the screen. --- @param RefractAmount number @This will adjust how much the material will refract your screen. function _G.DrawMaterialOverlay(Material, RefractAmount) end --- Creates a motion blur effect by drawing your screen multiple times. --- @param AddAlpha number @How much alpha to change per frame. --- @param DrawAlpha number @How much alpha the frames will have --- @param Delay number @Determines the amount of time between frames to capture. function _G.DrawMotionBlur(AddAlpha, DrawAlpha, Delay) end --- Draws the sharpen shader, which creates more contrast. --- @param Contrast number @How much contrast to create. --- @param Distance number @How large the contrast effect will be. function _G.DrawSharpen(Contrast, Distance) end --- Draws the sobel shader, which detects edges and draws a black border. --- @param Threshold number @Determines the threshold of edges function _G.DrawSobel(Threshold) end --- Renders the post-processing effect of beams of light originating from the map's sun. Utilises the "pp/sunbeams" material --- @param darken number @$darken property for sunbeams material --- @param multiplier number @$multiply property for sunbeams material --- @param sunSize number @$sunsize property for sunbeams material --- @param sunX number @$sunx property for sunbeams material --- @param sunY number @$suny property for sunbeams material function _G.DrawSunbeams(darken, multiplier, sunSize, sunX, sunY) end --- Draws the texturize shader, which replaces each pixel on your screen with a different part of the texture depending on its brightness. See g_texturize for information on making the texture. --- @param Scale number @Scale of the texture --- @param BaseTexture number @This will be the texture to use in the effect function _G.DrawTexturize(Scale, BaseTexture) end --- Draws the toy town shader, which blurs the top and bottom of your screen. This can make very large objects look like toys, hence the name. --- @param Passes number @An integer determining how many times to draw the effect --- @param Height number @The amount of screen which should be blurred on the top and bottom. function _G.DrawToyTown(Passes, Height) end --- Drops the specified entity if it is being held by any player with Gravity Gun or +use pickup. --- @param ent GEntity @The entity to drop. function _G.DropEntityIfHeld(ent) end --- Creates or replaces a dynamic light with the given id. --- ℹ **NOTE**: Only 32 dlights and 64 elights can be active at once. --- ⚠ **WARNING**: It is not safe to hold a reference to this object after creation since its data can be replaced by another dlight at any time. --- 🦟 **BUG**: [The minlight parameter affects the world and entities differently.](https://github.com/Facepunch/garrysmod-issues/issues/3798) --- @param index number @An unsigned Integer --- @param elight boolean @Allocates an elight instead of a dlight --- @return table @A DynamicLight structured table function _G.DynamicLight(index, elight) end --- Returns a CEffectData object to be used with util.Effect. --- 🦟 **BUG**: [This does not create a unique object, but instead returns a shared reference. That means you cannot use two or more of these objects at once.](https://github.com/Facepunch/garrysmod-issues/issues/2771) --- @return GCEffectData @The CEffectData object. function _G.EffectData() end --- A compact 'if then else'. This is *almost* equivalent to (`condition` and `truevar` or `falsevar`) in Lua. --- The difference is that if `truevar` evaluates to false, the plain Lua method stated would return `falsevar` regardless of `condition` whilst this function would take `condition` into account. --- @param condition any @The condition to check if true or false. --- @param truevar any @If the condition isn't nil/false, returns this value. --- @param falsevar any @If the condition is nil/false, returns this value. --- @return any @The result. function _G.Either(condition, truevar, falsevar) end --- Plays a sentence from `scripts/sentences.txt` --- @param soundName string @The sound to play --- @param position GVector @The position to play at --- @param entity number @The entity to emit the sound from --- @param channel number @The sound channel, see Enums/CHAN. --- @param volume number @The volume of the sound, from 0 to 1 --- @param soundLevel number @The sound level of the sound, see Enums/SNDLVL --- @param soundFlags number @The flags of the sound, see Enums/SND --- @param pitch number @The pitch of the sound, 0-255 function _G.EmitSentence(soundName, position, entity, channel, volume, soundLevel, soundFlags, pitch) end --- Emits the specified sound at the specified position. --- 🦟 **BUG**: Sounds must be precached serverside manually before they can be played. util.PrecacheSound does not work for this purpose, Entity.EmitSound does the trick --- 🦟 **BUG**: This does not work with soundscripts. TODO: Is this a bug or intended? --- @param soundName string @The sound to play --- @param position GVector @The position to play at --- @param entity number @The entity to emit the sound from --- @param channel number @The sound channel, see Enums/CHAN. --- @param volume number @The volume of the sound, from 0 to 1 --- @param soundLevel number @The sound level of the sound, see Enums/SNDLVL --- @param soundFlags number @The flags of the sound, see Enums/SND --- @param pitch number @The pitch of the sound, 0-255 function _G.EmitSound(soundName, position, entity, channel, volume, soundLevel, soundFlags, pitch) end --- Removes the currently active tool tip from the screen. --- @param panel GPanel @This is the panel that has a tool tip. function _G.EndTooltip(panel) end --- Returns the entity with the matching Entity:EntIndex. --- Indices 1 through game.MaxPlayers() are always reserved for players. --- ℹ **NOTE**: In examples on this wiki, **Entity( 1 )** is used when a player entity is needed (see ). In singleplayer and listen servers, **Entity( 1 )** will always be the first player. In dedicated servers, however, **Entity( 1 )** won't always be a valid player. --- @param entityIndex number @The entity index. --- @return GEntity @The entity if it exists, or NULL if it doesn't. function _G.Entity(entityIndex) end --- Throws an error. This is currently an alias of Global.ErrorNoHalt despite it once throwing a halting error like error without the stack trace appended. --- 🦟 **BUG**: [Using this function in the menu state exits the menu.](https://github.com/Facepunch/garrysmod-issues/issues/1810) --- 🦟 **BUG**: [This function throws a non-halting error instead of a halting error.](https://github.com/Facepunch/garrysmod-issues/issues/2113) --- @vararg any @Converts all arguments to strings and prints them with no spacing or line breaks. function _G.Error(...) end --- Throws a Lua error but does not break out of the current call stack. --- This function will not print a stack trace like a normal error would. --- Essentially similar if not equivalent to Global.Msg. --- 🦟 **BUG**: [Using this function in the menu state exits the menu.](https://github.com/Facepunch/garrysmod-issues/issues/1810) --- @vararg any @Converts all arguments to strings and prints them with no spacing. function _G.ErrorNoHalt(...) end --- Returns the angles of the current render context as calculated by GM:CalcView. --- 🦟 **BUG**: [This function is only reliable inside rendering hooks.](https://github.com/Facepunch/garrysmod-issues/issues/2516) --- @return GAngle @The angle of the currently rendered scene. function _G.EyeAngles() end --- Returns the origin of the current render context as calculated by GM:CalcView. --- 🦟 **BUG**: [This function is only reliable inside rendering hooks.](https://github.com/Facepunch/garrysmod-issues/issues/2516) --- @return GVector @Camera position. function _G.EyePos() end --- Returns the normal vector of the current render context as calculated by GM:CalcView, similar to Global.EyeAngles. --- 🦟 **BUG**: [This function is only reliable inside rendering hooks.](https://github.com/Facepunch/garrysmod-issues/issues/2516) --- @return GVector @View direction of the currently rendered scene. function _G.EyeVector() end --- Returns the meta table for the class with the matching name. --- Internally returns debug.getregistry()[metaName] --- You can learn more about meta tables on the Meta Tables page. --- You can find a list of meta tables that can be retrieved with this function on Enums/TYPE. The name in the description is the string to use with this function. --- @param metaName string @The object type to retrieve the meta table of. --- @return table @The corresponding meta table. function _G.FindMetaTable(metaName) end --- Returns the tool-tip text and tool-tip-panel (if any) of the given panel as well as itself --- @param panel GPanel @Panel to find tool-tip of --- @return string @tool-tip text --- @return GPanel @tool-tip panel --- @return GPanel @panel that the function was called with function _G.FindTooltip(panel) end --- Formats the specified values into the string given. Same as string.format. --- @param format string @The string to be formatted --- @vararg any @Values to be formatted into the string. --- @return string @The formatted string function _G.Format(format, ...) end --- Returns the number of frames rendered since the game was launched. function _G.FrameNumber() end --- Returns the Global.CurTime-based time in seconds it took to render the last frame. --- This should be used for frame/tick based timing, such as movement prediction or animations. --- For real-time-based frame time that isn't affected by host_timescale, use Global.RealFrameTime. RealFrameTime is more suited for things like GUIs or HUDs. --- @return number @time (in seconds) function _G.FrameTime() end --- Gets the ConVar with the specified name. --- ℹ **NOTE**: This function uses Global.GetConVar_Internal internally, but caches the result in Lua for quicker lookups. --- @param name string @Name of the ConVar to get --- @return GConVar @The ConVar object, or nil if no such ConVar was found. function _G.GetConVar(name) end --- 🛑 **DEPRECATED**: Store the ConVar object retrieved with Global.GetConVar and call ConVar:GetInt or ConVar:GetFloat on it. --- Gets the numeric value ConVar with the specified name. --- @param name string @Name of the ConVar to get. --- @return number @The ConVar's value. function _G.GetConVarNumber(name) end --- 🛑 **DEPRECATED**: Store the ConVar object retrieved with Global.GetConVar and call ConVar:GetString on it. --- Gets the string value ConVar with the specified name. --- @param name string @Name of the ConVar to get. --- @return string @The ConVar's value. function _G.GetConVarString(name) end --- Returns an angle that is shared between the server and all clients. --- @param index string @The unique index to identify the global value with. --- @param default GAngle @The value to return if the global value is not set. --- @return GAngle @The global value, or default if the global is not set. function _G.GetGlobalAngle(index, default) end --- Returns a boolean that is shared between the server and all clients. --- @param index string @The unique index to identify the global value with. --- @param default boolean @The value to return if the global value is not set. --- @return boolean @The global value, or the default if the global value is not set. function _G.GetGlobalBool(index, default) end --- Returns an entity that is shared between the server and all clients. --- @param index string @The unique index to identify the global value with. --- @param default GEntity @The value to return if the global value is not set. --- @return GEntity @The global value, or the default if the global value is not set. function _G.GetGlobalEntity(index, default) end --- Returns a float that is shared between the server and all clients. --- @param index string @The unique index to identify the global value with. --- @param default number @The value to return if the global value is not set. --- @return number @The global value, or the default if the global value is not set. function _G.GetGlobalFloat(index, default) end --- Returns an integer that is shared between the server and all clients. --- 🦟 **BUG**: [This function will not round decimal values as it actually networks a float internally.](https://github.com/Facepunch/garrysmod-issues/issues/3374) --- @param index string @The unique index to identify the global value with. --- @param default number @The value to return if the global value is not set. --- @return number @The global value, or the default if the global value is not set. function _G.GetGlobalInt(index, default) end --- Returns a string that is shared between the server and all clients. --- @param index string @The unique index to identify the global value with. --- @param default string @The value to return if the global value is not set. --- @return string @The global value, or the default if the global value is not set. function _G.GetGlobalString(index, default) end --- Returns a vector that is shared between the server and all clients. --- @param Index string @The unique index to identify the global value with. --- @param Default GVector @The value to return if the global value is not set. --- @return GVector @The global value, or the default if the global value is not set. function _G.GetGlobalVector(Index, Default) end --- Returns the panel that is used as a wrapper for the HUD. --- See also vgui.GetWorldPanel --- @return GPanel @The HUD panel function _G.GetHUDPanel() end --- Returns the name of the current server. --- @return string @The name of the server. function _G.GetHostName() end --- Returns the player whose movement commands are currently being processed. The player this returns can safely have Player:GetCurrentCommand() called on them. See Prediction. --- @return GPlayer @The player currently being predicted, or NULL if no command processing is currently being done. function _G.GetPredictionPlayer() end --- Creates or gets the rendertarget with the given name. --- See Global.GetRenderTargetEx for an advanced version of this function with more options. --- 🦟 **BUG**: [This crashes when used on a cubemap texture.](https://github.com/Facepunch/garrysmod-issues/issues/2885) --- @param name string @The internal name of the render target. --- @param width number @The width of the render target, must be power of 2 --- @param height number @The height of the render target, must be power of 2 --- @param additive boolean @Sets whenever the rt should be additive. --- @return GITexture @The render target function _G.GetRenderTarget(name, width, height, additive) end --- Gets (or creates if it does not exist) the rendertarget with the given name, this function allows to adjust the creation of a rendertarget more than Global.GetRenderTarget. --- See also render.PushRenderTarget and render.SetRenderTarget. --- @param name string @The internal name of the render target --- @param width number @The width of the render target, must be power of 2. --- @param height number @The height of the render target, must be power of 2. --- @param sizeMode number @Bitflag that influences the sizing of the render target, see Enums/RT_SIZE. --- @param depthMode number @Bitflag that determines the depth buffer usage of the render target Enums/MATERIAL_RT_DEPTH. --- @param textureFlags number @Bitflag that configurates the texture, see Enums/TEXTUREFLAGS --- @param rtFlags number @Flags that controll the HDR behaviour of the render target, see Enums/CREATERENDERTARGETFLAGS. --- @param imageFormat number @Image format, see Enums/IMAGE_FORMAT. --- @return GITexture @The new render target. function _G.GetRenderTargetEx(name, width, height, sizeMode, depthMode, textureFlags, rtFlags, imageFormat) end --- Returns the entity the client is using to see from (such as the player itself, the camera, or another entity). --- @return GEntity @The view entity. function _G.GetViewEntity() end --- Converts a color from [HSL color space](https://en.wikipedia.org/wiki/HSL_and_HSV) into RGB color space and returns a Color. --- 🦟 **BUG**: [The returned color will not have the color metatable.](https://github.com/Facepunch/garrysmod-issues/issues/2407) --- @param hue number @The hue in degrees from 0-360. --- @param saturation number @The saturation from 0-1. --- @param value number @The lightness from 0-1. --- @return table @The Color created from the HSL color space. function _G.HSLToColor(hue, saturation, value) end --- Converts a color from [HSV color space](https://en.wikipedia.org/wiki/HSL_and_HSV) into RGB color space and returns a Color. --- 🦟 **BUG**: [The returned color will not have the color metatable.](https://github.com/Facepunch/garrysmod-issues/issues/2407) --- @param hue number @The hue in degrees from 0-360. --- @param saturation number @The saturation from 0-1. --- @param value number @The value from 0-1. --- @return table @The Color created from the HSV color space. function _G.HSVToColor(hue, saturation, value) end --- Launches an asynchronous http request with the given parameters. --- 🦟 **BUG**: [This cannot send or receive multiple headers with the same name.](https://github.com/Facepunch/garrysmod-issues/issues/2232) --- ℹ **NOTE**: HTTP-requests on private networks don't work. To enable HTTP-requests on private networks use Command Line Parameters `-allowlocalhttp` --- @param parameters table @The request parameters --- @return boolean @true if we made a request, nil if we failed. function _G.HTTP(parameters) end --- 🛑 **DEPRECATED**: To send the target file to the client simply call AddCSLuaFile() in the target file itself. --- This function works exactly the same as Global.include both clientside and serverside. --- The only difference is that on the serverside it also calls Global.AddCSLuaFile on the filename, so that it gets sent to the client. --- @param filename string @The filename of the Lua file you want to include. function _G.IncludeCS(filename) end --- Returns whether the given object does or doesn't have a `metatable` of a color. --- 🦟 **BUG**: [Engine functions (i.e. those not written in plain Lua) that return color objects do not currently set the color metatable and this function will return false if you use it on them.](https://github.com/Facepunch/garrysmod-issues/issues/2407) --- @param Object any @The object to be tested --- @return boolean @Whether the given object is a color or not function _G.IsColor(Object) end --- Returns if the given NPC class name is an enemy. --- Returns true if the entity name is one of the following: --- * "npc_antlion" --- * "npc_antlionguard" --- * "npc_antlionguardian" --- * "npc_barnacle" --- * "npc_breen" --- * "npc_clawscanner" --- * "npc_combine_s" --- * "npc_cscanner" --- * "npc_fastzombie" --- * "npc_fastzombie_torso" --- * "npc_headcrab" --- * "npc_headcrab_fast" --- * "npc_headcrab_poison" --- * "npc_hunter" --- * "npc_metropolice" --- * "npc_manhack" --- * "npc_poisonzombie" --- * "npc_strider" --- * "npc_stalker" --- * "npc_zombie" --- * "npc_zombie_torso" --- * "npc_zombine" --- @param className string @Class name of the entity to check --- @return boolean @Is an enemy function _G.IsEnemyEntityName(className) end --- Returns if the passed object is an Entity. Alias of Global.isentity. --- @param variable any @The variable to check. --- @return boolean @True if the variable is an Entity. function _G.IsEntity(variable) end --- Returns if this is the first time this hook was predicted. --- This is useful for one-time logic in your SWEPs PrimaryAttack, SecondaryAttack and Reload and other (to prevent those hooks from being called rapidly in succession). It's also useful in a Move hook for when the client predicts movement. --- Visit Prediction for more information about this behavior. --- ℹ **NOTE**: This is already used internally for Entity:EmitSound, Weapon:SendWeaponAnim and Entity:FireBullets, but NOT in util.Effect. --- @return boolean @Whether or not this is the first time being predicted. function _G.IsFirstTimePredicted() end --- Returns if the given NPC class name is a friend. --- Returns true if the entity name is one of the following: --- * "npc_alyx" --- * "npc_barney" --- * "npc_citizen" --- * "npc_dog" --- * "npc_eli" --- * "npc_fisherman" --- * "npc_gman" --- * "npc_kleiner" --- * "npc_magnusson" --- * "npc_monk" --- * "npc_mossman" --- * "npc_odessa" --- * "npc_vortigaunt" --- @param className string @Class name of the entity to check --- @return boolean @Is a friend function _G.IsFriendEntityName(className) end --- Checks whether or not a game is currently mounted. Uses data given by engine.GetGames. --- @param game string @The game string/app ID to check. --- @return boolean @True if the game is mounted. function _G.IsMounted(game) end --- Returns whether or not every element within a table is a valid entity --- @param table table @Table containing entities to check --- @return boolean @All entities valid function _G.IsTableOfEntitiesValid(table) end --- Returns whether or not a model is useless by checking that the file path is that of a proper model. --- If the string ".mdl" is not found in the model name, the function will return true. --- The function will also return true if any of the following strings are found in the given model name: --- * "_gesture" --- * "_anim" --- * "_gst" --- * "_pst" --- * "_shd" --- * "_ss" --- * "_posture" --- * "_anm" --- * "ghostanim" --- * "_paths" --- * "_shared" --- * "anim_" --- * "gestures_" --- * "shared_ragdoll_" --- @param modelName string @The model name to be checked --- @return boolean @Whether or not the model is useless function _G.IsUselessModel(modelName) end --- Returns whether an object is valid or not. (Such as Entitys, Panels, custom table objects and more). --- Checks that an object is not nil, has an IsValid method and if this method returns true. --- ℹ **NOTE**: Due to vehicles being technically valid the moment they're spawned, also use Vehicle:IsValidVehicle to make sure they're fully initialized --- @param toBeValidated any @The table or object to be validated. --- @return boolean @True if the object is valid. function _G.IsValid(toBeValidated) end --- Adds javascript function 'language.Update' to an HTML panel as a method to call Lua's language.GetPhrase function. --- @param htmlPanel GPanel @Panel to add javascript function 'language.Update' to. function _G.JS_Language(htmlPanel) end --- Adds javascript function 'util.MotionSensorAvailable' to an HTML panel as a method to call Lua's motionsensor.IsAvailable function. --- @param htmlPanel GPanel @Panel to add javascript function 'util.MotionSensorAvailable' to. function _G.JS_Utility(htmlPanel) end --- Adds workshop related javascript functions to an HTML panel, used by the "Dupes" and "Saves" tabs in the spawnmenu. --- @param htmlPanel GPanel @Panel to add javascript functions to. function _G.JS_Workshop(htmlPanel) end --- Convenience function that creates a DLabel, sets the text, and returns it --- @param text string @The string to set the label's text to --- @param parent GPanel @Optional --- @return GPanel @The created DLabel function _G.Label(text, parent) end --- Performs a linear interpolation from the start number to the end number. --- This function provides a very efficient and easy way to smooth out movements. --- ℹ **NOTE**: This function is not meant to be used with constant value in the first argument, if you're dealing with animation! Use a value that changes over time. See example for **proper** usage of Lerp for animations --- @param t number @The fraction for finding the result --- @param from number @The starting number --- @param to number @The ending number --- @return number @The result of the linear interpolation, `(1 - t) * from + t * to`. function _G.Lerp(t, from, to) end --- Returns point between first and second angle using given fraction and linear interpolation --- ℹ **NOTE**: This function is not meant to be used with constant value in the first argument, if you're dealing with animation! Use a value that changes over time --- @param ratio number @Ratio of progress through values --- @param angleStart GAngle @Angle to begin from --- @param angleEnd GAngle @Angle to end at --- @return GAngle @angle function _G.LerpAngle(ratio, angleStart, angleEnd) end --- Linear interpolation between two vectors. It is commonly used to smooth movement between two vectors --- ℹ **NOTE**: This function is not meant to be used with constant value in the first argument, if you're dealing with animation! Use a value that changes over time --- @param fraction number @Fraction ranging from 0 to 1 --- @param from GVector @The initial Vector --- @param to GVector @The desired Vector --- @return GVector @The lerped vector. function _G.LerpVector(fraction, from, to) end --- Loads all preset settings for the presets and returns them in a table --- @return table @Preset data function _G.LoadPresets() end --- Returns the player object of the current client. --- ℹ **NOTE**: LocalPlayer() will return NULL until all entities have been initialized. See GM:InitPostEntity. --- @return GPlayer @The player object representing the client. function _G.LocalPlayer() end --- Translates the specified position and angle from the specified local coordinate system into worldspace coordinates. --- If you're working with an entity's local vectors, use Entity:LocalToWorld and/or Entity:LocalToWorldAngles instead. --- See also: Global.WorldToLocal, the reverse of this function. --- @param localPos GVector @The position vector in the source coordinate system, that should be translated to world coordinates --- @param localAng GAngle @The angle in the source coordinate system, that should be converted to a world angle --- @param originPos GVector @The origin point of the source coordinate system, in world coordinates --- @param originAngle GAngle @The angles of the source coordinate system, as a world angle --- @return GVector @The world position of the supplied local position. --- @return GAngle @The world angles of the supplied local angle. function _G.LocalToWorld(localPos, localAng, originPos, originAngle) end --- Returns a localisation for the given token, if none is found it will return the default (second) parameter. --- @param localisationToken string @The token to find a translation for. --- @param default string @The default value to be returned if no translation was found. function _G.Localize(localisationToken, default) end --- Either returns the material with the given name, or loads the material interpreting the first argument as the path. --- ℹ **NOTE**: When using .png or .jpg textures, try to make their sizes Power Of 2 (1, 2, 4, 8, 16, 32, 64, etc). While images are no longer scaled to Power of 2 sizes since February 2019, it is a good practice for things like icons, etc. --- @param materialName string @The material name or path --- @param pngParameters string @A string containing space separated keywords which will be used to add material parameters --- @return GIMaterial @Generated material --- @return number @How long it took for the function to run function _G.Material(materialName, pngParameters) end --- Returns a VMatrix object. --- @param data table @Initial data to initialize the matrix with --- @return GVMatrix @New matrix. function _G.Matrix(data) end --- Returns a new mesh object. --- @param mat GIMaterial @The material the mesh is intended to be rendered with --- @return GIMesh @The created object. function _G.Mesh(mat) end --- Runs util.PrecacheModel and returns the string --- @param model string @The model to precache --- @return string @The same string entered as an argument function _G.Model(model) end --- Writes every given argument to the console. --- Automatically attempts to convert each argument to a string. (See Global.tostring) --- Unlike Global.print, arguments are not separated by anything. They are simply concatenated. --- Additionally, a newline isn't added automatically to the end, so subsequent Msg or print operations will continue the same line of text in the console. See Global.MsgN for a version that does add a newline. --- The text is blue on the server, orange on the client, and green on the menu: --- @vararg any @List of values to print. function _G.Msg(...) end --- Works exactly like Global.Msg except that, if called on the server, will print to all players consoles plus the server console. --- @vararg any @List of values to print. function _G.MsgAll(...) end --- Just like Global.Msg, except it can also print colored text, just like chat.AddText. --- @vararg any @Values to print function _G.MsgC(...) end --- Same as Global.print, except it concatinates the arguments without inserting any whitespace in between them. --- See also Global.Msg, which doesn't add a newline (`"\n"`) at the end. --- @vararg any @List of values to print function _G.MsgN(...) end --- Returns named color defined in resource/ClientScheme.res. --- @param name string @Name of color --- @return table @A Color or nil function _G.NamedColor(name) end --- Returns the amount of skins the specified model has. --- See also Entity:SkinCount if you have an entity. --- @param modelName string @Model to return amount of skins of --- @return number @Amount of skins function _G.NumModelSkins(modelName) end --- Modifies the given vectors so that all of vector2's axis are larger than vector1's by switching them around. Also known as ordering vectors. --- ℹ **NOTE**: This function will irreversibly modify the given vectors --- @param vector1 GVector @Bounding box min resultant --- @param vector2 GVector @Bounding box max resultant function _G.OrderVectors(vector1, vector2) end --- Calls game.AddParticles and returns given string. --- @param file string @The particle file. --- @return string @The particle file. function _G.Particle(file) end --- Creates a particle effect. --- ℹ **NOTE**: The particle effect must be precached with Global.PrecacheParticleSystem and the file its from must be added via game.AddParticles before it can be used! --- @param particleName string @The name of the particle effect. --- @param position GVector @The start position of the effect. --- @param angles GAngle @The orientation of the effect. --- @param parent GEntity @If set, the particle will be parented to the entity. function _G.ParticleEffect(particleName, position, angles, parent) end --- Creates a particle effect with specialized parameters. --- ℹ **NOTE**: The particle effect must be precached with Global.PrecacheParticleSystem and the file its from must be added via game.AddParticles before it can be used! --- @param particleName string @The name of the particle effect. --- @param attachType number @Attachment type using Enums/PATTACH. --- @param entity GEntity @The entity to be used in the way specified by the attachType. --- @param attachmentID number @The id of the attachment to be used in the way specified by the attachType. function _G.ParticleEffectAttach(particleName, attachType, entity, attachmentID) end --- Creates a new CLuaEmitter. --- ℹ **NOTE**: Do not forget to delete the emitter with CLuaEmitter:Finish once you are done with it --- @param position GVector @The start position of the emitter --- @param use3D boolean @Whenever to render the particles in 2D or 3D mode. --- @return GCLuaEmitter @The new particle emitter. function _G.ParticleEmitter(position, use3D) end --- Creates a path for the bot to follow --- @param type string @The name of the path to create --- @return GPathFollower @The path function _G.Path(type) end --- Returns the player with the matching Player:UserID. --- For a function that returns a player based on their Entity:EntIndex, see Global.Entity. --- For a function that returns a player based on their connection ID, see player.GetByID. --- @param playerIndex number @The player index. --- @return GPlayer @The retrieved player. function _G.Player(playerIndex) end --- Moves the given model to the given position and calculates appropriate camera parameters for rendering the model to an icon. --- The output table interacts nicely with Panel:RebuildSpawnIconEx with a few key renames. --- @param model GEntity @Model that is being rendered to the spawn icon --- @param position GVector @Position that the model is being rendered at --- @param noAngles boolean @If true the function won't reset the angles to 0 for the model. --- @return table @Table of information of the view which can be used for rendering function _G.PositionSpawnIcon(model, position, noAngles) end --- Precaches the particle with the specified name. --- @param particleSystemName string @The name of the particle system. function _G.PrecacheParticleSystem(particleSystemName) end --- Precaches a scene file. --- @param scene string @Path to the scene file to precache. function _G.PrecacheScene(scene) end --- Load and precache a custom sentence file. --- @param filename string @The path to the custom sentences.txt. function _G.PrecacheSentenceFile(filename) end --- Precache a sentence group in a sentences.txt definition file. --- @param group string @The group to precache. function _G.PrecacheSentenceGroup(group) end --- Displays a message in the chat, console, or center of screen of every player. --- This uses the archaic user message system (umsg) and hence is limited to ≈250 characters. --- @param type number @Which type of message should be sent to the players (see Enums/HUD) --- @param message string @Message to be sent to the players function _G.PrintMessage(type, message) end --- Recursively prints the contents of a table to the console. --- @param tableToPrint table @The table to be printed --- @param indent number @Number of tabs to start indenting at --- @param done table @Internal argument, you shouldn't normally change this function _G.PrintTable(tableToPrint, indent, done) end --- Creates a new ProjectedTexture. --- @return GProjectedTexture @Newly created projected texture. function _G.ProjectedTexture() end --- Runs a function without stopping the whole script on error. --- This function is similar to Global.pcall and Global.xpcall except the errors are still printed and sent to the error handler (i.e. sent to server console if clientside and GM:OnLuaError called). --- @param func function @Function to run --- @return boolean @Whether the function executed successfully or not function _G.ProtectedCall(func) end --- Returns an iterator function that can be used to loop through a table in random order --- @param table table @Table to create iterator for --- @param descending boolean @Whether the iterator should iterate descending or not --- @return function @Iterator function function _G.RandomPairs(table, descending) end --- Returns the real frame-time which is unaffected by host_timescale. To be used for GUI effects (for example) --- @return number @Real frame time function _G.RealFrameTime() end --- Returns the uptime of the game/server in seconds (to at least 4 decimal places) --- ℹ **NOTE**: This is **not** synchronised or affected by the game. --- ℹ **NOTE**: This will be affected by precision loss if the uptime is more than 30+(?) days, and effectively cease to be functional after 50+(?) days. --- Changing the map will **not** fix it like it does with CurTime. A server restart is necessary. --- You should use this function (or SysTime) for timing real-world events such as user interaction, but not for timing game events such as animations. --- See also: Global.CurTime, Global.SysTime --- @return number @Uptime of the game/server. function _G.RealTime() end --- Creates a new CRecipientFilter. --- @return GCRecipientFilter @The new created recipient filter. function _G.RecipientFilter() end --- Registers a Derma element to be closed the next time Global.CloseDermaMenus is called --- @param menu GPanel @Menu to be registered for closure function _G.RegisterDermaMenuForClose(menu) end --- Saves position of your cursor on screen. You can restore it by using --- Global.RestoreCursorPosition. function _G.RememberCursorPosition() end --- Does the removing of the tooltip panel. Called by Global.EndTooltip. function _G.RemoveTooltip() end --- Returns the angle that the clients view is being rendered at --- @return GAngle @Render Angles function _G.RenderAngles() end --- Renders a Depth of Field effect --- @param origin GVector @Origin to render the effect at --- @param angle GAngle @Angle to render the effect at --- @param usableFocusPoint GVector @Point to focus the effect at --- @param angleSize number @Angle size of the effect --- @param radialSteps number @Amount of radial steps to render the effect with --- @param passes number @Amount of render passes --- @param spin boolean @Whether to cycle the frame or not --- @param inView table @Table of view data --- @param fov number @FOV to render the effect with function _G.RenderDoF(origin, angle, usableFocusPoint, angleSize, radialSteps, passes, spin, inView, fov) end --- Renders the stereoscopic post-process effect --- @param viewOrigin GVector @Origin to render the effect at --- @param viewAngles GAngle @Angles to render the effect at function _G.RenderStereoscopy(viewOrigin, viewAngles) end --- Renders the Super Depth of Field post-process effect --- @param viewOrigin GVector @Origin to render the effect at --- @param viewAngles GAngle @Angles to render the effect at --- @param viewFOV number @Field of View to render the effect at function _G.RenderSuperDoF(viewOrigin, viewAngles, viewFOV) end --- Restores position of your cursor on screen. You can save it by using Global.RememberCursorPosition. function _G.RestoreCursorPosition() end --- Executes the given console command with the parameters. --- ℹ **NOTE**: Some commands/convars are blocked from being ran/changed using this function, usually to prevent harm/annoyance to clients. For a list of blocked commands, see Blocked ConCommands. --- @param command string @The command to be executed. --- @vararg any @The arguments function _G.RunConsoleCommand(command, ...) end --- Evaluates and executes the given code, will throw an error on failure. --- ℹ **NOTE**: Local variables are not passed to the given code. --- @param code string @The code to execute. --- @param identifier string @The name that should appear in any error messages caused by this code. --- @param handleError boolean @If false, this function will return a string containing any error messages instead of throwing an error. --- @return string @If handleError is false, the error message (if any). function _G.RunString(code, identifier, handleError) end --- Alias of Global.RunString. --- 🛑 **DEPRECATED**: Use Global.RunString instead. function _G.RunStringEx() end --- Returns the input value in an escaped form so that it can safely be used inside of queries. The returned value is surrounded by quotes unless noQuotes is true. Alias of sql.SQLStr --- @param input string @String to be escaped --- @param noQuotes boolean @Whether the returned value should be surrounded in quotes or not --- @return string @Escaped input function _G.SQLStr(input, noQuotes) end --- 🛑 **DEPRECATED**: You should be using Global.ScreenScale instead. --- Returns a number based on the Size argument and your screen's width. Alias of Global.ScreenScale. --- @param Size number @The number you want to scale. function _G.SScale(Size) end --- Returns the ordinal suffix of a given number. --- @param number number @The number to find the ordinal suffix of. --- @return string @suffix function _G.STNDRD(number) end --- Removes the given entity unless it is a player or the world entity --- @param ent GEntity @Entity to safely remove. function _G.SafeRemoveEntity(ent) end --- Removes entity after delay using Global.SafeRemoveEntity --- @param entity GEntity @Entity to be removed --- @param delay number @Delay for entity removal in seconds function _G.SafeRemoveEntityDelayed(entity, delay) end --- Overwrites all presets with the supplied table. Used by the presets for preset saving --- @param presets table @Presets to be saved function _G.SavePresets(presets) end --- Gets the height of the game's window (in pixels). --- @return number @The height of the game's window in pixels function _G.ScrH() end --- Gets the width of the game's window (in pixels). --- @return number @The width of the game's window in pixels function _G.ScrW() end --- Returns a number based on the Size argument and your screen's width. The screen's width is always equal to size 640. This function is primarily used for scaling font sizes. --- @param Size number @The number you want to scale. function _G.ScreenScale(Size) end --- 🛑 **DEPRECATED**: This uses the umsg internally, which has been deprecated. Use the net instead. --- Send a usermessage --- ℹ **NOTE**: Useless on client, only server can send info to client. --- @param name string @The name of the usermessage --- @param recipients any @Can be a CRecipientFilter, table or Player object. --- @vararg any @Data to send in the usermessage function _G.SendUserMessage(name, recipients, ...) end --- Returns approximate duration of a sentence by name. See Global.EmitSentence --- @param name string @The sentence name --- @return number @The approximate duration function _G.SentenceDuration(name) end --- Prints "ServerLog: PARAM" without a newline, to the server log and console. --- @param parameter string @The value to be printed to console. function _G.ServerLog(parameter) end --- Adds the given string to the computers clipboard, which can then be pasted in or outside of GMod with Ctrl + V. --- @param text string @The text to add to the clipboard. function _G.SetClipboardText(text) end --- Defines an angle to be automatically networked to clients --- ℹ **NOTE**: Running this function clientside will only set it clientside for the client it is called on! --- @param index any @Index to identify the global angle with --- @param angle GAngle @Angle to be networked function _G.SetGlobalAngle(index, angle) end --- Defined a boolean to be automatically networked to clients --- ℹ **NOTE**: Running this function clientside will only set it clientside for the client it is called on! --- @param index any @Index to identify the global boolean with --- @param bool boolean @Boolean to be networked function _G.SetGlobalBool(index, bool) end --- Defines an entity to be automatically networked to clients --- ℹ **NOTE**: Running this function clientside will only set it clientside for the client it is called on! --- @param index any @Index to identify the global entity with --- @param ent GEntity @Entity to be networked function _G.SetGlobalEntity(index, ent) end --- Defines a floating point number to be automatically networked to clients --- ℹ **NOTE**: Running this function clientside will only set it clientside for the client it is called on! --- @param index any @Index to identify the global float with --- @param float number @Float to be networked function _G.SetGlobalFloat(index, float) end --- Sets an integer that is shared between the server and all clients. --- ℹ **NOTE**: Running this function clientside will only set it clientside for the client it is called on! --- 🦟 **BUG**: [This function will not round decimal values as it actually networks a float internally.](https://github.com/Facepunch/garrysmod-issues/issues/3374) --- @param index string @The unique index to identify the global value with. --- @param value number @The value to set the global value to function _G.SetGlobalInt(index, value) end --- Defines a string with a maximum of 199 characters to be automatically networked to clients --- ℹ **NOTE**: Running this function clientside will only set it clientside for the client it is called on! --- @param index any @Index to identify the global string with --- @param string string @String to be networked function _G.SetGlobalString(index, string) end --- Defines a vector to be automatically networked to clients --- ℹ **NOTE**: Running this function clientside will only set it clientside for the client it is called on! --- @param index any @Index to identify the global vector with --- @param vec GVector @Vector to be networked function _G.SetGlobalVector(index, vec) end --- Called by the engine to set which constraint system [https://developer.valvesoftware.com/wiki/Phys_constraintsystem] the next created constraints should use --- @param constraintSystem GEntity @Constraint system to use function _G.SetPhysConstraintSystem(constraintSystem) end --- This function can be used in a for loop instead of Global.pairs. It sorts all **keys** alphabetically. --- For sorting by specific **value member**, use Global.SortedPairsByMemberValue. --- For sorting by **value**, use Global.SortedPairsByValue. --- @param table table @The table to sort --- @param desc boolean @Reverse the sorting order --- @return function @Iterator function --- @return table @The table being iterated over function _G.SortedPairs(table, desc) end --- Returns an iterator function that can be used to loop through a table in order of member values, when the values of the table are also tables and contain that member. --- To sort by **value**, use Global.SortedPairsByValue. --- To sort by **keys**, use Global.SortedPairs. --- @param table table @Table to create iterator for. --- @param memberKey any @Key of the value member to sort by. --- @param descending boolean @Whether the iterator should iterate in descending order or not. --- @return function @Iterator function --- @return table @The table the iterator was created for. function _G.SortedPairsByMemberValue(table, memberKey, descending) end --- Returns an iterator function that can be used to loop through a table in order of its **values**. --- To sort by specific **value member**, use Global.SortedPairsByMemberValue. --- To sort by **keys**, use Global.SortedPairs. --- @param table table @Table to create iterator for --- @param descending boolean @Whether the iterator should iterate in descending order or not --- @return function @Iterator function --- @return table @The table which will be iterated over function _G.SortedPairsByValue(table, descending) end --- Runs util.PrecacheSound and returns the string. --- 🦟 **BUG**: util.PrecacheSound does nothing and therefore so does this function --- @param soundPath string @The soundpath to precache --- @return string @The string passed as the first argument function _G.Sound(soundPath) end --- Returns the duration of the sound specified in seconds. --- 🦟 **BUG**: [This only works properly for .wav files.](https://github.com/Facepunch/garrysmod-issues/issues/936) --- @param soundName string @The sound file path. --- @return number @Sound duration in seconds. function _G.SoundDuration(soundName) end --- Suppress any networking from the server to the specified player. This is automatically called by the engine before/after a player fires their weapon, reloads, or causes any other similar shared-predicted event to occur. --- @param suppressPlayer GPlayer @The player to suppress any networking to. function _G.SuppressHostEvents(suppressPlayer) end --- Returns a highly accurate time in seconds since the start up, ideal for benchmarking. --- @return number @Uptime of the server. function _G.SysTime() end --- Returns a TauntCamera object --- @return table @TauntCamera function _G.TauntCamera() end --- Clears focus from any text entries player may have focused. function _G.TextEntryLoseFocus() end --- Returns a cosine value that fluctuates based on the current time --- @param frequency number @The frequency of fluctuation --- @param min number @Minimum value --- @param max number @Maxmimum value --- @param offset number @Offset variable that doesn't affect the rate of change, but causes the returned value to be offset by time --- @return number @Cosine value function _G.TimedCos(frequency, min, max, offset) end --- Returns a sine value that fluctuates based on Global.CurTime. The value returned will be between the start value plus/minus the range value. --- 🦟 **BUG**: The range arguments don't work as intended. The existing (bugged) behavior is documented below. --- @param frequency number @The frequency of fluctuation, in --- @param origin number @The center value of the sine wave. --- @param max number @This argument's distance from origin defines the size of the full range of the sine wave --- @param offset number @Offset variable that doesn't affect the rate of change, but causes the returned value to be offset by time --- @return number @Sine value function _G.TimedSin(frequency, origin, max, offset) end --- Gets the associated type ID of the variable. Unlike Global.type, this does not work with no value - an argument must be provided. --- 🦟 **BUG**: [This returns garbage for _LOADLIB objects.](https://github.com/Facepunch/garrysmod-requests/issues/1120) --- 🦟 **BUG**: [This returns TYPE_NIL for protos.](https://github.com/Facepunch/garrysmod-requests/issues/1459) --- @param variable any @The variable to get the type ID of. --- @return number @The type ID of the variable function _G.TypeID(variable) end --- 🛑 **DEPRECATED**: You should use Global.IsUselessModel instead. --- Returns whether or not a model is useless by checking that the file path is that of a proper model. --- If the string ".mdl" is not found in the model name, the function will return true. --- The function will also return true if any of the following strings are found in the given model name: --- * "_gesture" --- * "_anim" --- * "_gst" --- * "_pst" --- * "_shd" --- * "_ss" --- * "_posture" --- * "_anm" --- * "ghostanim" --- * "_paths" --- * "_shared" --- * "anim_" --- * "gestures_" --- * "shared_ragdoll_" --- @param modelName string @The model name to be checked --- @return boolean @Whether or not the model is useless function _G.UTIL_IsUselessModel(modelName) end --- Returns the current asynchronous in-game time. --- @return number @The asynchronous in-game time. function _G.UnPredictedCurTime() end --- Returns the time in seconds it took to render the VGUI. function _G.VGUIFrameTime() end --- Creates and returns a DShape rectangle GUI element with the given dimensions. --- @param x number @X position of the created element --- @param y number @Y position of the created element --- @param w number @Width of the created element --- @param h number @Height of the created element --- @return GPanel @DShape element function _G.VGUIRect(x, y, w, h) end --- 🛑 **DEPRECATED**: You should use Global.IsValid instead --- Returns if a panel is safe to use. --- @param panel GPanel @The panel to validate. function _G.ValidPanel(panel) end --- Creates a Vector object. --- @param x number @The x component of the vector --- @param y number @The y component of the vector. --- @param z number @The z component of the vector. --- @return GVector @The created vector object. function _G.Vector(x, y, z) end --- Returns a random vector whose components are each between min(inclusive), max(exclusive). --- @param min number @Min bound inclusive. --- @param max number @Max bound exclusive. --- @return GVector @The random direction vector. function _G.VectorRand(min, max) end --- Translates the specified position and angle into the specified coordinate system. --- @param position GVector @The position that should be translated from the current to the new system. --- @param angle GAngle @The angles that should be translated from the current to the new system. --- @param newSystemOrigin GVector @The origin of the system to translate to. --- @param newSystemAngles GAngle @The angles of the system to translate to. --- @return GVector @Local position --- @return GAngle @Local angles function _G.WorldToLocal(position, angle, newSystemOrigin, newSystemAngles) end --- If the result of the first argument is false or nil, an error is thrown with the second argument as the message. --- @param expression any @The expression to assert. --- @param errorMessage string @The error message to throw when assertion fails --- @vararg any @Any arguments past the error message will be returned by a successful assert. --- @return any @If successful, returns the first argument. --- @return any @If successful, returns the error message --- @return any @Returns any arguments past the error message. function _G.assert(expression, errorMessage, ...) end --- Executes the specified action on the garbage collector. --- @param action string @The action to run --- @param arg number @The argument of the specified action, only applicable for "step", "setpause" and "setstepmul". --- @return any @If the action is count this is the number of kilobytes of memory used by Lua function _G.collectgarbage(action, arg) end --- Throws a Lua error and breaks out of the current call stack. --- @param message string @The error message to throw --- @param errorLevel number @The level to throw the error at. function _G.error(message, errorLevel) end --- 🛑 **DEPRECATED**: This function was deprecated in Lua 5.1 and is removed in Lua 5.2. Use Global.collectgarbage( "count" ) instead. --- Returns the current floored dynamic memory usage of Lua in kilobytes. --- @return number @The current floored dynamic memory usage of Lua, in kilobytes. function _G.gcinfo() end --- Returns the environment table of either the stack level or the function specified. --- @param location function @The object to get the enviroment from --- @return table @The environment. function _G.getfenv(location) end --- Returns the metatable of an object. This function obeys the metatable's __metatable field, and will return that field if the metatable has it set. --- Use debug.getmetatable if you want the true metatable of the object. --- @param object any @The value to return the metatable of. --- @return any @The metatable of the value function _G.getmetatable(object) end --- Executes a Lua script. --- ℹ **NOTE**: Addon files (.gma files) do not support relative parent folders (`..` notation). --- ⚠ **WARNING**: The file you are attempting to include MUST NOT be empty or the include will fail. Files over a certain size may fail as well. --- ⚠ **WARNING**: If the file you are including is clientside or shared, it **must** be Global.AddCSLuaFile'd or this function will error saying the file doesn't exist. --- ℹ **NOTE**: This function will try to load local client file if `sv_allowcslua` is **1** --- 🦟 **BUG**: [Global.pcalling this function will break autorefresh.](https://github.com/Facepunch/garrysmod-issues/issues/1976) --- @param fileName string @The name of the script to be executed --- @return any @Anything that the executed Lua script returns. function _G.include(fileName) end --- Returns an iterator function for a for loop, to return ordered key-value pairs from a table. --- This will only iterate though **numerical** keys, and these must also be **sequential**; starting at 1 with no gaps. --- For unordered pairs, see Global.pairs. --- For pairs sorted by key in alphabetical order, see Global.SortedPairs. --- @param tab table @The table to iterate over. --- @return function @The iterator function. --- @return table @The table being iterated over --- @return number @The origin index **=0** function _G.ipairs(tab) end --- Returns if the passed object is an Angle. --- @param variable any @The variable to perform the type check for. --- @return boolean @True if the variable is an Angle. function _G.isangle(variable) end --- Returns if the passed object is a boolean. --- @param variable any @The variable to perform the type check for. --- @return boolean @True if the variable is a boolean. function _G.isbool(variable) end --- Returns if the passed object is a function. --- @param variable any @The variable to perform the type check for. --- @return boolean @True if the variable is a function. function _G.isfunction(variable) end --- Returns whether the passed object is a VMatrix. --- @param variable any @The variable to perform the type check for. --- @return boolean @True if the variable is a VMatrix. function _G.ismatrix(variable) end --- Returns if the passed object is a number. --- @param variable any @The variable to perform the type check for. --- @return boolean @True if the variable is a number. function _G.isnumber(variable) end --- Returns if the passed object is a Panel. --- @param variable any @The variable to perform the type check for. --- @return boolean @True if the variable is a Panel. function _G.ispanel(variable) end --- Returns if the passed object is a string. --- @param variable any @The variable to perform the type check for. --- @return boolean @True if the variable is a string. function _G.isstring(variable) end --- Returns if the passed object is a table. --- @param variable any @The variable to perform the type check for. --- @return boolean @True if the variable is a table. function _G.istable(variable) end --- Returns if the passed object is a Vector. --- @param variable any @The variable to perform the type check for. --- @return boolean @True if the variable is a Vector. function _G.isvector(variable) end --- Creates a table with the specified module name and sets the function environment for said table. --- Any passed loaders are called with the table as an argument. An example of this is package.seeall. --- @param name string @The name of the module --- @vararg any @Calls each function passed with the new table as an argument. function _G.module(name, ...) end --- Returns a new userdata object. --- @param addMetatable boolean @If true, the userdata will get its own metatable automatically. --- @return userdata @The newly created userdata. function _G.newproxy(addMetatable) end --- Returns the next key and value pair in a table. --- ℹ **NOTE**: Table keys in Lua have no specific order, and will be returned in whatever order they exist in memory. This may not always be in ascending order or alphabetical order. If you need to iterate over an array in order, use Global.ipairs. --- @param tab table @The table --- @param prevKey any @The previous key in the table. --- @return any @The next key for the table --- @return any @The value associated with that key function _G.next(tab, prevKey) end --- Returns an iterator function(Global.next) for a for loop that will return the values of the specified table in an arbitrary order. --- For alphabetical **key** order use Global.SortedPairs. --- For alphabetical **value** order use Global.SortedPairsByValue. --- @param tab table @The table to iterate over --- @return function @The iterator (Global.next) --- @return table @The table being iterated over --- @return any @**nil** (for the constructor) function _G.pairs(tab) end --- Calls a function and catches an error that can be thrown while the execution of the call. --- 🦟 **BUG**: [Using this function with Global.include will break autorefresh.](https://github.com/Facepunch/garrysmod-issues/issues/1976) --- 🦟 **BUG**: [This cannot stop errors from hooks called from the engine.](https://github.com/Facepunch/garrysmod-issues/issues/2036) --- 🦟 **BUG**: [This does not stop Global.Error and Global.ErrorNoHalt from sending error messages to the server (if called clientside) or calling the GM:OnLuaError hook. The success boolean returned will always return true and thus you will not get the error message returned. Global.error does not exhibit these behaviours.](https://github.com/Facepunch/garrysmod-issues/issues/2498) --- 🦟 **BUG**: [This does not stop errors incurred by Global.include.](https://github.com/Facepunch/garrysmod-issues/issues/3112) --- @param func function @Function to be executed and of which the errors should be caught of --- @vararg any @Arguments to call the function with. --- @return boolean @If the function had no errors occur within it. --- @return any @If an error occurred, this will be a string containing the error message function _G.pcall(func, ...) end --- Writes every given argument to the console. --- Automatically attempts to convert each argument to a string. (See Global.tostring) --- Seperates lines with a line break (`"\n"`) --- Separates arguments with a tab character (`"\t"`). --- @vararg any @List of values to print. function _G.print(...) end --- Compares the two values without calling their __eq operator. --- @param value1 any @The first value to compare. --- @param value2 any @The second value to compare. --- @return boolean @Whether or not the two values are equal. function _G.rawequal(value1, value2) end --- Gets the value with the specified key from the table without calling the __index method. --- @param table table @Table to get the value from. --- @param index any @The index to get the value from. --- @return any @The value. function _G.rawget(table, index) end --- Sets the value with the specified key from the table without calling the __newindex method. --- @param table table @Table to get the value from. --- @param index any @The index to get the value from. --- @param value any @The value to set for the specified key. function _G.rawset(table, index, value) end --- First tries to load a binary module with the given name, if unsuccessful, it tries to load a Lua module with the given name. --- 🦟 **BUG**: [Running this function with Global.pcall or Global.xpcall will still print an error that counts towards sv_kickerrornum.](https://github.com/Facepunch/garrysmod-issues/issues/1041" request="813) --- ℹ **NOTE**: This function will try to load local client file if `sv_allowcslua` is **1** --- @param name string @The name of the module to be loaded. function _G.require(name) end --- Used to select single values from a vararg or get the count of values in it. --- @param parameter any @Can be a number or string --- @vararg any @The vararg --- @return any @Returns a number or vararg, depending on the select method. function _G.select(parameter, ...) end --- Sets the enviroment for a function or a stack level, if a function is passed, the return value will be the function, otherwise nil. --- @param location function @The function to set the enviroment for or a number representing stack level. --- @param enviroment table @Table to be used as enviroment. function _G.setfenv(location, enviroment) end --- Sets, changes or removes a table's metatable. Returns Tab (the first argument). --- @param Tab table @The table who's metatable to change. --- @param Metatable table @The metatable to assign --- @return table @The first argument. function _G.setmetatable(Tab, Metatable) end --- Attempts to return an appropriate boolean for the given value --- @param val any @The object to be converted to a boolean --- @return boolean @**false** for the boolean false function _G.tobool(val) end --- Attempts to convert the value to a number. --- Returns nil on failure. --- @param value any @The value to convert --- @param base number @The used in the string --- @return number @The numeric representation of the value with the given base, or nil if the conversion failed. function _G.tonumber(value, base) end --- Attempts to convert the value to a string. If the value is an object and its metatable has defined the __tostring metamethod, this will call that function. --- Global.print also uses this functionality. --- @param value any @The object to be converted to a string. --- @return string @The string representation of the value. function _G.tostring(value) end --- Returns a string representing the name of the type of the passed object. --- @param var any @The object to get the type of. --- @return string @The name of the object's type. function _G.type(var) end --- This function takes a numeric indexed table and return all the members as a vararg. If specified, it will start at the given index and end at end index. --- @param tbl table @The table to generate the vararg from. --- @param startIndex number @Which index to start from --- @param endIndex number @Which index to end at --- @return any @Output values function _G.unpack(tbl, startIndex, endIndex) end --- Attempts to call the first function. If the execution succeeds, this returns `true` followed by the returns of the function. If execution fails, this returns `false` and the second function is called with the error message. --- Unlike in Global.pcall, the stack is not unwound and can therefore be used for stack analyses with the debug. --- 🦟 **BUG**: [Using this function with Global.include will break autorefresh.](https://github.com/Facepunch/garrysmod-issues/issues/1976) --- 🦟 **BUG**: [This cannot stop errors from hooks called from the engine.](https://github.com/Facepunch/garrysmod-issues/issues/2036) --- 🦟 **BUG**: [This does not stop Global.Error and Global.ErrorNoHalt from sending error messages to the server (if called clientside) or calling the GM:OnLuaError hook. The success boolean returned will always return true and thus you will not get the error message returned. Global.error does not exhibit these behaviours.](https://github.com/Facepunch/garrysmod-issues/issues/2498) --- 🦟 **BUG**: [This does not stop errors incurred by Global.include.](https://github.com/Facepunch/garrysmod-issues/issues/3112) --- @param func function @The function to call initially. --- @param errorCallback function @The function to be called if execution of the first fails; the error message is passed as a string --- @vararg any @Arguments to pass to the initial function. --- @return boolean @Status of the execution; `true` for success, `false` for failure. --- @return any @The returns of the first function if execution succeeded, otherwise the **first** return value of the error callback. function _G.xpcall(func, errorCallback, ...) end
local followchars = true; local xx = 420.95; local yy = 275; local xx2 = 1222.9; local yy2 = 455; local ofs = 50; local ofs2 = 40; local del = 0; local del2 = 0; local angleshit = 0.3; local anglevar = 0.3; function onUpdate() if mustHitSection == true then if getProperty('boyfriend.animation.curAnim.name') == 'idle' then triggerEvent('Camera Follow Pos',xx2,yy2) setProperty('defaultCamZoom',1) end if getProperty('boyfriend.animation.curAnim.name') == 'singLEFT' then triggerEvent('Camera Follow Pos',xx2-ofs2,yy2) setProperty('defaultCamZoom',1) end if getProperty('boyfriend.animation.curAnim.name') == 'singRIGHT' then triggerEvent('Camera Follow Pos',xx2+ofs2,yy2) setProperty('defaultCamZoom',1) end if getProperty('boyfriend.animation.curAnim.name') == 'singUP' then triggerEvent('Camera Follow Pos',xx2,yy2-ofs2) setProperty('defaultCamZoom',1) end if getProperty('boyfriend.animation.curAnim.name') == 'singDOWN' then triggerEvent('Camera Follow Pos',xx2,yy2+ofs2) setProperty('defaultCamZoom',1) end end end
ENT.Type = "Anim" ENT.Base = "sent_kgren_base" ENT.PrintName = "Grenade" ENT.Author = "VurtualRuler98" ENT.Contact = "steam" ENT.Purpose = "Getting more ammo!" ENT.Instructions = "Spawn. Use. Reload." ENT.Category = "Vurtual's base" ENT.Spawnable = false ENT.AdminSpawnable = false ENT.ThrowFearVolume=768 ENT.DetonateSound="glassbottle.break" if (CLIENT) then function ENT:Draw() --AddWorldTip( self.Entity:EntIndex(), "ammo", 0.5, self.Entity:GetPos(),self.Entity) self.Entity:DrawModel() end end if (SERVER) then AddCSLuaFile() function ENT:Initialize() self.Entity:SetModel( "models/props_junk/garbage_glassbottle003a.mdl") self.Entity:PhysicsInit( SOLID_VPHYSICS) self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) self.Entity:SetUseType(SIMPLE_USE) self.Entity:SetCollisionGroup(COLLISION_GROUP_PROJECTILE) local phys = self.Entity:GetPhysicsObject() if (phys:IsValid()) then phys:SetMass(1) phys:Wake() end self:CreateFear() end end function ENT:Detonate() if (not IsFirstTimePredicted()) then return end self:EmitGunSound(self.DetonateSound) self:DetMolotov() self:Remove() end function ENT:Think() if (self.Igniting) then self:Detonate() end end function ENT:PhysicsCollide(data,phys) self.Igniting=true end
------------------- -- Adonis Server -- ------------------- --[[ If you find bugs, typos, or ways to improve something please message me (Sceleratis/Davey_Bones) with what you found so the script can be better. Also just be aware that I'm a very messy person, so a lot of this may or may not be spaghetti. ]] math.randomseed(os.time()) --// Todo: --// Fix a loooootttttttt of bugged commands --// Probably a lot of other stuff idk --// Transform from Sceleratis into Dr. Sceleratii; Evil alter-ego; Creator of bugs, destroyer of all code that is good --// Maybe add a celery command at some point --// Say hi to people reading the script --// ... --// "Hi." - Me --// Holiday roooaaAaaoooAaaooOod local _G, game, script, getfenv, setfenv, workspace, getmetatable, setmetatable, loadstring, coroutine, rawequal, typeof, print, math, warn, error, pcall, xpcall, select, rawset, rawget, ipairs, pairs, next, Rect, Axes, os, tick, Faces, unpack, string, Color3, newproxy, tostring, tonumber, Instance, TweenInfo, BrickColor, NumberRange, ColorSequence, NumberSequence, ColorSequenceKeypoint, NumberSequenceKeypoint, PhysicalProperties, Region3int16, Vector3int16, elapsedTime, require, table, type, wait, Enum, UDim, UDim2, Vector2, Vector3, Region3, CFrame, Ray, spawn = _G, game, script, getfenv, setfenv, workspace, getmetatable, setmetatable, loadstring, coroutine, rawequal, typeof, print, math, warn, error, pcall, xpcall, select, rawset, rawget, ipairs, pairs, next, Rect, Axes, os, tick, Faces, unpack, string, Color3, newproxy, tostring, tonumber, Instance, TweenInfo, BrickColor, NumberRange, ColorSequence, NumberSequence, ColorSequenceKeypoint, NumberSequenceKeypoint, PhysicalProperties, Region3int16, Vector3int16, elapsedTime, require, table, type, wait, Enum, UDim, UDim2, Vector2, Vector3, Region3, CFrame, Ray, spawn local unique = {} local origEnv = getfenv(); setfenv(1,setmetatable({}, {__metatable = unique})) local locals = {} local server = {} local Queues = {} local service = {} local RbxEvents = {} local Debounces = {} local LoopQueue = {} local ErrorLogs = {} local RealMethods = {} local RunningLoops = {} local HookedEvents = {} local WaitingEvents = {} local ServiceSpecific = {} local ServiceVariables = {} local oldReq = require local Folder = script.Parent local oldInstNew = Instance.new local isModule = function(module)for ind,modu in next,server.Modules do if module == modu then return true end end end local logError = function(plr,err) if server.Core and server.Core.DebugMode then warn("Error: "..tostring(plr)..": "..tostring(err)) end if server then server.Logs.AddLog(server.Logs.Errors,{Text = tostring(plr),Desc = err,Player=plr}) end end local message = function(...) game:GetService("TestService"):Message(...) end local print = function(...)for i,v in next,{...}do if server.Core and server.Core.DebugMode then message("::DEBUG:: Adonis ::"..tostring(v)) else print(':: Adonis :: '..tostring(v)) end end end local warn = function(...)for i,v in next,{...}do if server.Core and server.Core.DebugMode then message("::DEBUG:: Adonis ::"..tostring(v)) else warn(':: Adonis :: '..tostring(v)) end end end local cPcall = function(func,...) local function cour(...) coroutine.resume(coroutine.create(func),...) end local ran,error = pcall(cour,...) if error then warn(error) logError("SERVER",error) warn(error) end end local Pcall = function(func,...) local ran,error = pcall(func,...) if error then warn(error) logError("SERVER",error) warn(error) end end local Routine = function(func,...) coroutine.resume(coroutine.create(func),...) end local sortedPairs = function(t, f) local a = {} for n in next,t do table.insert(a, n) end table.sort(a, f) local i = 0 local iter = function () i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local GetEnv; GetEnv = function(env, repl) local scriptEnv = setmetatable({},{ __index = function(tab,ind) return (locals[ind] or (env or origEnv)[ind]) end; __metatable = unique; }) if repl and type(repl)=="table" then for ind, val in next,repl do scriptEnv[ind] = val end end return scriptEnv end; local GetVargTable = function() return { Server = server; Service = service; } end local LoadModule = function(plugin, yield, envVars, noEnv) noEnv = false --// Seems to make loading take longer when true (?) local isFunc = type(plugin) == "function" local plugin = (isFunc and service.New("ModuleScript", {Name = "Non-Module Loaded"})) or plugin local plug = (isFunc and plugin) or require(plugin) if server.Modules and type(plugin) ~= "function" then table.insert(server.Modules,plugin) end if type(plug) == "function" then if yield then --Pcall(setfenv(plug,GetEnv(getfenv(plug), envVars))) local ran,err = service.TrackTask("Plugin: ".. tostring(plugin), (noEnv and plug) or setfenv(plug, GetEnv(getfenv(plug), envVars)), GetVargTable()) if not ran then warn("Module encountered an error while loading: "..tostring(plugin)) warn(tostring(err)) end else --service.Threads.RunTask("PLUGIN: "..tostring(plugin),setfenv(plug,GetEnv(getfenv(plug), envVars))) local ran, err = service.TrackTask("Thread: Plugin: ".. tostring(plugin), (noEnv and plug) or setfenv(plug, GetEnv(getfenv(plug), envVars)),GetVargTable()) if not ran then warn("Module encountered an error while loading: "..tostring(plugin)) warn(tostring(err)) end end else server[plugin.Name] = plug end if server.Logs then server.Logs.AddLog(server.Logs.Script,{ Text = "Loaded "..tostring(plugin).." Module"; Desc = "Adonis loaded a core module or plugin"; }) end end; local CleanUp = function() --local env = getfenv(2) --local ran,ret = pcall(function() return env.script:GetFullName() end) warn("Beginning Adonis cleanup & shutdown process...") --warn("CleanUp called from "..tostring((ran and ret) or "Unknown")) --local loader = server.Core.ClientLoader server.Model.Parent = service.ServerScriptService server.Model.Name = "Adonis_Loader" server.Running = false service.Threads.StopAll() for i,v in next,RbxEvents do print("Disconnecting event") v:Disconnect() table.remove(RbxEvents, i) end --loader.Archivable = false --loader.Disabled = true --loader:Destroy() if server.Core.RemoteEvent then server.Core.RemoteEvent.Security:Disconnect() server.Core.RemoteEvent.Event:Disconnect() server.Core.RemoteEvent.DecoySecurity1:Disconnect() server.Core.RemoteEvent.DecoySecurity2:Disconnect() pcall(service.Delete,server.Core.RemoteEvent.Object) pcall(service.Delete,server.Core.RemoteEvent.Decoy1) pcall(service.Delete,server.Core.RemoteEvent.Decoy2) end warn("Unloading complete") end; server = { Running = true; Modules = {}; Pcall = Pcall; cPcall = cPcall; Routine = Routine; LogError = logError; ErrorLogs = ErrorLogs; FilteringEnabled = workspace.FilteringEnabled; ServerStartTime = os.time(); CommandCache = {}; }; locals = { server = server; CodeName = ""; Settings = server.Settings; HookedEvents = HookedEvents; sortedPairs = sortedPairs; ErrorLogs = ErrorLogs; logError = logError; origEnv = origEnv; Routine = Routine; Folder = Folder; GetEnv = GetEnv; cPcall = cPcall; Pcall = Pcall; } service = setfenv(require(Folder.Core.Service), GetEnv(nil, {server = server}))(function(eType, msg, desc, ...) local extra = {...} if eType == "MethodError" then if server and server.Logs and server.Logs.AddLog then server.Logs.AddLog("Script", { Text = "Cached method doesn't match found method: "..tostring(extra[1]); Desc = "Method: "..tostring(extra[1]) }) end elseif eType == "ServerError" then --print("Server error") logError("Server", msg) elseif eType == "TaskError" then --print("Task error") logError("Task", msg) end end, function(c, parent, tab) if not isModule(c) and c ~= server.Loader and c ~= server.Dropper and c ~= server.Runner and c ~= server.Model and c ~= script and c ~= Folder and parent == nil then tab.UnHook() end end, ServiceSpecific) --// Localize os = service.Localize(os) math = service.Localize(math) table = service.Localize(table) string = service.Localize(string) coroutine = service.Localize(coroutine) Instance = service.Localize(Instance) Vector2 = service.Localize(Vector2) Vector3 = service.Localize(Vector3) CFrame = service.Localize(CFrame) UDim2 = service.Localize(UDim2) UDim = service.Localize(UDim) Ray = service.Localize(Ray) Rect = service.Localize(Rect) Faces = service.Localize(Faces) Color3 = service.Localize(Color3) NumberRange = service.Localize(NumberRange) NumberSequence = service.Localize(NumberSequence) NumberSequenceKeypoint = service.Localize(NumberSequenceKeypoint) ColorSequenceKeypoint = service.Localize(ColorSequenceKeypoint) PhysicalProperties = service.Localize(PhysicalProperties) ColorSequence = service.Localize(ColorSequence) Region3int16 = service.Localize(Region3int16) Vector3int16 = service.Localize(Vector3int16) BrickColor = service.Localize(BrickColor) TweenInfo = service.Localize(TweenInfo) Axes = service.Localize(Axes) --// Wrap require = function(obj) return service.Wrap(oldReq(service.UnWrap(obj))) end --]] Instance = {new = function(obj, parent) return oldInstNew(obj, service.UnWrap(parent)) end} require = function(obj) return oldReq(service.UnWrap(obj)) end rawequal = service.RawEqual --service.Players = service.Wrap(service.Players) --Folder = service.Wrap(Folder) server.Folder = Folder server.Deps = Folder.Dependencies; server.CommandModules = Folder.Commands; server.Client = Folder.Parent.Client; server.Dependencies = Folder.Dependencies; server.PluginsFolder = Folder.Plugins; server.Service = service --// Setting things up for ind,loc in next,{ _G = _G; game = game; spawn = spawn; script = script; getfenv = getfenv; setfenv = setfenv; workspace = workspace; getmetatable = getmetatable; setmetatable = setmetatable; loadstring = loadstring; coroutine = coroutine; rawequal = rawequal; typeof = typeof; print = print; math = math; warn = warn; error = error; pcall = pcall; xpcall = xpcall; select = select; rawset = rawset; rawget = rawget; ipairs = ipairs; pairs = pairs; next = next; Rect = Rect; Axes = Axes; os = os; tick = tick; Faces = Faces; unpack = unpack; string = string; Color3 = Color3; newproxy = newproxy; tostring = tostring; tonumber = tonumber; Instance = Instance; TweenInfo = TweenInfo; BrickColor = BrickColor; NumberRange = NumberRange; ColorSequence = ColorSequence; NumberSequence = NumberSequence; ColorSequenceKeypoint = ColorSequenceKeypoint; NumberSequenceKeypoint = NumberSequenceKeypoint; PhysicalProperties = PhysicalProperties; Region3int16 = Region3int16; Vector3int16 = Vector3int16; elapsedTime = elapsedTime; require = require; table = table; type = type; wait = wait; Enum = Enum; UDim = UDim; UDim2 = UDim2; Vector2 = Vector2; Vector3 = Vector3; Region3 = Region3; CFrame = CFrame; Ray = Ray; service = service }do locals[ind] = loc end --// Init return service.NewProxy({__metatable = "Adonis"; __tostring = function() return "Adonis" end; __call = function(tab, data) if _G["__Adonis_MODULE_MUTEX"] and type(_G["__Adonis_MODULE_MUTEX"])=="string" then warn("\n-----------------------------------------------" .."\nAdonis server-side is already running! Aborting..." .."\n-----------------------------------------------") script:Destroy() return "FAILED" else _G["__Adonis_MODULE_MUTEX"] = "Running" end if not data or not data.Loader then warn("WARNING: MainModule loaded without using the loader;") end --// Begin Script Loading setfenv(1,setmetatable({}, {__metatable = unique})) data = service.Wrap(data or {}) --// Server Variables local setTab = require(server.Deps.DefaultSettings) server.Defaults = setTab server.Settings = data.Settings or setTab.Settings or {} server.Descriptions = data.Descriptions or setTab.Descriptions or {} server.Order = data.Order or setTab.Order or {} server.Data = data or {} server.Model = data.Model or service.New("Model") server.Dropper = data.Dropper or service.New("Script") server.Loader = data.Loader or service.New("Script") server.Runner = data.Runner or service.New("Script") server.ServerPlugins = data.ServerPlugins server.ClientPlugins = data.ClientPlugins server.Threading = require(server.Deps.ThreadHandler) server.Changelog = require(server.Client.Dependencies.Changelog) server.Credits = require(server.Client.Dependencies.Credits) locals.Settings = server.Settings locals.CodeName = server.CodeName if server.Settings.HideScript and data.Model then data.Model.Parent = nil script:Destroy() end for setting,value in next,setTab.Settings do if server.Settings[setting] == nil then server.Settings[setting] = value end end for desc,value in next,setTab.Descriptions do if server.Descriptions[desc] == nil then server.Descriptions[desc] = value end end --// Load services for ind, serv in next,{ "Workspace"; "Players"; "Lighting"; "ServerStorage"; "ReplicatedStorage"; "JointsService"; "ReplicatedFirst"; "ScriptContext"; "ServerScriptService"; "LogService"; "Teams"; "SoundService"; "StarterGui"; "StarterPack"; "StarterPlayers"; "TestService"; "HttpService"; "InsertService"; "NetworkServer" }do local temp = service[serv] end --// Module LoadOrder List local LoadingOrder = { "Logs"; "Variables"; "Core"; "Remote"; "Functions"; "Process"; "Admin"; "HTTP"; "Anti"; "Commands"; } --// Load core modules for ind,load in next,LoadingOrder do local modu = Folder.Core:FindFirstChild(load) if modu then LoadModule(modu,true,{script = script}, true) --noenv end end --// Initialize Cores for i,name in next,LoadingOrder do local core = server[name] if core and type(core) == "table" and core.Init then core.Init() core.Init = nil elseif type(core) == "userdata" and getmetatable(core) == "ReadOnly_Table" and core.Init then core.Init() end end --// More Variable Initialization server.Variables.CodeName = server.Functions:GetRandom() server.Remote.MaxLen = 0 server.Logs.Errors = ErrorLogs server.Client = Folder.Parent.Client server.Core.Name = server.Functions:GetRandom() server.Core.Themes = data.Themes or {} server.Core.Plugins = data.Plugins or {} server.Core.ModuleID = data.ModuleID or 2373501710 server.Core.LoaderID = data.LoaderID or 2373505175 server.Core.DebugMode = data.DebugMode or false server.Core.DataStore = server.Core.GetDataStore() server.Core.Loadstring = require(server.Deps.Loadstring) server.HTTP.Trello.API = require(server.Deps.TrelloAPI) server.LoadModule = LoadModule server.ServiceSpecific = ServiceSpecific --// Bind cleanup service.DataModel:BindToClose(CleanUp) --// Server Specific Service Functions ServiceSpecific.GetPlayers = server.Functions.GetPlayers --// Load data if server.Core.DataStore then service.TrackTask("Thread: DSLoadAndHook", function() pcall(server.Core.LoadData) --// Occasionally the below line causes a script execution timeout error, so lets just pcall the whole thing and hope loading doesn't break yolo(?) local ds = server.Core.DataStore; --pcall(ds.OnUpdate, ds, server.Core.DataStoreEncode("CrossServerChat"), server.Process.CrossServerChat) -- WE NEED TO UPGRADE THIS TO THAT CROSS SERVER MESSAGE SERVICE THING. This is big bad currently. --pcall(ds.OnUpdate, ds, server.Core.DataStoreEncode("SavedSettings"), function(data) server.Process.DataStoreUpdated("SavedSettings",data) end) --pcall(ds.OnUpdate, ds, server.Core.DataStoreEncode("SavedTables"), function(data) server.Process.DataStoreUpdated("SavedTables",data) end) end) --server.Core.DataStore:OnUpdate(server.Core.DataStoreEncode("CrossServerChat"), server.Process.CrossServerChat) --server.Core.DataStore:OnUpdate(server.Core.DataStoreEncode("SavedSettings"), function(data) server.Process.DataStoreUpdated("SavedSettings",data) end) --server.Core.DataStore:OnUpdate(server.Core.DataStoreEncode("SavedTables"), function(data) server.Process.DataStoreUpdated("SavedTables",data) end) --server.Core.DataStore:OnUpdate(server.Core.DataStoreEncode("SavedVariables"), function(data) server.Process.DataStoreUpdated("SavedVariables",data) end) --server.Core.DataStore:OnUpdate(server.Core.DataStoreEncode("FullShutdown"), function(data) if data then local id,user,reason = data.ID,data.User,data.Reason if id == game.PlaceId then server.Functions.Shutdown(reason) end end end) end --// NetworkServer Events if service.NetworkServer then service.RbxEvent(service.NetworkServer.ChildAdded, server.Process.NetworkAdded) service.RbxEvent(service.NetworkServer.DescendantRemoving, server.Process.NetworkRemoved) end --// Load Plugins for index,plugin in next,server.PluginsFolder:GetChildren() do LoadModule(plugin, false, {script = plugin}, true); --noenv end for index,plugin in next,(data.ServerPlugins or {}) do LoadModule(plugin, false, {script = plugin}); end --// RemoteEvent Handling server.Core.MakeEvent() service.JointsService.Changed:Connect(function(p) if server.Anti.RLocked(service.JointsService) then server.Core.PanicMode("JointsService RobloxLocked") end end) service.JointsService.ChildRemoved:Connect(function(c) if server.Core.RemoteEvent and not server.Core.FixingEvent and (function() for i,v in next,server.Core.RemoteEvent do if c == v then return true end end end)() then wait(); server.Core.MakeEvent() end end) --// Do some things for com in next,server.Remote.Commands do if string.len(com)>server.Remote.MaxLen then server.Remote.MaxLen = string.len(com) end end for index,plugin in next,(data.ClientPlugins or {}) do plugin:Clone().Parent = server.Client.Plugins end for index,theme in next,(data.Themes or {}) do theme:Clone().Parent = server.Client.UI end --// Prepare the client loader --server.Core.PrepareClient() --// Add existing players in case some are already in the server for index,player in next,service.Players:GetPlayers() do service.TrackTask("Thread: LoadPlayer ".. tostring(player.Name), server.Core.LoadExistingPlayer, player); end --// Events service.RbxEvent(service.Players.PlayerAdded, service.EventTask("PlayerAdded", server.Process.PlayerAdded)) service.RbxEvent(service.Players.PlayerRemoving, service.EventTask("PlayerRemoving", server.Process.PlayerRemoving)) service.RbxEvent(service.Workspace.ChildAdded, server.Process.WorkspaceChildAdded) service.RbxEvent(service.LogService.MessageOut, server.Process.LogService) service.RbxEvent(service.ScriptContext.Error, server.Process.ErrorMessage) --// Fake finder service.RbxEvent(service.Players.ChildAdded, server.Anti.RemoveIfFake) --// Start API if service.NetworkServer then --service.Threads.RunTask("_G API Manager",server.Core.StartAPI) service.TrackTask("Thread: API Manager", server.Core.StartAPI) end --// Queue handler --service.StartLoop("QueueHandler","Heartbeat",service.ProcessQueue) --// Client check service.StartLoop("ClientCheck",30,server.Core.CheckAllClients,true) --// Trello updater if server.Settings.Trello_Enabled then service.StartLoop("TRELLO_UPDATER",server.Settings.HttpWait,server.HTTP.Trello.Update,true) end --// Load minor stuff server.Threading.NewThread(function() for ind, music in next,server.Settings.MusicList or {} do table.insert(server.Variables.MusicList,music) end for ind, music in next,server.Settings.InsertList or {} do table.insert(server.Variables.InsertList,music) end for ind, cape in next,server.Settings.CapeList or {} do table.insert(server.Variables.Capes,cape) end for ind, cmd in next,server.Settings.Permissions or {} do local com,level = cmd:match("^(.*):(.*)") if com and level then if level:find(",") then local newLevels = {} for lvl in level:gmatch("[^%,]+") do table.insert(newLevels, service.Trim(lvl)) end server.Admin.SetPermission(com, newLevels) else server.Admin.SetPermission(com, level) end end end pcall(function() service.Workspace.AllowThirdPartySales = true end) server.Functions.GetOldDonorList() end) --// Backup Map if server.Settings.AutoBackup then service.TrackTask("Thread: Initial Map Backup", server.Admin.RunCommand, server.Settings.Prefix.."backupmap") end --service.Threads.RunTask("Initial Map Backup",server.Admin.RunCommand,server.Settings.Prefix.."backupmap") --// AutoClean if server.Settings.AutoClean then service.StartLoop("AUTO_CLEAN",server.Settings.AutoCleanDelay,server.Functions.CleanWorkspace,true) end --// Worksafe service.TrackTask("WorkSafe",function() if server.Settings.AntiLeak and not service.ServerScriptService:FindFirstChild("ADONIS_AntiLeak") then local ancsafe = server.Deps.Assets.WorkSafe:clone() ancsafe.Mode.Value = "AntiLeak" ancsafe.Name = "ADONIS_AntiLeak" ancsafe.Archivable = false ancsafe.Parent = service.ServerScriptService ancsafe.Disabled = false end end) --// Finished loading server.Variables.BanMessage = server.Settings.BanMessage server.Variables.LockMessage = server.Settings.LockMessage for i,v in next,server.Settings.OnStartup do server.Logs.AddLog("Script",{Text = "Startup: Executed "..tostring(v); Desc = "Executed startup command; "..tostring(v)}) server.Threading.NewThread(server.Admin.RunCommand, v) end server.Logs.AddLog(server.Logs.Script,{ Text = "Finished Loading"; Desc = "Adonis finished loading"; }) if data.Loader then warn("Loading Complete; Required by "..tostring(data.Loader:GetFullName())) else warn("Loading Complete;") end return "SUCCESS" end})
local Builder = {} Builder.DarkTheme = Color3.fromRGB(20, 20, 20) Builder.LightTheme = Color3.fromRGB(250, 250, 250) Builder.ClassName = "ScreenCoverBuilder" function Builder:CreateFrame(Theme) local Frame = Instance.new("Frame") Frame.Size = UDim2.new(1, 0, 1, 0) Frame.Position = UDim2.new(0, 0, 0, 0) Frame.Active = true Frame.BackgroundColor3 = Theme == "Light" and Builder.LightTheme or Builder.DarkTheme Frame.BorderSizePixel = 0 Frame.ZIndex = 100 Frame.Name = "ScreenCover" return Frame end function Builder:CreateScreenGui() local ScreenGui = Instance.new("ScreenGui") ScreenGui.Name = "ScreenCover" ScreenGui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling ScreenGui.DisplayOrder = 10 ScreenGui.IgnoreGuiInset = true ScreenGui.ResetOnSpawn = false return ScreenGui end return Builder
-- This code is derived from the SOM benchmarks, see AUTHORS.md file. -- -- Copyright (c) 2016 Francois Perrad <[email protected]> -- -- 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 towers = {} do setmetatable(towers, {__index = require'benchmark'}) local function create_disk (size) return {size = size, next = nil} end function towers:benchmark () self.piles = {} self:build_tower_at(1, 13) self.moves_done = 0 self:move_disks(13, 1, 2) return self.moves_done end function towers:verify_result (result) return 8191 == result end function towers:push_disk (disk, pile) local top = self.piles[pile] if top and disk.size >= top.size then error 'Cannot put a big disk on a smaller one' end disk.next = top self.piles[pile] = disk end function towers:pop_disk_from (pile) local top = self.piles[pile] assert(top, 'Attempting to remove a disk from an empty pile') self.piles[pile] = top.next top.next = nil return top end function towers:move_top_disk (from_pile, to_pile) self:push_disk(self:pop_disk_from(from_pile), to_pile) self.moves_done = self.moves_done + 1 end function towers:build_tower_at (pile, disks) for i = disks, 1, -1 do self:push_disk(create_disk(i), pile) end end function towers:move_disks (disks, from_pile, to_pile) if disks == 1 then self:move_top_disk(from_pile, to_pile) else local other_pile = 6 - from_pile - to_pile self:move_disks(disks - 1, from_pile, other_pile) self:move_top_disk(from_pile, to_pile) self:move_disks(disks - 1, other_pile, to_pile) end end end -- object towers return towers
local lunit = require "lunit" package.path = 'lualib/?/init.lua;lualib/?.lua;'..package.path local utils = require "smithsnmp.utils" module("test_utils", lunit.testcase, package.seeall) test_iter1 = function() -- test iter local i = 0 for v in utils.iter({1, 2, 3, 4, 5}) do i = i + 1 assert_true(v == i) end assert_true(i == 5) end test_iter2 = function() -- test iter local i = utils.iter(function() return nil end) local x = true for v in i do x = false end assert_true(x) end -- helper: compare 2 array table local array_compare = function(ta, tb) if #ta ~= #tb then return false end for i, a in ipairs(ta) do if a ~= tb[i] then return false end end return true end -- test map test_map = function() assert_true(array_compare( utils.map( function (x) return x + 1 end, {1, 2, 3, 4, 5} ), {2, 3, 4, 5, 6} )) end -- test filter test_filter = function() assert_true(array_compare( utils.filter( function (x) return (x % 2) == 1 end, {1, 2, 3, 4, 5} ), {1, 3, 5} )) end -- test reduce w/o init test_reduce1 = function() assert_true( utils.reduce( function (x, y) return x * y end, {1, 2, 3, 4, 5} ) == 120 ) end -- test reduce with init test_reduce2 = function() assert_true( utils.reduce( function (x, y) return x * y end, {1, 2, 3, 4, 5}, 0 ) == 0 ) end -- test str2mac test_str2mac = function() assert_true(array_compare(utils.str2mac("00:00:00:00:00:00"), {0, 0, 0, 0, 0, 0})) assert_true(array_compare(utils.str2mac("ff:ff:ff:ff:ff:ff"), {255, 255, 255, 255, 255, 255})) assert_true(array_compare(utils.str2mac("FF:FF:FF:FF:FF:FF"), {255, 255, 255, 255, 255, 255})) assert_true(array_compare(utils.str2mac("11:22:33:44:55:66"), {0x11, 0x22, 0x33, 0x44, 0x55, 0x66})) end -- test mac2oct test_mac2oct = function() assert_true(utils.mac2oct({0x61, 0x62, 0x63, 0x64, 0x65, 0x66}) == 'abcdef') assert_true(utils.mac2oct("61:62:63:64:65:66") == 'abcdef') end lunit.main()
-- ===================================================================== -- -- asynctasks.lua - -- -- Created by liubang on 2021/08/29 03:39 -- Last Modified: 2021/08/29 03:39 -- -- ===================================================================== vim.g.asyncrun_open = 25 vim.g.asyncrun_bell = 1 vim.g.asyncrun_rootmarks = {'.svn', '.git', '.root', '_darcs', 'build.xml'} vim.g.asynctasks_term_pos = 'floaterm' vim.g.asynctasks_term_reuse = 0
--- -- @author wesen -- @copyright 2019-2020 wesen <[email protected]> -- @release 0.1 -- @license MIT -- local Object = require "classic" --- -- Contains information about a parsed function argument. -- -- @type Argument -- local Argument = Object:extend() --- -- The Argument's name -- -- @tfield string name -- Argument.name = nil --- -- The Argument's description -- -- @tfield string description -- Argument.description = nil --- -- The Argument's notes -- -- @tfield string notes -- Argument.notes = nil --- -- True if the Argument's values have a variable length, false otherwise -- -- @tfield bool hasVariableLength -- Argument.hasVariableLength = nil --- -- Argument constructor. -- -- @tparam string _name The Argument's name -- @tparam string _description The Argument's description -- @tparam string _notes The Argument's notes -- @tparam bool _hasVariableLength True if the Argument's values have a variable length, false otherwise -- function Argument:new(_name, _description, _notes, _hasVariableLength) self.name = _name self.description = _description self.notes = _notes self.hasVariableLength = _hasVariableLength end -- Getters and Setters --- -- Returns the Argument's name. -- -- @treturn string The Argument's name -- function Argument:getName() return self.name end --- -- Returns the Argument's description. -- -- @treturn string The Argument's description -- function Argument:getDescription() return self.description end --- -- Returns the Argument's notes. -- -- @treturn string The Argument's notes -- function Argument:getNotes() return self.notes end --- -- Returns whether the Argument's values have a variable length. -- -- @treturn bool True if the Argument's values have a variable length, false otherwise -- function Argument:getHasVariableLength() return self.hasVariableLength end return Argument
require "Polycode/ScreenShape" class "ScreenImage" (ScreenShape) function ScreenImage:ScreenImage(...) if type(arg[1]) == "table" and count(arg) == 1 then if ""..arg[1]:class() == "ScreenShape" then self.__ptr = arg[1].__ptr return end end for k,v in pairs(arg) do if type(v) == "table" then if v.__ptr ~= nil then arg[k] = v.__ptr end end end if self.__ptr == nil and arg[1] ~= "__skip_ptr__" then self.__ptr = Polycore.ScreenImage(unpack(arg)) Polycore.__ptr_lookup[self.__ptr] = self end end function ScreenImage:setImageCoordinates(x, y, width, height) local retVal = Polycore.ScreenImage_setImageCoordinates(self.__ptr, x, y, width, height) end function ScreenImage:getImageWidth() local retVal = Polycore.ScreenImage_getImageWidth(self.__ptr) return retVal end function ScreenImage:getImageHeight() local retVal = Polycore.ScreenImage_getImageHeight(self.__ptr) return retVal end function ScreenImage:__delete() Polycore.__ptr_lookup[self.__ptr] = nil Polycore.delete_ScreenImage(self.__ptr) end
local local0 = 0.5 local local1 = 3.4 - local0 local local2 = 0.5 - local0 local local3 = 4.2 - local0 local local4 = 0.5 - local0 local local5 = 2.7 - local0 local local6 = 9.2 - local0 local local7 = 0.5 - local0 local local8 = 2.5 - local0 local local9 = 0.5 - local0 local local10 = 2.5 - local0 local local11 = 3.7 - local0 local local12 = 6.5 - local0 local local13 = 5.7 - local0 local local14 = 17.6 - local0 local local15 = 7.5 - local0 local local16 = 19.6 - local0 local local17 = 0.5 - local0 local local18 = 15 - local0 local local19 = 0.5 - local0 local local20 = 3.7 - local0 local local21 = 0.5 - local0 local local22 = 2.7 - local0 local local23 = 3.5 - local0 local local24 = 6.5 - local0 local local25 = 5.4 - local0 local local26 = 17.1 - local0 local local27 = 7.2 - local0 local local28 = 19.2 - local0 local local29 = 0.5 - local0 local local30 = 15 - local0 function OnIf_240000(arg0, arg1, arg2) if arg2 == 0 then AbandonedGiant_Thrower240010_ActAfter_RealTime(arg0, arg1) end return end function AbandonedGiant_Thrower240010Battle_Activate(arg0, arg1) local local0 = {} local local1 = {} local local2 = {} Common_Clear_Param(local0, local1, local2) local local3 = arg0:GetDist(TARGET_ENE_0) local local4 = arg0:GetEventRequest() local local5 = arg0:GetRandam_Int(1, 100) if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 120) then local0[20] = 100 elseif 10 <= local3 then local0[10] = 100 elseif 7 <= local3 then local0[1] = 20 local0[2] = 5 local0[3] = 15 local0[4] = 15 local0[8] = 20 elseif 3 <= local3 then local0[1] = 30 local0[2] = 10 local0[3] = 15 local0[4] = 20 local0[8] = 5 else local0[1] = 35 local0[2] = 10 local0[3] = 15 local0[4] = 15 local0[8] = 0 end local1[1] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act01) local1[2] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act02) local1[3] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act03) local1[4] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act04) local1[5] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act05) local1[6] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act06) local1[7] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act07) local1[8] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act08) local1[9] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act09) local1[10] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act10) local1[11] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act11) local1[15] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act15) local1[20] = REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_Act20) Common_Battle_Activate(arg0, arg1, local0, local1, REGIST_FUNC(arg0, arg1, AbandonedGiant_Thrower240010_ActAfter_AdjustSpace), local2) return end local0 = 4.7 - local0 local0 = 0.5 - local0 local0 = local1 local0 = 0.5 - local0 function AbandonedGiant_Thrower240010_Act01(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) if arg0:HasSpecialEffectId(TARGET_SELF, 5671) == true then local local2 = UPVAL1 local local3 = UPVAL0 + 1 Approach_Act(arg0, arg1, UPVAL0, 999, 0, 2) if local1 <= 30 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3020, TARGET_ENE_0, local3, 0, 20) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3020, TARGET_ENE_0, local3, 0, -1) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3021, TARGET_ENE_0, UPVAL0 + 1, 0) end else local local2 = UPVAL3 local local3 = UPVAL2 + 1 Approach_Act(arg0, arg1, UPVAL2, 999, 0, 2) if local1 <= 30 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, local3, 0, 20) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local3, 0, -1) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, UPVAL0 + 1, 0) end end GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 3.8 - local0 local0 = 0.5 - local0 local0 = 3.5 - local0 local0 = 0.5 - local0 function AbandonedGiant_Thrower240010_Act02(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) if arg0:HasSpecialEffectId(TARGET_SELF, 5671) == true then local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, 999, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3023, TARGET_ENE_0, UPVAL0 + 1, 0, -1) else local local2 = UPVAL3 Approach_Act(arg0, arg1, UPVAL2, 12, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3003, TARGET_ENE_0, UPVAL2 + 1, 0, -1) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 3.3 - local0 local0 = 0.5 - local0 local0 = 2.9 - local0 local0 = 0.5 - local0 function AbandonedGiant_Thrower240010_Act03(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) if arg0:HasSpecialEffectId(TARGET_SELF, 5671) == true then local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, 999, 0, 3.5) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3024, TARGET_ENE_0, UPVAL0 + 1, 0, -1) else local local2 = UPVAL3 Approach_Act(arg0, arg1, UPVAL2, 12, 0, 3.5) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3004, TARGET_ENE_0, UPVAL2 + 1, 0, -1) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 3.3 - local0 local0 = 0.5 - local0 local0 = 3 - local0 local0 = 0.5 - local0 function AbandonedGiant_Thrower240010_Act04(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) if arg0:HasSpecialEffectId(TARGET_SELF, 5671) == true then local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, 999, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3025, TARGET_ENE_0, UPVAL0, 0, -1) else local local2 = UPVAL3 Approach_Act(arg0, arg1, UPVAL2, 999, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, UPVAL2 + 1, 0, -1) end GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 3.9 - local0 local0 = 0.5 - local0 function AbandonedGiant_Thrower240010_Act05(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, 999, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3006, TARGET_ENE_0, UPVAL0 + 1, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 4.4 - local0 local0 = 0.5 - local0 function AbandonedGiant_Thrower240010_Act06(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, 999, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, UPVAL0 + 1, 1.5, 20) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 11.6 - local0 local0 = 5 - local0 function AbandonedGiant_Thrower240010_Act07(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, UPVAL0, 0, 5) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3008, TARGET_ENE_0, UPVAL0 + 1, 0, -1) arg0:SetTimer(1, 7) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 9.5 - local0 local0 = 5.7 - local0 local0 = local6 local0 = 5.7 - local0 function AbandonedGiant_Thrower240010_Act08(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) if arg0:HasSpecialEffectId(TARGET_SELF, 5671) == true then local local2 = UPVAL1 if arg0:IsFinishTimer(0) ~= false then Approach_Act(arg0, arg1, UPVAL0, UPVAL0, 0, 5) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3029, TARGET_ENE_0, UPVAL0 + 1, 0, -1) else local local2 = UPVAL3 if arg0:IsFinishTimer(0) == false then arg1:AddSubGoal(GOAL_COMMON_Wait, 0.9, TARGET_ENE_0, 0, 0, 0) else Approach_Act(arg0, arg1, UPVAL2, UPVAL2, 0, 5) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3009, TARGET_ENE_0, UPVAL2 + 1, 0, -1) end arg0:SetTimer(1, 7) arg0:SetTimer(0, 0) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function AbandonedGiant_Thrower240010_Act10(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = DIST_None if 5 <= arg0:GetDistYSigned(TARGET_ENE_0) then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3036, TARGET_ENE_0, local2, 0, -1) elseif 35 <= local0 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3019, TARGET_ENE_0, local2, 0, -1) elseif 25 <= local0 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3018, TARGET_ENE_0, local2, 0, -1) else arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3017, TARGET_ENE_0, local2, 0, -1) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end function AbandonedGiant_Thrower240010_Act20(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_Turn, 2, TARGET_ENE_0, 0, 0, 0) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function AbandonedGiant_Thrower240010_ActAfter_AdjustSpace(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_If, 10, 0) return end function AbandonedGiant_Thrower240010_ActAfter_RealTime(arg0, arg1) local local0 = arg0:GetDist(TARGET_ENE_0) if arg0:GetRandam_Int(1, 100) <= 50 then arg0:SetTimer(0, 2) end return end function AbandonedGiant_Thrower240010Battle_Update(arg0, arg1) return GOAL_RESULT_Continue end function AbandonedGiant_Thrower240010Battle_Terminate(arg0, arg1) return end local0 = local1 local0 = local6 function AbandonedGiant_Thrower240010Battle_Interupt(arg0, arg1) if arg0:IsLadderAct(TARGET_SELF) then return false else local local0 = arg0:GetRandam_Int(1, 100) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Int(1, 100) if UseItem_Act(arg0, arg1, 10, 40) then arg1:ClearSubGoal() if arg0:GetDist(TARGET_ENE_0) < 5.2 then Approach_Act(arg0, arg1, UPVAL0, UPVAL0, 0, 3.5) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, UPVAL0, 0, -1) else Approach_Act(arg0, arg1, UPVAL1, UPVAL1, 0, 3.5) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3009, TARGET_ENE_0, UPVAL1, 0, -1) end return true else local local3 = arg0:GetRandam_Int(1, 100) local local4 = arg0:GetRandam_Int(1, 100) local local5 = arg0:GetDist(TARGET_ENE_0) local local6 = Shoot_2dist(arg0, arg1, 6, 20, 20, 40) if local6 == 1 then Approach_Act(arg0, arg1, UPVAL0, UPVAL0, 0, 3.5) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, UPVAL0, 0, -1) return true elseif local6 == 2 then Approach_Act(arg0, arg1, UPVAL1, UPVAL1, 0, 3.5) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3009, TARGET_ENE_0, UPVAL1, 0, -1) return true else return false end end end end return
local function OnPlayerJoin(player) player.diedEvent:Connect(function (player) Task.Wait(2.5) if Object.IsValid(player) then player:Respawn() end end) end Game.playerJoinedEvent:Connect(OnPlayerJoin)
kHallucinationHoverHeight = 1 if Server then function Hallucination:GetHoverHeight() if self.assignedTechId == kTechId.Lerk or self.assignedTechId == kTechId.Drifter then return kHallucinationHoverHeight else return 0 end end end
-- Copyright (c) 2020-2021 shadmansaleh -- MIT license, see LICENSE for more details. local M = require('lualine.component'):extend() function M:update_status() local component = self.options[1] local ok, status if self.options.type == nil then ok, status = pcall(M.lua_eval, component) if not ok then status = M.vim_function(component) end else if self.options.type == 'lua_expr' then ok, status = pcall(M.lua_eval, component) if not ok then status = nil end elseif self.options.type == 'vim_fun' then status = M.vim_function(component) end end return status end function M.lua_eval(code) local result = loadstring('return ' .. code)() assert(result, 'String expected got nil') return tostring(result) end function M.vim_function(name) -- vim function component local ok, return_val = pcall(vim.api.nvim_call_function, name, {}) if not ok then return '' end -- function call failed ok, return_val = pcall(tostring, return_val) return ok and return_val or '' end return M
local discordia = require('discordia') local client = discordia.Client() client:on('ready', function() print('Logged in as '.. client.user.tag) end) client:on('messageCreate', function(message) if message.content == 'hello world' then message.channel:send('Hello, World! Discordia') end end) client:run('TOKEN')
-- An applications menu -- Required depends: awesome-freedesktop or xdg_menu -- awesome-freedesktop : automatic -- xdg_menu : manual -- Your choice local awful = require("awful") local gears = require("gears") local beautiful = require("beautiful") local apps = require('configuration.apps') local hotkeys_popup = require('awful.hotkeys_popup').widget terminal = apps.default.terminal editor = os.getenv("EDITOR") or "nano" editor_cmd = terminal .. " -e " .. editor -- Theming Menu beautiful.menu_font = "SFNS Display Regular 10" beautiful.menu_submenu = '' -- ➤ -- icon theme is in `awesome/theme/default-theme.lua` -- Search for `theme.icon_theme` -- Check first if freedesktop module is installed -- `awesome-freedesktop-git` is in AUR -- https://github.com/lcpz/awesome-freedesktop -- Check on your distro's repo -- Checks if module exists, also checks syntax. Returns false if syntax error local function isModuleAvailable(name) if package.loaded[name] then return true else for _, searcher in ipairs(package.searchers or package.loaders) do local loader = searcher(name) if type(loader) == 'function' then package.preload[name] = loader return true end end return false end end -- Create a launcher widget and a main menu myawesomemenu = { { "Hotkeys", function() hotkeys_popup.show_help(nil, awful.screen.focused()) end }, { "Edit config", editor_cmd .. " " .. awesome.conffile }, { "Restart", awesome.restart }, { "Quit", function() awesome.quit() end }, } -- Screenshot menu local screenshot = { {"Full", apps.bins.fullShot }, {"Area", apps.bins.areaShot }, {"Select", apps.bins.selectShot } } -- Terminal menu local terminal = { {"kitty", "kitty"}, {"xterm", "xterm"}, } -- Generate a list of app if isModuleAvailable("freedesktop") == true then -- A menu generated by awesome-freedesktop -- https://github.com/lcpz/awesome-freedesktop local freedesktop = require("freedesktop") local menubar = require("menubar") mymainmenu = freedesktop.menu.build({ icon_size = 16, before = { { "Terminal", terminal, menubar.utils.lookup_icon("utilities-terminal") }, -- other triads can be put here }, after = { {"Awesome", myawesomemenu--[[, "/usr/share/awesome/icons/awesome32.png"--]]}, {"Take a Screenshot", screenshot}, {"End Session", function() _G.exit_screen_show() end}, -- other triads can be put here } }) mylauncher = awful.widget.launcher({ image = beautiful.awesome_icon, menu = mymainmenu }) -- Menubar configuration else -- A menu generated by xdg_menu -- Replace with the list generated by xdg_menu local a = { } local b = { } local c = { } local d = { } local e = { } local f = { } local g = { {"show_script", "notify-send 'Script:' 'xdg_menu --format awesome --root-menu /etc/xdg/menus/arch-applications.menu >~/.config/awesome/archmenu.lua'"} } mymainmenu = awful.menu({ items = { {"Terminal", terminal}, -- Replace the alphabets with the list generated by xdg_menu {"Replace", a}, {"With", b}, {"the", c}, {"Apps", d}, {"Generated", e}, {"by", f}, {"xdg_menu", g}, {"Awesome", myawesomemenu}, {"Take a Screenshot", screenshot}, {"End Session", function() _G.exit_screen_show() end}, } }) mylauncher = awful.widget.launcher({ image = beautiful.awesome_icon, menu = mymainmenu }) end -- Embed mouse bindings root.buttons(gears.table.join(awful.button({ }, 3, function () mymainmenu:toggle() end)))
#!/usr/bin/env tarantool package.path = "../?/init.lua;./?/init.lua;" .. package.path local tap = require 'tap' local tnt = require 'tests.tnt' local stat = require 'stat' local function fixture_info_memory() local backup return { f_start = function() backup = box.info.memory box.info.memory = function() return { cache = 0, data = 14064, tx = 0, lua = 1771334, net = 98304, index = 1196032 } end end, f_end = function() box.info = backup end } end local function test_cfg(test) test:plan(4) local s = stat.stat() test:isstring(s['cfg.listen'], 'check cfg.listen') test:ok(tonumber(s['cfg.current_time']) ~= nil, 'check cfg.current_time') test:isstring(s['cfg.hostname'], 'check cfg.hostname') test:isboolean(s['cfg.read_only'], 'check cfg.read_only') end local function test_info(test) test:plan(4) local s = stat.stat() test:isnumber(s['info.pid'], 'check info.pid') test:isstring(s['info.uuid'], 'check info.uuid') test:isnumber(s['info.lsn'], 'check info.lsn') test:isnumber(s['info.uptime'], 'check info.uptime') end local function test_slab(test) test:plan(9) local s = stat.stat() test:isnumber(s['slab.items_size'], 'check slab.items_size') test:isnumber(s['slab.items_used'], 'check slab.items_used') test:isnumber(s['slab.items_used_ratio'], 'check slab.items_used_ratio') test:isnumber(s['slab.quota_size'], 'check slab.quota_size') test:isnumber(s['slab.quota_used'], 'check slab.quota_used') test:isnumber(s['slab.quota_used_ratio'], 'check slab.quota_used_ratio') test:isnumber(s['slab.arena_size'], 'check slab.arena_size') test:isnumber(s['slab.arena_used'], 'check slab.arena_used') test:isnumber(s['slab.arena_used_ratio'], 'check slab.arena_used_ratio') end local function test_runtime(test) test:plan(3) local s = stat.stat() test:isnumber(s['runtime.lua'], 'check runtime.lua') test:isnumber(s['runtime.used'], 'check runtime.used') test:isnil(s['runtime.maxalloc'], 'check that runtime.maxalloc is nil') end local function test_stat(test) test:plan(20) local ops = { 'delete', 'select', 'insert', 'eval', 'call', 'replace', 'upsert', 'auth', 'error', 'update' } local s = stat.stat() local function _check(op) test:isnumber(s['stat.op.' .. op .. '.total'], 'check stat.op.' .. op .. 'total') test:isnumber(s['stat.op.' .. op .. '.rps'], 'check stat.op.' .. op .. 'rps') end for _, op in ipairs(ops) do _check(op) end end local function test_stat_net(test) test:plan(4) local s = stat.stat() test:isnumber(s['stat.net.sent.total'], 'check stat.net.sent.total') test:isnumber(s['stat.net.sent.rps'], 'check stat.net.sent.rps') test:isnumber(s['stat.net.received.total'], 'check stat.net.received.total') test:isnumber(s['stat.net.received.rps'], 'check stat.net.received.rps') end local function test_space(test) test:plan(5) local sp = box.schema.space.create('test', {}) sp:create_index('primary', { unique = true, parts = { 1, 'unsigned', } }) local s = stat.stat() test:isnumber(s['space.test.len'], 'check space.test.len') test:isnumber(tonumber(s['space.test.bsize']), 'check space.test.bsize') test:isnumber(tonumber(s['space.test.index_bsize']), 'check space.test.index_bsize') test:isnumber(tonumber(s['space.test.total_bsize']), 'check space.test.total_bsize') test:isnumber(tonumber(s['space.test.index.primary.bsize']), 'check space.test.index.primary.bsize') end local function test_fiber(test) test:plan(4) local s = stat.stat() test:isnumber(s['fiber.count'], 'check fiber.count') test:isnumber(s['fiber.csw'], 'check fiber.csw') test:isnumber(s['fiber.memalloc'], 'check fiber.memalloc') test:isnumber(s['fiber.memused'], 'check fiber.memused') end local function test_memory(test) test:plan(6) local info_memory = fixture_info_memory() info_memory.f_start() local s = stat.stat() test:isnumber(s['info.memory.cache'], 'check info.memory.cache') test:isnumber(s['info.memory.data'], 'check info.memory.data') test:isnumber(s['info.memory.tx'], 'check info.memory.tx') test:isnumber(s['info.memory.lua'], 'check info.memory.lua') test:isnumber(s['info.memory.net'], 'check info.memory.net') test:isnumber(s['info.memory.index'], 'check info.memory.index') info_memory.f_end() end local function test_only_numbers(test) test:plan(5) local s = stat.stat({ only_numbers = true }) test:ok(tonumber(s['cfg.current_time']) ~= nil, 'check cfg.current_time') test:isnil(s['cfg.listen'], 'check that cfg.listen is nil') test:isnil(s['cfg.hostname'], 'check that cfg.hostname is nil') test:isnil(s['cfg.read_only'], 'check that cfg.read_only is nil') test:isnil(s['info.uuid'], 'check that info.uuid is nil') end local function main() local test = tap.test() test:plan(10) tnt.cfg { listen = 33301 } test:test('test_cfg', test_cfg) test:test('test_info', test_info) test:test('test_slab', test_slab) test:test('test_runtime', test_runtime) test:test('test_stat', test_stat) test:test('test_stat_net', test_stat_net) test:test('test_space', test_space) test:test('test_fiber', test_fiber) test:test('test_only_numbers', test_only_numbers) test:test('test_memory', test_memory) tnt.finish() os.exit(test:check() == true and 0 or -1) end main()
local stock_tags = { -- bipd -- "characters\\cyborg_mp\\cyborg_mp", -- !jpt "characters\\cyborg\\melee", "weapons\\assault rifle\\melee", "weapons\\assault rifle\\melee_response", "weapons\\assault rifle\\bullet", "weapons\\assault rifle\\trigger", "weapons\\pistol\\melee", "weapons\\pistol\\melee_response", "weapons\\pistol\\bullet", "weapons\\pistol\\trigger", "vehicles\\warthog\\bullet", "vehicles\\warthog\\trigger", "vehicles\\scorpion\\shell explosion", "weapons\\frag grenade\\shock wave", "vehicles\\scorpion\\shell shock wave", "vehicles\\scorpion\\bullet", "vehicles\\scorpion\\secondary trigger", "vehicles\\ghost\\ghost bolt", "vehicles\\ghost\\trigger", "weapons\\rocket launcher\\explosion", "vehicles\\rwarthog\\effects\\trigger", "vehicles\\banshee\\banshee bolt", "vehicles\\banshee\\trigger", "vehicles\\banshee\\mp_fuel rod explosion", "vehicles\\banshee\\fuel rod trigger", "weapons\\shotgun\\melee", "weapons\\shotgun\\melee_response", "weapons\\shotgun\\pellet", "weapons\\shotgun\\trigger", "weapons\\plasma rifle\\melee", "weapons\\plasma rifle\\melee_response", "weapons\\plasma rifle\\bolt", "weapons\\plasma rifle\\trigger", "weapons\\plasma rifle\\misfire", "weapons\\frag grenade\\explosion", "weapons\\rocket launcher\\melee", "weapons\\rocket launcher\\melee_response", "weapons\\rocket launcher\\trigger", "weapons\\sniper rifle\\melee", "weapons\\sniper rifle\\melee_response", "weapons\\sniper rifle\\sniper bullet", "weapons\\sniper rifle\\trigger", "weapons\\plasma grenade\\shock wave", "weapons\\plasma grenade\\explosion", "weapons\\flamethrower\\melee", "weapons\\flamethrower\\melee_response", "weapons\\flamethrower\\explosion", "weapons\\flamethrower\\impact damage", "weapons\\flamethrower\\burning", "weapons\\flamethrower\\trigger", "weapons\\plasma_cannon\\effects\\plasma_cannon_melee", "weapons\\plasma_cannon\\effects\\plasma_cannon_melee_response", "weapons\\plasma_cannon\\effects\\plasma_cannon_explosion", "weapons\\plasma_cannon\\impact damage", "weapons\\plasma_cannon\\effects\\plasma_cannon_trigger", "weapons\\plasma_cannon\\effects\\plasma_cannon_misfire", "weapons\\plasma pistol\\melee", "weapons\\plasma pistol\\melee_response", "weapons\\plasma pistol\\bolt", "weapons\\plasma pistol\\trigger", "weapons\\plasma pistol\\misfire", "weapons\\plasma rifle\\charged bolt", "weapons\\plasma pistol\\trigger overcharge", "weapons\\plasma grenade\\attached", "weapons\\needler\\melee", "weapons\\needler\\melee_response", "weapons\\needler\\shock wave", "weapons\\needler\\explosion", "weapons\\needler\\detonation damage", "weapons\\needler\\impact damage", "weapons\\needler\\trigger", "weapons\\ball\\melee", "weapons\\ball\\melee_response", "weapons\\flag\\melee", "weapons\\flag\\melee_response", "vehicles\\c gun turret\\mp bolt", "globals\\falling", "globals\\distance", "globals\\vehicle_hit_environment", "globals\\vehicle_killed_unit", "globals\\vehicle_collision", "globals\\flaming_death", -- equipment -- "powerups\\active camouflage", "powerups\\health pack", "powerups\\over shield", "powerups\\double speed", "powerups\\full-spectrum vision", "weapons\\frag grenade\\frag grenade", "weapons\\plasma grenade\\plasma grenade", "powerups\\assault rifle ammo\\assault rifle ammo", "powerups\\needler ammo\\needler ammo", "powerups\\pistol ammo\\pistol ammo", "powerups\\rocket launcher ammo\\rocket launcher ammo", "powerups\\shotgun ammo\\shotgun ammo", "powerups\\sniper rifle ammo\\sniper rifle ammo", "powerups\\flamethrower ammo\\flamethrower ammo", -- vehicles -- "vehicles\\warthog\\mp_warthog", "vehicles\\ghost\\ghost_mp", "vehicles\\rwarthog\\rwarthog", "vehicles\\banshee\\banshee_mp", "vehicles\\scorpion\\scorpion_mp", "vehicles\\c gun turret\\c gun turret_mp", -- weapons -- "weapons\\assault rifle\\assault rifle", "weapons\\ball\\ball", "weapons\\flag\\flag", "weapons\\flamethrower\\flamethrower", "weapons\\gravity rifle\\gravity rifle", "weapons\\needler\\mp_needler", "weapons\\pistol\\pistol", "weapons\\plasma pistol\\plasma pistol", "weapons\\plasma rifle\\plasma rifle", "weapons\\plasma_cannon\\plasma_cannon", "weapons\\rocket launcher\\rocket launcher", "weapons\\shotgun\\shotgun", "weapons\\sniper rifle\\sniper rifle", "weapons\\energy sword\\energy sword", } api_version = "1.12.0.0" function OnScriptLoad() register_callback(cb["EVENT_GAME_START"], "OnGameStart") end function IsStock(TAG) for i = 1, #stock_tags do if (TAG == stock_tags[i]) then return true end end return false end function OnGameStart() local tag_address = read_dword(0x40440000) local tag_count = read_dword(0x4044000C) cprint("!jpt", 10) for i = 0, tag_count - 1 do local tag = tag_address + 0x20 * i local tag_name = read_string(read_dword(tag + 0x10)) local tag_class = read_dword(tag) if (tag_class == 1785754657) then cprint('{"' .. tag_name:gsub("\\", "\\\\") .. '"},') end end cprint(" ") cprint("eqip", 10) for i = 0, tag_count - 1 do local tag = tag_address + 0x20 * i local tag_name = read_string(read_dword(tag + 0x10)) local tag_class = read_dword(tag) if (tag_class == 1701931376 and not IsStock(tag_name)) then cprint('{"' .. tag_name:gsub("\\", "\\\\") .. '"},') end end cprint(" ") cprint("vehicles", 10) for i = 0, tag_count - 1 do local tag = tag_address + 0x20 * i local tag_name = read_string(read_dword(tag + 0x10)) local tag_class = read_dword(tag) if (tag_class == 1986357353 and not IsStock(tag_name)) then cprint('{"' .. tag_name:gsub("\\", "\\\\") .. '"},') end end cprint(" ") cprint("weap", 10) for i = 0, tag_count - 1 do local tag = tag_address + 0x20 * i local tag_name = read_string(read_dword(tag + 0x10)) local tag_class = read_dword(tag) if (tag_class == 2003132784 and not IsStock(tag_name)) then cprint('{"' .. tag_name:gsub("\\", "\\\\") .. '"},') end end cprint(" ") cprint("proj", 10) for i = 0, tag_count - 1 do local tag = tag_address + 0x20 * i local tag_name = read_string(read_dword(tag + 0x10)) local tag_class = read_dword(tag) if (tag_class == 1886547818 and not IsStock(tag_name)) then cprint('{"' .. tag_name:gsub("\\", "\\\\") .. '"},') end end end function OnScriptUnload() -- N/A end
local require = using("EffectEditor.Script") local CCSprite = require("CCSprite") local oLine = require("oLine") local oVec2 = require("oVec2") local ccColor4 = require("ccColor4") local CCSize = require("CCSize") local CCDirector = require("CCDirector") local oSelectionPanel = require("oSelectionPanel") local CCDrawNode = require("CCDrawNode") local CCSequence = require("CCSequence") local CCDelay = require("CCDelay") local oPos = require("oPos") local oEase = require("oEase") local CCHide = require("CCHide") local function oClipViewer(file,rect) local width = 130 local sprite = CCSprite(file) sprite.textureRect = rect local contentSize = sprite.contentSize if contentSize.width > width or contentSize.height > width then local scale = contentSize.width > contentSize.height and (width-2)/contentSize.width or (width-2)/contentSize.height sprite.scaleX = scale sprite.scaleY = scale end local frame = oLine( { oVec2.zero, oVec2(width,0), oVec2(width,width), oVec2(0,width), oVec2.zero, },ccColor4(0xff00ffff)) frame.cascadeColor = false frame.contentSize = CCSize(width,width) frame.anchor = oVec2.zero sprite.position = oVec2(width*0.5,width*0.5) frame:addChild(sprite) return frame end local function oFrameViewer() local oEditor = require("oEditor") local winSize = CCDirector.winSize local halfW = winSize.width*0.5 local halfH = winSize.height*0.5 local borderW = halfW*2 - 240 - 30 local borderH = 150 local borderSize = CCSize(borderW,borderH) local panel = oSelectionPanel(borderSize,false,true,true) panel.touchPriority = oEditor.touchPrioritySettingPanel local menu = panel.menu menu.touchPriority = oEditor.touchPrioritySettingPanel+1 local border = panel.border local halfBW = borderSize.width*0.5 local halfBH = borderSize.height*0.5 local endPos = oVec2(10-halfW+borderW*0.5,10-halfH+borderH*0.5) local startPos = oVec2(endPos.x,endPos.y-borderH-10) local background = CCDrawNode() background:drawPolygon( { oVec2(-halfBW,-halfBH), oVec2(halfBW,-halfBH), oVec2(halfBW,halfBH), oVec2(-halfBW,halfBH) },ccColor4(0x88100000),0.5,ccColor4(0xffffafaf)) border:addChild(background,-1) panel.position = startPos panel.visible = false panel:gslot("Effect.editor.particle",function() if panel.visible then panel:perform(CCSequence({CCDelay(0.3),oPos(0.5,startPos.x,startPos.y,oEase.InBack),CCHide()})) end end) panel:gslot("Effect.editor.frame",function() panel.visible = true panel.position = startPos panel:perform(oPos(0.5,endPos.x,endPos.y,oEase.OutBack)) end) panel:gslot("Effect.frameViewer.data",function(data) menu:removeAllChildrenWithCleanup() local width = 0 local currentFile = oEditor.currentFile local file = currentFile:match("[^\\/]*$") local prefix = (#file == #currentFile and "" or currentFile:sub(1,-1-#file)) if data.file:sub(1,#prefix) == prefix then prefix = "" end local imageFile = oEditor.prefix..prefix..data.file for i,item in ipairs(data) do width = 10+140*(i-1) local clip = oClipViewer(imageFile,item.rect) clip.position = oVec2(width,10) menu:addChild(clip) end width = width + 140 panel:reset(width,borderSize.height,50,0) end) panel:gslot("Effect.viewArea.changeEffect",function(effectName) if not effectName then menu:removeAllChildrenWithCleanup() end end) local isHide = false panel:gslot("Effect.hideEditor",function(args) local hide,instant = unpack(args) if not hide and oEditor.type ~= "Frame" then return end if isHide == hide then return end isHide = hide if instant then panel.position = hide and startPos or endPos else local pos = hide and startPos or endPos panel:perform(oPos(0.5,pos.x,pos.y,oEase.OutQuad)) end end) return panel end return oFrameViewer
VERSION = "1.0.0" local micro = import("micro") micro.Log("ccc - init 2021...") micro.InfoBar():Message("-- 0dn plugin activated.") function onBufferOpen(b) micro.Log(b.Line(1) .. ": open " .. b.FileName or "<>") end
return { -- Table: {1} { ["CH_DETECTED"]="[color=green][b]Autofill date[/b] detect conect to channel id %s try fill current date and time[/color]", ["HELP"]="\r\ [color=green][b][url=http://teamspeak.az.pl/wiki/Plugin:AutofillDate]Autofill Date [/url][/b] help command\r\ To get this plugin work you must connect to specific channel witch bookmarks and Your Deflaut Channel.\r\ If you skip connect to a specific channel plugin will not work.\r\ To turn off plugin just disable it on CRTL+SHIFT+P (lua plugins settings) list\r\ [/color]", ["PERMISSION_ERROR"]="[color=red]AutoFill detect insufficient client permissions[/color] You don`t have b_channel_modify_topic. ", ["MODULE_NAME"]="AutofillDate", ["CLIENT_DEFAULT_CHANNEL_ERROR"]="AFD.ERROR ID: (%s) WHILE REQUEST DEFAULT CHANNEL: %s", ["CHANNEL_TOPIC_ERROR"]="AFD.ERROR ID: (%s) WHILE SET CHANNEL TOPIC: %s", ["CHANNEL_FLUSH_ERROR"]="AFD.ERROR ID: (%s) WHILE FLUSH CHANNEL UPDATE: %s", ["WELCOME_MSG"]="[color=red]AutofillDate initiated[/color] [url=http://teamspeak.az.pl/wiki/Plugin:AutofillDate]Oficcial Plugin Page[/url]", ["CH_NOT_DETECT"]="[color=green][b]Autofill date[/b] not detect conection to specific channel, skipping filling date[/color]", ["DATE_FORMAT"]="%d.%m.%Y %H:%M", }, }
-- Update member privileges from LDAP -- -------------------------------------------------------------------------- -- -- arguments: -- member: the member for which the privileges should be updated -- ldap_entry: the ldap entry to be used for updating the privileges -- -- returns: -- err: an error code, if an error occured (string) -- err2: Error dependent extra error information function ldap.update_member_privileges(member, ldap_entry) local privileges, err = config.ldap.member.privilege_map(ldap_entry, member) if err then return false, "privilege_map_error", err end local privileges_by_unit_id = {} for i, privilege in ipairs(privileges) do privileges_by_unit_id[privilege.unit_id] = privilege end local current_privileges = Privilege:by_member_id(member.id) local current_privilege_ids = {} for i, privilege in ipairs(current_privileges) do if privileges_by_unit_id[privilege.unit_id] then current_privilege_ids[privilege.unit_id] = privilege else privilege:destroy() end end for i, privilege in ipairs(privileges) do local current_privilege = current_privilege_ids[privilege.unit_id] if not current_privilege then current_privilege = Privilege:new() current_privilege.member_id = member.id current_privileges[#current_privileges+1] = current_privilege end for key, val in pairs(privilege) do current_privilege[key] = val end end for i, privilege in ipairs(current_privileges) do local err = privilege:try_save() if err then return false, "privilege_save_error", err end end return true end
local S = ethereal.intllib -- Seaweed minetest.register_node("ethereal:seaweed", { description = S("Seaweed"), drawtype = "plantlike", tiles = {"seaweed.png"}, inventory_image = "seaweed.png", wield_image = "seaweed.png", paramtype = "light", walkable = false, climbable = true, drowning = 1, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.5, 0.3} }, post_effect_color = {a = 64, r = 100, g = 100, b = 200}, groups = {food_seaweed = 1, snappy = 3, flammable = 3}, on_use = minetest.item_eat(1), sounds = default.node_sound_leaves_defaults(), after_dig_node = function(pos, node, metadata, digger) default.dig_up(pos, node, digger) end, }) minetest.register_craft( { type = "shapeless", output = "dye:dark_green 3", recipe = {"ethereal:seaweed",}, }) -- agar powder minetest.register_craftitem("ethereal:agar_powder", { description = S("Agar Powder"), inventory_image = "ethereal_agar_powder.png", groups = {food_gelatin = 1, flammable = 2}, }) minetest.register_craft({ output = "ethereal:agar_powder 3", recipe = { {"group:food_seaweed", "group:food_seaweed", "group:food_seaweed"}, {"bucket:bucket_water", "bucket:bucket_water", "default:torch"}, {"bucket:bucket_water", "bucket:bucket_water", "default:torch"}, }, replacements = { {"bucket:bucket_water", "bucket:bucket_empty 4"}, }, }) -- Blue Coral minetest.register_node("ethereal:coral2", { description = S("Blue Coral"), drawtype = "plantlike", tiles = {"coral2.png"}, inventory_image = "coral2.png", wield_image = "coral2.png", paramtype = "light", selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, 1 / 4, 6 / 16}, }, light_source = 3, groups = {snappy = 3}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_craft( { type = "shapeless", output = "dye:cyan 3", recipe = {"ethereal:coral2",}, }) -- Orange Coral minetest.register_node("ethereal:coral3", { description = S("Orange Coral"), drawtype = "plantlike", tiles = {"coral3.png"}, inventory_image = "coral3.png", wield_image = "coral3.png", paramtype = "light", selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, 1 / 4, 6 / 16}, }, light_source = 3, groups = {snappy = 3}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_craft( { type = "shapeless", output = "dye:orange 3", recipe = {"ethereal:coral3",}, }) -- Pink Coral minetest.register_node("ethereal:coral4", { description = S("Pink Coral"), drawtype = "plantlike", tiles = {"coral4.png"}, inventory_image = "coral4.png", wield_image = "coral4.png", paramtype = "light", selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, 8 / 16, 6 / 16}, }, light_source = 3, groups = {snappy = 3}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_craft( { type = "shapeless", output = "dye:pink 3", recipe = {"ethereal:coral4",}, }) -- Green Coral minetest.register_node("ethereal:coral5", { description = S("Green Coral"), drawtype = "plantlike", tiles = {"coral5.png"}, inventory_image = "coral5.png", wield_image = "coral5.png", paramtype = "light", selection_box = { type = "fixed", fixed = {-6 / 16, -0.5, -6 / 16, 6 / 16, 3 / 16, 6 / 16}, }, light_source = 3, groups = {snappy = 3}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_craft( { type = "shapeless", output = "dye:green 3", recipe = {"ethereal:coral5",}, }) -- Undersea Sand minetest.register_node("ethereal:sandy", { description = S("Sandy"), tiles = {"default_sand.png"}, is_ground_content = true, groups = { crumbly = 3, falling_node = 1, sand = 1, not_in_creative_inventory = 1 }, drop = "default:sand", sounds = default.node_sound_sand_defaults(), }) -- randomly generate coral or seaweed and have seaweed grow up to 14 high if ethereal.sealife == 1 then minetest.register_abm({ label = "Grow coral/seaweed", nodenames = {"ethereal:sandy"}, neighbors = {"group:water"}, interval = 15, chance = 10, catch_up = false, action = function(pos, node) local sel = math.random(1, 5) pos.y = pos.y + 1 local nod = minetest.get_node(pos).name if nod == "default:water_source" and sel > 1 then if minetest.get_node(pos).name == "default:water_source" then minetest.swap_node(pos, {name = "ethereal:coral" .. sel}) end return end if nod == "ethereal:seaweed" or sel == 1 then local height = 0 local high = 14 while height < high and minetest.get_node(pos).name == "ethereal:seaweed" do height = height + 1 pos.y = pos.y + 1 end if pos.y < 1 and height < high and minetest.get_node(pos).name == "default:water_source" then minetest.swap_node(pos, {name = "ethereal:seaweed"}) end end end, }) end
local rootElement = getRootElement() local busses = {[431] = true, [437] = true} local busRoutes = {} local started = {} busRoutes["Los Santos"] = { -- { x, y, z, isStop, stop number} [1]={1825.5222,-1819.0747,13.4037,true,1}, [2]={1847.2609,-1754.3463,13.3751,false,0}, [3]={1922.6714,-1755.9180,13.3752,true,2}, [4]={2144.0254,-1754.4574,13.3857,false,0}, [5]={2220.9336,-1712.7439,13.3701,false,0}, [6]={2291.5940,-1662.8654,14.7959,true,3}, [7]={2340.1425,-1689.7734,13.3593,false,0}, [8]={2398.7548,-1735.1572,13.3828,false,0}, [9]={2481.8867,-1735.1953,13.3828,true,4}, [10]={2622.7998,-1734.9023,11.3093,false,0}, [11]={2685.3623,-1660.2822,11.3453,false,0}, [12]={2740.8818,-1552.9648,24.0011,false,0}, [13]={2740.9121,-1436.5507,30.2812,true, 5}, [14]={2735.4316,-1335.8515,47.3734,false,0}, [15]={2621.0566,-1253.6796,48.9659,false,0}, [16]={2424.6201,-1252.7261,23.6982,true,6}, [17]={2374.0664,-1225.7890,27.1437,false,0}, [18]={2339.6667,-1151.8619,26.9376,false,0}, [19]={2154.5393,-1113.0920,25.3323,true,7}, [20]={2065.9500,-1155.1235,23.6985,false,0}, [21]={2065.6633,-1254.4645,23.8122,false,0}, [22]={1997.7284,-1257.4001,23.8125,true,8}, [23]={1846.0527,-1279.8642,12.9596,false,0}, [24]={1821.1875,-1574.8125,13.3536,true,9}, [25]={1766.5739,-1602.9021,13.3683,false,0}, [26]={1491.5818,-1588.4076,13.3745,true,10}, [27]={1360.0137,-1578.5935,13.3768,false,0}, [28]={1351.8754,-1474.9437,13.3749,false,0}, [29]={1361.4806,-1288.0685,13.3491,true,11}, [30]={1364.6495,-1094.6451,24.1111,false,0}, [31]={1333.6823,-924.2286,36.0750,false,0}, [32]={1112.4703,-942.3127,42.6810,true,12}, [33]={1047.8228,-1036.9039,31.8199,false,0}, [34]={959.0685,-1119.5323,23.6708,true,13}, [35]={873.3333,-1139.9399,23.7442,false,0}, [36]={759.7260,-1049.3702,23.8522,false,0}, [37]={573.0375,-1221.7246,17.5006,true,14}, [38]={430.7755,-1324.5621,14.8815,false,0}, [39]={198.4696,-1476.8871,12.7383,false,0}, [40]={110.9657,-1638.4880,10.0730,false,0}, [41]={167.6030,-1740.0616,4.4372,true,15}, [42]={317.3379,-1741.2506,4.3995,false,0}, [43]={419.5071,-1774.9253,5.2732,false,0}, [44]={530.0619,-1733.6987,12.1128,false,0}, [45]={787.5512,-1785.6987,13.1211,false,0}, [46]={813.1080,-1717.0001,13.3753,false,0}, [47]={854.2473,-1602.5085,13.3834,true,16}, [48]={920.4056,-1507.9554,13.3641,false,0}, [49]={959.7448,-1408.3657,13.1925,false,0}, [50]={1165.9882,-1409.5631,13.3811,true,17}, [51]={1290.8201,-1408.6349,13.0440,false,0}, [52]={1297.5280,-1540.7646,13.2577,false,0}, [53]={1293.6631,-1814.7549,13.2578,true,18}, [54]={1352.7914,-1867.4207,13.2579,false,0}, [55]={1391.5159,-1755.3124,13.2578,false,0}, [56]={1459.4001,-1736.0459,13.3752,true,19}, [57]={1667.8722,-1735.0980,13.3747,false,0}, [58]={1767.8871,-1829.3638,13.2578,true,20}, } busRoutes["San Fierro"] = { -- { x, y, z, isStop, stop number} [1]={-2004.5703125,-53.552734375,34.298252105713,false}, [2]={-2148.7099609375,-67.7998046875,34.30525970459,true}, [3]={-2351.9873046875,-68.44140625,34.297409057617,false}, [4]={-2274.587890625,47.4296875,34.29740524292,true}, [5]={-2248.7548828125,174.4375,34.305137634277,false}, [6]={-2224.361328125,489.9091796875,34.148761749268,true}, [7]={-2024.376953125,501.5791015625,34.147701263428,true}, [8]={-1896.7646484375,622.1181640625,34.145721435547,false}, [9]={-1895.0107421875,815.767578125,34.606506347656,true}, [10]={-1814.103515625,914.4287109375,23.928504943848,false}, [11]={-1789.6689453125,1083.7099609375,44.188053131104,true}, [12]={-1880.125,1155.15625,44.430370330811,false}, [13]={-2046.7041015625,1182.302734375,44.430198669434,true}, [14]={-2236.517578125,1181.255859375,54.711437225342,false}, [15]={-2270.861328125,880.955078125,65.631683349609,true}, [16]={-2270.185546875,686.83984375,48.430233001709,false}, [17]={-2269.6669921875,588.8408203125,36.482364654541,true}, [18]={-2507.59375,569.5859375,13.610645294189,false}, [19]={-2588.3076171875,470.2373046875,13.593816757202,true} , [20]={-2608.41796875,344.0419921875,3.3191819190979,false}, [21]={-2708.0908203125,303.75,3.3126063346863,true}, [22]={-2707.470703125,98.7509765625,3.3089895248413,false}, [23]={-2708.1435546875,-192.6484375,3.3130583763123,true}, [24]={-2419.296875,-87.4541015625,34.306995391846,false}, [25]={-2277.71875,-72.5234375,34.297630310059,true}, [26]={-2164.3369140625,15.0380859375,34.304836273193,true}, [27]={-2027.4130859375,26.73046875,33.169208526611,false}, [28]={-1990.47265625,148.20703125,26.672004699707,true}, } --[[ local locations = {} addCommandHandler("addloc", function (player, cmd, stop) local index = #locations +1 local x, y, z = getElementPosition(player) locations[index] = {x, y, z-1, stop} end) addCommandHandler("getlocs", function (player) for index, location in pairs(locations) do local position = tostring(location[1])..","..tostring(location[2])..","..tostring(location[3])..","..tostring(location[4]) outputChatBox("["..tostring(index).."]={"..position.."},",player) end end)]] function setNewBusLocation(thePlayer, city, ID) if busRoutes[city] and busRoutes[city][ID] then local x, y, z = unpack(busRoutes[city][ID]) triggerClientEvent(thePlayer,"bus_set_location",thePlayer,x,y,z) end end local timer = {} setTimer( function() for _, thePlayer in pairs(getElementsByType("player")) do if timer[thePlayer] == true then timer[thePlayer] = false end end end, 300000, 0) addCommandHandler("mrota", function (thePlayer) if not isPedInVehicle(thePlayer) then return end if timer[thePlayer] then outputChatBox ( "#d9534f[M:ÔNIBUS] #FFFFFFAguarde 5 minutos para iniciar uma nova rota.", thePlayer, 255, 255, 255, true ) return end if started[thePlayer] then outputChatBox ( "#d9534f[M:ÔNIBUS] #FFFFFFSua rota já foi iniciada, finalize-a.", thePlayer, 255, 255, 255, true ) return end if not busses[getElementModel(getPedOccupiedVehicle(thePlayer))] then return end local job = tostring ( getElementData ( thePlayer, "Job" ) or "" ) if ( job == "Motorista" ) then local city = getElementZoneName(thePlayer, true) setElementData(thePlayer,"busData",1) setNewBusLocation(thePlayer, city, 1) started[thePlayer] = true timer[thePlayer] = true outputChatBox ( "#d9534f[M:ÔNIBUS] #FFFFFFSua rota começou, fique de olho no seu radar.", thePlayer, 255, 255, 255, true ) end end) addEventHandler("onVehicleEnter",root, function (thePlayer) if not busses[getElementModel(source)] then return end started[thePlayer] = false local job = tostring ( getElementData ( thePlayer, "Job" ) or "" ) if ( job == "Motorista" ) then outputChatBox ( "#d9534f[M:ÔNIBUS]#FFFFFF Use #ffa500/mrota#FFFFFF para iniciar uma rota.", thePlayer, 255, 255, 255, true ) end end) addEvent("bus_finish",true) addEventHandler("bus_finish",rootElement, function (client) if not isPedInVehicle(client) then return end if not busses[getElementModel(getPedOccupiedVehicle(client))] then return end local city = getElementZoneName(client, true) if busRoutes[city][tonumber(getElementData(client,"busData"))][4] then local reward = math.random(50, 250) if ( reward ) then triggerEvent ( "VDBGJobs->GivePlayerMoney", source, source, "paradasbus", reward, 1 ) triggerEvent ( "VDBGJobs->SQL->UpdateColumn", source, source, "paradasbus", "AddOne" ) end outputChatBox ( "#d9534f[M:ÔNIBUS]#FFFFFF Você fez uma parada, e ganhou: #acd373R$:"..reward..".00", source, 255, 255, 255, true ) end if #busRoutes[city] == tonumber(getElementData(client,"busData")) then outputChatBox ( "#d9534f[M:ÔNIBUS]#FFFFFF Você terminou sua rota, volte para a estação para bater o cartão.", thePlayer, 255, 255, 255, true ) started[thePlayer] = false else setElementData(client,"busData",tonumber(getElementData(client,"busData"))+1) setNewBusLocation(client, city, tonumber(getElementData(client,"busData"))) end end)
--[[ Copyright (C) 2019 Blue Mountains GmbH This program is free software: you can redistribute it and/or modify it under the terms of the Onset Open Source License as published by Blue Mountains GmbH. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Onset Open Source License for more details. You should have received a copy of the Onset Open Source License along with this program. If not, see https://bluemountains.io/Onset_OpenSourceSoftware_License.txt ]]-- function OnPlayerChat(player, message) if (PlayerData[player].mute ~= 0) then if (not CheckForUnmute(player)) then return AddPlayerChat(player, "You have been muted") end end if (GetTimeSeconds() - PlayerData[player].chat_cooldown < 0.8) then return AddPlayerChat(player, "Slow down chatting") end PlayerData[player].chat_cooldown = GetTimeSeconds() local c = string.sub(message, 1, 1) if (c == '#') then return AddAdminChat(GetPlayerName(player).."("..player.."): "..string.sub(message, 2)) end message = message:gsub("<span.->(.-)</>", "%1") -- removes chat span tag local fullchatmessage = '<span color="'..GetPlayerColorHEX(player)..'">'..GetPlayerName(player)..'('..player..'):</> '..message AddPlayerChatAll(fullchatmessage) -- Log full chat message local query = mariadb_prepare(sql, "INSERT INTO log_chat VALUES (?, UNIX_TIMESTAMP(), '?');", PlayerData[player].accountid, fullchatmessage) mariadb_async_query(sql, query) end AddEvent("OnPlayerChat", OnPlayerChat) function CheckForUnmute(player) if (GetTimeSeconds() > PlayerData[player].mute) then PlayerData[player].mute = 0 return true end return false end function OnPlayerChatCommand(player, cmd, exists) if (GetTimeSeconds() - PlayerData[player].cmd_cooldown < 0.5) then CancelChatCommand() return AddPlayerChat(player, "Slow down with your commands") end PlayerData[player].cmd_cooldown = GetTimeSeconds() if (exists == 0) then AddPlayerChat(player, "Command '/"..cmd.."' not found!") end end AddEvent("OnPlayerChatCommand", OnPlayerChatCommand)
--[[ LuCI - Lua Configuration Interface - Aria2 support Copyright 2016 maz-1 <[email protected]> ]]-- local sys = require "luci.sys" local util = require "luci.util" local uci = require "luci.model.uci".cursor() ptype = { "socks5", "socks4", "http", "socks4a", } whocan = { "anyone", "friends", "nobody", } function titlesplit(Value) return "<p style=\"font-size:20px;font-weight:bold;color: DodgerBlue\">" .. translate(Value) .. "</p>" end m = Map("amule", translate("aMule"), translate("aMule is a ED2K/KAD client for all platforms.") .. "<br/><a href=\"https://github.com/maz-1\">luci interface by maz-1</a>") m:section(SimpleSection).template = "amule/overview_status" s = m:section(TypedSection, "amule", translate("aMule Settings")) s.addremove = false s.anonymous = true s:tab("general", translate("General")) s:tab("connection", translate("Connections")) s:tab("server", translate("Server")) s:tab("path_and_file", translate("Path And File")) s:tab("security", translate("Security")) s:tab("remote", translate("External Control")) s:tab("template", translate("Edit Template")) s:tab("logview", translate("Log File Viewer")) s:tab("amulecmd", translate("aMule command")) -- GENERAL -- o = s:taboption("general", Flag, "enabled", translate("Enabled")) o.rmempty = false user = s:taboption("general", ListValue, "runasuser", translate("Run daemon as user")) local p_user for _, p_user in util.vspairs(util.split(sys.exec("cat /etc/passwd | cut -f 1 -d :"))) do user:value(p_user) end o = s:taboption("general", Value, "config_dir", translate("Configuration directory")) o.rmempty = false o.placeholder = "/var/run/amule" o = s:taboption("general", Value, "mem_percentage", translate("Memory Limit"), translate("Percentage")) o.rmempty = false o.placeholder = "50" o.datatype = "range(1, 99)" o = s:taboption("general", Value, "nick", translate("Nickname")) o.placeholder = "http://www.aMule.org" o = s:taboption("general", Value, "max_upload", translate("Max upload speed"), translate("Unlimited when set to 0")) o.datatype = "uinteger" o.rmempty = false o.placeholder = "0" o = s:taboption("general", Value, "max_download", translate("Max download speed"), translate("Unlimited when set to 0")) o.datatype = "uinteger" o.rmempty = false o.placeholder = "0" o = s:taboption("general", Value, "slot_allocation", translate("Slot allocation")) o.datatype = "uinteger" o.rmempty = false o.placeholder = "2" o = s:taboption("general", Value, "max_connections", translate("Max connections")) o.datatype = "uinteger" o.rmempty = false o.placeholder = "500" o = s:taboption("general", Value, "max_sources_per_file", translate("Max sources per file")) o.datatype = "uinteger" o.rmempty = false o.placeholder = "300" -- CONNECTIONS -- o = s:taboption("connection", Value, "port", translate("TCP port")) o.datatype = "port" o.rmempty = false o.placeholder = "4662" o = s:taboption("connection", Flag, "udp_enable", translate("Enable UDP port")) o.rmempty = false o = s:taboption("connection", Value, "udp_port", translate("UDP port")) o.datatype = "port" o.rmempty = false o.placeholder = "4672" o = s:taboption("connection", Flag, "upnp_enabled", translate("Enable UPnP")) o.rmempty = false o = s:taboption("connection", Value, "upnp_tcp_port", translate("UPnP TCP port")) o.datatype = "port" o.rmempty = false o.placeholder = "50000" o = s:taboption("connection", Value, "address", translate("Bind Address"), translate("Leave blank to bind all")) o.datatype = "ip4addr" o.rmempty = true o = s:taboption("connection", Flag, "auto_connect", translate("Automatically connect")) o.rmempty = false o = s:taboption("connection", Flag, "reconnect", translate("Automatically reconnect")) o.rmempty = false o = s:taboption("connection", Flag, "connect_to_kad", translate("Connect to Kad network")) o.rmempty = false o = s:taboption("connection", Flag, "connect_to_ed2k", translate("Connect to ED2K network")) o.rmempty = false s:taboption("connection", DummyValue,"titlesplit1" ,titlesplit(translate("Proxy Configuration"))) o = s:taboption("connection", Flag, "proxy_enable_proxy", translate("Enable proxy")) o.rmempty = false o = s:taboption("connection", ListValue, "proxy_type", translate("Proxy type")) for i,v in ipairs(ptype) do o:value(v) end o.rmempty = false o = s:taboption("connection", Value, "proxy_name", translate("Proxy name")) o.rmempty = true o = s:taboption("connection", Value, "proxy_port", translate("Proxy port")) o.datatype = "port" o.rmempty = true o = s:taboption("connection", Flag, "proxy_enable_password", translate("Proxy requires authentication")) o.rmempty = true o = s:taboption("connection", Value, "proxy_user", translate("Proxy user")) --o:depends("proxy_enable_password", "1") o.rmempty = true o = s:taboption("connection", Value, "proxy_password", translate("Proxy password")) o.password = true o.rmempty = true -- SERVER -- o = s:taboption("server", Value, "kad_nodes_url", translate("Kad Nodes Url"), "<input type=\"button\" size=\"0\" title=\"" .. translate("Download now") .. "\" onclick=\"onclick_down_kad(this.id)\" " .. "value=\"&#10597;&#10597;&#10597;\" " .. "style=\"font-weight:bold;text-decoration:overline;\"" .. "/>") o.rmempty = false o.placeholder = "http://upd.emule-security.org/nodes.dat" o = s:taboption("server", Value, "ed2k_servers_url", translate("Ed2k Servers List Url"), "<input type=\"button\" size=\"0\" title=\"" .. translate("Download now") .. "\" onclick=\"onclick_down_ed2k(this.id)\" " .. "value=\"&#10597;&#10597;&#10597;\" " .. "style=\"font-weight:bold;text-decoration:overline;\"" .. "/>") o.rmempty = false o.placeholder = "http://upd.emule-security.org/server.met" o = s:taboption("server", Flag, "remove_dead_server", translate("Remove Dead Server")) o.rmempty = false o = s:taboption("server", Value, "dead_server_retry", translate("Dead Server Retry")) --o:depends("remove_dead_server", "1") o.datatype = "uinteger" o.rmempty = false o.placeholder = "3" o.default = "3" o = s:taboption("server", Flag, "add_server_list_from_server", translate("Update server list when connecting to a server")) o.rmempty = false o = s:taboption("server", Flag, "add_server_list_from_client", translate("Update server list when a client connects")) o.rmempty = false o = s:taboption("server", Flag, "scoresystem", translate("Use priority system")) o.rmempty = false o = s:taboption("server", Flag, "smart_id_check", translate("Use smart LowID check on connect")) o.rmempty = false o = s:taboption("server", Flag, "safe_server_connect", translate("Safe connect")) o.rmempty = false o = s:taboption("server", Flag, "auto_connect_static_only", translate("Auto connect to servers in static list only")) o.rmempty = false o = s:taboption("server", Flag, "manual_high_prio", translate("Set manually added servers to high priority")) o.rmempty = false o = s:taboption("server", Flag, "serverlist", translate("Auto update server list at startup"), translate("addresses.dat file")) o.rmempty = false addr = s:taboption("server", Value, "addresses", translate("Server addresses"), translate("Content of addresses.dat. One address per line")) addr:depends("serverlist", "1") addr.template = "cbi/tvalue" addr.rows = 5 addr.rmempty = true function addr.cfgvalue(self, section) return nixio.fs.readfile("/etc/amule/addresses.dat") end function addr.write(self, section, value) value = value:gsub("\r\n?", "\n") nixio.fs.writefile("//etc/amule/addresses.dat", value) end -- PATH AND FILE -- o = s:taboption("path_and_file", Value, "temp_dir", translate("Temporary directory")) o.rmempty = false o.placeholder = "/var/run/amule/.aMule/Temp" o = s:taboption("path_and_file", Value, "incoming_dir", translate("Incoming directory")) o.rmempty = false o.placeholder = "/var/run/amule/.aMule/Incoming" shareddir = s:taboption("path_and_file", Value, "shareddir", translate("Shared directory"), translate("Content of shareddir.dat. One directory per line")) shareddir.template = "cbi/tvalue" shareddir.titleref = luci.dispatcher.build_url("admin", "system", "fstab") shareddir.rows = 5 shareddir.rmempty = true function shareddir.cfgvalue(self, section) return nixio.fs.readfile("/etc/amule/shareddir.dat") end function shareddir.write(self, section, value) value = value:gsub("\r\n?", "\n") nixio.fs.writefile("//etc/amule/shareddir.dat", value) end o = s:taboption("path_and_file", Flag, "ich", translate("Intelligent corruption handling (I.C.H.)")) o.rmempty = false o = s:taboption("path_and_file", Flag, "a_ich_trust", translate("Advanced I.C.H trusts every hash (not recommended)")) o.rmempty = false o = s:taboption("path_and_file", Flag, "add_new_files_paused", translate("Add files to download in pause mode")) o.rmempty = false o = s:taboption("path_and_file", Flag, "dap_pref", translate("Add files to download with auto priority")) o.rmempty = false o = s:taboption("path_and_file", Flag, "start_next_file", translate("Start next paused file when a file completes")) o.rmempty = false o = s:taboption("path_and_file", Flag, "start_next_file_same_cat", translate("Start next paused file from the same category")) o:depends("start_next_file", "1") o.rmempty = true o = s:taboption("path_and_file", Flag, "start_next_file_alpha", translate("Start next paused file in alphabetic order")) o:depends("start_next_file", "1") o.rmempty = true o = s:taboption("path_and_file", Flag, "allocate_full_file", translate("Preallocate disk space for new files")) o.rmempty = false o = s:taboption("path_and_file", Value, "min_free_disk_space", translate("Minimum free disk space. in Mbytes")) o.datatype = "uinteger" o.placeholder = "1" o.rmempty = false o = s:taboption("path_and_file", Flag, "use_src_seed", translate("Save 10 sources on rare files (< 20 sources)")) o.rmempty = false o = s:taboption("path_and_file", Flag, "uap_pref", translate("Add new shares with auto priority")) o.rmempty = false -- SECURITY -- o = s:taboption("security", Flag, "use_sec_ident", translate("Use secure user identification")) o.rmempty = false o = s:taboption("security", Flag, "is_crypt_layer_requested", translate("Use obfuscation for outgoing connections")) o.rmempty = false o = s:taboption("security", Flag, "is_client_crypt_layer_required", translate("Accept only obfuscation connections")) o.rmempty = false o = s:taboption("security", ListValue, "see_share", translate("Who can see my shared files")) for i,v in ipairs(whocan) do o:value(v) end o.rmempty = false s:taboption("security", DummyValue,"titlesplit2" ,titlesplit(translate("IP Filter Configuration"))) shareddir = s:taboption("security", Value, "ipfilter_static", translate("Static IP list for filtering"), translate("Content of ipfilter_static.dat")) shareddir.template = "cbi/tvalue" shareddir.titleref = luci.dispatcher.build_url("admin", "system", "fstab") shareddir.rows = 5 shareddir.rmempty = true function shareddir.cfgvalue(self, section) return nixio.fs.readfile("/etc/amule/ipfilter_static.dat") end function shareddir.write(self, section, value) value = value:gsub("\r\n?", "\n") nixio.fs.writefile("//etc/amule/ipfilter_static.dat", value) end o = s:taboption("security", Flag, "ip_filter_clients", translate("Filter clients by IP")) o.rmempty = false o = s:taboption("security", Flag, "ip_filter_servers", translate("Filter servers by IP")) o.rmempty = false o = s:taboption("security", Value, "ip_filter_url", translate("IP filter list URL")) o.rmempty = true o = s:taboption("security", Flag, "ip_filter_auto_load", translate("Auto-update ipfilter at startup")) o.rmempty = false o = s:taboption("security", Value, "filter_level", translate("Filtering Level")) o.datatype = "range(1, 255)" o.rmempty = false o.placeholder = "127" o = s:taboption("security", Flag, "filter_lan_ips", translate("Always filter LAN IPs")) o.rmempty = false o = s:taboption("security", Flag, "paranoid_filtering", translate("Paranoid handling of non-matching IPs")) o.rmempty = false o = s:taboption("security", Flag, "ip_filter_system", translate("Use system-wide ipfilter.dat if available")) o.rmempty = false -- REMOTE CONTROL -- o = s:taboption("remote", Value, "ec_address", translate("IP of the listening interface for external connection")) o.datatype = "ip4addr" o.placeholder = "127.0.0.1" o.rmempty = true o = s:taboption("remote", Value, "ec_port", translate("TCP port for EC")) o.datatype = "port" o.placeholder = "4712" o.rmempty = false o = s:taboption("remote", Flag, "upnp_ec_enabled", translate("Enable upnp port forwarding on the EC port")) o.rmempty = false o = s:taboption("remote", Value, "ec_password", translate("EC password")) o.password = true o.rmempty = false s:taboption("remote", DummyValue,"titlesplit3", titlesplit(translate("aMule Web Configuration"))) o = s:taboption("remote", Flag, "web_enabled", translate("Enable web server on startup")) o.rmempty = false o = s:taboption("remote", Value, "template", translate("Web template")) o.rmempty = false local tpth_suggestions = luci.sys.exec("ls /usr/share/amule/webserver/|sed ':a;N;$!ba;s/\\n/:/g'") if tpth_suggestions then for entry in string.gmatch(tpth_suggestions, "[^:]+") do o:value(entry) end end o = s:taboption("remote", Value, "web_password", translate("Web full rights password")) o.password = true o.rmempty = true o = s:taboption("remote", Flag, "use_low_rights_user", translate("Use low rights user")) o.rmempty = false o = s:taboption("remote", Value, "password_low", translate("Web low rights password")) o.password = true o.rmempty = true o = s:taboption("remote", Value, "web_port", translate("Web TCP port")) o.datatype = "port" o.placeholder = "4711" o.rmempty = false o = s:taboption("remote", Flag, "upnp_web_server_enabled", translate("Enable UPnP port forwarding of the web server port")) o.rmempty = false o = s:taboption("remote", Value, "web_upnp_tcp_port", translate("Web UPnP TCP port")) o.datatype = "port" o.placeholder = "50001" o.rmempty = false o = s:taboption("remote", Value, "page_refresh_time", translate("Page refresh time(in secs)")) o.datatype = "range(1, 600)" o.rmempty = false o.placeholder = "121" o = s:taboption("remote", Flag, "use_gzip", translate("Enable Gzip compression")) o.rmempty = false -- TEMPLATE -- tmpl = s:taboption("template", Value, "_tmpl", translate("Edit the template that is used for generating the aMule configuration."), translate("This is the content of the file '/etc/amule/amule.conf.template' from which your amule configuration will be generated. " .. "Values enclosed by pipe symbols ('|') should not be changed. They get their values from other tabs.")) tmpl.template = "cbi/tvalue" tmpl.rows = 20 function tmpl.cfgvalue(self, section) return nixio.fs.readfile("/etc/amule/amule.conf.template") end function tmpl.write(self, section, value) value = value:gsub("\r\n?", "\n") nixio.fs.writefile("//etc/amule/amule.conf.template", value) end -- LOGVIEW -- local lv = s:taboption("logview", DummyValue, "_logview") lv.template = "amule/detail_logview" lv.inputtitle = translate("Read / Reread log file") lv.rows = 50 function lv.cfgvalue(self, section) return translate("Please press [Read] button") end -- AMULECMD -- local cmd = s:taboption("amulecmd", DummyValue, "_amulecmd") cmd.template = "amule/webshell" return m
C_PlayerChoice = {} ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerChoice.GetCurrentPlayerChoiceInfo) ---@return PlayerChoiceInfo choiceInfo function C_PlayerChoice.GetCurrentPlayerChoiceInfo() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerChoice.GetNumRerolls) ---@return number numRerolls function C_PlayerChoice.GetNumRerolls() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerChoice.GetRemainingTime) ---@return number? remainingTime function C_PlayerChoice.GetRemainingTime() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerChoice.IsWaitingForPlayerChoiceResponse) ---@return boolean isWaitingForResponse function C_PlayerChoice.IsWaitingForPlayerChoiceResponse() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerChoice.OnUIClosed) function C_PlayerChoice.OnUIClosed() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerChoice.RequestRerollPlayerChoice) function C_PlayerChoice.RequestRerollPlayerChoice() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerChoice.SendPlayerChoiceResponse) ---@param responseID number function C_PlayerChoice.SendPlayerChoiceResponse(responseID) end ---@class PlayerChoiceInfo ---@field objectGUID string ---@field choiceID number ---@field questionText string ---@field pendingChoiceText string ---@field uiTextureKit string ---@field hideWarboardHeader boolean ---@field keepOpenAfterChoice boolean ---@field options PlayerChoiceOptionInfo[] ---@field soundKitID number|nil ---@field closeUISoundKitID number|nil ---@class PlayerChoiceOptionButtonInfo ---@field id number ---@field text string ---@field disabled boolean ---@field confirmation string|nil ---@field tooltip string|nil ---@field rewardQuestID number|nil ---@field soundKitID number|nil ---@class PlayerChoiceOptionInfo ---@field id number ---@field description string ---@field header string ---@field choiceArtID number ---@field desaturatedArt boolean ---@field disabledOption boolean ---@field hasRewards boolean ---@field rewardInfo PlayerChoiceOptionRewardInfo ---@field uiTextureKit string ---@field maxStacks number ---@field buttons PlayerChoiceOptionButtonInfo[] ---@field widgetSetID number|nil ---@field spellID number|nil ---@field rarity PlayerChoiceRarity|nil ---@field rarityColor ColorMixin|nil ---@field typeArtID number|nil ---@field headerIconAtlasElement string|nil ---@field subHeader string|nil ---@class PlayerChoiceOptionRewardInfo ---@field currencyRewards PlayerChoiceRewardCurrencyInfo[] ---@field itemRewards PlayerChoiceRewardItemInfo[] ---@field repRewards PlayerChoiceRewardReputationInfo[] ---@class PlayerChoiceRewardCurrencyInfo ---@field currencyId number ---@field name string ---@field currencyTexture number ---@field quantity number ---@field isCurrencyContainer boolean ---@class PlayerChoiceRewardItemInfo ---@field itemId number ---@field name string ---@field quantity number ---@class PlayerChoiceRewardReputationInfo ---@field factionId number ---@field quantity number
for _, creature_raw in pairs(df.global.world.raws.creatures.all) do for _, caste_raw in pairs(creature_raw.caste) do if caste_raw.flags.ARENA_RESTRICTED then caste_raw.flags.ARENA_RESTRICTED = false print(('Unrestricted %s:%s'):format(creature_raw.creature_id, caste_raw.caste_id)) end end end
-- -- Created by IntelliJ IDEA. -- User: Kunkka Huang -- Date: 17/1/18 -- Time: 下午6:03 -- To change this template use File | Settings | File Templates. -- local panel = {} local marginTop = 15 local leftX = 10 local stepY = 20 local stepX = 11 local fontSize = 11 * 4 --local fontName = "Consolas" local fontName = gk.theme.font_fnt local scale = 0.25 function panel.create(parent) local winSize = cc.Director:getInstance():getWinSize() local self = cc.LayerColor:create(gk.theme.config.backgroundColor, gk.display.leftWidth, winSize.height - gk.display.topHeight) setmetatableindex(self, panel) self.parent = parent self:setPosition(0, 0) local size = self:getContentSize() local createLine = function(y) gk.util:drawLineOnNode(self, cc.p(10, y), cc.p(size.width - 10, y), cc.c4f(102 / 255, 102 / 255, 102 / 255, 1), -2) end createLine(size.height - 0.5) self.displayInfoNode = cc.Node:create() self:addChild(self.displayInfoNode) self:handleEvent() return self end function panel:undisplayNode() -- do not remove cached node local children = self.displayInfoNode:getChildren() for _, child in ipairs(children) do if child:getTag() ~= 0 then self.displayInfoNode:removeChild(child) end end self.draggingNode = nil self.sortedChildren = nil self._containerNode = nil self.selectedNode = nil end function panel:displayDomTree(rootLayer, force, notForceUnfold) if rootLayer and rootLayer.__info then if gk.mode == gk.MODE_RELEASE_CURRENT then self:displaySceneStack(rootLayer) return end if not force and self.lastDisplayingNode and self.parent.displayingNode == self.lastDisplayingNode and self.parent.displayingNode.__info._id == self.lastDisplayingNode.__info._id then return end local forceUnfold = not notForceUnfold -- gk.log("displayDomTree %s, %s", rootLayer.__info._id, forceUnfold) -- gk.profile:start("displayDomTree") self.lastDisplayingNode = self.parent.displayingNode -- current layout self:undisplayNode() self.domDepth = 0 self.displayingDomDepth = -1 self.foldDomDepth = -1 self.lastDisplayingPos = self.lastDisplayingPos or cc.p(0, 0) self.cachedOthers = self.cachedOthers or {} for _, v in pairs(self.cachedOthers) do v.button1:hide() v.button2:hide() end -- scan layouts if not self.domTree then local total = clone(gk.resource.genNodes) if gk.resource.isDisplayInternalNodes then table.merge(total, gk.resource.genNodesInternal) end local keys = table.keys(total) table.sort(keys, function(k1, k2) local dir1, dir2 = gk.resource:getGenNode(k1).genSrcPath, gk.resource:getGenNode(k2).genSrcPath if dir1 == dir2 then return k1 < k2 else local len1, len2 = #dir1:split("/"), #dir2:split("/") if len1 == len2 then return dir1 < dir2 else return len1 > len2 end end end) self.domTree = { _children = {}, _fold = false } for _, key in ipairs(keys) do local value = gk.resource:getGenNode(key) local displayName = value.genSrcPath:starts(gk.resource.genSrcPath) and value.genSrcPath:sub(gk.resource.genSrcPath:len() + 1) .. key or value.path local ks = string.split(displayName, "/") local parent = self.domTree for i = 1, #ks - 1 do local group = ks[i] if not parent[group] then local fold = cc.UserDefault:getInstance():getBoolForKey("gkdom_" .. group) parent[group] = { _children = {}, _fold = fold } end parent = parent[group] end local var = ks[#ks] table.insert(parent._children, var) end end local value = gk.resource:getGenNode(rootLayer.__cname) local displayingPath = value.genSrcPath:starts(gk.resource.genSrcPath) and value.genSrcPath:sub(gk.resource.genSrcPath:len() + 1) .. rootLayer.__cname or value.genSrcPath self.displayDom = self.displayDom or function(rootLayer, dom, layer, forceUnfold) local keys = table.keys(dom) table.sort(keys) for _, key in ipairs(keys) do if key ~= "_fold" and key ~= "_children" then if forceUnfold and dom[key]._fold and string.find(displayingPath, key .. "/") then -- force unfold dom[key]._fold = false end self:displayGroup(key, layer, nil, dom[key]) if not dom[key]._fold then self.displayDom(rootLayer, dom[key], layer + 1, forceUnfold) end end end for _, child in ipairs(dom._children) do local value = gk.resource:getGenNode(child) local displayName = child --value.genSrcPath:starts(gk.resource.genSrcPath) and value.genSrcPath:sub(gk.resource.genSrcPath:len() + 1) .. child or value.genSrcPath if child == rootLayer.__cname then cc.UserDefault:getInstance():setStringForKey(gk.lastLaunchEntryKey, value.path) cc.UserDefault:getInstance():flush() self:displayDomNode(rootLayer, layer, displayName) else self:displayOthers(child, layer, displayName) end end end self.displayDom(rootLayer, self.domTree, 0, forceUnfold) self.displayInfoNode:setContentSize(cc.size(gk.display.leftWidth, stepY * self.domDepth + 20)) -- scroll to displaying node if self.displayingDomDepth ~= -1 and forceUnfold then -- gk.log("displayingDomDepth = %d", self.displayingDomDepth) local size = self.displayInfoNode:getContentSize() if size.height > self:getContentSize().height then local topY = size.height - marginTop local offsetY = topY - (stepY * self.displayingDomDepth + gk.display.bottomHeight) local y = size.height - offsetY - self:getContentSize().height / 2 y = cc.clampf(y, 0, size.height - self:getContentSize().height) local dt = 0.2 + 0.2 * math.abs(self.lastDisplayingPos.y - y) / 150 if dt > 0.5 then dt = 0.5 end if self.lastDisplayingPos.y ~= 0 then self.displayInfoNode:runAction(cc.EaseInOut:create(cc.MoveTo:create(dt, cc.p(0, y)), 2)) else self.displayInfoNode:setPositionY(y) end self.lastDisplayingPos = cc.p(0, y) end elseif (not forceUnfold) or (self.displayingDomDepth ~= -1 and self.foldDomDepth and self.foldDomDepth > self.displayingDomDepth) then -- fold node below displaying node self.displayInfoNode:setPosition(self.lastDisplayingPos) end -- gk.profile:stop("displayDomTree") end end function panel:createButton(content, x, y, displayName, fixChild, node, widgetParent) local realNode = node local group = false local children = node:getChildren() if children then for i = 1, #children do local child = children[i] if child and tolua.type(child) ~= "cc.DrawNode" and child:getTag() ~= -99 then --and child.__info and child.__info._id then group = true break end end end local lock = node.__info and node.__info._lock == 0 if group then local label = gk.create_label("▶", fontName, fontSize, gk.theme.config.fontColorNormal) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) if fixChild or not node.__info._fold then label:setRotation(90) end if lock or widgetParent then label:setOpacity(150) end label:setDimensions(16 / scale, 16 / scale) label:setContentSize(16 / scale, 16 / scale) local button = gk.ZoomButton.new(label) if fixChild or not node.__info._fold then button:setScale(scale, scale * 0.8) button:setPosition(x - 5, y) else button:setScale(scale * 0.8, scale) button:setPosition(x - 2, y) end self.displayInfoNode:addChild(button) button:setAnchorPoint(0, 0.5) button:onClicked(function() if fixChild then return end node.__info._fold = not node.__info._fold gk.event:post("displayNode", node) gk.event:post("displayDomTree", true, true) end) x = x + 11 end if lock then local label = gk.create_label("🔒", "Consolas", fontSize, gk.theme.config.fontColorNormal) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) label:setDimensions(16 / scale, 16 / scale) label:setContentSize(16 / scale, 16 / scale) gk.set_label_color(label, cc.c3b(0x99, 0x99, 0x99)) label:setScale(scale) label:setAnchorPoint(0, 0.5) label:setPosition(x - 4, y) label:setOpacity(150) self.displayInfoNode:addChild(label) x = x + 11 end local string = string.format("%s(%d", displayName and displayName or (fixChild and "*" .. content or content), node:getLocalZOrder()) local label = gk.create_label(string, fontName, fontSize) local contentSize = cc.size(gk.display.leftWidth / scale, 20 / scale) label:setDimensions(contentSize.width - x / scale, contentSize.height) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) gk.set_label_color(label, cc.c3b(0x99, 0xcc, 0x00)) local visible = gk.util:isAncestorsVisible(node) local isWidget = (node.__info and node.__info._isWidget) if isWidget then gk.set_label_color(label, cc.c3b(0xFF, 0x88, 0xFF)) end if fixChild or widgetParent or not visible or lock then if not isWidget then gk.set_label_color(label, gk.theme.config.fontColorNormal) end label:setOpacity(150) end local cur = widgetParent and widgetParent[content] or self.parent.scene.layer[content] if cur and cur == self.parent.draggingNode then gk.set_label_color(label, cc.c3b(0xFF, 0x00, 0x00)) end label:setScale(scale) self.displayInfoNode:addChild(label) label:setAnchorPoint(0, 0.5) label:setPosition(x, y) gk.util:addMouseMoveEffect(label) -- select if self.parent.displayingNode == node then self.displayingDomDepth = self.domDepth -- label:runAction(cc.Sequence:create(cc.DelayTime:create(0.2), cc.CallFunc:create(function() gk.util:drawNodeBg(label, cc.c4f(0.5, 0.5, 0.5, 0.5), -2) -- end))) self.selectedNode = label end -- drag button if not fixChild then label:setTag(1) label.content = content local node = label local listener = cc.EventListenerTouchOneByOne:create() listener:setSwallowTouches(true) listener:registerScriptHandler(function(touch, event) self._containerNode = nil local location = touch:getLocation() self._touchBegainLocation = cc.p(location) if gk.util:hitTest(self, touch) and not self.draggingNode and gk.util:hitTest(node, touch) then gk.log("dom:choose node %s", content) local nd = widgetParent and widgetParent[content] or self.parent.scene.layer[content] nd = nd or realNode local _voidContent = realNode.__info and realNode.__info._voidContent if nd or _voidContent then if self.selectedNode ~= node then if self.selectedNode then gk.util:clearDrawNode(self.selectedNode, -2) end end self.selectedNode = node gk.util:drawNodeBg(node, cc.c4f(0.5, 0.5, 0.5, 0.5), -2) gk.event:post("displayNode", nd) end if _voidContent or widgetParent then gk.log("[Warning] cannot modify _voidContent or widget's children") return false end return true else return false end end, cc.Handler.EVENT_TOUCH_BEGAN) listener:registerScriptHandler(function(touch, event) local location = touch:getLocation() local p = self:convertToNodeSpace(location) if not self.draggingNode then gk.log("dom:create dragging node %s", content) local label = gk.create_label(content, fontName, fontSize) local contentSize = cc.size(gk.display.leftWidth / scale, 20 / scale) label:setDimensions(contentSize.width - 2 * leftX / scale, contentSize.height) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) gk.set_label_color(label, gk.theme.config.fontColorNormal) label:setAnchorPoint(0, 0.5) label:setScale(scale) self.displayInfoNode:addChild(label) self.draggingNode = label end local dragPos = cc.pAdd(cc.p(x, y), cc.pSub(p, self.displayInfoNode:convertToNodeSpace(self._touchBegainLocation))) dragPos.x = dragPos.x - self.displayInfoNode:getPositionX() dragPos.y = dragPos.y - self.displayInfoNode:getPositionY() self.draggingNode:setPosition(dragPos) -- find dest container if self.sortedChildren == nil then self:sortChildrenOfSceneGraphPriority(self.displayInfoNode, true) end if self._containerNode then gk.util:clearDrawNode(self._containerNode, -2) end if self.selectedNode then gk.util:clearDrawNode(self.selectedNode, -2) end self.lastContainerNode = self._containerNode self._containerNode = nil local children = self.sortedChildren for i = #children, 1, -1 do local node = children[i] local s = node:getContentSize() local rect = { x = 0, y = 0, width = s.width, height = s.height } local p = node:convertToNodeSpace(location) if cc.rectContainsPoint(rect, p) then local nd1 = self.parent.scene.layer[node.content] local nd2 = self.parent.scene.layer[content] if nd1 and nd2 then if nd1 == nd2 or nd1:getParent() == nd2 or gk.util:isAncestorOf(nd2, nd1) then break end if p.y < s.height / 2 and nd1 and nd2 and (nd1:getParent() == nd2:getParent() or nd2:getParent() == nd1) then -- reorder mode local size = node:getContentSize() gk.util:drawSolidRectOnNode(node, cc.p(0, 5), cc.p(size.width, 0), cc.c4f(0, 1, 0, 1), -2) self.mode = 1 elseif nd2:getParent() == nd1 then break else -- change container mode gk.util:drawNode(node, cc.c4f(1, 0, 0, 1), -2) self.mode = 2 end self._containerNode = node -- gk.log("dom:find container node %s", self._containerNode.content) if self.lastContainerNode ~= self._containerNode then local nd = self.parent.scene.layer[self._containerNode.content] if nd then gk.event:post("displayNode", nd, true) end self.lastContainerNode = self._containerNode end break end end end end, cc.Handler.EVENT_TOUCH_MOVED) listener:registerScriptHandler(function(touch, event) if self._containerNode then if self.mode == 2 then -- change container mode local container = self.parent.scene.layer[self._containerNode.content] local node = self.parent.scene.layer[content] if node and container then local parent = node:getParent() local p = cc.p(node:getPosition()) p = container:convertToNodeSpace(node:getParent():convertToWorldSpace(p)) local sx = clone(node.__info.scaleX) local sy = clone(node.__info.scaleY) local sxy = clone(node.__info.scaleXY) gk.event:post("executeCmd", "CHANGE_CONTAINER", { id = node.__info._id, fromPid = node.__info.parentId, toPid = container.__info._id, fromPos = cc.p(node.__info.x, node.__info.y), sx = sx, sy = sy, sxy = sxy, }) node:retain() -- button child if parent and parent.__info and gk.util:instanceof(parent, "Button") and parent:getContentNode() == node then parent:setContentNode(nil) end self.parent:rescaleNode(node, container) local x = math.round(gk.generator:parseXRvs(node, p.x, node.__info.scaleXY.x)) local y = math.round(gk.generator:parseYRvs(node, p.y, node.__info.scaleXY.y)) node.__info.x, node.__info.y = x, y node:removeFromParentAndCleanup(false) container:addChild(node) node:release() gk.log("dom:change node container, new pos = %.2f, %.2f", node.__info.x, node.__info.y) gk.event:post("displayDomTree", true) gk.event:post("displayNode", node) gk.event:post("postSync") self.mode = 0 end elseif self.mode == 1 then -- reorder mode local bro = self.parent.scene.layer[self._containerNode.content] local node = self.parent.scene.layer[content] if node and bro and (node:getParent() == bro:getParent() or node:getParent() == bro) then -- gen ordersBefore gk.event:post("executeCmd", "REORDER", { parentId = node.__info.parentId, }) if node:getParent() == bro then -- put in the first place local parent = node:getParent() parent:sortAllChildren() local children = parent:getChildren() -- local child = children[1] for i = 1, #children do local child = children[i] if child.__info then if child ~= node then local z1, z2 = child:getLocalZOrder(), node:getLocalZOrder() if z2 > z1 then -- demotion z2 = z1 end parent:reorderChild(node, z2) for i = 1, #children do local c = children[i] if c and c.__info then if c:getLocalZOrder() == z1 and node ~= c then parent:reorderChild(c, z1) end end end node.__info.localZOrder = z2 gk.log("dom:reorder node %s before %s", node.__info._id, child.__info._id) end break end end else local parent = node:getParent() local z1, z2 = bro:getLocalZOrder(), node:getLocalZOrder() if z2 < z1 then -- promotion z2 = z1 end parent:sortAllChildren() local reorder = false local children = parent:getChildren() for i = 1, #children do local child = children[i] if child and child.__info then if z2 > z1 then if child:getLocalZOrder() == z2 and node ~= child then parent:reorderChild(child, z2) end else if child:getLocalZOrder() == z1 then if child == bro then reorder = true parent:reorderChild(node, z2) elseif reorder and child ~= node then parent:reorderChild(child, z1) end end end end end node.__info.localZOrder = z2 gk.log("dom:reorder node %s after %s", node.__info._id, bro.__info._id) end gk.event:post("displayDomTree", true) gk.event:post("postSync") end end end if self._containerNode then gk.util:clearDrawNode(self._containerNode, -2) end if self.draggingNode then self.draggingNode:removeFromParent() self.draggingNode = nil end self.sortedChildren = nil self._containerNode = nil end, cc.Handler.EVENT_TOUCH_ENDED) listener:registerScriptHandler(function(touch, event) if self.draggingNode then self.draggingNode:removeFromParent() self.draggingNode = nil end self.sortedChildren = nil self._containerNode = nil end, cc.Handler.EVENT_TOUCH_CANCELLED) cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(listener, node) end return label end function panel:displayDomNode(node, layer, displayName, widgetParent) if tolua.type(node) == "cc.DrawNode" or gk.util:isDebugNode(node) then return end local fixChild = node.__info == nil or node.__ignore local size = self:getContentSize() local topY = size.height - marginTop local title = fixChild and tolua.type(node) or node.__info._id if node.__ignore then title = node.__info._type end self:createButton(title, leftX + stepX * layer, topY - stepY * self.domDepth, displayName, fixChild, node, widgetParent) self.domDepth = self.domDepth + 1 layer = layer + 1 local preWidgetParent = widgetParent local widgetParent = widgetParent if (node.__info and node.__info._isWidget) then widgetParent = node end if node.__info and node.__info._fold and node ~= self.lastDisplayingNode and gk.util:isAncestorOf(node, self.lastDisplayingNode) then -- force unfold node.__info._fold = false end if fixChild or not node.__info._fold then if tolua.type(node) == "cc.TMXLayer" or node.__ignore then return end node:sortAllChildren() local children = node:getChildren() if children then for _, child in ipairs(children) do --and child.__info and child.__info._id then if child.__rootTable == widgetParent then self:displayDomNode(child, layer, nil, widgetParent) elseif child.__rootTable == preWidgetParent then self:displayDomNode(child, layer, nil, preWidgetParent) else self:displayDomNode(child, layer, nil, nil) end end end end if gk.util:instanceof(node, "cc.ProgressTimer") then local sprite = node:getSprite() self:displayDomNode(sprite, layer) end end function panel:createButtonOthers(content, x, y, displayName) -- cache others, do not recreate self.cachedOthers = self.cachedOthers or {} if self.cachedOthers[content] then local button1 = self.cachedOthers[content].button1 local button2 = self.cachedOthers[content].button2 button1:setPosition(x, y - 1) button2:setPosition(x, y) button1:onClicked(function() gk.event:post("unfoldRootLayout", content) end) button2:onClicked(function() gk.log("post changeRootLayout") gk.event:post("changeRootLayout", content) end) button1:show() button2:show() else local label = gk.create_label("◉", fontName, fontSize - 5, gk.theme.config.fontColorNormal) label:setDimensions(12 / scale, 20 / scale) label:setContentSize(12 / scale, 20 / scale) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) local button = gk.ZoomButton.new(label) button:setScale(scale, scale) self.displayInfoNode:addChild(button) button:setAnchorPoint(0, 0.5) button:setPosition(x, y - 1) button:onClicked(function() gk.event:post("unfoldRootLayout", content) end) button.noneMouseMoveEffect = true local button1 = button local label = gk.create_label(" " .. (displayName and displayName or content), fontName, fontSize) local contentSize = cc.size(gk.display.leftWidth / scale, 20 / scale) label:setPosition(cc.p(contentSize.width / 2, contentSize.height / 2)) label:setDimensions(contentSize.width - x / scale, contentSize.height) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) gk.set_label_color(label, gk.theme.config.fontColorNormal) local button = gk.ZoomButton.new(label) button:setScale(scale) self.displayInfoNode:addChild(button) button:setAnchorPoint(0, 0.5) button:setPosition(x, y) button:onClicked(function() gk.log("post changeRootLayout") gk.event:post("changeRootLayout", content) end) button1:setTag(0) button:setTag(0) self.cachedOthers[content] = { button1 = button1, button2 = button } end end function panel:displayOthers(key, layer, displayName) local size = self:getContentSize() local topY = size.height - marginTop self:createButtonOthers(key, leftX + stepX * layer, topY - stepY * self.domDepth, displayName) self.domDepth = self.domDepth + 1 end function panel:createButtonGroup(content, x, y, displayName, domItem) local label = gk.create_label("❑", fontName, fontSize + 5, cc.c3b(180, 120, 75)) label:setDimensions(12 / scale, 20 / scale) label:setContentSize(12 / scale, 20 / scale) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) local button = gk.ZoomButton.new(label) button:setScale(scale, scale) self.displayInfoNode:addChild(button) button:setAnchorPoint(0, 0.5) button:setPosition(x, y - 1) button:onClicked(function() domItem._fold = not domItem._fold self.foldDomDepth = self.domDepth gk.event:post("displayDomTree", true, true) cc.UserDefault:getInstance():setBoolForKey("gkdom_" .. content, domItem._fold) cc.UserDefault:getInstance():flush() end) button.noneMouseMoveEffect = true local label = gk.create_label(" " .. (displayName and displayName or content), fontName, fontSize) local contentSize = cc.size(gk.display.leftWidth / scale, 20 / scale) label:setPosition(cc.p(contentSize.width / 2, contentSize.height / 2)) label:setDimensions(contentSize.width - x / scale, contentSize.height) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) gk.set_label_color(label, cc.c3b(180, 120, 75)) local button = gk.ZoomButton.new(label) button:setScale(scale) self.displayInfoNode:addChild(button) button:setAnchorPoint(0, 0.5) button:setPosition(x, y) button:onClicked(function() domItem._fold = not domItem._fold self.foldDomDepth = self.domDepth gk.event:post("displayDomTree", true, true) cc.UserDefault:getInstance():setBoolForKey("gkdom_" .. content, domItem._fold) cc.UserDefault:getInstance():flush() end) return button end function panel:displayGroup(key, layer, displayName, domItem) local size = self:getContentSize() local topY = size.height - marginTop self:createButtonGroup(key, leftX + stepX * layer, topY - stepY * self.domDepth, key or displayName, domItem) self.domDepth = self.domDepth + 1 end function panel:createTitle(content, x, y, type, layerDepth) local string = type == "Dialog" and string.format("[%s]", content) or content for i = 0, layerDepth do string = " " .. string end local label = gk.create_label(string, fontName, fontSize) local contentSize = cc.size(gk.display.leftWidth / scale, 20 / scale) label:setDimensions(contentSize.width - x / scale, contentSize.height) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) if type == "Title" then gk.set_label_color(label, cc.c3b(180, 120, 75)) else gk.set_label_color(label, cc.c3b(0x99, 0xcc, 0x00)) end label:setScale(scale) self.displayInfoNode:addChild(label) label:setAnchorPoint(0, 0.5) label:setPosition(x, y) label:setTag(1) gk.util:addMouseMoveEffect(label) return label end function panel:displaySceneStack(rootLayer) self:undisplayNode() self.domDepth = 0 local layerDepth = 0 local size = self:getContentSize() local topY = size.height - marginTop self:createTitle("************ SceneStack ************", leftX, topY - stepY * self.domDepth, "Title", layerDepth) self.domDepth = self.domDepth + 1 for i = gk.SceneManager.sceneStack.first, gk.SceneManager.sceneStack.last do local s = gk.SceneManager.sceneStack[i] local st = s.__sceneType or "unknown SceneType" self:createTitle(st, leftX, topY - stepY * self.domDepth, "Layer", layerDepth) self.domDepth = self.domDepth + 1 if s.layer then self:displayDialogStack(s.layer, layerDepth + 1) end end self.domDepth = self.domDepth + 1 end function panel:displayDialogStack(layer, layerDepth) local size = self:getContentSize() local topY = size.height - marginTop if layer.dialogsStack then for i = 1, #layer.dialogsStack do local d = layer.dialogsStack[i] self:createTitle(d.__dialogType or "unknown DialogType", leftX, topY - stepY * self.domDepth, "Dialog", layerDepth) self.domDepth = self.domDepth + 1 self:displayDialogStack(d, layerDepth + 1) end end end function panel:sortChildrenOfSceneGraphPriority(node, isRootNode) if isRootNode then self.sortedChildren = {} end node:sortAllChildren() local children = node:getChildren() local childrenCount = #children if childrenCount > 0 then for i = 1, childrenCount do local child = children[i] if child and child:getLocalZOrder() < 0 and child:getTag() == 1 then self:sortChildrenOfSceneGraphPriority(child, false) else break end end if not table.indexof(self.sortedChildren, node) then table.insert(self.sortedChildren, node) end for i = 1, childrenCount do local child = children[i] if child and child:getTag() == 1 then self:sortChildrenOfSceneGraphPriority(child, false) end end else if not table.indexof(self.sortedChildren, node) then table.insert(self.sortedChildren, node) end end end function panel:handleEvent() local listener = cc.EventListenerMouse:create() listener:registerScriptHandler(function(touch, event) local location = touch:getLocationInView() if self.displayInfoNode and gk.util:touchInNode(self, location) then if self.displayInfoNode:getContentSize().height > self:getContentSize().height then local scrollY = touch:getScrollY() local x, y = self.displayInfoNode:getPosition() y = y + scrollY * 10 y = cc.clampf(y, 0, self.displayInfoNode:getContentSize().height - self:getContentSize().height) self.displayInfoNode:setPosition(x, y) self.lastDisplayingPos = cc.p(self.displayInfoNode:getPosition()) if not self.scrollBar then self.scrollBar = cc.LayerColor:create(cc.c3b(102, 102, 102), 0, 0) self.scrollBar:setPositionX(self:getContentSize().width - 4) self:addChild(self.scrollBar) end local barSize = self:getContentSize().height * self:getContentSize().height / self.displayInfoNode:getContentSize().height local scrollLen = self.displayInfoNode:getContentSize().height - self:getContentSize().height self.scrollBar:setContentSize(cc.size(1.5, barSize)) -- [0, scrollLen] <--> [self:getContentSize().height-barSize, 0] self.scrollBar:setPositionY((1 - y / scrollLen) * (self:getContentSize().height - barSize)) self.scrollBar:stopAllActions() self.scrollBar:setOpacity(255) self.scrollBar:runAction(cc.Sequence:create(cc.DelayTime:create(0.2), cc.FadeOut:create(0.5))) end end end, cc.Handler.EVENT_MOUSE_SCROLL) cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(listener, self) -- swallow touches local listener = cc.EventListenerTouchOneByOne:create() listener:setSwallowTouches(true) listener:registerScriptHandler(function(touch, event) if gk.util:hitTest(self, touch) then return true end end, cc.Handler.EVENT_TOUCH_BEGAN) cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(listener, self) end return panel
slot1 = { ["award.mp3"] = { time = 2, priority = ({ BUTTON = 4, Fish = 1, WAVE = 3, ATHER = 6, ATHER_II = 2, HIT = 5 })["ATHER"] }, ["bigAward.mp3"] = { time = 4.6, priority = ()["ATHER_II"] }, ["BigBang.mp3"] = { time = 2.2, priority = ()["ATHER_II"] }, ["Bigfireworks.mp3"] = { time = 1.9, priority = ()["ATHER_II"] }, ["ChangeScore.mp3"] = { time = 0.4, priority = ()["ATHER"] }, ["ChangeType.mp3"] = { time = 1.3, priority = ()["ATHER"] }, ["CJ.mp3"] = { time = 4.9, priority = ()["ATHER_II"] }, ["click.mp3"] = { time = 0.3, priority = ()["BUTTON"] }, ["electric.mp3"] = { time = 0.7, priority = ()["ATHER_II"] }, ["Fire.mp3"] = { time = 0, priority = ()["HIT"] }, ["fireworks.mp3"] = { time = 0.9, priority = ()["ATHER_II"] }, ["collect_coin.mp3"] = { time = 0.75, priority = ()["ATHER_II"] }, ["drop_gold.mp3"] = { time = 1.56, priority = ()["ATHER_II"] }, ["GunFire0.mp3"] = { time = 0, priority = ()["ATHER"] }, ["GunFire1.mp3"] = { time = 0, priority = ()["ATHER"] }, ["HaiLang.mp3"] = { time = 9.6, priority = ()["WAVE"] }, ["Hit0.mp3"] = { time = 1, priority = ()["HIT"] }, ["Hit1.mp3"] = { time = 1, priority = ()["HIT"] }, ["Hit2.mp3"] = { time = 1.7, priority = ()["HIT"] }, ["laser.mp3"] = { time = 0.5, priority = ()["ATHER_II"] }, ["MakeUP.mp3"] = { time = 0.7, priority = ()["ATHER"] }, ["Net0.mp3"] = { time = 0.5, priority = ()["HIT"] }, ["Net1.mp3"] = { time = 0.8, priority = ()["HIT"] }, ["rotaryturn.mp3"] = { time = 0.4, priority = ()["ATHER"] }, ["surf.mp3"] = { time = 7.2, priority = ()["WAVE"] }, ["TNNFDCLNV.mp3"] = { time = 5.2, priority = ()["ATHER"] }, ["fisha1.mp3"] = { time = 3, priority = ()["Fish"] }, ["fisha2.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha3.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha4.mp3"] = { time = 1, priority = ()["Fish"] }, ["fisha5.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha6.mp3"] = { time = 3, priority = ()["Fish"] }, ["fisha7.mp3"] = { time = 3, priority = ()["Fish"] }, ["fisha8.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha9.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha10.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha11.mp3"] = { time = 3, priority = ()["Fish"] }, ["fisha12.mp3"] = { time = 3, priority = ()["Fish"] }, ["fisha13.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha14.mp3"] = { time = 3, priority = ()["Fish"] }, ["fisha15.mp3"] = { time = 3, priority = ()["Fish"] }, ["fisha16.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha17.mp3"] = { time = 3, priority = ()["Fish"] }, ["fisha18.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha19.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha20.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha21.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha22.mp3"] = { time = 4, priority = ()["Fish"] }, ["fisha23.mp3"] = { time = 4, priority = ()["Fish"] }, ["fisha24.mp3"] = { time = 3, priority = ()["Fish"] }, ["fisha25.mp3"] = { time = 2, priority = ()["Fish"] }, ["fisha26.mp3"] = { time = 3, priority = ()["Fish"] }, ["fisha27.mp3"] = { time = 4, priority = ()["Fish"] }, ["fisha28.mp3"] = { time = 3, priority = ()["Fish"] } } slot2 = { [FISHINGJOY_SOUND_EFFECT.CANNON_SWITCH] = "MakeUP.mp3", [FISHINGJOY_SOUND_EFFECT.CASTING_NORMAL] = "Net0.mp3", [FISHINGJOY_SOUND_EFFECT.CASTING_ION] = "Net1.mp3", [FISHINGJOY_SOUND_EFFECT.CATCH] = "Hit0.mp3", [FISHINGJOY_SOUND_EFFECT.CATCH1] = "Hit1.mp3", [FISHINGJOY_SOUND_EFFECT.CATCH2] = "Hit2.mp3", [FISHINGJOY_SOUND_EFFECT.FIRE] = "GunFire0.mp3", [FISHINGJOY_SOUND_EFFECT.IONFIRE] = "GunFire1.mp3", [FISHINGJOY_SOUND_EFFECT.INSERT] = "ChangeScore.mp3", [FISHINGJOY_SOUND_EFFECT.AWARD] = "award.mp3", [FISHINGJOY_SOUND_EFFECT.BIGAWARD] = "bigAward.mp3", [FISHINGJOY_SOUND_EFFECT.ROTARYTURN] = "rotaryturn.mp3", [FISHINGJOY_SOUND_EFFECT.BINGO] = "CJ.mp3", [FISHINGJOY_SOUND_EFFECT.BINGO2] = "TNNFDCLNV.mp3", [FISHINGJOY_SOUND_EFFECT.WAVE] = "surf.mp3", [FISHINGJOY_SOUND_EFFECT.BOMB_LASER] = "laser.mp3", [FISHINGJOY_SOUND_EFFECT.BOMB_ELECTRIC] = "electric.mp3", [FISHINGJOY_SOUND_EFFECT.BOMB_ELECTRIC] = "electric.mp3", [FISHINGJOY_SOUND_EFFECT.EFFECT_PARTICAL_BIG_BOMB] = "BigBang.mp3", [FISHINGJOY_SOUND_EFFECT.EFFECT_PARTICAL_BIG_FIREWORKS] = "Bigfireworks.mp3", [FISHINGJOY_SOUND_EFFECT.EFFECT_PARTICAL_FIREWORKS] = "fireworks.mp3", [FISHINGJOY_SOUND_EFFECT.EFFECT_COLLECT_COIN] = "collect_coin.mp3", [FISHINGJOY_SOUND_EFFECT.EFFECT_DROP_COIN] = "drop_gold.mp3", [FISHINGJOY_SOUND_EFFECT.BUTTON_CLICK] = "click.mp3" } slot3 = { [21] = { 13, 14 }, [22] = { 13, 14 }, [20] = { 15, 16 }, [23] = { 17 }, [25] = { 18 }, [30] = { 19, 20, 21 }, [27] = { 22, 23, 24 }, [24] = { 25, 26, 27 }, [6] = { 28 } } slot4 = { "fisha1.mp3", "fisha2.mp3", "fisha3.mp3", "fisha4.mp3", "fisha5.mp3", "fisha7.mp3", "fisha8.mp3", "fisha10.mp3", "fisha11.mp3", "fisha12.mp3", "fisha13.mp3", "fisha14.mp3", "fisha6.mp3", "fisha15.mp3", "fisha9.mp3", "fisha17.mp3", "fisha16.mp3", "fisha18.mp3", "fisha19.mp3", "fisha20.mp3", "fisha21.mp3", "fisha22.mp3", "fisha23.mp3", "fisha24.mp3", "fisha25.mp3", "fisha26.mp3", "fisha27.mp3", "fisha28.mp3" } slot5 = { [1.0] = "bgm/buyuBgMusic1.mp3", [2.0] = "effect/HaiLang.mp3" } slot6 = math.random FishingJoyController.resetFishingJoySoundParam = function (slot0) slot0.lastGameEffectPlayTime = 0 slot0.lastGameEffectPriority = slot0.HIT slot0.lastFishEffectPlayTime = 0 slot0.lastFishEffectPriority = slot0.Fish end FishingJoyController.playFishingJoySoundEffect = function (slot0, slot1) if not slot0[slot1] or slot2 == "" then return end if not slot1[slot2] then return end slot5 = socket.gettime() - slot0.lastGameEffectPlayTime if slot0.lastGameEffectPriority == slot3.priority and slot5 < slot3.time then return end slot0.lastGameEffectPlayTime = slot4 slot0.lastGameEffectPriority = slot3.priority slot9 = "effect/" .. slot2 slot0.playGameEffect(slot7, slot0) end FishingJoyController.playFishingJoyFishEffect = function (slot0, slot1) if slot0[slot1] == nil then slot7 = 12 slot2 = slot1[slot2(slot5, 1)] elseif #slot2 > 1 then slot7 = (slot2[1] + #slot2) - 1 slot2 = slot1[slot2(slot5, slot2[1])] else slot2 = slot1[slot2[1]] end if not slot2 then return end if not slot3[slot2] then return end slot5 = socket.gettime() - slot0.lastFishEffectPlayTime if slot0.lastFishEffectPriority == slot3.priority and slot5 < slot3.time then return end slot0.lastFishEffectPlayTime = slot4 slot0.lastFishEffectPriority = slot3.priority slot9 = "effect/" .. slot2 slot0.playGameEffect(slot7, slot0) end FishingJoyController.playFishingJoyMusic = function (slot0, slot1) slot5 = slot0[slot1] slot0.playMusic(slot3, slot0) end return
local Suite = require "loop.test.Suite" local Template = require "oil.dtests.Template" local template = Template{"Client"} -- master process name Server = [=====================================================================[ Object = {} function Object:someoperation() return "I'm some operation" end Interceptor = {} function Interceptor:receiverequest(request) if request.object_key == "objectA" and request.operation_name == "_is_a" then oil.sleep(1) end end orb = oil.dtests.init{ port = 2809 } orb:setserverinterceptor(Interceptor) orb:loadidl[[ interface A { void someoperation(); }; interface B { void someoperation(); }; ]] orb:newservant(Object, "objectA", "::A") orb:newservant(Object, "objectB", "::B") orb:run() --[Server]=====================================================================] Client = [=====================================================================[ orb = oil.dtests.init() objA = orb:newproxy(oil.dtests.resolve("Server", 2809, "objectA"), "asynchronous") objB = oil.dtests.resolve("Server", 2809, "objectB") local fut = objA:_is_a("IDL:A:1.0") assert(objB:_is_a("IDL:B:1.0") == true) assert(fut:evaluate() == true) orb:shutdown() --[Client]=====================================================================] return template:newsuite{ corba = true, interceptedcorba = true }
local present, lualine = pcall(require, 'lualine') if present then local gps = require('nvim-gps') gps.setup() lualine.setup({ sections = { lualine_b = { 'branch', 'diff', 'diagnostics', { gps.get_location, cond = gps.is_available }, }, }, }) end
console.clear() json = require "json" -- left is negative, right is positive -- caps out at 14 without triggers, and 16 with triggers addTurning = 0x0000D6 -- 1000 = 145km, 1500 = 253km, 2000 = 386km, 3000 = 722km addSpeed = 0x000B20 -- max 2048, death if hit again when it's below 0 addPower = 0x0000C9 -- "Race finish state. Bitmask: lefcr--h -- l = Race lost (ranked/timed out); e = Executing explosion animation (player); f = Crossed finish line; c = Camera is following CPU car; r = Show results; - = Unknown; h = Horizon moves with X coordinate instead of angle." addState = 0x0000C3 -- Timer, centiseconds addTimerCs = 0x0000C2 -- Player rank in race addRank = 0x000DC8 local function sendData(data) packet = json.encode(data) comm.socketServerSend(packet) end function intToBool(value) if value > 0 then value = true; else value = false; end return value end function updateSpeed() return memory.read_s16_le(addSpeed) end function updateTurn() return memory.readbyte(addTurning) end function updatePower() return memory.read_s16_le(addPower) end function updateState() return memory.readbyte(addState) end -- We're only concerned with the centiseconds, since we're only checking to see whether the timer is actually running function updateTimer() return memory.readbyte(addTimerCs) end function updateRank() return memory.readbyte(addRank) end function updateVelocity() local speedVal = updateSpeed() local turnVal = updateTurn() local powerVal = updatePower() local stateVal = updateState() local timerVal = updateTimer() local rankVal = updateRank() local packet = {speed=speedVal, turn=turnVal, power=powerVal, state=stateVal, timer=timerVal, rank=rankVal} sendData(packet) end while true do --if an address is changed too often, an event handler will slow down the game --so for those problematic addresses, we manually check those addresses every X number of frames local frame = emu.framecount() if frame % 10 == 0 then updateVelocity() end emu.frameadvance(); end
function nDonationProcess( len ) GAMEMODE:AddChat( Color( 229, 201, 98, 255 ), "CombineControl.ChatNormal", "Your donation has been processed and applied!", { CB_ALL, CB_OOC } ); end net.Receive( "nDonationProcess", nDonationProcess );
object_mobile_dressed_corellia_vani_korr = object_mobile_shared_dressed_corellia_vani_korr:new { } ObjectTemplates:addTemplate(object_mobile_dressed_corellia_vani_korr, "object/mobile/dressed_corellia_vani_korr.iff")
-- timers.lua -- babyjeans -- -- a simple timer class -- -- use: -- Timers:newTimer(seconds, callback, repeats) -- create a new timer that will call the callback after seconds. if repeats is true it will repeat indefinitely -- if repeats is a number it will repeat that many times. -- -- Timers:update() -- must call this every update to update the timers values -- -- Timer:start() -- restart a timer -- -- Timer:stop() -- stop the timer -- --- local Timers = class("Timers") local Timer = class("Timer") local timerList = { } --- -- function Timer:init(seconds, callback, repeats) self.timeElapsed = 0 self.seconds = seconds self.startTime = love.timer.getTime() self.lastTime = self.startTime self.callback = callback self.repeats = repeats if self.repeats == nil then self.repeats = true end self.og_repeats = self.repeats end function Timer:start() if not self.isGoing then self.isGoing = true timerList[#timerList + 1] = self end end function Timer:reset() self.lastTime = love.timer.getTime() self.isGoing = true self.repeats = self.og_repeats end function Timer:stop(callCallback) self.isGoing = false if callCallback and self.callback then self.callback() end end --- -- function Timers:init() app:hookUpdate( { self, self.update } ) end function Timers:newTimer(seconds, callback, repeats) local timer = Timer(seconds, callback, repeats) timer:start() return timer end function Timers:update() local currentTime = love.timer.getTime() local toRemove = { } for i, timer in ipairs(timerList) do if timer.isGoing then timer.timeElapsed = currentTime - timer.lastTime if timer.timeElapsed >= timer.seconds then timer.callback() if type(timer.repeats) == "number" then timer.repeats = timer.repats - 1 end if not timer.repeats then timer.isGoing = false end timer.lastTime = currentTime end else toRemove[#toRemove + 1] = i end end for i, timer in ipairs(toRemove) do table.remove(timerList, timer) end end return Timers()
local cave_rock = { type = "simple-entity", name = "cave-rock", flags = {"placeable-neutral", "placeable-off-grid", "not-on-map"}, icon = "__base__/graphics/icons/stone-rock.png", subgroup = "grass", order = "b[decorative]-k[stone-rock]-a[big]", collision_box = {{-1.1, -1.1}, {1.1, 1.1}}, selection_box = {{-1.3, -1.3}, {1.3, 1.3}}, vehicle_impact_sound = { filename = "__base__/sound/car-stone-impact.ogg", volume = 1.0 }, minable = { mining_particle = "stone-particle", mining_time = 8, result = "stone", count = 20 }, loot = { {item = "stone", probability = 1, count_min = 5, count_max = 10} }, count_as_rock_for_filtered_deconstruction = true, mined_sound = { filename = "__base__/sound/deconstruct-bricks.ogg" }, render_layer = "object", max_health = 200, resistances = { { type = "fire", percent = 100 } }, autoplace = { order = "a[doodad]-a[rock]", peaks = { { influence = 0.0002 }, { influence = 0.002; min_influence = 0, elevation_optimal = 30000, elevation_range = 23000, elevation_max_range = 30000, } } }, pictures = { { filename = "__base__/graphics/decorative/stone-rock/stone-rock-01.png", width = 76, height = 60, shift = {0.1, 0} }, { filename = "__base__/graphics/decorative/stone-rock/stone-rock-02.png", width = 83, height = 86, shift = {0.2, 0} }, { filename = "__base__/graphics/decorative/stone-rock/stone-rock-03.png", width = 126, height = 98, shift = {0.7, 0} }, { filename = "__base__/graphics/decorative/stone-rock/stone-rock-04.png", width = 92, height = 108, shift = {0.1, 0} }, { filename = "__base__/graphics/decorative/stone-rock/stone-rock-05.png", width = 140, height = 99, shift = {0.5, 0} } } } data:extend{cave_rock}
slot0 = class("GuildResPage", import("....base.BaseSubView")) slot0.getUIName = function (slot0) return "GuildResPanel" end slot0.Load = function (slot0) if slot0._state ~= slot0.STATES.NONE then return end slot0._state = slot0.STATES.LOADING pg.UIMgr.GetInstance():LoadingOn() slot0:Loaded(LoadAndInstantiateSync("UI", slot0:getUIName(), true, false)) slot0:Init() end slot0.OnLoaded = function (slot0) slot0.captailBg = slot0:findTF("captail"):GetComponent(typeof(Image)) slot0.contributionBg = slot0:findTF("contribution"):GetComponent(typeof(Image)) slot0.resCaptailTxt = slot0:findTF("captail/Text"):GetComponent(typeof(Text)) slot0.resContributionTxt = slot0:findTF("contribution/Text"):GetComponent(typeof(Text)) slot0.resourceLogBtn = slot0:findTF("captail/log") setActive(slot0._tf, true) end slot0.OnInit = function (slot0) onButton(slot0, slot0.resourceLogBtn, function () slot0:emit(GuildMainMediator.ON_FETCH_CAPITAL_LOG) end, SFX_PANEL) end slot0.Update = function (slot0, slot1, slot2) slot0.resCaptailTxt.text = slot2:getCapital() slot0.resContributionTxt.text = slot1:getResource(8) if slot0.faction ~= slot2:getFaction() then slot0.contributionBg.sprite = GetSpriteFromAtlas("ui/GuildMainUI_atlas", "res_" .. ((slot3 == GuildConst.FACTION_TYPE_BLHX and "blue") or "red")) slot0.captailBg.sprite = GetSpriteFromAtlas("ui/GuildMainUI_atlas", "res_" .. ((slot3 == GuildConst.FACTION_TYPE_BLHX and "blue") or "red")) slot0.faction = slot3 end end slot0.OnDestroy = function (slot0) return end return slot0
--- === cp.is === --- --- A simple class that lets you test if a value `is` a particular type. --- Note: for best performance, assign the specific checks you want to use to local functions. Eg: --- --- ```lua --- local is_nothing = require("cp.is").nothing --- is_nothing(nil) == true --- ``` --- --- You can also get functions that negate the functions below by calling `is.nt.XXX(...)` (read: "isn't XXX"). --- The individual functions are not documented, but all will work as expected. Eg: --- --- ```lua --- is.blank("") == true --- is.nt.blank("") == false --- ``` --- --- They can also be assigned directly to local values for better performance: --- --- ```lua --- local isnt_blank = is.nt.blank --- isnt_blank(nil) == false --- ``` local type = type --- cp.is.nothing(value) -> boolean --- Function --- Check if the value is `nil`. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_nothing(value) return value == nil end --- cp.is.something(value) -> boolean --- Function --- Check if the value is not `nil`. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_something(value) return value ~= nil end --- cp.is.string(value) -> boolean --- Function --- Check if the value is a string. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_string(value) return type(value) == "string" end --- cp.is.fn(value) -> boolean --- Function --- Check if the value is a `function`. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_fn(value) return type(value) == "function" end --- cp.is.number(value) -> boolean --- Function --- Check if the value is a `number`. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_number(value) return type(value) == "number" end --- cp.is.boolean(value) -> boolean --- Function --- Check if the value is a `function`. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_boolean(value) return type(value) == "boolean" end --- cp.is.table(value) -> boolean --- Function --- Check if the value is a `table`. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_table(value) return type(value) == "table" end --- cp.is.userdata(value) -> boolean --- Function --- Check if the value is a `userdata` object. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_userdata(value) return type(value) == "userdata" end --- cp.is.object(value) -> boolean --- Function --- Check if the value is a `object`. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_object(value) return is_table(value) or is_userdata(value) end --- cp.is.list(value) -> boolean --- Function --- Check if the value is a `list`. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_list(value) return is_object(value) and #value > 0 end --- cp.is.truthy(value) -> boolean --- Function --- Check if the value is a `truthy` value. --- A value is considered to be truthy if it is not `nil` nor `false`. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_truthy(value) return value ~= nil and value ~= false end --- cp.is.falsey(value) -> boolean --- Function --- Check if the value is a `falsey` value. --- A value is considered to be `falsey` if it is `nil` or `false`. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_falsey(value) return not is_truthy(value) end -- has_callable(value) -> boolean -- Private Function -- Checks if the value is a table with a `__call` function, or if its metatable (if present) has one. -- -- Parameters: -- * value - The value to check. -- -- Returns: -- * `true` if the value is a `table` and has a `__call` function or a metatable ancestor has one. local function has_callable(value, checked) if is_table(value) then checked = checked or {} checked[value] = true if is_fn(value.__call) then return true else local mt = getmetatable(value) if not checked[mt] then return has_callable(getmetatable(value), checked) end end end return false end --- cp.is.callable(value) -> boolean --- Function --- Check if the value is a callable - either a `function` or a `table` with `__call` in it's metatable hierarchy. --- --- Parameters: --- * value - the value to check --- --- Returns: --- * `true` if it matches, `false` if not. local function is_callable(value) return is_fn(value) or is_table(value) and has_callable(getmetatable(value)) end --- cp.is.blank(value) -> boolean --- Function --- Check if the value is a blank string value - either `nil` or `tostring(value) == ""`. --- --- Parameters: --- * value - the value to check. --- --- Returns: --- * `true` if it matches, `false` if not. local function is_blank(value) return value == nil or tostring(value) == "" end --- cp.is.instance(value, class) -> boolean --- Function --- Check if the value is an instance of the provided class `table`. It is considered --- an instance if the `class` is either the value itself, or is the `__index` or `__class` field --- of the `metatable`. --- --- Parameters: --- * value - the value to check --- * class - the class table to check --- --- Returns: --- * `true` if it is an instance. local function is_instance(value, class) if type(value) == "table" then if value == class then return true else local mt = getmetatable(value) if mt then return is_instance(mt.__index, class) or is_instance(mt.__class, class) end end end return false end local is = { nothing = is_nothing, something = is_something, string = is_string, fn = is_fn, number = is_number, boolean = is_boolean, table = is_table, userdata = is_userdata, instance = is_instance, object = is_object, list = is_list, truthy = is_truthy, falsey = is_falsey, falsy = is_falsey, callable = is_callable, blank = is_blank, } -- prepare `is.nt` local isnt = {} for k,fn in pairs(is) do isnt[k] = function(value) return not fn(value) end end is.nt = isnt return is
-- taken from https://forum.fivem.net/t/release-es-emotes/16669 emotes = {} emotes['cop'] = {name = 'cop', anim = 'WORLD_HUMAN_COP_IDLES'} emotes['binoculars'] = {name = 'binoculars', anim = 'WORLD_HUMAN_BINOCULARS'} emotes['cheer'] = {name = 'cheer', anim = 'WORLD_HUMAN_CHEERING'} emotes['drink'] = {name = 'drink', anim = 'WORLD_HUMAN_DRINKING'} emotes['smoke'] = {name = 'smoke', anim = 'WORLD_HUMAN_SMOKING'} emotes['film'] = {name = 'film', anim = 'WORLD_HUMAN_MOBILE_FILM_SHOCKING'} emotes['plant'] = {name = 'plant', anim = 'WORLD_HUMAN_GARDENER_PLANT'} emotes['guard'] = {name = 'guard', anim = 'WORLD_HUMAN_GUARD_STAND'} emotes['hammer'] = {name = 'hammer', anim = 'WORLD_HUMAN_HAMMERING'} emotes['hangout'] = {name = 'hangout', anim = 'WORLD_HUMAN_HANG_OUT_STREET'} emotes['hiker'] = {name = 'hiker', anim = 'WORLD_HUMAN_HIKER_STANDING'} emotes['statue'] = {name = 'statue', anim = 'WORLD_HUMAN_HUMAN_STATUE'} emotes['jog'] = {name = 'jog', anim = 'WORLD_HUMAN_JOG_STANDING'} emotes['lean'] = {name = 'lean', anim = 'WORLD_HUMAN_LEANING'} emotes['flex'] = {name = 'flex', anim = 'WORLD_HUMAN_MUSCLE_FLEX'} emotes['camera'] = {name = 'camera', anim = 'WORLD_HUMAN_PAPARAZZI'} emotes['sit'] = {name = 'sit', anim = 'WORLD_HUMAN_PICNIC'} emotes['sitchair'] = {name = 'sitchair', anim = 'PROP_HUMAN_SEAT_CHAIR_MP_PLAYER'} emotes['hoe'] = {name = 'hoe', anim = 'WORLD_HUMAN_PROSTITUTE_HIGH_CLASS'} emotes['hoe2'] = {name = 'hoe2', anim = 'WORLD_HUMAN_PROSTITUTE_LOW_CLASS'} emotes['pushups'] = {name = 'pushups', anim = 'WORLD_HUMAN_PUSH_UPS'} emotes['situps'] = {name = 'situps', anim = 'WORLD_HUMAN_SIT_UPS'} emotes['fish'] = {name = 'fish', anim = 'WORLD_HUMAN_STAND_FISHING'} emotes['impatient'] = {name = 'impatient', anim = 'WORLD_HUMAN_STAND_IMPATIENT'} emotes['mobile'] = {name = 'mobile', anim = 'WORLD_HUMAN_STAND_MOBILE'} emotes['diggit'] = {name = 'diggit', anim = 'WORLD_HUMAN_STRIP_WATCH_STAND'} emotes['sunbath'] = {name = 'sunbath', anim = 'WORLD_HUMAN_SUNBATHE_BACK'} emotes['sunbath2'] = {name = 'sunbath2', anim = 'WORLD_HUMAN_SUNBATHE'} emotes['weld'] = {name = 'weld', anim = 'WORLD_HUMAN_WELDING'} emotes['yoga'] = {name = 'yoga', anim = 'WORLD_HUMAN_YOGA'} emotes['kneel'] = {name = 'kneel', anim = 'CODE_HUMAN_MEDIC_KNEEL'} emotes['crowdcontrol'] = {name = 'crowdcontrol', anim = 'CODE_HUMAN_POLICE_CROWD_CONTROL'} emotes['investigate'] = {name = 'investigate', anim = 'CODE_HUMAN_POLICE_INVESTIGATE'} --[[ What this will look like after the code above is ran emotes = { "cop"= {name = 'cop', anim = 'WORLD_HUMAN_COP_IDLES'} ... } ]]
local CollectionService = game:GetService("CollectionService") local Modules = script.Parent.Parent.Parent local Dom = require(Modules.Anatta.Library.Dom) local Constants = require(Modules.Anatta.Library.Core.Constants) local ENTITY_ATTRIBUTE_NAME = Constants.EntityAttributeName local INSTANCE_REF_FOLDER = Constants.InstanceRefFolder local ComponentAnnotation = {} local function getAttributeMap(instance, definition) if definition.pluginType then definition = { name = definition.name, type = definition.pluginType } end local defaultSuccess, default = definition.type:tryDefault() if not defaultSuccess and not definition.type.typeName == "none" then return false, default end local attributeSuccess, attributeMap = Dom.tryToAttributes(instance, 0, definition, default) return attributeSuccess, attributeMap, default end function ComponentAnnotation.add(instance, definition) local success, attributeMap = getAttributeMap(instance, definition) if not success then return false, attributeMap end for attributeName, attributeValue in pairs(attributeMap) do if typeof(attributeValue) == "Instance" then attributeValue.Parent = workspace.Terrain attributeValue.Archivable = false instance[INSTANCE_REF_FOLDER][attributeName].Value = attributeValue elseif attributeName ~= ENTITY_ATTRIBUTE_NAME then instance:SetAttribute(attributeName, attributeValue) end end CollectionService:AddTag(instance, definition.name) return true end function ComponentAnnotation.remove(instance, definition) local success, attributeMap = getAttributeMap(instance, definition) if not success then return false, attributeMap end for attributeName, attributeValue in pairs(attributeMap) do if typeof(attributeValue) == "Instance" then local anattaRefs = instance:FindFirstChild(INSTANCE_REF_FOLDER) if anattaRefs then local objectValue = anattaRefs:FindFirstChild(attributeName) if objectValue then objectValue.Parent = nil end if not next(anattaRefs:GetChildren()) then anattaRefs.Parent = nil end end elseif attributeName ~= ENTITY_ATTRIBUTE_NAME then instance:SetAttribute(attributeName, nil) end end CollectionService:RemoveTag(instance, definition.name) return true end return ComponentAnnotation
function onCreate() -- background shit makeLuaSprite('sadbg', 'sadbg', -600, -300); setScrollFactor('sadbg', 0.9, 0.9); makeLuaSprite('sadbgfront', 'sadbgfront', -650, 600); setScrollFactor('sadbgfront', 0.9, 0.9); scaleObject('sadbgfront', 1.1, 1.1); addLuaSprite('sadbg', false); addLuaSprite('sadbgfront', false); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
shared = require "shared" require "scripts.use_equipment" local informatron = require "scripts.informatron" remote.add_interface(shared.name, { -- informatron implementation informatron_menu = function(data) return informatron.menu(data.player_index) end, informatron_page_content = function(data) return informatron.page_content(data.page_name, data.player_index, data.element) end, })
local menuThread = false local isUnicorn = false RMenu.Add("unicorn_dynamicmenu", "unicorn_dynamicmenu_main", RageUI.CreateMenu("Tablette Unicorn","Interactions possibles")) RMenu:Get("unicorn_dynamicmenu", "unicorn_dynamicmenu_main").Closed = function()end local menuOpen = false local function jobMenu() if menuThread then return end menuThread = true if not menuOpen then menuOpen = true Citizen.CreateThread(function() while isUnicorn do if IsControlJustPressed(1, 167) then RageUI.Visible(RMenu:Get("unicorn_dynamicmenu",'unicorn_dynamicmenu_main'), not RageUI.Visible(RMenu:Get("unicorn_dynamicmenu",'unicorn_dynamicmenu_main'))) end Citizen.Wait(1) end menuThread = false end) end end local function init() menuThread = false isUnicorn = true jobMenu() end local function jobChanged() if ESX.PlayerData.job.name == "unicorn" then isUnicorn = true jobMenu() else isUnicorn = false menuThread = false end end local function createBlip() local blip = AddBlipForCoord(130.77, -1302.67, 29.23) SetBlipSprite(blip, 121) SetBlipAsShortRange(blip, true) SetBlipColour(blip, 61) SetBlipScale(blip, 1.0) SetBlipCategory(blip, 12) BeginTextCommandSetBlipName("STRING") AddTextComponentString("Unicorn") EndTextCommandSetBlipName(blip) end local function spawnCar(car, ped) local hash = GetHashKey(car) local p = vector3(116.54, -1318.81, 28.98) Citizen.CreateThread(function() RequestModel(hash) while not HasModelLoaded(hash) do Citizen.Wait(10) end local vehicle = CreateVehicle(hash, p.x, p.y, p.z, 90.0, true, false) TaskWarpPedIntoVehicle(PlayerPedId(), vehicle, -1) end) end local function setUniform(ped,id) TriggerEvent('skinchanger:getSkin', function(skin) local uniformObject if skin.sex == 0 then uniformObject = pzCore.jobs[ESX.PlayerData.job.name].config.clothes[id].male else uniformObject = pzCore.jobs[ESX.PlayerData.job.name].config.clothes[id].female end if uniformObject then TriggerEvent('skinchanger:loadClothes', skin, uniformObject) else -- Rien end end) end local current = "unicorn" pzCore.jobs[current].init = init pzCore.jobs[current].jobChanged = jobChanged pzCore.jobs[current].spawnCar = spawnCar pzCore.jobs[current].setUniform = setUniform pzCore.jobs[current].hasBlip = true pzCore.jobs[current].createBlip = createBlip
local Physic = Component.create("Physic") function Physic:initialize(body, fixture, shape) self.body = body self.shape = shape self.fixture = fixture end
function OnStartTouch1(trigger) print("start") end function OnEndTouch1(trigger) print("end") end
--[[ Licensed under GNU General Public License v2 * (c) 2013, Luca CPZ --]] local helpers = require("lain.helpers") local wibox = require("wibox") local tonumber = tonumber -- {thermal} temperature info -- lain.widget.temp_ryzen local function factory(args) local temp = { widget = wibox.widget.textbox() } local args = args or {} local timeout = args.timeout or 30 local settings = args.settings or function() end function temp.update() helpers.async({"/home/box/bin/cputemp"}, function(f) coretemp_now = f or "N/A" widget = temp.widget settings() end) end helpers.newtimer("thermal", timeout, temp.update) return temp end return factory
local Class = require("facto.class") local Prototype = Class.create() function Prototype:clone() local class = getmetatable(self) return class() end local Chest = Class.extend({}, Prototype) function Chest:__constructor() self.name = "steel-chest" self.minable = true self.destructible = true self.inventory = { "wood", "coal", "iron" } end function Chest:__tostring() return string.format("Chest: name(%s), minable(%s), destructible(%s), %d items in inventory", self.name, tostring(self.minable), tostring(self.destructible), #self.inventory) end local Car = Class.extend({}, Prototype) function Car:__constructor() self.color = "white" self.speed = 10 self.inventory = { "ammo", "pistol" } end function Car:__tostring() return string.format("Car: color(%s), speed(%s), %d items in inventory", self.color, self.speed, #self.inventory) end local chest_prototype = Chest() local car_prototype = Car() local cloned_chest = chest_prototype:clone() local cloned_car = car_prototype:clone() print(cloned_chest) print(cloned_car) local PrototypeManager = Class.create() function PrototypeManager:__constructor() self.prototypes = {} self:setup() end function PrototypeManager:registerPrototype(prototype_name, class) if self.prototypes[prototype_name] == nil then self.prototypes[prototype_name] = class() end end function PrototypeManager:getPrototype(prototype_name) return self.prototypes[prototype_name] end function PrototypeManager:setup() self:registerPrototype("chest", Chest) self:registerPrototype("car", Car) end function PrototypeManager:clone(prototype_name) local prototype = self:getPrototype(prototype_name) if prototype == nil then error("Invalid prototype") end return prototype:clone() end local Pm = PrototypeManager() local car, chest = Pm:clone("car"), Pm:clone("chest") print(car, chest)
-- -*- Mode: lua; tab-width: 2; lua-indent-level: 2; indent-tabs-mode: nil; -*- ---------------------------------------------------------- -- Based on: https://www.openprocessing.org/sketch/152169 ---------------------------------------------------------- local utils = require "p5utils" local vector = require "hump.vector" local app = {} local width = love.graphics.getWidth() local height = love.graphics.getHeight() local twopi = math.pi * 2 -- config function app.liveconf(t) t.live = true t.use_pcall = true t.autoreload.enable = false t.autoreload.interval = 1.0 t.reloadkey = "f5" t.gc_before_reload = false t.error_file = nil -- "error.txt" end local g, bs, a g = .06 ------------- -- Body Class ------------- local Body = {} Body.__index = Body function Body:new(m, p) local mt = { m = m, p = p, q = p, s = vector.new(0, 0) } return setmetatable(mt, Body) end function Body:update() self.s = self.s * 0.98 self.p = self.p + self.s end function Body:attract(b) local d = utils.constrain((self.p - b.p):len(), 10, 100) local f = (b.p - self.p) * (b.m * self.m * g / (d * d)) local a = f / self.m self.s = self.s + a end function Body:show() love.graphics.line(self.p.x, self.p.y, self.q.y, self.q.x) q = p end -- callbacks function app.load() love.window.setMode(800, 600, {resizable=true}) app.reload() end function app.reload() bs = {} love.graphics.setBackgroundColor(0, 0, 0) for i = 1, 999 do bs[i] = Body:new(100, vector.new(math.random(width), math.random(height))) end -- reload by lovelive end function app.update(dt) end function app.draw() love.graphics.clear(love.graphics.getBackgroundColor()) love.graphics.setColor(255, 255, 250, 20) a = Body:new(1000, vector.new(math.random(width), math.random(height))) for b = 1, 999 do bs[b]:show() bs[b]:attract(a) bs[b]:update() end end return app
--夜尽心术 local m=14000537 local cm=_G["c"..m] cm.named_with_Nightend=1 function cm.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(m,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_REMOVE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMING_END_PHASE) e1:SetTarget(cm.target) e1:SetOperation(cm.activate) c:RegisterEffect(e1) end function cm.tfilter(c,e,tp) return c:IsCode(14000538) and c:IsCanBeSpecialSummoned(e,0,tp,true,false) end function cm.filter(c,e,tp) return c:IsFaceup() and c:IsRace(RACE_SPELLCASTER) and c:IsAttribute(ATTRIBUTE_DARK) and c:IsAbleToRemove() and Duel.IsExistingMatchingCard(cm.tfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp) and Duel.GetLocationCountFromEx(tp,tp,c)>0 end function cm.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE+LOCATION_GRAVE) and cm.filter(chkc,e,tp) end if chk==0 then return Duel.IsExistingTarget(cm.filter,tp,LOCATION_MZONE+LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectTarget(tp,cm.filter,tp,LOCATION_MZONE+LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0) end function cm.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if not tc:IsType(TYPE_MONSTER) or not tc:IsRelateToEffect(e) then return end if Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)==0 then return end if Duel.GetLocationCountFromEx(tp)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=Duel.SelectMatchingCard(tp,cm.tfilter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp) if sg:GetCount()>0 then Duel.BreakEffect() Duel.SpecialSummon(sg,0,tp,tp,true,false,POS_FACEUP) sg:GetFirst():CompleteProcedure() end end
/******************************************************************************\ Color support \******************************************************************************/ local Clamp = math.Clamp local floor = math.floor local function RGBClamp(r,g,b) return Clamp(r,0,255),Clamp(g,0,255),Clamp(b,0,255) end local function ColorClamp(c) c.r = Clamp(c.r,0,255) c.g = Clamp(c.g,0,255) c.b = Clamp(c.b,0,255) c.a = Clamp(c.a,0,255) return c end /******************************************************************************/ __e2setcost(2) e2function vector entity:getColor() if !IsValid(this) then return {0,0,0} end local c = this:GetColor() return { c.r, c.g, c.b } end e2function vector4 entity:getColor4() if not IsValid(this) then return {0,0,0,0} end local c = this:GetColor() return {c.r,c.g,c.b,c.a} end e2function number entity:getAlpha() return IsValid(this) and this:GetColor().a or 0 end e2function void entity:setColor(r,g,b) if !IsValid(this) then return end if !isOwner(self, this) then return end this:SetColor(ColorClamp(Color(r,g,b,this:GetColor().a))) end e2function void entity:setColor(r,g,b,a) if !IsValid(this) then return end if !isOwner(self, this) then return end this:SetColor(ColorClamp(Color(r, g, b, this:IsPlayer() and this:GetColor().a or a))) this:SetRenderMode(this:GetColor().a == 255 and RENDERMODE_NORMAL or RENDERMODE_TRANSALPHA) end e2function void entity:setColor(vector c) if !IsValid(this) then return end if !isOwner(self, this) then return end this:SetColor(ColorClamp(Color(c[1],c[2],c[3],this:GetColor().a))) end e2function void entity:setColor(vector c, a) if !IsValid(this) then return end if !isOwner(self, this) then return end this:SetColor(ColorClamp(Color(c[1],c[2],c[3], this:IsPlayer() and this:GetColor().a or a))) this:SetRenderMode(this:GetColor().a == 255 and RENDERMODE_NORMAL or RENDERMODE_TRANSALPHA) end e2function void entity:setColor(vector4 c) if !IsValid(this) then return end if !isOwner(self, this) then return end this:SetColor(ColorClamp(Color(c[1],c[2],c[3], this:IsPlayer() and this:GetColor().a or c[4]))) this:SetRenderMode(this:GetColor().a == 255 and RENDERMODE_NORMAL or RENDERMODE_TRANSALPHA) end e2function void entity:setAlpha(a) if !IsValid(this) then return end if !isOwner(self, this) then return end if this:IsPlayer() then return end local c = this:GetColor() c.a = Clamp(a, 0, 255) this:SetColor(c) this:SetRenderMode(c.a == 255 and RENDERMODE_NORMAL or RENDERMODE_TRANSALPHA) end e2function void entity:setRenderMode(mode) if !IsValid(this) then return end if !isOwner(self, this) then return end if this:IsPlayer() then return end this:SetRenderMode(mode) end --- HSV --- Converts <hsv> from the [http://en.wikipedia.org/wiki/HSV_color_space HSV color space] to the [http://en.wikipedia.org/wiki/RGB_color_space RGB color space] e2function vector hsv2rgb(vector hsv) local col = HSVToColor(hsv[1], hsv[2], hsv[3]) return { col.r, col.g, col.b } end e2function vector hsv2rgb(h, s, v) local col = HSVToColor(h, s, v) return { col.r, col.g, col.b } end --- Converts <rgb> from the [http://en.wikipedia.org/wiki/RGB_color_space RGB color space] to the [http://en.wikipedia.org/wiki/HSV_color_space HSV color space] e2function vector rgb2hsv(vector rgb) return { ColorToHSV(Color(rgb[1], rgb[2], rgb[3])) } end e2function vector rgb2hsv(r, g, b) return { ColorToHSV(Color(r, g, b)) } end --- HSL local function Convert_hue2rgb(p, q, t) if t < 0 then t = t + 1 end if t > 1 then t = t - 1 end if t < 1/6 then return p + (q - p) * 6 * t end if t < 1/2 then return q end if t < 2/3 then return p + (q - p) * (2/3 - t) * 6 end return p end local function Convert_hsl2rgb(h, s, l) local r = 0 local g = 0 local b = 0 if s == 0 then r = l g = l b = l else local q = l + s - l * s if l < 0.5 then q = l * (1 + s) end local p = 2 * l - q r = Convert_hue2rgb(p, q, h + 1/3) g = Convert_hue2rgb(p, q, h) b = Convert_hue2rgb(p, q, h - 1/3) end return floor(r * 255), floor(g * 255), floor(b * 255) end local function Convert_rgb2hsl(r, g, b) r = r / 255 g = g / 255 b = b / 255 local max = math.max(r, g, b) local min = math.min(r, g, b) local h = (max + min) / 2 local s = h local l = h if max == min then h = 0 s = 0 else local d = max - min s = d / (max + min) if l > 0.5 then s = d / (2 - max - min) end if max == r then if g < b then h = (g - b) / d + 6 else h = (g - b) / d + 0 end elseif max == g then h = (b - r) / d + 2 elseif max == b then h = (r - g) / d + 4 end h = h / 6 end return h, s, l end --- Converts <hsl> HSL color space to RGB color space e2function vector hsl2rgb(vector hsl) return { RGBClamp(Convert_hsl2rgb(hsl[1] / 360, hsl[2], hsl[3])) } end e2function vector hsl2rgb(h, s, l) return { RGBClamp(Convert_hsl2rgb(h / 360, s, l)) } end --- Converts <rgb> RGB color space to HSL color space e2function vector rgb2hsl(vector rgb) local h,s,l = Convert_rgb2hsl(RGBClamp(rgb[1], rgb[2], rgb[3])) return { floor(h * 360), s, l } end e2function vector rgb2hsl(r, g, b) local h,s,l = Convert_rgb2hsl(RGBClamp(r, g, b)) return { floor(h * 360), s, l } end --- DIGI local converters = {} converters[0] = function(r, g, b) local r = Clamp(floor(r/28),0,9) local g = Clamp(floor(g/28),0,9) local b = Clamp(floor(b/28),0,9) return r*100000+g*10000+b*1000 end converters[1] = false converters[2] = function(r, g, b) return floor(r)*65536+floor(g)*256+floor(b) end converters[3] = function(r, g, b) return floor(r)*1000000+floor(g)*1000+floor(b) end --- Converts an RGB vector <rgb> to a number in digital screen format. <mode> Specifies a mode, either 0, 2 or 3, corresponding to Digital Screen color modes. e2function number rgb2digi(vector rgb, mode) local conv = converters[mode] if not conv then return 0 end return conv(rgb[1], rgb[2], rgb[3]) end --- Converts the RGB color (<r>,<g>,<b>) to a number in digital screen format. <mode> Specifies a mode, either 0, 2 or 3, corresponding to Digital Screen color modes. e2function number rgb2digi(r, g, b, mode) local conv = converters[mode] if not conv then return 0 end return conv(r, g, b) end
-- Global Functions local funcs = {} local bufnum = -1 local nodeID = 999 local groupID = 1 local busIndex = 15 local osctypes = {int32=true,float=true} function parseArgsX(args,useint) local a = {} local numbertype = useint and "int32" or "float" if args ~= nil then for name,value in pairs(args) do table.insert(a,name) if type(value) ~= "table" then if type(value)=="number" then table.insert(a,{numbertype,value}) else table.insert(a,value) end else -- is table if type(value[1]) == "string" then if osctypes[value[1]] then assert(#value == 2) table.insert(a,value) else table.insert(a,{"["}) for i,val in ipairs(value) do table.insert(a,val) end table.insert(a,{"]"}) end else table.insert(a,{"["}) for i,val in ipairs(value) do table.insert(a,{numbertype,val}) end table.insert(a,{"]"}) end end end -- for arg, val in pairs(args) do -- table.insert(a, arg) -- table.insert(a, val) -- end end return a end function nextBufNum() bufnum = bufnum + 1 return bufnum end nextBufNum = GetBuffNum or nextBufNum function nextNodeID() nodeID = nodeID + 1 return nodeID end nextNodeID = GetNode or nextNodeID function nextGroupID() groupID = groupID + 1 return groupID end nextGroupID = GetNode or nextGroupID return funcs
------------------------------------------------------------------------------ -- FILE: Lekmapv2.2.lua (Modified Pangaea_Plus.lua) -- AUTHOR: Original Bob Thomas, Changes HellBlazer, lek10, EnormousApplePie, Cirra, Meota -- PURPOSE: Global map script - Simulates a Pan-Earth Supercontinent, with -- numerous tectonic island chains. ------------------------------------------------------------------------------ -- Copyright (c) 2011 Firaxis Games, Inc. All rights reserved. ------------------------------------------------------------------------------ include("HBMapGenerator"); include("FractalWorld"); include("HBFeatureGenerator"); include("HBTerrainGenerator"); include("IslandMaker"); include("MultilayeredFractal"); ------------------------------------------------------------------------------ function GetMapScriptInfo() local world_age, temperature, rainfall, sea_level, resources = GetCoreMapOptions() return { Name = "Lekmap: Small Continents (v3.2)", Description = "A map script made for Lekmod based of HB's Mapscript v8.1. Small Continents", IsAdvancedMap = false, IconIndex = 1, SortIndex = 2, SupportsMultiplayer = true, CustomOptions = { { Name = "TXT_KEY_MAP_OPTION_WORLD_AGE", -- 1 Values = { "TXT_KEY_MAP_OPTION_THREE_BILLION_YEARS", "TXT_KEY_MAP_OPTION_FOUR_BILLION_YEARS", "TXT_KEY_MAP_OPTION_FIVE_BILLION_YEARS", "No Mountains", "TXT_KEY_MAP_OPTION_RANDOM", }, DefaultValue = 2, SortPriority = -99, }, { Name = "TXT_KEY_MAP_OPTION_TEMPERATURE", -- 2 add temperature defaults to random Values = { "TXT_KEY_MAP_OPTION_COOL", "TXT_KEY_MAP_OPTION_TEMPERATE", "TXT_KEY_MAP_OPTION_HOT", "TXT_KEY_MAP_OPTION_RANDOM", }, DefaultValue = 2, SortPriority = -98, }, { Name = "TXT_KEY_MAP_OPTION_RAINFALL", -- 3 add rainfall defaults to random Values = { "TXT_KEY_MAP_OPTION_ARID", "TXT_KEY_MAP_OPTION_NORMAL", "TXT_KEY_MAP_OPTION_WET", "TXT_KEY_MAP_OPTION_RANDOM", }, DefaultValue = 2, SortPriority = -97, }, { Name = "TXT_KEY_MAP_OPTION_SEA_LEVEL", -- 4 add sea level defaults to random. Values = { "TXT_KEY_MAP_OPTION_LOW", "TXT_KEY_MAP_OPTION_MEDIUM", "TXT_KEY_MAP_OPTION_HIGH", "TXT_KEY_MAP_OPTION_RANDOM", }, DefaultValue = 2, SortPriority = -96, }, { Name = "Start Quality", -- 5 add resources defaults to random Values = { "Legendary Start - Strat Balance", "Legendary - Strat Balance + Uranium", "TXT_KEY_MAP_OPTION_STRATEGIC_BALANCE", "Strategic Balance With Coal", "Strategic Balance With Aluminum", "Strategic Balance With Coal & Aluminum", "TXT_KEY_MAP_OPTION_RANDOM", }, DefaultValue = 2, SortPriority = -95, }, { Name = "Start Distance", -- 6 add resources defaults to random Values = { "Close", "Normal", "Far - Warning: May sometimes crash during map generation", }, DefaultValue = 2, SortPriority = -94, }, { Name = "Natural Wonders", -- 7 number of natural wonders to spawn Values = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "Random", "Default", }, DefaultValue = 15, SortPriority = -93, }, { Name = "Grass Moisture", -- add setting for grassland mositure (8) Values = { "Wet", "Normal", "Dry", }, DefaultValue = 2, SortPriority = -92, }, { Name = "Rivers", -- add setting for rivers (9) Values = { "Sparse", "Average", "Plentiful", }, DefaultValue = 2, SortPriority = -91, }, { Name = "Tundra", -- add setting for tundra (10) Values = { "Sparse", "Average", "Plentiful", }, DefaultValue = 2, SortPriority = -90, }, { Name = "Land Size X", -- add setting for land type (11) +28 Values = { "30", "32", "34", "36", "38", "40", "42", "44", "46", "48", "50", "52", "54", "56", "58", "60", "62", "64", "66", "68", "70", "72", "74", "76", "78", "80", "82", "84", "86", "88", "90", "92", "94", "96", "98", "100", "102", "104", "106", "108", "110", }, DefaultValue = 17, SortPriority = -89, }, { Name = "Land Size Y", -- add setting for land type (12) +18 Values = { "20", "22", "24", "26", "28", "30", "32", "34", "36", "38", "40", "42", "44", "46", "48", "50", "52", "54", "56", "58", "60", "62", "64", "66", "68", "70", "72", "74", "76", }, DefaultValue = 16, SortPriority = -88, }, { Name = "TXT_KEY_MAP_OPTION_RESOURCES", -- add setting for resources (13) Values = { "1 -- Nearly Nothing", "2", "3", "4", "5 -- Default", "6", "7", "8", "9", "10 -- Almost no normal tiles left", }, DefaultValue = 5, SortPriority = -87, }, }, }; end ------------------------------------------------------------------------------ function GetMapInitData(worldSize) local LandSizeX = 28 + (Map.GetCustomOption(11) * 2); local LandSizeY = 18 + (Map.GetCustomOption(12) * 2); local worldsizes = {}; worldsizes = { [GameInfo.Worlds.WORLDSIZE_DUEL.ID] = {LandSizeX, LandSizeY}, -- 720 [GameInfo.Worlds.WORLDSIZE_TINY.ID] = {LandSizeX, LandSizeY}, -- 1664 [GameInfo.Worlds.WORLDSIZE_SMALL.ID] = {LandSizeX, LandSizeY}, -- 2480 [GameInfo.Worlds.WORLDSIZE_STANDARD.ID] = {LandSizeX, LandSizeY}, -- 3900 [GameInfo.Worlds.WORLDSIZE_LARGE.ID] = {LandSizeX, LandSizeY}, -- 6076 [GameInfo.Worlds.WORLDSIZE_HUGE.ID] = {LandSizeX, LandSizeY} -- 9424 } local grid_size = worldsizes[worldSize]; -- local world = GameInfo.Worlds[worldSize]; if (world ~= nil) then return { Width = grid_size[1], Height = grid_size[2], WrapX = true, }; end end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ function GeneratePlotTypes() print("Generating Plot Types (Lua Small Continents) ..."); -- Fetch Sea Level and World Age user selections. local sea = Map.GetCustomOption(4) if sea == 4 then sea = 1 + Map.Rand(3, "Random Sea Level - Lua"); end local age = Map.GetCustomOption(1) if age == 4 then age = 1 + Map.Rand(3, "Random World Age - Lua"); end local fractal_world = FractalWorld.Create(); fractal_world:InitFractal{ continent_grain = 3}; local args = { sea_level = sea, world_age = age, sea_level_low = 69, sea_level_normal = 75, sea_level_high = 80, extra_mountains = 10, adjust_plates = 1.5, tectonic_islands = true } local plotTypes = fractal_world:GeneratePlotTypes(args); SetPlotTypes(plotTypes); local args = {expansion_diceroll_table = {10, 4, 4}}; GenerateCoasts(args); end ------------------------------------------------------------------------------ function GenerateTerrain() local DesertPercent = 28; -- Get Temperature setting input by user. local temp = Map.GetCustomOption(2) if temp == 4 then temp = 1 + Map.Rand(3, "Random Temperature - Lua"); end local grassMoist = Map.GetCustomOption(8); local args = { temperature = temp, iDesertPercent = DesertPercent, iGrassMoist = grassMoist, }; local terraingen = TerrainGenerator.Create(args); terrainTypes = terraingen:GenerateTerrain(); SetTerrainTypes(terrainTypes); end ------------------------------------------------------------------------------ function AddFeatures() -- Get Rainfall setting input by user. local rain = Map.GetCustomOption(3) if rain == 4 then rain = 1 + Map.Rand(3, "Random Rainfall - Lua"); end local args = {rainfall = rain} local featuregen = FeatureGenerator.Create(args); -- False parameter removes mountains from coastlines. featuregen:AddFeatures(false); end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ function StartPlotSystem() local RegionalMethod = 2; -- Get Resources setting input by user. local res = Map.GetCustomOption(13) local starts = Map.GetCustomOption(5) --if starts == 7 then --starts = 1 + Map.Rand(8, "Random Resources Option - Lua"); --end -- Handle coastal spawns and start bias MixedBias = false; BalancedCoastal = false; OnlyCoastal = false; CoastLux = false; print("Creating start plot database."); local start_plot_database = AssignStartingPlots.Create() print("Dividing the map in to Regions."); -- Regional Division Method 1: Biggest Landmass local args = { method = RegionalMethod, start_locations = starts, resources = res, CoastLux = CoastLux, NoCoastInland = OnlyCoastal, BalancedCoastal = BalancedCoastal, MixedBias = MixedBias; }; start_plot_database:GenerateRegions(args) print("Choosing start locations for civilizations."); start_plot_database:ChooseLocations() print("Normalizing start locations and assigning them to Players."); start_plot_database:BalanceAndAssign(args) print("Placing Natural Wonders."); local wonders = Map.GetCustomOption(7) if wonders == 14 then wonders = Map.Rand(13, "Number of Wonders To Spawn - Lua"); else wonders = wonders - 1; end print("########## Wonders ##########"); print("Natural Wonders To Place: ", wonders); local wonderargs = { wonderamt = wonders, }; start_plot_database:PlaceNaturalWonders(wonderargs); print("Placing Resources and City States."); start_plot_database:PlaceResourcesAndCityStates() -- tell the AI that we should treat this as a naval expansion map Map.ChangeAIMapHint(4); end ------------------------------------------------------------------------------
-------------------------------------------------------------------------------- local class = require "lib.middleclass" local GenericCalculator = require "app.calculators.generic_calculator" -------------------------------------------------------------------------------- local Calculator = class("Calculator", GenericCalculator) Calculator.required_inputs = { "f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12" } -------------------------------------------------------------------------------- -- Vypocet (dle dodanych podkladu) -------------------------------------------------------------------------------- -- Snahou je vypocet prevest tak, aby byl co nejpodobnejsi dodanym podkladum -- -- Pole "body" a "vypoctene" odpovida dodanym podkladum (s tim rozdilem, -- ze prvni prvek ma v Lua index 1, ne 0). -- -- V promenne inp jsou ulozene zvalidovane a jiz na cisla prevedene vstupy. -------------------------------------------------------------------------------- function Calculator:compute() local inp = self.inputs local body = {} local vypoctene = {} vypoctene[1] = (inp.f01 + inp.f02) / 2 body[1] = vypoctene[1] * 0.5 vypoctene[2] = inp.f03 body[2] = vypoctene[2] * 0.1 vypoctene[3] = inp.f04 body[3] = vypoctene[3] * 0.3 vypoctene[4] = inp.f05 / vypoctene[1] if vypoctene[4] <= 0.3 or vypoctene[4] > 0.75 then body[4] = 0 elseif vypoctene[4] > 0.3 and vypoctene[4] <= 0.35 then body[4] = 1 elseif vypoctene[4] > 0.35 and vypoctene[4] <= 0.4 then body[4] = 2 elseif vypoctene[4] > 0.4 and vypoctene[4] <= 0.45 then body[4] = 3 elseif vypoctene[4] > 0.45 and vypoctene[4] <= 0.75 then body[4] = 4 end vypoctene[5] = inp.f06 body[5] = vypoctene[5] vypoctene[6] = inp.f07 body[6] = vypoctene[6] vypoctene[7] = inp.f08 body[7] = vypoctene[7] vypoctene[8] = inp.f09 body[8] = vypoctene[8] vypoctene[9] = inp.f10 body[9] = vypoctene[9] vypoctene[10] = inp.f11 body[10] = vypoctene[10] vypoctene[11] = inp.f12 body[11] = vypoctene[11] self.kladne = 0 for i = 1, 10 do self.kladne = self.kladne + body[i] end self.zaporne = body[11] self.soucet = self.kladne - self.zaporne if self.soucet < 105 then self.medal = "none" elseif self.soucet < 115 then self.medal = "bronze" elseif self.soucet < 130 then self.medal = "silver" else self.medal = "gold" end self.vypoctene = vypoctene self.body = body end return Calculator
impulse.string = impulse.string or {} local strSub = string.sub local strLen = string.len local mathCeil = math.ceil local tblInsert = table.insert local tblConcat = table.concat -- Explode a string with multiple separators function impulse.string.Explode( seperators, str ) local p = "[^"..tblConcat(seperators).."]+" local words = {} for w in str:gmatch(p) do tblInsert(words, w) end return words end if CLIENT then local setFont = surface.SetFont local getTextSize = surface.GetTextSize local strSub = string.sub local strLen = string.len local mathCeil = math.ceil local tblInsert = table.insert local tblConcat = table.concat local DOTS = "..." -- Breaks text into lines function impulse.string.WrapText( text, font, wLimit, dotLimit ) local lines = {} local index = 1 -- Return line with an added word without modify the line local function testLine(word) local line = lines[index] if ( line ) then return line.." "..word else return word end end -- Update line local function setLine(line) lines[index] = line end -- Add a new line to work on it local function lineBreak() index = index + 1 end -- dotLimit represents the max word size to do a dotted line ( half the line width limit by default ) dotLimit = dotLimit or mathCeil(wLimit * 0.65) local function processWord(w) local tLine = testLine(w) if ( getTextSize(tLine) < wLimit ) then -- If tested line size is lower than the line width limit then append the word setLine(tLine) else -- If tested line size is higher than the line width limit then : local wordSize = getTextSize(w) if ( wordSize < dotLimit ) then -- If the word size is lower than the dot limit then add the word in a new line lineBreak() setLine(w) else -- If the word size is higher than the dot limit then set word dotted and finish it in a new line local wordLen = strLen(w) for i = wordLen, 1, -1 do local oldLinePart = strSub( w, 1, i )..DOTS local tLine = testLine( oldLinePart ) if ( getTextSize(tLine) < wLimit ) then setLine(tLine) local newLinePart = strSub( w, i + 1, wordLen ) lineBreak() processWord(newLinePart) break elseif (i == 1) then lineBreak() processWord(w) end end end end end -- Store words from text in a table local words = impulse.string.Explode( {" ", "\n"}, text ) surface.SetFont(font) for k, w in pairs( words ) do processWord(w) end return lines end end
-- Copyright (c) 2019 teverse.com -- main.lua return function(workshop) local controllers = { selection = require("tevgit:create/controllers/select.lua"), theme = require("tevgit:create/controllers/theme.lua"), ui = require("tevgit:create/controllers/ui.lua"), camera = require("tevgit:create/controllers/camera.lua"), console = require("tevgit:create/controllers/console.lua"), tool = require("tevgit:create/controllers/tool.lua"), env = require("tevgit:create/controllers/environment.lua") } controllers.ui.createMainInterface(workshop) controllers.console.createConsole() local tools = { add = require("tevgit:create/tools/add.lua"), select = require("tevgit:create/tools/select.lua"), move = require("tevgit:create/tools/move.lua"), scale = require("tevgit:create/tools/scale.lua"), rotate = require("tevgit:create/tools/rotate.lua") } -- create default environment controllers.env.setDefault() controllers.env.createStarterMap() -- Starter map, or the enviroment, may be overriden by teverse if the user is opening an existing .tev file. wait(2) controllers.ui.setLoading(false) end
//DAK loader/Base Config DAK.adminsettings = { groups = { }, users = { } } DAK.serveradmincommands = { } DAK.serveradmincommandsfunctions = { } DAK.serveradmincommandshooks = { } local ServerAdminFileName = "config://ServerAdmin.json" local ServerAdminWebFileName = "config://ServerAdminWeb.json" local ServerAdminWebCache = nil local lastwebupdate = 0 local function LoadServerAdminSettings() local defaultConfig = { groups = { admin_group = { type = "disallowed", commands = { }, level = 10 }, mod_group = { type = "allowed", commands = { "sv_reset", "sv_kick" }, level = 5 } }, users = { NsPlayer = { id = 10000001, groups = { "admin_group" }, level = 2 } } } DAK:WriteDefaultConfigFile(ServerAdminFileName, defaultConfig) DAK.adminsettings = DAK:LoadConfigFile(ServerAdminFileName) or defaultConfig assert(DAK.adminsettings.groups, "groups must be defined in " .. ServerAdminFileName) assert(DAK.adminsettings.users, "users must be defined in " .. ServerAdminFileName) end LoadServerAdminSettings() local function LoadServerAdminWebSettings() ServerAdminWebCache = DAK:LoadConfigFile(ServerAdminWebFileName) or { } end local function SaveServerAdminWebSettings(users) DAK:SaveConfigFile(ServerAdminWebFileName, users) ServerAdminWebCache = users end local function tablemerge(tab1, tab2) if tab2 ~= nil then for k, v in pairs(tab2) do if (type(v) == "table") and (type(tab1[k] or false) == "table") then tablemerge(tab1[k], tab2[k]) else tab1[k] = v end end end return tab1 end local function ProcessAdminsWebResponse(response) local sstart = string.find(response,"<body>") if type(sstart) == "number" then local rstring = string.sub(response, sstart) if rstring then rstring = rstring:gsub("<body>\n", "{") rstring = rstring:gsub("<body>", "{") rstring = rstring:gsub("</body>", "}") rstring = rstring:gsub("<div id=\"username\"> ", "\"") rstring = rstring:gsub(" </div> <div id=\"steamid\"> ", "\": { \"id\": ") rstring = rstring:gsub(" </div> <div id=\"group\"> ", ", \"groups\": [ \"") rstring = rstring:gsub("\\,", "\", \"") rstring = rstring:gsub(" </div> <br>", "\" ] },") rstring = rstring:gsub("\n", "") return json.decode(rstring) end end return nil end local function OnServerAdminWebResponse(response) if response then local addusers = ProcessAdminsWebResponse(response) if addusers and ServerAdminWebCache ~= addusers then //If loading from file, that wont update so its not an issue. However web queries are realtime so admin abilities can expire mid game and/or be revoked. Going to have this reload and //purge old list, will insure greater accuracy (still has a couple loose ends). Considering also adding a periodic check, or a check on command exec (still wouldnt be perfect), this seems good for now. LoadServerAdminSettings() DAK.adminsettings.users = tablemerge(DAK.adminsettings.users, addusers) SaveServerAdminWebSettings(addusers) end end end local function QueryForAdminList() if DAK.config.serveradmin.QueryURL ~= "" then Shared.SendHTTPRequest(DAK.config.serveradmin.QueryURL, "GET", OnServerAdminWebResponse) end end local function OnServerAdminClientConnect(client) local tt = Shared.GetTime() if tt > DAK.config.serveradmin.MapChangeDelay and (lastwebupdate == nil or (lastwebupdate + DAK.config.serveradmin.UpdateDelay) < tt) then QueryForAdminList() lastwebupdate = tt end end DAK:RegisterEventHook("OnClientConnect", OnServerAdminClientConnect, 5, "serveradminusers") local function CheckServerAdminQueries() if DAK.config.serveradmin.QueryURL ~= "" and ServerAdminWebCache == nil then Shared.Message("ServerAdmin WebQuery failed, falling back on cached list.") DAK.adminsettings.users = tablemerge(DAK.adminsettings.users, LoadServerAdminWebSettings()) end return false end local function UpdateClientConnectionTime() if DAK.settings.connectedclients == nil then DAK.settings.connectedclients = { } end for id, conntime in pairs(DAK.settings.connectedclients) do if DAK:GetClientMatchingNS2Id(tonumber(id)) == nil then DAK.settings.connectedclients[id] = nil end end DAK:SaveSettings() return false end local function DelayedServerCommandRegistration() QueryForAdminList() DAK:SetupTimedCallBack(CheckServerAdminQueries, DAK.config.serveradmin.QueryTimeout) DAK:SetupTimedCallBack(UpdateClientConnectionTime, DAK.config.serveradmin.ReconnectTime) end DAK:RegisterEventHook("OnPluginInitialized", DelayedServerCommandRegistration, 5, "serveradminusers") local kMaxPrintLength = 128 local kServerAdminMessage = { message = string.format("string (%d)", kMaxPrintLength), } Shared.RegisterNetworkMessage("ServerAdminPrint", kServerAdminMessage) function ServerAdminPrint(client, message) if client then // First we must split up the message into a list of messages no bigger than kMaxPrintLength each. local messageList = { } while string.len(message) > kMaxPrintLength do local messagePart = string.sub(message, 0, kMaxPrintLength) table.insert(messageList, messagePart) message = string.sub(message, kMaxPrintLength + 1) end table.insert(messageList, message) for m = 1, #messageList do Server.SendNetworkMessage(client:GetControllingPlayer(), "ServerAdminPrint", { message = messageList[m] }, true) end else Shared.Message(message) end end //Block Default ServerAdmin load DAK:OverrideScriptLoad("lua/ServerAdmin.lua")
--[[ Copyright 2012-2020 João Cardoso PetTracker is distributed under the terms of the GNU General Public License (Version 3). As a special exception, the copyright holders of this addon do not give permission to redistribute and/or modify it. This addon is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the addon. If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>. This file is part of PetTracker. --]] local MODULE = ... local ADDON, Addon = MODULE:match('[^_]+'), _G[MODULE:match('[^_]+')] local Battle = Addon.Pet:NewClass('Battle') --[[ Static ]]-- function Battle:AnyUpgrade() for i = 1, self:NumPets(LE_BATTLE_PET_ENEMY) do local pet = self(LE_BATTLE_PET_ENEMY, i) if pet:IsUpgrade() then return true end end end function Battle:GetRival() if self:IsPvE() then local specie1 = self(LE_BATTLE_PET_ENEMY, 1):GetSpecie() local specie2 = self(LE_BATTLE_PET_ENEMY, 2):GetSpecie() local specie3 = self(LE_BATTLE_PET_ENEMY, 3):GetSpecie() for id, rival in pairs(Addon.RivalInfo) do local first = tonumber(rival:match('^[^:]+:[^:]+:[^:]*:[^:]+:%w%w%w%w(%w%w%w)'), 36) if first == specie1 or first == specie2 or first == specie3 then return id end end end end function Battle:IsPvE() return C_PetBattles.IsPlayerNPC(LE_BATTLE_PET_ENEMY) end function Battle:NumPets(owner) return C_PetBattles.GetNumPets(owner) end function Battle:New(owner, index) return self:Bind{owner = owner, index = index or C_PetBattles.GetActivePet(owner)} end --[[ Instance ]]-- function Battle:IsUpgrade() if self:IsWildBattle() and not self:IsAlly() then if self:GetSpecie() and self:GetSource() == 5 then local _, quality, level = self:GetBestOwned() if self:GetQuality() > quality then return true elseif self:GetQuality() == quality then if level > 20 then level = level + 2 elseif level > 15 then level = level + 1 end return self:GetLevel() > level end end end return false end function Battle:CanSwap() return self:IsAlly() and C_PetBattles.CanPetSwapIn(self.index) end function Battle:IsAlly() return self.owner ~= LE_BATTLE_PET_ENEMY end function Battle:IsAlive() return self:GetHealth() > 0 end function Battle:Exists() return self:NumPets(self.owner) >= self.index end --[[ Overrides ]]-- function Battle:GetAbility(i) local abilities, levels = self:GetAbilities() if self:IsAlly() or self:IsPvE() then if i < 4 then local usable, cooldown = self:GetAbilityState(i) local requisite = not (cooldown or usable) and levels[i] local id = self:GetAbilityInfo(i) or abilities[i] return Addon.Ability(id, self, cooldown, requisite, true) end else local k = i % 3 local casts = Addon.state.casts[self.index] if not casts.id[k] and self:GetLevel() >= max(levels[i], levels[i+3] or 0) then return Addon.Ability(abilities[i], self) end if i < 4 then local id = casts.id[k] or abilities[i] local cooldown = select(4, C_PetBattles.GetAbilityInfoByID(id)) or 0 local requisite = self:GetLevel() < levels[i] and levels[i] local remaining = casts.turn[k] and (cooldown + casts.turn[k] - Addon.state.turn) or 0 return Addon.Ability(id, self, remaining, requisite, true) end end end function Battle:GetStats() local speedScale = self:GetStateValue(25) local healthScale = self:GetStateValue(99) local healthBonus = self:GetStateValue(2) if speedScale and healthScale and healthBonus then speedScale = 100/(speedScale+100) healthScale = 100/(healthScale+100) local isWild = self:IsWildBattle() and not self:IsAlly() local healthNerf = isWild and 1.2 or 1 local powerNerf = isWild and 1.25 or 1 return floor((self:GetMaxHealth() * healthScale - healthBonus) * healthNerf + .5), floor(self:GetPower() * powerNerf + .5), floor(self:GetSpeed() * speedScale + .5) end end function Battle:GetSpecie() return self:GetPetSpeciesID() end function Battle:GetModel() return self:GetDisplayID() end function Battle:GetQuality() return self:GetBreedQuality() end function Battle:GetType() return self:GetPetType() end for k,v in pairs(C_PetBattles) do Battle[k] = rawget(Battle, k) or function(self, ...) return C_PetBattles[k](self.owner, self.index, ...) end end
----------------------------------------- -- ID: 17588 -- Treat staff II -- Transports the user to their Home Point ----------------------------------------- function onItemCheck(target) return 0 end function onItemUse(target) target:warp() end
local severities = { error = vim.lsp.protocol.DiagnosticSeverity.Error; warning = vim.lsp.protocol.DiagnosticSeverity.Warning; refactor = vim.lsp.protocol.DiagnosticSeverity.Information; convention = vim.lsp.protocol.DiagnosticSeverity.Hint; } return { cmd = 'pylint'; stdin = true; args = { '--from-stdin'; '-f', 'json'; '-j', '0'; '--exit-zero'; vim.api.nvim_buf_get_name(0) }; parser = function(output) local decoded = vim.fn.json_decode(output) local diagnostics = {} for _, item in ipairs(decoded or {}) do local column = 0 if item.column > 0 then column = item.column - 1 end table.insert(diagnostics, { range = { ['start'] = { line = item.line - 1; character = column; }; ['end'] = { line = item.line - 1; character = column; }; }; severity = assert(severities[item.type], 'missing mapping for severity ' .. item.type); message = item.message; }) end return diagnostics end; }
local function _error_if_not_number (a) if type(a) ~= "number" then SU.error("We tried to do impossible arithmetic on a " .. SU.type(a) .. ". (That's a bug)", true) end end return pl.class({ type = "length", length = nil, stretch = nil, shrink = nil, _init = function (self, spec, stretch, shrink) if stretch or shrink then self.length = SILE.measurement(spec or 0) self.stretch = SILE.measurement(stretch or 0) self.shrink = SILE.measurement(shrink or 0) elseif type(spec) == "number" then self.length = SILE.measurement(spec) elseif SU.type(spec) == "measurement" then self.length = spec elseif SU.type(spec) == "glue" then self.length = SILE.measurement(spec.width.length or 0) self.stretch = SILE.measurement(spec.width.stretch or 0) self.shrink = SILE.measurement(spec.width.shrink or 0) elseif type(spec) == "table" then self.length = SILE.measurement(spec.length or 0) self.stretch = SILE.measurement(spec.stretch or 0) self.shrink = SILE.measurement(spec.shrink or 0) elseif type(spec) == "string" then local amount = tonumber(spec) if type(amount) == "number" then self:_init(amount) else local parsed = SILE.parserBits.length:match(spec) if not parsed then SU.error("Could not parse length '"..spec.."'") end self:_init(parsed) end end if not self.length then self.length = SILE.measurement() end if not self.stretch then self.stretch = SILE.measurement() end if not self.shrink then self.shrink = SILE.measurement() end end, absolute = function (self) return SILE.length(self.length:tonumber(), self.stretch:tonumber(), self.shrink:tonumber()) end, negate = function (self) return self:__unm() end, tostring = function (self) return self:__tostring() end, tonumber = function (self) return self.length:tonumber() end, new = function (spec) SU.deprecated("SILE.length.new", "SILE.length", "0.10.0") return SILE.length(spec) end, make = function (spec) SU.deprecated("SILE.length.make", "SILE.length", "0.10.0") return SILE.length(spec) end, parse = function (spec) SU.deprecated("SILE.length.parse", "SILE.length", "0.10.0") return SILE.length(spec) end, fromLengthOrNumber = function (_, spec) SU.deprecated("SILE.length.fromLengthOrNumber", "SILE.length", "0.10.0") return SILE.length(spec) end, __index = function (_, key) -- luacheck: ignore SU.deprecated("SILE.length." .. key, "SILE.length", "0.10.0") return SILE.length() end, __tostring = function (self) local str = tostring(self.length) if self.stretch.amount ~= 0 then str = str .. " plus " .. self.stretch end if self.shrink.amount ~= 0 then str = str .. " minus " .. self.shrink end return str end, __add = function (self, other) if type(self) == "number" then self, other = other, self end other = SU.cast("length", other) return SILE.length(self.length + other.length, self.stretch + other.stretch, self.shrink + other.shrink) end, -- See usage comments on SILE.measurement:___add() ___add = function (self, other) if SU.type(other) ~= "length" then self.length:___add(other) else self.length:___add(other.length) self.stretch:___add(other.stretch) self.shrink:___add(other.shrink) end return nil end, __sub = function (self, other) local result = SILE.length(self) other = SU.cast("length", other) result.length = result.length - other.length result.stretch = result.stretch - other.stretch result.shrink = result.shrink - other.shrink return result end, -- See usage comments on SILE.measurement:___add() ___sub = function (self, other) self.length:___sub(other.length) self.stretch:___sub(other.stretch) self.shrink:___sub(other.shrink) return nil end, __mul = function (self, other) if type(self) == "number" then self, other = other, self end _error_if_not_number(other) local result = SILE.length(self) result.length = result.length * other result.stretch = result.stretch * other result.shrink = result.shrink * other return result end, __div = function (self, other) local result = SILE.length(self) _error_if_not_number(other) result.length = result.length / other result.stretch = result.stretch / other result.shrink = result.shrink / other return result end, __unm = function (self) local result = SILE.length(self) result.length = result.length:__unm() return result end, __lt = function (self, other) local a = SU.cast("number", self) local b = SU.cast("number", other) return a - b < 0 end, __le = function (self, other) local a = SU.cast("number", self) local b = SU.cast("number", other) return a - b <= 0 end, __eq = function (self, other) local a = SU.cast("length", self) local b = SU.cast("length", other) return a.length == b.length and a.stretch == b.stretch and a.shrink == b.shrink end })
local jobs = {} local n_jobs = tonumber(ARGV[1]) local n = 0 repeat local job = redis.call('RPOPLPUSH', KEYS[1], KEYS[2]) if job then n = n + 1 table.insert(jobs, job) else break end until n == n_jobs return jobs
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() math.randomseed(CurTime()) self.Entity:SetModel("models/weltensturm/wac/rockets/rocket01.mdl") self.Entity:PhysicsInit(SOLID_VPHYSICS) self.Entity:SetMoveType(MOVETYPE_VPHYSICS) self.Entity:SetSolid(SOLID_VPHYSICS) self.phys = self.Entity:GetPhysicsObject() if (self.phys:IsValid()) then self.phys:SetMass(400) self.phys:EnableGravity(false) self.phys:EnableCollisions(true) self.phys:EnableDrag(false) self.phys:Wake() end self.sound = CreateSound(self.Entity, "WAC/rocket_idle.wav") self.matType = MAT_DIRT self.hitAngle = Angle(270, 0, 0) end function ENT:Explode(tr) if self.Exploded then return end self.Exploded = true util.BlastDamage(self, self.Owner or self, self:GetPos(), self.Radius, self.Damage) local explode = ents.Create("env_physexplosion") explode:SetPos(self:GetPos()) explode:Spawn() explode:SetKeyValue("magnitude", self.Damage) explode:SetKeyValue("radius", self.Radius*0.75) explode:SetKeyValue("spawnflags","19") explode:Fire("Explode", 0, 0) local ed = EffectData() ed:SetEntity(self.Entity) ed:SetOrigin(self:GetPos()) ed:SetScale(self.Scale or 10) ed:SetRadius(self.matType) ed:SetAngles(self.hitAngle) util.Effect("wac_tankshell_impact",ed) self.Entity:Remove() end function ENT:OnTakeDamage(dmginfo) self:Explode() end function ENT:OnRemove() self.sound:Stop() end function ENT:StartRocket() if self.Started then return end self.Owner = self.Owner or self.Entity self.Fuel=self.Fuel or 1000 self.Started = true local pos = self:GetPos() local ang = self:GetAngles() --[[self.SmokeTrail=ents.Create("env_rockettrail") self.SmokeTrail:SetPos(self:GetPos()) self.SmokeTrail:SetParent(self.Entity) self.SmokeTrail:SetLocalAngles(Vector(0,0,0)) self.SmokeTrail:Spawn()]] local ed=EffectData() ed:SetOrigin(pos) ed:SetScale(1) ed:SetRadius(self.TrailLength) ed:SetMagnitude(self.SmokeDens) ed:SetEntity(self.Entity) util.Effect("wac_rocket_trail", ed) local light = ents.Create("env_sprite") light:SetPos(self.Entity:GetPos()) light:SetKeyValue("renderfx", "0") light:SetKeyValue("rendermode", "5") light:SetKeyValue("renderamt", "255") light:SetKeyValue("rendercolor", "250 200 100") light:SetKeyValue("framerate12", "20") light:SetKeyValue("model", "light_glow03.spr") light:SetKeyValue("scale", "0.4") light:SetKeyValue("GlowProxySize", "50") light:Spawn() light:SetParent(self.Entity) self.sound:Play() self.OldPos=self:GetPos() self.phys:EnableCollisions(false) end function ENT:GetFuelMul() self.MaxFuel=self.MaxFuel or self.Fuel or 0 if self.Fuel then return math.Clamp(self.Fuel/self.MaxFuel*5,0,1) end return 1 end function ENT:PhysicsUpdate(ph) if !self.Started or self.HasNoFuel then return end local trd = { start = self.OldPos, endpos = self:GetPos(), filter = {self,self.Owner,self.Launcher}, mask = CONTENTS_SOLID + CONTENTS_MOVEABLE + CONTENTS_OPAQUE + CONTENTS_DEBRIS + CONTENTS_HITBOX + CONTENTS_MONSTER + CONTENTS_WINDOW + CONTENTS_WATER, } local tr = util.TraceLine(trd) if tr.Hit and !self.Exploded then if tr.HitSky then self:Remove() return end util.Decal("Scorch", tr.HitPos + tr.HitNormal, tr.HitPos - tr.HitNormal) self.matType = tr.MatType self.hitAngle = tr.HitNormal:Angle() self:Explode() return end self.OldPos = trd.endpos local vel = self:WorldToLocal(self:GetPos()+self:GetVelocity())*0.4 vel.x = 0 local m = self:GetFuelMul() ph:AddVelocity(self:GetForward()*m*self.Speed-self:LocalToWorld(vel*Vector(0.1, 1, 1))+self:GetPos()) ph:AddAngleVelocity( ph:GetAngleVelocity()*-0.4 + Vector(math.Rand(-1,1), math.Rand(-1,1), math.Rand(-1,1))*5 + Vector(0, -vel.z, vel.y) ) if self.calcTarget then local target = self:calcTarget() local dist = self:GetPos():Distance(target) if dist > 2000 then target = target + Vector(0,0,200) end local v = self:WorldToLocal(target + Vector( 0, 0, math.Clamp((self:GetPos()*Vector(1,1,0)):Distance(target*Vector(1,1,0))/5 - 50, 0, 1000) )):GetNormal() v.y = math.Clamp(v.y*10,-0.5,0.5)*300 v.z = math.Clamp(v.z*10,-0.5,0.5)*300 self:TakeFuel(math.abs(v.y) + math.abs(v.z)) ph:AddAngleVelocity(Vector(0,-v.z,v.y)) end self:TakeFuel(self.Speed) end function ENT:TakeFuel(amt) self.Fuel = self.Fuel-amt/10*FrameTime() if self.Fuel < 0 then self:Remove() end end function ENT:Think() if self.StartTime and self.StartTime < CurTime() and !self.Started then self:StartRocket() end end
local M = {} M.setup = function() vim.g.bullets_enabled_file_types = { 'markdown', 'text', 'gitcommit', 'scratch', } vim.g.bullets_enable_in_empty_buffers = 0 vim.g.bullets_set_mappings = 1 vim.g.bullets_mapping_leader = '' vim.g.bullets_delete_last_bullet_if_empty = 1 vim.g.bullets_line_spacing = 1 vim.g.bullets_pad_right = 1 vim.g.bullets_max_alpha_characters = 2 vim.g.bullets_outline_levels = {'ROM', 'ABC', 'num', 'abc', 'rom', 'std-', 'std*', 'std+'} vim.g.bullets_renumber_on_change = 1 vim.g.bullets_nested_checkboxes = 1 vim.g.bullets_checkbox_markers = ' ○◐●✓' -- '✗○◐●✓' or ' .oOX' vim.g.bullets_checkbox_partials_toggle = 1 -- <leader>x end -- local function config() -- -- -- end return M -- return { -- setup = setup(), -- config = config() -- }
-- bootstrap the compiler fennel = require("fennel") table.insert(package.loaders, fennel.make_searcher({correlate=true})) pp = function(x) print(fennel.view(x)) end local make_love_searcher = function(env) return function(module_name) local path = module_name:gsub("%.", "/") .. ".fnl" local folderPath = module_name:gsub("%.", "/") .. "/init.fnl" if love.filesystem.getInfo(path) then return function(...) local code = love.filesystem.read(path) return fennel.eval(code, {env=env}, ...) end, path end if love.filesystem.getInfo(folderPath) then return function(...) local code = love.filesystem.read(folderPath) return fennel.eval(code, {env=env}, ...) end, path end end end table.insert(package.loaders, make_love_searcher(_G)) table.insert(fennel["macro-searchers"], make_love_searcher("_COMPILER"))
require 'nn' require 'gnuplot' ntm = require '../models/ntm' require '../models/rmsprop' --[[ The aim of this NTM is to repeat a tensor a number of times, like in a for loop. We give a tensor of random(0,1) as input, with a int on a specific channel (column) to give the number of copies. Then, we give an end delimiter on another specific column. Example of input: 3 0 0 0 0 0 0 Number of copies to make, column 1 0 0 1 0 0 0 0 tensor to copy 0 0 1 1 0 1 0 tensor to copy 0 0 1 0 1 1 1 tensor to copy 0 1 0 0 0 0 0 end deliminter, column 2 ]]-- -- Parameters local INPUT_SIZE = 5 + 2 local OUTPUT_SIZE = 5 + 2 local MEMORY_SLOTS = 128 -- Number of addressable slots in memory local MEMORY_SIZE = 20 -- Size of each memory slot local CONTROLLER_SIZE = 100 local SHIFT_SIZE = 1 local MAX_NUMBER_0F_COPY = 5 local COPY_SIZE = 40 local TEMPORAL_HORIZON = 2 + 2 * COPY_SIZE -- Other inputs of the NTM are zeros local dataRead = torch.Tensor(MEMORY_SIZE):zero() local memory = torch.Tensor(MEMORY_SLOTS, MEMORY_SIZE):zero() -- Initialize read/write weights to a vector that stimulates -- reading/writing at slot 1 first local readWeights = nn.SoftMax():forward(torch.range(MEMORY_SLOTS, 1, -1)) local writeWeights = readWeights:clone() -- Create the model local model = ntm.NTM(INPUT_SIZE, OUTPUT_SIZE, MEMORY_SLOTS, MEMORY_SIZE, CONTROLLER_SIZE, SHIFT_SIZE, TEMPORAL_HORIZON) -- Create the criterions local criterion = nn.BCECriterion() -- Meta parameters local config = { learningRate = 1e-4, momentum = 0.9, decay = 0.95 } local maxEpoch = 10000 local allLosses = {} local params, gradParams = model:getParameters() local input = torch.Tensor(TEMPORAL_HORIZON, INPUT_SIZE):zero() local delta = torch.Tensor(TEMPORAL_HORIZON, INPUT_SIZE):zero() local output, target, numberOfCopy for iteration = 1, maxEpoch do function feval(params) gradParams:zero() -- Generate random data to copy input:zero() numberOfCopy = math.random(1, MAX_NUMBER_0F_COPY) local inputLength = 2 input[{{2, inputLength + 1}, {3, INPUT_SIZE}}]:random(0, 1) input[1][1] = numberOfCopy -- number of copies input[inputLength + 2][2] = 1 -- end delimiter local modelInput = ntm.prepareModelInput(input, dataRead, memory, readWeights, writeWeights) -- Forward local modelOutput = model:forward(modelInput) output = ntm.unpackModelOutput(modelOutput, TEMPORAL_HORIZON) output = output[{{2 + inputLength + 2, 3 + inputLength * (numberOfCopy + 1)}}] cell = input[{{2, inputLength + 1}}] target = torch.repeatTensor(cell, numberOfCopy, 1) local loss = criterion:forward(output, target) -- -- Backward delta:zero() delta[{{2 + inputLength + 2, 3 + inputLength * (numberOfCopy + 1)}}] = criterion:backward(output, target) delta:mul(numberOfCopy) -- Prepare delta essentially like the input, but with zeros for delta on everything except the model's output local modelDelta = ntm.prepareModelInput(delta, dataRead, memory, readWeights, writeWeights) model:backward(modelInput, modelDelta) return loss, gradParams end local _, loss = ntm.rmsprop(feval, params, config) loss = loss[1] if iteration % 25 == 0 then print('After epoch ' .. iteration .. ', loss is ' .. loss) print('Grad: ' .. gradParams:min() .. ' ' .. gradParams:max()) print('Number of copies: ' .. numberOfCopy) print('Output:') print(output) print('Target:') print(target) print('') end allLosses[iteration] = loss end gnuplot.plot(torch.Tensor(allLosses))
function _init() --debug collision = false debugnum = 10 game_scene_freeze = false -- logo logo_angle = 0 logo_y = 20 logo_tic = 0 top_type = flr(rnd(5) + 1) bottom_type = flr(rnd(5) + 1) --debug outline outline_col = 0 -- animation sprite number s = 17 -- animation delay d = 30 -- background setup line_col = 7 -- pad setup pad_x = 55 pad_y = 63 --pad speed pad_dx = 0 pad_dy = 0 pad_position = "horizontal" pad_width = 30 pad_height = 3 pad_color = 2 pad_hitbox_x = 0 pad_hitbox_y = 0 pad_hitbox_width = 0 pad_hitbox_height= 0 pad_speed = 5 -- bouncebox left setup --pad_bouncebox_left_x = 0 --pad_bouncebox_left_y = 0 -- ball setup ball_radius = 3 ball_x = 30 ball_y = 20 -- max speed ball_dm = 0.5 ball_dx = ball_dm ball_dy = ball_dm ball_ang = 0 ball_col = 9 -- freeze freezetimer = 0 ball_frosted = false frosted_timer = 0 -- target setup target_x = rnd(100) target_y = 6 target_radius = 5 -- max speed target_dm = 0.25 -- initial setup for top left of the screen target_dx = target_dm target_dy = 0 -- sec target setup sectarget_x = 6 sectarget_y = rnd(100) sectarget_radius = 5 -- max speed sectarget_dm = 0.25 -- initial setup for top left of the screen sectarget_dx = 0 sectarget_dy = -target_dm -- max speed -- bad target setup badtarget_sprite = 1 badtarget_x = rnd(100) badtarget_y = 122 badtarget_radius = 5 -- max speed badtarget_dm = 0.3 -- initial setup for bottom right corner badtarget_dx = - badtarget_dm badtarget_dy = 0 --score setup score = 0 -- particles setup part = {} -- order system variables order_time = 0 ingr_total_number = 5 total_orders = 0 -- number of n per ingredient ing_1 = 0 ing_2 = 0 ing_3 = 0 ing_4 = 0 ing_5 = 0 -- starting ing_types array ing_types_start = {ing_1,ing_2,ing_3,ing_4,ing_5} -- how many ing types will be in play in this round ing_ammount = 0 -- how many ings in this order are left to be disposed between ing types ing_to_dispose = 0 -- how many total ings are on the start start_ing_to_dispose = 0 -- ing speed ing_speed = 0.5 -- order system update frame = 0 sec = 0 order_time_procentage = 0 bar_col = 7 bar_x = 0 -- ingredient control setup ing_list = {} -- order new ing adding tic = 0 ings_avaible = {} -- game over screen effect ing_matrix_tic = 0 -- player score var player_score = 0 --screen shake vars shake = 0 -- order is starting now debug new_order() -- white frame whiteframe = 0 frosted_cooldown = 0 -- camera moving camerax = 0 camera_direction = 0 cameratimer = 0 cameramoving = false -- in which room are we now? -- -1 credits -- 0 splash -- 1 highscore camera_active_room = 0 -- if true the bombs can go off -- fixes the double bomb row safebomb = false -- high score cartdata("lkg_picomaki") hs = {} loadhs() sort_high_score() -- order showing part rows_table = {} rows_number = 0 scene = "menu" -- game scenes: -- menu -- tutorial -- game -- gameover -- coin = 0 -- advance and skiping of tutorial tutorial_part = 0 music(1) --reseths() end function _update60() if scene == "menu" then -- x to start the game if btnp(5) then scene = "tutorial" end -- moving between rooms in the menu scene -- we start in the room 0 -- right if btn(1) then if cameramoving == false and (camera_active_room == 0 or camera_active_room == -1) then cameramoving = true camera_direction = 1 sfx(34) end end -- left if btn(0) then if cameramoving == false and (camera_active_room == 0 or camera_active_room == 1) then cameramoving = true camera_direction = -1 sfx(34) end end update_camera() --logo smooth movement logo_tic += 1 if logo_tic >= 1 then logo_angle += 0.03 / 0.02 --logo_y += sin(logo_angle / 200) logo_tic = 0 end end if scene == "gameover" then whiteframe = 10 if btn(5) then game_vars_fresh_start() scene = "game" music(4,5000) end if btn(4) then game_vars_fresh_start() scene = "menu" end end if scene == "tutorial" then if btnp(5) then tutorial_part += 1 sfx(34) end if btnp(4) then tutorial_part -= 1 sfx(34) end if tutorial_part == 0 then scene = "menu" tutorial_part = 0 sfx(34) end if tutorial_part == 5 then tutorial_part = 0 scene = "game" sfx(34) music(4,5000) end end if scene == "game" then -- game start sfx --sfx(26) --debug debug = '' -- ball collision against the serve boxes if ball_box(0,0,16,16) then -- bottom wall if ball_x < 16 then ball_dy = - ball_dy else ball_dx = - ball_dx end end -- bottom serve box if ball_box(111,96,16,16) then -- top if ball_x >= 111 then ball_dy = - ball_dy else ball_dx = - ball_dx end end frosted_cooldown -= 1 --display that you can frost if frosted_cooldown <= 0 then outline_col = 7 -- TODO sfx loaded end -- if x is pressed if btnp(5) then -- player can frost every 3 seconds if frosted_cooldown <= 0 then ball_frosted = true frosted_timer = 100 -- frost SFX sfx(27) frosted_cooldown = 180 end end if ball_frosted == true then frosted_timer -= 1 --ball_col = 12 --outline_col = 12 ball_col = 12 outline_col = 12 if frosted_timer < 0 then ball_frosted = false ball_col = 8 outline_col = 2 -- unfrost sfx sfx(28) end end -- debug if btnp(4) then --player_score += 8001 -- --outline_col += 1 -- debug --if outline_col > 15 then --outline_col = 0 --end end collision = false -- debug animation tomatoblink() update_order() -- local var if any button pressed local butpress = false -- trail particle spawntrail(ball_x, ball_y) -- updating the particles updateparts() -- ball movement -- ball frosting if ball_frosted == false then ball_x += ball_dx ball_y += ball_dy -- bug fix ball going out of border else ball_x += 0 ball_y += 0 end -- ball wall bouncing -- radius is added or removed for better collision detection if ball_x > 127 - ball_radius then ball_dx = -ball_dm ball_dy = 1 * sign(ball_dy) -- wall collision sfx sfx(1) -- ball out of space bug fix ball_x = mid(0,ball_x,127) end if ball_x < 0 + ball_radius then ball_dx = ball_dm ball_dy = 1 * sign(ball_dy) -- wall collision sfx sfx(1) ball_x = mid(0,ball_x,127) end if ball_y > 111 - ball_radius then ball_dy = -ball_dm ball_dx = 1 * sign(ball_dx) -- wall collision sfx sfx(1) ball_y = mid(0,ball_y,111) end if ball_y < 0 + ball_radius then ball_dy = ball_dm ball_dx = 1 * sign(ball_dx) -- wall collision sfx sfx(1) ball_y = mid(0,ball_y,111) end -- horizontal -- only one button can be held at a time -- the second variable is moving if (btn(0)) and not (btn(2)) and not (btn(3)) then --pad_x -= 3 --pad_dx = - pad_speed pad_dx = pad_dx - 0.75 butpress = true pad_position = "horizontal" end if (btn(1)) and not (btn(2)) and not (btn(3))then --pad_x += 3 --pad_dx = pad_speed pad_dx = pad_dx + 0.75 butpress = true pad_position = "horizontal" end -- vertical pad movement if (btn(2)) and not (btn(0)) and not (btn(1)) and not (btn(3)) then --pad_y -= 3 --pad_dy = - pad_speed pad_dy = pad_dy - 0.75 butpress = true pad_position = "vertical" end if (btn(3)) and not (btn(0)) then --pad_y += 3 --pad_dy = pad_speed pad_dy = pad_dy + 0.75 butpress = true pad_position = "vertical" end if not(butpress) then pad_dx = pad_dx/1.7 pad_dy = pad_dy/1.7 end if pad_x <= 13 or pad_x >= 84 then if abs(pad_dx) > 1 then if sign(pad_dx) == -1 then pad_x = 100 pad_dx = -1 end if sign(pad_dx) == 1 then pad_dx = 1 end end end --pad clamp border --pad_x = mid(16,pad_x, 91) --pad_y = mid(26,pad_y,85) if pad_position == "horizontal" then pad_x += pad_dx pad_x = mid(14,pad_x, 84) end if pad_position == "vertical" then pad_y += pad_dy pad_y = mid(29,pad_y,82) end pad_color = 2 -- check if ball hit pad -- pad horizontal collision if (pad_position == "horizontal") then --everything is alright pad_hitbox_x = pad_x pad_hitbox_y = pad_y pad_hitbox_width = pad_width pad_hitbox_height = pad_height -- bouncebox left setup --pad_bouncebox_left_x = pad_hitbox_x --pad_bouncebox_left_y = pad_hitbox_y end -- pad vertical coliistion if (pad_position == "vertical") then -- addusting the variables for the hitbox pad_hitbox_x = pad_x + pad_width / 2 - pad_height / 2 pad_hitbox_y = pad_y - pad_width / 2 pad_hitbox_width = pad_height pad_hitbox_height = pad_width -- bouncebox left setup -- left meaning on top end --if ball_box(pad_bouncebox_left_x,pad_bouncebox_left_y,pad_bouncebox_left_x,pad_bouncebox_left_y + pad_hitbox_height) then -- if (ball_box(pad_x - 1,pad_y,pad_x-1,pad_y + pad_height)) then -- ball_x = 5 -- -- pad_color = 11 -- end -- pad collision check against the new variables if (ball_box(pad_hitbox_x, pad_hitbox_y, pad_hitbox_width, pad_hitbox_height)) then -- deal with collision pad_color = 8 sfx(0) -- ball angle change -- absolute value --horizontal check if abs(pad_dx) > 1 then -- change angle if sign(pad_dx) == sign(ball_dx) then -- pad and ball moving in the same direction -- flatten the angle -- mid locks value above 0 setang(mid(0,ball_ang-1,2)) else -- raise angle if ball_ang==2 then ball_dx = - ball_dx else setang(mid(0,ball_ang+1,2)) end end end if abs(pad_dy) > 1 then -- change angle if sign(pad_dy) == sign(ball_dy) then -- pad and ball moving in the same direction -- flatten the angle -- mid locks value above 0 setang(mid(0,ball_ang+1,2)) else -- raise angle if ball_ang==2 then ball_dy = - ball_dy else setang(mid(0,ball_ang-1,2)) end end end if (pad_position == "horizontal") then ball_dy = - ball_dy end if (pad_position == "vertical") then ball_dx = - ball_dx end end if pad_position == "horizontal" then -- left pad check --if ball_box(pad_hitbox_x - 1, pad_hitbox_y + 1,1,pad_hitbox_height / 2) then --if ball_box(pad_hitbox_x -1, pad_hitbox_y,1,pad_hitbox_height) then if ball_box(pad_hitbox_x -3, pad_hitbox_y,3,pad_hitbox_height) then --debug = "left hit" ball_x -= abs(pad_dx + pad_dy) * 2 + 5 ball_dx = - ball_dx sfx(0) end -- right pad check --if ball_box(pad_hitbox_x + pad_hitbox_width, pad_hitbox_y + 1,1,pad_hitbox_height / 2) then --if ball_box(pad_hitbox_x + pad_hitbox_width +1, pad_hitbox_y,1,pad_hitbox_height) then if ball_box(pad_hitbox_x + pad_hitbox_width +3, pad_hitbox_y,3,pad_hitbox_height) then --debug = "right hit" ball_x += abs(pad_dx + pad_dy) * 2 + 5 ball_dx = - ball_dx sfx(0) end end if pad_position == "vertical" then -- top pad check if ball_box(pad_hitbox_x + pad_hitbox_width /2, pad_hitbox_y - 3, pad_height , 3) then --if ball_box(pad_hitbox_x + pad_hitbox_width /2, pad_hitbox_y - pad_hitbox_width /2 -1, pad_hitbox_height, 1) then ball_y -= abs(pad_dx + pad_dy) * 2 + 5 ball_dy = - ball_dy sfx(0) --debug = "top hit" end -- bottom pad check --if ball_box(pad_hitbox_x + pad_hitbox_width / 2, pad_hitbox_y + pad_hitbox_height, pad_hitbox_width / 2, pad_hitbox_width /2) then if ball_box(pad_hitbox_x + pad_hitbox_width / 2, pad_hitbox_y + pad_width, pad_height , 3) then ball_y += abs(pad_dx + pad_dy) * 2 + 5 ball_dy = - ball_dy sfx(0) --debug = "bottom hit" end end --rectfill(pad_bouncebox_left_x,pad_bouncebox_left_y,pad_bouncebox_left_x,pad_bouncebox_left_y + pad_hitbox_height) --if pad_position == "horizontal" then --if ball_box(pad_bouncebox_left_x,pad_bouncebox_left_y,pad_bouncebox_left_x + 0,pad_bouncebox_left_y+3) then -- ball_x = 5 -- pad_color = 11 --end --end -- ing system update update_ing() -- if we've got order rolling spawnnew_ing() if ing_1 == 0 and ing_2 == 0 and ing_3 == 0 and ing_4 == 0 and ing_5 == 0 then player_score += 250 show_completed_order() new_order() --generate_new_sushi_set(5) --new order sfx sfx(6) end end end function _draw() if scene == "menu" then cls() -- background color rectfill(0,0,127,127,0) -- background pattern drawbackgroundpattern() -- logo spr(96,12,10,12,12) outline("press x to start",33,80,8,1) outline("\145 highscore",45,90,1,8) outline("\139 credits",45,100,1,8) --debug drawcredits() drawhighscore() -- cross pattern --spr(137,0,30,2,2) --spr(141,112,46,2,2) camera(camerax,0) --debug --debug --pset(0,0,7) end if scene == "gameover" then cls() whiteframe += 10 local y_offset = 15 local is_on_highscore = false ing_matrix_tic += 0.1 draw_game_scene() rectfill(0,45 -y_offset,127,104 -y_offset,2) rect(0,45 -y_offset,127,104 -y_offset,10) --print("game over",45,50,7) outline("game over", 45,50 -y_offset,8,0) -- high score print("score:",42,68 -y_offset,7) --print(player_score,70,60,7) print(player_score,70,68 -y_offset,7) outline("x restart",45,85 -y_offset,8,1) outline("z menu",50,95 -y_offset,1,8) spr(ing_matrix_tic,20,50 -y_offset) spr(ing_matrix_tic,101,50 -y_offset) if ing_matrix_tic >= 5 then ing_matrix_tic = 1 end -- TODO -- spritey składników end if scene == "tutorial" then if tutorial_part == 1 then cls() local onboarding_buttons_x_offset = -5 rectfill(0,0,127,127,13) print("welcome chef",5,5,7) print("your goal is to", 5,25,7) print("complete sushi orders",5,35,7) spr(71,93,33,2,1) spr(75,107,33) print("by collecting",5,55,7) print("the ingriedients",5,65,7) spr(1,73,63) spr(2,86,63) spr(3,99,63) spr(4,112,63) print("with the cook ball",5,85,7) circ(84,87,ball_radius + 1,2) circfill(84,87,ball_radius,8) print("x to continue",72,105,7) print("z to go back",5,105,6) circfill(53 + onboarding_buttons_x_offset,120,2,7) circ(62 + onboarding_buttons_x_offset,120,2,6) circ(71 + onboarding_buttons_x_offset,120,2,6) circ(80 + onboarding_buttons_x_offset,120,2,6) end if tutorial_part == 2 then cls() local onboarding_buttons_x_offset = -5 local gamepad_offset = 5 local gamepad_offset_y = -27 local vertical_pad_offset = -10 rectfill(0,0,127,127,13) print("control the cook ball",5,5,7) print("with the chef pad", 5,15,7) print("using the arrow keys",5,25,7) print("you can move",5,45,7) print("in all directions",5,55,7) -- left arrow spr(14,90 + gamepad_offset,43 + gamepad_offset_y) -- right arrow spr(14,104 + gamepad_offset,43 + gamepad_offset_y,1,1,1,0) -- top arrow spr(46,97 + gamepad_offset,37 + gamepad_offset_y) -- bottom arrow spr(46,97 + gamepad_offset,49 + gamepad_offset_y,1,1,1,0) local xoffset = -20 -- left arrow spr(14,32 + xoffset,71) rectfill(pad_x - 10 + xoffset, pad_y + 10, pad_x + pad_width - 10 + xoffset, pad_y + pad_height + 10, pad_color) -- right arrow spr(14,81 + xoffset,71,1,1,1,0) rectfill( pad_x + pad_width / 2 - pad_height / 2 - pad_height / 2 + 30, pad_y - pad_width / 2 + 15 + vertical_pad_offset, pad_x + pad_width / 2 + 30, pad_y + pad_width / 2 + 15 + vertical_pad_offset, pad_color ) -- top arrow spr(46,95,50 + vertical_pad_offset) -- bottom arrow spr(46,95,99 + vertical_pad_offset,1,1,1,0) --print("the pad can go up and down",5,65,7) --print("and left and right",5,75,7) print("x to continue",72,105,7) print("z to go back",5,105,6) circ(53 + onboarding_buttons_x_offset,120,2,6) circfill(62 + onboarding_buttons_x_offset,120,2,7) circ(71 + onboarding_buttons_x_offset,120,2,6) circ(80 + onboarding_buttons_x_offset,120,2,6) end if tutorial_part == 3 then cls() local onboarding_buttons_x_offset = -5 rectfill(0,0,127,127,13) print("if the ball outline is white", 5,5,7) print("you can press x",5,15,7) print("to freeze it for a moment",5,25,7) print("x",59,50,6) print("you can use freeze again",5,65,7) print("once the outline goes white",5,75,7) -- frosted ball circfill(80,41,4,12) circ(40,41,ball_radius + 1,7) circfill(40,41,ball_radius,8) -- arrow in between -- left arrow spr(31,56,38) -- onboarding buttons print("x to continue",72,105,7) print("z to go back",5,105,6) circ(53 + onboarding_buttons_x_offset,120,2,6) circ(62 + onboarding_buttons_x_offset,120,2,6) circfill(71 + onboarding_buttons_x_offset,120,2,7) circ(80 + onboarding_buttons_x_offset,120,2,6) end if tutorial_part == 4 then cls() local onboarding_buttons_x_offset = -5 rectfill(0,0,127,127,2) print("watch the timer", 5,5,7) -- progress bar box rect(0,15,127,18,bar_col) -- progress bar rectfill(0,15, 80,18,bar_col) print("if it goes down to zero",5,25,7) print("you loose",5,35,7) -- progress bar box rect(0,45,127,48,8) -- progress bar rectfill(0,15, 80,18,bar_col) print("hitting the bombs",5,55,7) spr(5,76,53) print("damages the timer",5,65,7) print("are you ready chef?",5,85,7) --print("x to continue",5,95,7) print("x to continue",72,105,7) print("z to go back",5,105,6) circ(53 + onboarding_buttons_x_offset,120,2,6) circ(62 + onboarding_buttons_x_offset,120,2,6) circ(71 + onboarding_buttons_x_offset,120,2,6) circfill(80 + onboarding_buttons_x_offset,120,2,7) end end if scene == "game" then draw_game_scene() end end function ball_box(box_x, box_y, box_width, box_height) --checks the collision of a ball with a rectangle -- top edge check if ball_y - ball_radius > box_y + box_height then return false end -- botton edge check if ball_y + ball_radius < box_y then return false end -- left edge check if ball_x - ball_radius > box_x + box_width then return false end -- right edge check if ball_x + ball_radius < box_x then return false end -- collision occured collision = true return true end -- particles -- adds a particle function addpart(_x,_y,_type,_maxage,_col, _oldcol) local _p = {} _p.x = _x _p.y = _y _p.tpe = _type _p.mage = _maxage -- age starts at zero, goes to maxage _p.age = 0 _p.col = _col -- color near death _p.oldcol = _oldcol -- we're adding a particle to particle array add(part,_p) end -- sprawns a trail function spawntrail(_x, _y) -- random angle local _ang = rnd() -- random x and y offset local _ox = sin(_ang) * ball_radius * 0.6 local _oy = cos(_ang) * ball_radius * 0.6 addpart(_x + _ox,_y + _oy,0,20 + rnd(15), 8, 2) end function spawnboom(_x,_y) addpart(_x,_y,8,200,8,0) end function updateparts() local _p for i=#part,1, -1 do _p = part[i] _p.age += 1 if (_p.age > _p.mage) then del(part, part[i]) else if (_p.age / _p.mage) > 0.6 then _p.col = _p.oldcol end end end end function drawparts() for i = 1,#part do _p = part[i] --print(_p.tpe,1,20,10) -- checks if particle is trail type if _p.tpe == 0 then --print("PSET", 1,10, 10) pset(_p.x,_p.y,_p.col) else end -- if bomb if _p.tpe == 8 then -- big explosion circle range local bigrange local t = 0 local col1 = 8 local col2 = 9 local col3 = 7 -- function that I made -- - 1/10 x^2 + 10 -- dodaj przesunięcie na b żeby symetria była gdzie indziej --bigrange = mid(0,_p.age,15) -- fast function --bigrange = - bigrange * (bigrange - 10) -- new function bigrange = _p.age bigrange = (- bigrange / 60) * (bigrange - 120) --bigrange = (- bigrange / 20) * (bigrange - 50) if _p.age > 0 then _p.col = 7 end if _p.age > 10 then _p.col = 10 end if _p.age > 20 then _p.col = 9 end if _p.age > 30 then _p.col = 8 end if _p.age > 40 then _p.col = 0 col1 = 0 col2 = 0 col3 = 0 end circfill(_p.x,_p.y,bigrange,col1) circfill(_p.x,_p.y,bigrange /2,col2) circfill(_p.x,_p.y,bigrange /4, col3) circfill(_p.x + 2,_p.y + 3,bigrange,col1) circfill(_p.x - 4,_p.y,bigrange /2,col2) circfill(_p.x,_p.y + 2,bigrange /4, col3) --pset(_p.x,_p.y,_p.col) end end end -- ball angle changing function setang(ang) ball_ang = ang if ang == 2 then -- 0.50 -- 1.30 ball_dx = 0.50 * sign(ball_dx) ball_dy = 1.30 * sign(ball_dy) elseif ang == 0 then ball_dx = 1.30 * sign(ball_dx) ball_dy = 0.50 * sign(ball_dy) else ball_dx = 1 * sign(ball_dx) ball_dy = 1 * sign(ball_dy) end end -- returns a sign (+,-) of a variable function sign(n) if n<0 then return -1 elseif n>0 then return 1 else return 0 end end function drawbackground() -- background rectfill(0,0,128,128,0) drawsmallbox() -- big box - ramka -- top right corner spr(8,112,0,2,2) -- bottom left corner spr(38,0,96,2,2) -- wall joining the corners drawwall() -- outline of big box --rect(0,0,127,111,line_col) -- small box -- pattern test -- fillp(0b1000010000100001) -- rectfill(13,13,114,98,4) -- fillp() -- pattern inside small box --rect(13,13,114,98,4) -- progress bar box rect(0,124,127,127,bar_col) -- progress bar rectfill(0,124,bar_x,127,bar_col) -- counter -- number 1 if ing_1 == 0 then print(ing_1,4,116,11) else print(ing_1,4,116,9) end -- sprite 1 spr(1,13,114) -- number 2 if ing_2 == 0 then print(ing_2,30,116,11) else print(ing_2,30,116,9) end -- sprite 2 spr(2,39,114) -- number 3 if ing_3 == 0 then print(ing_3,56,116,11) else print(ing_3,56,116,9) end -- sprite 3 spr(3,65,114) -- number 4 if ing_4 == 0 then print(ing_4,82,116,11) else print(ing_4,82,116,9) end -- sprite 4 spr(4,91,114) -- score bar print(player_score,108,116,7) --print(order_time,60,80,8) --print(frame,60,90,9) --print(order_time_procentage,60,70,10) end function drawserveboxes() -- serve boxes -- rectfill(0,0,12,12,line_col) --rectfill(115,99,127,111,line_col) -- top left corner spr(6,0,0,2,2) -- top right corner --spr(8,112,0,2,2) -- bottom left corner --spr(38,0,96,2,2) -- bottom right corner spr(6,112,96,2,2,true,true) end -- debug function tomatoblink() d -= 1 if d < 0 then s += 1 if s > 20 then s = 17 end d = 30 end end function new_order() -- time to complete the order order_time = 60 total_orders += 1 -- bar green bar_col = 11 -- getting a num in <1,4> range ing_ammount = flr(rnd(4)) + 1 ing_ammount = mid(1,ing_ammount,4) -- setting which ing_types will be used ing_to_dispose = flr(rnd(total_orders)) + 1 ing_to_dispose = mid(ing_ammount * 2,ing_to_dispose,20) -- ing_to_dispose = mid(total_orders,ing_to_dispose,20) start_ing_to_dispose = ing_to_dispose -- assigning all ings to buckets -- first ing type operation if flr(rnd(1)) == 0 then ing_1 = flr(rnd(ing_to_dispose) / 2) ing_to_dispose -= ing_1 else ing_1 = flr(rnd(ing_to_dispose)) ing_to_dispose -= ing_1 end ing_2 = flr(rnd(ing_to_dispose)) ing_to_dispose -= ing_2 ing_3 = flr(rnd(ing_to_dispose)) ing_to_dispose -= ing_3 ing_4 = flr(rnd(ing_to_dispose)) ing_to_dispose -= ing_4 -- temporary disabled due to UI --ing_5 = flr(ing_to_dispose) --ing_to_dispose -= ing_2 -- 0 0 0 0 0 ing bug fix if ing_1 == 0 and ing_2 == 0 and ing_3 == 0 and ing_4 == 0 and ing_5 == 0 then ing_1 = 1 ing_3 = 2 end -- fixing the bug with 0 0 0 0 0 end function update_order() -- decreasing order time -- making a countdown timer from 60 to 1 in every second frame += 1 if frame > 60 then frame = 0 sec += 1 end if sec == 1 then order_time -= 1 sec = 0 end -- if timer reaches 0 it doesn't go negative if order_time < 0 then order_time = 0 scene = "gameover" music(10) insertscoretohighscore() sort_high_score() savehs() end -- translating the order_time to % value order_time_procentage = flr(order_time / 60 * 100) bar_x = 128 * (order_time_procentage / 100) if order_time_procentage < 60 then bar_col = 9 end if order_time_procentage < 30 then bar_col = 8 end if order_time_procentage == 0 then bar_col = 7 end -- the order is completed end function add_ing(x,y,_type,_tray) local ing = {} ing.x = x ing.y = y ing.tpe = _type -- _tray referes to the tray type that will serve the ing ing.tray = _tray -- used to remove the old ings on contact with new tray -- it's like a magical trick ing.mage = _maxage -- age starts at zero, goes to maxage ing.age = 0 -- we're adding an ingredient to ingredient array add(ing_list,ing) end function update_ing() local ing -- iterating on each ingrediant in the ingredient list for i = #ing_list,1,-1 do -- local ing_dx local ing_dx = 0 -- local ing_dy local ing_dy = 0 ing = ing_list[i] -- aging of the ing ing.age += 1 -- moving the ing -- debug values --ing.x += 1 --ing.y += 1 -- calculating the movement if ing.tray == "BOTTOM" then -- bottom right corner hit if ing.x > 3 and ing.y > 100 then ing.x -= ing_speed end if ing.x <= 3 and ing.y > 3 then ing.y -= ing_speed end if ing.y == 0 then del(ing_list,ing) end -- top left corner hit if ing.x <= 117 and ing.y <= 5 then del(ing_list,ing) end end if ing.tray == "TOP" then -- left upper corner hit if ing.x < 117 and ing.y < 101 then ing_dx = ing_speed ing_dy = 0 end -- top right corner hit if ing.x >= 117 and ing.y < 101 then ing_dx = 0 ing_dy = ing_speed end -- bottom right corner hit if ing.x >= 117 and ing.y >= 101 then del(ing_list,ing) end end -- moving the ing ing.x += ing_dx ing.y += ing_dy -- hitbox check if ball_box(ing.x,ing.y,8,8) then -- changing the values of ing types on the UI -- if bomb if ing.tpe == 5 then -- explosion in the middle spawnboom(ing.x + 4,ing.y + 4) whiteframe = 0 --sfx of explosion sfx(29) order_time -= 10 shake+=1 --spawnboom(ing.x,ing.y) end --sfx of good ing sfx(3) if flr(ing.tpe) == 1 then ing_1 -= 1 ing_1 = mid(0,ing_1,100) end if flr(ing.tpe) == 2 then ing_2 -= 1 ing_2 = mid(0,ing_2,100) end if flr(ing.tpe) == 3 then ing_3 -= 1 ing_3 = mid(0,ing_3,100) end if flr(ing.tpe) == 4 then ing_4 -= 1 ing_4 = mid(0,ing_4,100) end if flr(ing.tpe) == 5 then ing_5 -= 1 ing_5 = mid(0,ing_5,100) end del(ing_list,ing) end end end function draw_ing() local ing for i = 1,#ing_list do ing = ing_list[i] spr(ing.tpe,ing.x,ing.y) end end function spawnnew_ing() tic += 1 coin = flr(rnd(2)) local isbomb = flr(rnd(10)) if ing_1 > 0 then ings_avaible[#ings_avaible + 1] = 1 end if ing_2 > 0 then ings_avaible[#ings_avaible + 1] = 2 end if ing_3 > 0 then ings_avaible[#ings_avaible + 1] = 3 end if ing_4 > 0 then ings_avaible[#ings_avaible + 1] = 4 end -- don't overflow if #ings_avaible >= 5 then ings_avaible = {} if ing_1 > 0 then ings_avaible[#ings_avaible + 1] = 1 end if ing_2 > 0 then ings_avaible[#ings_avaible + 1] = 2 end if ing_3 > 0 then ings_avaible[#ings_avaible + 1] = 3 end if ing_4 > 0 then ings_avaible[#ings_avaible + 1] = 4 end end -- previously 120 -- testing with 180 if tic > 180 then if order_time > 0 then --top_type = flr(rnd(5) + 1) --debug = top_type --bottom_type = flr(rnd(5) + 1) -- do we spawn bombs? if rnd(1) >= 0.9 and safebomb == true then top_type = 5 bottom_type = 5 safebomb = false else -- do we spawn perfect or inperfect ings? if rnd(1) >= 0.5 then top_type = ings_avaible[flr(rnd(#ings_avaible) +1)] bottom_type = ings_avaible[flr(rnd(#ings_avaible) +1)] if top_type == 0 then top_type = 1 end if bottom_type == 0 then top_type = 2 end else top_type = flr(rnd(5) + 1) bottom_type = flr(rnd(5) + 1) end -- that what we want turn safebomb = true end end -- add_ing(1,3,flr(rnd(5) + 1),"TOP") -- add_ing(115,101,flr(rnd(5) + 1),"BOTTOM") add_ing(1,3,top_type,"TOP") add_ing(115,101,bottom_type,"BOTTOM") tic = 0 sfx(7) end end function drawsmallbox() local n = 0 local row = 0 -- for each row for p=1,11 do n = 0 -- filling the row for i=1,13 do spr(36,13 + n * 8,13 + row * 8) n += 1 end row +=1 end end function drawwall() local n = 0 -- left wall for i=1,5 do spr(42,0,16 + 16 * n,2,2) n += 1 end -- right wall n = 0 for i=1,5 do spr(44,112,16 + 16 * n,2,2) n += 1 end -- top wall n = 0 for i=1,6 do spr(10,16 + 16* n,0,2,2) n += 1 end -- bottom wall n = 0 for i=1,6 do spr(12,16 + 16* n,96,2,2) n += 1 end -- fix for the pattern end function doshake() -- this function does the -- shaking -- first we generate two -- random numbers between -- -16 and +16 local shakex=16-rnd(32) local shakey=16-rnd(32) -- then we apply the shake -- strength shakex*=shake shakey*=shake -- then we move the camera -- this means that everything -- you draw on the screen -- afterwards will be shifted -- by that many pixels camera(shakex,shakey) -- finally, fade out the shake -- reset to 0 when very low shake = shake*0.95 if (shake<0.05) shake=0 end function drawbackgroundpattern() local n = 0 for i=0,8 do spr(206,0 + n,30,2,2) spr(206,0 + n,46,2,2) n += 16 end end function update_camera() -- if camera in main menu and moving right if camera_active_room == 0 and cameramoving == true and camera_direction == 1 then -- if camera moving right if camerax < 127 then --camerax += 5 camerax = camerax * 1.2 + 3 else camera_active_room = 1 cameramoving = false end end -- if camera in main menu and moving left if camera_active_room == 0 and cameramoving == true and camera_direction == -1 then -- if camera moving left if camerax > -128 then --camerax -= 5 camerax = camerax * 1.2 - 3 else camera_active_room = -1 cameramoving = false end end -- if camera in high score and moving left if camera_active_room == 1 and cameramoving == true and camera_direction == -1 then -- if camera moving left if camerax > 0 then camerax -= 5 camerax = mid(0,camerax,128) else camera_active_room = 0 cameramoving = false end end -- if camera in credits and moving right if camera_active_room == -1 and cameramoving == true and camera_direction == 1 then -- if camera moving left if camerax < 0 then camerax += 5 camerax = mid(-128,camerax,0) else camera_active_room = 0 cameramoving = false end end camerax = mid(-128,camerax,128) end function drawcredits() -- left from the start local xoffset = 128 --debug --pset(0 -xoffset,0,7) local n = 0 for i=0,7 do spr(206,0 + n - xoffset,30,2,2) spr(206,0 + n - xoffset,46,2,2) n += 16 end -- printing the credits -- header background rectfill(45 -xoffset,8,82 -xoffset,30,2) rect(45 -xoffset,8,82 -xoffset,30,10) print("credits", 50 - xoffset, 12,7) categories = {"code", "graphics","sfx", "music","ux/ui", "degign", "vfx", "mentoring"} authors = {"gabriel", "ola", "kacper,kornel", "kacper/kornel", "gabriel", "gabriel","gabriel","konrad,jedrzej,kamil"} local highsocrexoffset = -35 local highsocreyoffset = 10 --pset(0 -xoffset,0,7) local n = 0 for i=0,7 do spr(206,0 + n - xoffset + highsocrexoffset,30,2,2) spr(206,0 + n - xoffset + highsocrexoffset,46,2,2) n += 16 end -- header -- bottom text outline("menu \145",50 -xoffset,115,1,8) -- box rectfill(33 -xoffset + highsocrexoffset + 4,20,75-xoffset + highsocrexoffset + 85,108,2) rect(33 -xoffset + highsocrexoffset + 4,20,75-xoffset + highsocrexoffset + 85,108,10) line(46 -xoffset,20,81 -xoffset,20,2) -- letters for i=1,8 do print(categories[i],40 -xoffset + highsocrexoffset, 17 + i*10,7) print(authors[i],79 -xoffset + highsocrexoffset, 17 + i*10,7) --print(i,39 -xoffset + highsocrexoffset, 17 + i*10,7) end end function drawhighscore() local xoffset = -128 local highsocrexoffset = 0 local highsocreyoffset = 10 --pset(0 -xoffset,0,7) -- background pattern local n = 0 for i=0,7 do spr(206,0 + n - xoffset + highsocrexoffset,30,2,2) spr(206,0 + n - xoffset + highsocrexoffset,46,2,2) n += 16 end -- box rectfill(33 -xoffset + highsocrexoffset,20,94-xoffset + highsocrexoffset,78,2) rect(33 -xoffset + highsocrexoffset,20,94-xoffset + highsocrexoffset,78,10) -- letters for i=1,5 do print(hs[i],50 -xoffset + highsocrexoffset, 17 + i*10,7) print(i,39 -xoffset + highsocrexoffset, 17 + i*10,7) end rectfill(41 -xoffset,8,87 -xoffset,20,2) rect(41 -xoffset,8,87 -xoffset,20,10) line(42 -xoffset,20,86 -xoffset,20,2) -- header print("high score", 45 - xoffset, 12,7) -- bottom text outline("\139 menu",50 -xoffset,100,1,8) end -- resets the highscore function reseths() hs={500,7000,300,200,1000} savehs() end function loadhs() local _slot = 0 if dget(0) == 1 then -- load the data _slot += 1 for i=1,5 do hs[i] = dget(_slot) _slot += 1 end else reseths() end end function savehs() local _slot = 0 dset(0, 1) if dget(0) == 1 then -- load the data _slot = 1 for i=1,5 do dset(_slot,hs[i]) _slot += 1 end debug = dget(1) else hs={500,400,300,200,100} savehs() end end function insertscoretohighscore() -- appends the high score to the end of the list hs[#hs + 1] = player_score end -- sorts the high score and deletes the last bit function sort_high_score() for i=1,#hs do local j = i while j > 1 and hs[j-1] < hs[j] do hs[j],hs[j-1] = hs[j-1],hs[j] j = j - 1 end end hs[6] = nil end function game_vars_fresh_start() --debug collision = false debugnum = 10 --debug outline outline_col = 0 -- animation sprite number s = 17 -- animation delay d = 30 -- background setup line_col = 7 -- pad setup pad_x = 55 pad_y = 63 --pad speed pad_dx = 0 pad_dy = 0 pad_position = "horizontal" pad_width = 30 pad_height = 3 pad_color = 3 pad_hitbox_x = 0 pad_hitbox_y = 0 pad_hitbox_width = 0 pad_hitbox_height= 0 pad_speed = 5 -- bouncebox left setup --pad_bouncebox_left_x = 0 --pad_bouncebox_left_y = 0 -- ball setup ball_radius = 3 ball_x = 30 ball_y = 20 -- max speed ball_dm = 0.5 ball_dx = ball_dm ball_dy = ball_dm ball_ang = 0 ball_col = 9 -- freeze freezetimer = 0 ball_frosted = false frosted_timer = 0 -- target setup target_x = rnd(100) target_y = 6 target_radius = 5 -- max speed target_dm = 0.25 -- initial setup for top left of the screen target_dx = target_dm target_dy = 0 -- sec target setup sectarget_x = 6 sectarget_y = rnd(100) sectarget_radius = 5 -- max speed sectarget_dm = 0.25 -- initial setup for top left of the screen sectarget_dx = 0 sectarget_dy = -target_dm -- max speed -- bad target setup badtarget_sprite = 1 badtarget_x = rnd(100) badtarget_y = 122 badtarget_radius = 5 -- max speed badtarget_dm = 0.3 -- initial setup for bottom right corner badtarget_dx = - badtarget_dm badtarget_dy = 0 --score setup score = 0 -- particles setup part = {} -- order system variables order_time = 0 ingr_total_number = 5 total_orders = 0 -- number of n per ingredient ing_1 = 0 ing_2 = 0 ing_3 = 0 ing_4 = 0 ing_5 = 0 -- starting ing_types array ing_types_start = {ing_1,ing_2,ing_3,ing_4,ing_5} -- how many ing types will be in play in this round ing_ammount = 0 -- how many ings in this order are left to be disposed between ing types ing_to_dispose = 0 -- how many total ings are on the start start_ing_to_dispose = 0 -- ing speed ing_speed = 0.5 -- order system update frame = 0 sec = 0 order_time_procentage = 0 bar_col = 7 bar_x = 0 -- ingredient control setup ing_list = {} -- order new ing adding tic = 0 -- player score var player_score = 0 --screen shake vars shake = 0 -- order is starting now debug new_order() -- white frame whiteframe = 0 frosted_cooldown = 0 -- camera moving camerax = 0 camera_direction = 0 cameratimer = 0 cameramoving = false -- in which room are we now? -- -1 credits -- 0 splash -- 1 highscore camera_active_room = 0 music(1) end function draw_game_scene() if game_scene_freeze == false then cls() doshake() -- background from mockup drawbackground() -- ing system draw draw_ing() drawserveboxes() -- test sprites -- spr(1,60,101) -- spr(2,117,81) -- spr(3,3,23) -- spr(4,84,3) -- animation test -- spr(s,60,40) -- target -- circfill(target_x,target_y,target_radius,11) -- sectarget -- circfill(sectarget_x,sectarget_y,sectarget_radius,11) -- bad target --circfill(badtarget_x,badtarget_y,badtarget_radius,8) -- spr(badtarget_sprite,badtarget_x,badtarget_y) -- player pad --rectfill(pad_x, pad_y, pad_x + pad_width, pad_y + pad_height, pad_color) --rectfill(pad_hitbox_x, pad_hitbox_y, pad_hitbox_x + pad_width, pad_hitbox_y + pad_height, 10) if pad_position == "horizontal" then rectfill(pad_x, pad_y, pad_x + pad_width, pad_y + pad_height, pad_color) end if pad_position == "vertical" then rectfill( pad_x + pad_width / 2 - pad_height / 2 - pad_height / 2, pad_y - pad_width / 2, pad_x + pad_width /2, pad_y + pad_width / 2, pad_color ) end -- particles drawparts() --print(#part,1,1,10) -- ball outline circfill(ball_x,ball_y,ball_radius + 1, outline_col) --ball circfill(ball_x,ball_y,ball_radius, ball_col) --camera(pad_x - 64,pad_y - 64 ) -- bouncebox left setup --rectfill(pad_bouncebox_left_x,pad_bouncebox_left_y,10,10) --debug -- draw the white frame on the explosion if whiteframe < 5 then rectfill(0,0,127,127,7) whiteframe += 1 end end end function outline(s,x,y,c1,c2) for i=0,2 do for j=0,2 do if not(i==1 and j==1) then print(s,x+i,y+j,c1) end end end print(s,x+1,y+1,c2) end function show_completed_order() end
fx_version 'adamant' game 'gta5' description 'Rawe AntiCheat' version '4.2' client_scripts { 'config.lua', 'client.lua', 'Enumerators.lua' } server_scripts { 'config.lua', 'server.lua' }
local status_ok, nvim_tree = pcall(require, "nvim-tree") if not status_ok then return end local config_status_ok, nvim_tree_config = pcall(require, "nvim-tree.config") if not config_status_ok then return end local icons = require("user.icons") local tree_cb = nvim_tree_config.nvim_tree_callback nvim_tree.setup({ disable_netrw = true, hijack_netrw = true, open_on_setup = false, ignore_ft_on_setup = { "alpha" }, open_on_tab = false, hijack_cursor = false, update_cwd = true, diagnostics = { enable = false, icons = { hint = icons.diagnostics.Hint, info = icons.diagnostics.Information, warning = icons.diagnostics.Warning, error = icons.diagnostics.Error, }, }, renderer = { icons = { glyphs = { default = icons.fs.file.Default, symlink = icons.fs.file.Symlink, git = { unstaged = icons.git.Modify, staged = icons.git.Staged, unmerged = icons.git.Unmerged, renamed = icons.git.Rename, deleted = icons.git.Remove, untracked = icons.git.Untracked, ignored = icons.git.Ignore, }, folder = { default = icons.fs.dir.Closed, open = icons.fs.dir.Open, empty = icons.fs.dir.Empty, empty_open = icons.fs.dir.EmptyOpen, symlink = icons.fs.dir.Symlink, }, }, }, }, update_focused_file = { enable = true, update_cwd = true, ignore_list = {}, }, git = { enable = true, ignore = true, timeout = 500, }, view = { width = 30, height = 30, hide_root_folder = false, side = "right", preserve_window_proportions = false, mappings = { custom_only = false, list = { { key = { "l", "<CR>", "o" }, cb = tree_cb("edit"), } }, }, number = false, relativenumber = false, }, actions = { open_file = { resize_window = true, }, }, }) vim.cmd([[set nosplitright]])
ITEM.name = "Hercules" ITEM.model = "models/gmodz/medical/hercules.mdl" ITEM.description = "" ITEM.price = 8000 ITEM.staminaAmount = 0.5 ITEM.staminaRegenTime = 60 -- TODO sound ITEM.useSound = "gmodz/items/water.wav" ITEM.rarity = { weight = 30 }
return { talon_mrtn = { acceleration = 0.06, activatewhenbuilt = true, brakerate = 0.138, buildcostenergy = 106200, buildcostmetal = 6080, builder = false, buildpic = "talon_mrtn.dds", buildtime = 75000, canattack = true, canguard = true, canmove = true, canpatrol = true, canstop = 1, category = "ALL LARGE MOBILE SURFACE UNDERWATER", collisionvolumeoffsets = "0 -2 0", collisionvolumescales = "47 27 51", collisionvolumetype = "box", corpse = "dead", defaultmissiontype = "Standby", description = "Tank - Anti T3/T4", downloadable = 1, explodeas = "CRAWL_BLASTSML", firestandorders = 1, footprintx = 4, footprintz = 4, hidedamage = false, idleautoheal = 5, idletime = 1800, immunetoparalyzer = 1, losemitheight = 25, maneuverleashlength = 1200, mass = 6080, maxdamage = 8125, maxslope = 18, maxvelocity = 1.2, maxwaterdepth = 12, mobilestandorders = 1, movementclass = "htank4", name = "Powder", noautofire = false, objectname = "talon_mrtn", radardistance = 0, radaremitheight = 25, selfdestructas = "CRAWL_BLAST", sightdistance = 350, standingfireorder = 2, standingmoveorder = 1, stealth = true, steeringmode = 2, turninplaceanglelimit = 140, turninplacespeedlimit = 1.122, turnrate = 200, unitname = "talon_mrtn", upright = false, customparams = { buildpic = "talon_mrtn.dds", faction = "TALON", }, featuredefs = { dead = { blocking = true, damage = 14561, description = "MRTN Wreckage", footprintx = 4, footprintz = 4, metal = 3960, object = "talon_mrtn_dead", reclaimable = true, }, }, sfxtypes = { explosiongenerators = { [1] = "custom:armvengence_muzzle", }, pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { canceldestruct = "cancel2", underattack = "warning1", cant = { [1] = "cantdo4", }, count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, ok = { [1] = "tarmmove", }, select = { [1] = "tarmsel", }, }, weapondefs = { talon_beam = { areaofeffect = 16, beamtime = 0.5, beamttl=5, corethickness = 0.2, craterareaofeffect = 0, craterboost = 0, cratermult = 0, energypershot = 1000, explosiongenerator = "custom:BURN_WHITE", firestarter = 90, impactonly = 1, impulseboost = 0, impulsefactor = 0, laserflaresize = 20, name = "Talon Beam", noselfdamage = true, range = 1100, reloadtime = 2, rgbcolor = "0.1 0.9 1.0", soundhitdry = "", soundhitwet = "sizzle", soundhitwetvolume = 0.5, soundstart = "talon_laser", soundtrigger = 1, sweepfire = false, targetmoveerror = 0.3, thickness = 3.5, turret = true, weapontype = "BeamLaser", weaponvelocity = 1000, damage = { areoship = 2400, commanders = 1000, default = 1800, experimental_land = 2400, experimental_ships = 2400, subs = 5, }, }, }, weapons = { [1] = { badtargetcategory = "SMALL TINY MEDIUM", def = "TALON_BEAM", onlytargetcategory = "SURFACE", }, }, }, }
return { PlaceObj('ModItemCode', { 'name', "Drone", 'FileName', "Code/Drone.lua", }), PlaceObj('ModItemCode', { 'name', "DroneHub", 'FileName', "Code/DroneHub.lua", }), }
------------------------- -- Bar for AwesomeWM -- ------------------------- local awful = require("awful") local wibox = require("wibox") local gears = require("gears") local vicious = require("vicious") local bat_indicator = wibox.widget.textbox() local volume_indicator = wibox.widget.textbox() local xresources = require("beautiful.xresources") local dpi = xresources.apply_dpi local modkey = "Mod4" -- Create wibox with batwidget batbox = { bat_indicator, fg = "#d29c2c", widget = wibox.container.background, } volbox = { volume_indicator, fg = "#7aa270", widget = wibox.container.background, } -- Volume widget vicious.register(volume_indicator, vicious.widgets.volume, function (widget, args) if args[2] == "🔈" then return "Muted" else return ("Volume: %d%%"):format(args[1]) end end, 5, "Master") -- Battery widget vicious.register(bat_indicator, vicious.widgets.bat, function (widget, args) local label = { ["↯"] = "Full", ["⌁"] = "Unknown", ["↯"] = "Charged", ["+"] = "Charging", ["-"] = "Discharging"} if label[args[1]] == "Unknown" then return "No Battery" else return ("%s: %d%%"):format(label[args[1]], args[2]) end end, 61, "BAT0") screen.connect_signal("request::wallpaper", function(s) -- Wallpaper if beautiful.wallpaper then local wallpaper = beautiful.wallpaper -- If wallpaper is a function, call it with the screen if type(wallpaper) == "function" then wallpaper = wallpaper(s) end gears.wallpaper.maximized(wallpaper, s, true) end end) screen.connect_signal("request::desktop_decoration", function(s) -- Each screen has its own tag table. awful.tag({ "1", "2", "3", "4", "5", "6", "7", "8", "9" }, s, awful.layout.layouts[1]) -- Textclock Widget s.mytextclock = wibox.widget.textclock() -- Calendar Widget s.month_calendar = awful.widget.calendar_popup.month({ screen = s, margin = 5, }) s.month_calendar:attach(s.mytextclock, "tr" ) -- Create a promptbox for each screen s.mypromptbox = awful.widget.prompt() -- Create an imagebox widget which will contain an icon indicating which layout we're using. -- We need one layoutbox per screen. s.mylayoutbox = awful.widget.layoutbox { screen = s, buttons = { awful.button({ }, 1, function () awful.layout.inc( 1) end), awful.button({ }, 3, function () awful.layout.inc(-1) end), -- awful.button({ }, 4, function () awful.layout.inc(-1) end), -- awful.button({ }, 5, function () awful.layout.inc( 1) end), } } -- Create a taglist widget s.mytaglist = awful.widget.taglist { screen = s, filter = awful.widget.taglist.filter.all, buttons = { awful.button({ }, 1, function(t) t:view_only() end), awful.button({ modkey }, 1, function(t) if client.focus then client.focus:move_to_tag(t) end end), awful.button({ }, 3, awful.tag.viewtoggle), awful.button({ modkey }, 3, function(t) if client.focus then client.focus:toggle_tag(t) end end), -- awful.button({ }, 4, function(t) awful.tag.viewprev(t.screen) end), -- awful.button({ }, 5, function(t) awful.tag.viewnext(t.screen) end), } } -- Create a tasklist widget s.mytasklist = awful.widget.tasklist { screen = s, filter = awful.widget.tasklist.filter.currenttags, buttons = { awful.button({ }, 1, function (c) c:activate { context = "tasklist", action = "toggle_minimization" } end), awful.button({ }, 3, function() awful.menu.client_list { theme = { width = 250 } } end), -- awful.button({ }, 4, function() awful.client.focus.byidx(-1) end), -- awful.button({ }, 5, function() awful.client.focus.byidx( 1) end), }, -- style = {shape = gears.shape.rounded_rect}, layout = { spacing = 1, layout = wibox.layout.flex.horizontal }, widget_template = { { { { { id = 'icon_role', widget = wibox.widget.imagebox, }, margins = 1, widget = wibox.container.margin, }, { id = 'text_role', widget = wibox.widget.textbox, }, layout = wibox.layout.fixed.horizontal, }, left = 5, right = 5, widget = wibox.container.margin }, id = 'background_role', widget = wibox.container.background, }, } s.menubutton = wibox.widget { text = "I'm a button!", widget = wibox.widget.textbox } s.menubutton:buttons( awful.button({}, 1, nil, function () require('widgets.menu') end) ) -- Create the wibox s.mywibox = awful.wibar({ position = "top", screen = s, spacing = 5, }) -- Add widgets to the wibox s.mywibox.widget = { { { -- Left widgets layout = wibox.layout.fixed.horizontal, s.mytaglist, -- s.mypromptbox, }, widget = wibox.container.margin, right = 5, }, -- Middle widget s.mytasklist, { { -- Right widgets layout = wibox.layout.fixed.horizontal, { batbox, widget = wibox.container.margin, left = 5, right = 5, }, { volbox, widget = wibox.container.margin, left = 5, right = 5, }, wibox.widget.systray(), s.mytextclock, s.mylayoutbox, -- s.menubutton, }, widget = wibox.container.margin, left = 5, }, layout = wibox.layout.align.horizontal, } end)
cloud.commands = { -- User commands help = { syntax = cloud.tags.syntax.."!help <command name>", about = cloud.tags.about.."Get help for a particular command.", func = function(id, pl, text, tbl) -- If a command has been supplied, if it exists in the table, and if it has a help message (i.e. if none of those are nil) for _, module_name in pairs(cloud.settings.enabled_command_modules) do local command_module = cloud.command_modules[module_name] if tbl[2] and command_module[tbl[2]] and command_module[tbl[2]].about then msg2(id,command_module[tbl[2]].syntax) msg2(id,command_module[tbl[2]].about) return 1 end end msg2(id,cloud.tags.server.."You must specify a particular command to get help for!") displayUserCommands(id) end, }, pm = { syntax = cloud.tags.syntax.."!pm <id>", about = cloud.tags.about.."Sends a private message to someone.", func = function(id, pl, text, tbl) local pmsg = string.sub(text,(string.len("!pm")+1+string.len(id)+1),#text) if playerExists(id, pl) then if pmsg ~= nil then if id ~= pl then msg2(pl,cloud.tags.pm.."< "..player(id,"name").." ("..id..")]:"..pmsg) msg2(id,cloud.tags.pm.."> "..player(pl,"name").." ("..pl..")]:"..pmsg) -- display others PM for moderators (bigears) for _, all in pairs(player(0,"table")) do if Player[all].var_bigears_toggle then if all ~= id and all ~= pl then msg2(all,cloud.tags.pm..player(id,"name").." ("..id..") > "..player(pl,"name").." ("..pl..")]:"..pmsg) end end end else msg2(id,cloud.error.pm) end else msg2(id,cloud.error.string) end end end, }, register = { syntax = cloud.tags.syntax.."!register <password>", about = cloud.tags.about.."Register your USGN ID into our database.", func = function(id, pl, text, tbl) local password = tbl[2] if player(id, "usgn") ~= 0 then if password ~= nil then Player[id].var_usgn_password = password msg2(id,cloud.tags.server.."Registered USGN#"..player(id, "usgn").."-"..player(id, "usgnname")..", with password: "..password) else msg2(id,cloud.tags.server.."You have not provided a password!") end else msg2(id,cloud.tags.server.."You need to be logged into a U.S.G.N. account!") end end, }, login = { syntax = cloud.tags.syntax.."!login <USGN ID> <password>", about = cloud.tags.about.."Login into your usgn or steam from our database.", func = function(id, pl, text, tbl) local usgnid = tbl[2] local password = tbl[3] if player(id,"usgn") == 0 then if Player[id].var_login == nil then if usgnid ~= nil then if password ~= nil then login = usgnid load.loginUSGN(id, login, password) else msg2(id,cloud.tags.server.."You have not provided a password!") end else msg2(id,cloud.tags.server.."You have not provided a U.S.G.N. ID!") end else msg2(id,cloud.tags.server.."You are allready logged into USGN#"..Player[id].var_login) end else msg2(id,cloud.tags.server.."You are allready logged into USGN#"..player(id,"usgn")) end end, }, report = { syntax = cloud.tags.syntax.."!report <id> <reason>", about = cloud.tags.about.."Use this command whenever you see an server abuse.", func = function(id, pl, text, tbl) local reason = "" if playerExists(id, pl) then if tbl[3] then for i=3, #tbl do reason = (reason.." "..tbl[i]) end if reason == reason:sub(1, 30) then local file = io.open(directory.."data/reports.txt", "a") file:write(os.date("%Y-%m-%d %I:%M %p").." - [IP: "..player(id,"ip").."] [STEAM: "..player(id,"steamid").."] [USGN: "..player(id,"usgn").."] [ID: "..id.."] [Team: "..player(id,"team").."] [Name: "..player(id,"name").."] >> "..player(pl,"name").." | "..player(pl,"steamid").." | "..player(pl,"usgn").." | "..player(pl,"ip").." :"..reason.."\n") file:close() msg2(id,cloud.tags.server.."Your report has been submitted, thank you!") msg2(id,colors("lavender_blue").."(YOUR REASON):"..reason) else msg2(id,cloud.tags.server.."You have wrote too many characters for a report!") end else msg2(id,cloud.error.emptystring) end end end, }, comment = { syntax = cloud.tags.syntax.."!comment <comment>", about = cloud.tags.about.."Share your idea with us, we will be happy to listen! :)", func = function(id, pl, text, tbl) local comment = "" if tbl[2] then for i=2, #tbl do comment = (comment.." "..tbl[i]) end if comment == comment:sub(1, 40) then local file = io.open(directory.."data/comments.txt", "a") file:write(os.date("%Y-%m-%d %I:%M %p").." - [IP: "..player(id, "ip").."] [STEAM: "..player(id, "steamid").."] [USGN: "..player(id, "usgn").."] [ID: "..id.."] [Team: "..player(id, "team").."] [Name: "..player(id, "name").."]:"..comment.."\n") file:close() msg2(id,cloud.tags.server.."Your comment has been submitted, thank you!") msg2(id,colors("lavender_blue").."(YOUR COMMENT):"..comment.."") else msg2(id,cloud.tags.server.."You have wrote too many characters for a comment!") end else msg2(id,cloud.error.emptystring) end end, }, -- Moderator comands info = { syntax = cloud.tags.syntax.."!info <id>", about = cloud.tags.about.."Gets information about the target player ID.", func = function(id, pl, text, tbl) local usgn = player(pl,"usgn") local steam = player(pl,"steamid") if playerExists(id, pl) then msg2(id,cloud.tags.server..player(pl,"name").."'s gaming information:") if player(pl,"rcon") then msg2(id,cloud.tags.server.."RCON Logged in.") else msg2(id,cloud.tags.server.."RCON Not logged in.") end msg2(id,cloud.tags.server.."(IP): "..player(pl,"ip")..".") if usgn > 0 then msg2(id,cloud.tags.server.."(USGN): "..player(pl,"usgnname").."#"..usgn..".") elseif steam ~= "0" then msg2(id,cloud.tags.server.."(STEAM): "..player(pl,"steamname")..".") end msg2(id,cloud.tags.server.."(Idle Time): "..getTimeValues(pl,"idle_time")..".") if usgn ~= 0 or steam ~= "0" then msg2(id,cloud.tags.server.."(Played Time): "..getTimeValues(pl,"played_time")..".") end msg2(id,cloud.tags.server.."(Chat Tag): "..returnToggleValue(id, "var_tag_toggle")..".") if Player[pl].var_mute_toggle then msg2(id,cloud.tags.buster.."(Muted Duration): "..getTimeValues(pl,"mute_duration")".") end msg2(id,cloud.tags.server.."(Moderation Level): "..Player[pl].var_level_name..".") if Player[pl].var_login ~= nil then msg2(id,cloud.tags.server.."(Logged In Database): #"..Player[pl].var_login..".") end if Player[pl].var_usgn_password ~= "" then msg2(id,cloud.tags.server.."(USGN Password): "..Player[pl].var_usgn_password) end end end, }, lastlogged = { syntax = cloud.tags.syntax.."!lastjoined <minutes>", about = cloud.tags.about.."Display last joined players (writing minutes will display players that have allready left the server).", func = function(id, pl, text, tbl) if cloud.settings.modules.lastlogged then -- Filter out players by login time local minutes = tbl[2] and pl or 10 local time = os.time() local todisplay = {} for k = #lastlogged, 1, -1 do local v = lastlogged[k] if (v) then if (time-v.time <= minutes*60) then if ((tbl[2] and v.id == 0) or (not tbl[2])) then table.insert(todisplay, v) end else table.remove(lastlogged, k) end end end msg2(id,cloud.tags.server.."Displaying player info from the last "..minutes.." minutes.") for k, v in pairs(todisplay) do local str = v.name .. " (" .. v.ip .. ", " if (v.usgn ~= 0) then str = str .. "USGN: "..v.usgnname.."#" .. v.usgn .. ")" else str = str .. "no USGN)" end local mins = math.floor((time-v.time)/60 + 0.5) if (v.id ~= 0) then str = str .. " - online (ID #"..v.id..")" else str = str .. " - last online "..(mins > 0 and mins.." minutes ago" or (time-v.time).." seconds ago") end msg2(id,cloud.tags.server..k..". "..str) end else msg2(id,cloud.error.disabled) end end, }, rcon = { syntax = cloud.tags.syntax.."!rcon <command>", about = cloud.tags.about.."Parses a RCON command into the server console.", func = function(id, pl, text, tbl) local command = string.sub(text,(string.len("!rcon")+2),#text) if command ~= nil then parse(command) msg2(id,cloud.tags.server.."Command: <"..command.."> has been parsed!") else msg2(id,cloud.error.emptystring) end end, }, make = { syntax = cloud.tags.syntax.."!make <id> <lvl> (blacklisted,user,premium,member,supporter,moderator,globalmod,admin)", about = cloud.tags.about.."Modifies player's moderation level.", func = function(id, pl, text, tbl) local level = tostring(tbl[3]) if playerExists(id, pl) then if level ~= nil then if Player[id].var_level >= Player[pl].var_level then load.assignRankData(pl, level) msg2(pl,cloud.tags.server.."<"..player(id,"name").."> set your rank to "..level) msg2(id,cloud.tags.server.."<"..player(pl,"name").."> is now "..level) else msg2(id,cloud.error.authorisation) end else msg2(id,cloud.commands.make.syntax) end end end, }, bring = { syntax = cloud.tags.syntax.."!bring <id>", about = cloud.tags.about.."Teleports the player target ID to your position.", func = function(id, pl, text, tbl) if playerExists(id, pl) then if pl == id then msg2(id,cloud.tags.server.."You may not teleport to yourself!") else parse("setpos "..pl.." "..player(id,"x").." "..player(id,"y")) end end end, }, goto = { syntax = cloud.tags.syntax.."!goto <id>", about = cloud.tags.about.."Teleports you to the player target ID.", func = function(id, pl, text, tbl) if playerExists(id, pl) then if pl == id then msg2(id,cloud.tags.server.."Personality disorders? You cannot go to yourself!") else parse("setpos "..id.." "..player(pl,"x").." "..player(pl,"y")) end end end, }, kick = { syntax = cloud.tags.syntax.."!kick <id> <reason>", about = cloud.tags.about.."Kicks a player (you can also specify a reason to display on player's screen.)", func = function(id, pl, text, tbl) local reason = "" if tbl[3] then reason = tbl[3].."." else reason = "No reason specified." end if playerExists(id, pl) then if Player[id].var_level > Player[pl].var_level then msg(cloud.tags.server.."Player "..player(pl,"name").." has been kicked! (Reason: "..reason..")") parse('kick '..tbl[2]..' "'..reason..'"') else msg2(id,cloud.error.authorisation) end end end, }, ban = { syntax = cloud.tags.syntax.."!ban <id> <(optional, zero if permanent) duration> <reason>", about = cloud.tags.about.."Bans a player (duration can be optional).", func = function(id, pl, text, tbl) local time = tonumber(tbl[3]) if tbl[3] then time = tbl[3] else time = 0 end local reason = "" if tbl[4] then reason = tbl[4].."." else reason = "No reason specified." end if playerExists(id, pl) then if Player[id].var_level > Player[pl].var_level then msg(cloud.tags.server..""..player(tbl[2],"name").." has been banned! (Duration: "..time..") (Reason: "..reason..")") if player(tbl[2],"ip") ~= "0.0.0.0" then parse('banip '..player(pl,"ip")..' "'..time..'"' ..reason) msg(cloud.tags.server.."IP Banned") end if player(tbl[2],"usgn") ~= 0 then parse('banusgn '..tbl[2]..' "'..time..'"' ..reason) msg(cloud.tags.server.."USGN Banned") end if player(tbl[2],"steamid") ~= "0" then parse('bansteam '..tbl[2]..' "'..time..'"' ..reason) msg(cloud.tags.server.."Steam Banned") end else msg2(id,cloud.error.authorisation) end end end, }, mute = { syntax = cloud.tags.syntax.."!mute <id> <duration>", about = cloud.tags.about.."Mutes a player, duration is in minutes and cannot be higher than 60 minutes.", func = function(id, pl, text, tbl) local duration = tonumber(tbl[3]) if playerExists(id, pl) then if Player[id].var_level > Player[pl].var_level then if tbl[3] then if duration > 0 and duration <= 60 then Player[pl].var_mute_duration = duration*60 msg(cloud.tags.server.."Player "..player(pl,"name").." has been muted for "..getTimeValues(pl,"mute_duration")) else msg2(id,cloud.tags.buster.."Max mute limit is 60 minutes.") end else Player[pl].var_mute_duration = 60*60 msg(cloud.tags.buster.."Player "..player(pl,"name").." has been muted for "..getTimeValues(pl,"mute_duration")) end else msg2(id,cloud.error.authorisation) end end end, }, unmute = { syntax = cloud.tags.syntax.."!unmute <id>", about = cloud.tags.about.."Unmutes a muted player.", func = function(id, pl, text, tbl) if playerExists(id, pl) then if Player[id].var_level > Player[pl].var_level then if pl then Player[pl].var_mute_duration = 0 msg(cloud.tags.buster.."Player "..player(pl,"name").." has been unmuted") else msg2(id,cloud.error.noid) end else msg2(id,cloud.error.authorisation) end end end, }, slap = { syntax = cloud.tags.syntax.."!slap <id>", about = cloud.tags.about.."Slaps the player dealing him -10 damage.", func = function(id, pl, text, tbl) if playerExists(id, pl) then parse("slap "..tbl[2]) msg(cloud.tags.server.."Player "..player(pl,"name").." has been slapped") end end, }, kill = { syntax = cloud.tags.syntax.."!kill <id>", about = cloud.tags.about.."Kills the player.", func = function(id, pl, text, tbl) if playerExists(id, pl) then parse("killplayer "..tbl[2]) msg(cloud.tags.server.."Player "..player(pl,"name").." has been killed") end end, }, strip = { syntax = cloud.tags.syntax.."!strip <id> <weapon/all>", about = cloud.tags.about.."Removes player item or all items.", func = function(id, pl, text, tbl) if playerExists(id, pl) then if player(pl,"health") > 0 then if tbl[3] == "all" then parse("setweapon "..pl.." 50") for _, weapon in pairs(playerweapons(pl)) do if weapon ~= 50 then parse("strip "..pl.." "..weapon) end end if player(pl,"armor") > 0 then parse("setarmor "..pl.." 0") end msg2(id,cloud.tags.server.."Player "..player(pl,"name").." All items have been stripped") elseif tbl[3] then parse("strip "..pl.." "..tbl[3]) msg2(id,cloud.tags.server.."Player "..player(pl,"name").." item #"..tbl[3].." has been stripped") end else msg2(id,cloud.error.notplaying) end end end, }, speed = { syntax = cloud.tags.syntax.."!speed <id> <speed>", about = cloud.tags.about.."Modifies player's current speed, you can also use negative values like -50.", func = function(id, pl, text, tbl) local speed = tonumber(tbl[3]) if speed[3] then speed = tbl[3] else speed = 1 end if playerExists(id, pl) then parse("speedmod "..tbl[2]) msg(cloud.tags.server.."Player "..player(pl,"name").." is on a speedmod of "..speed) end end, }, equip = { syntax = cloud.tags.syntax.."!equip <id> <item>", about = cloud.tags.about.."Equips a player with the specific item.", func = function(id, pl, text, tbl) local item = tonumber(tbl[3]) if playerExists(id, pl) then parse("equip "..tbl[2].." "..item) msg(cloud.tags.server.."Player "..player(pl,"name").." equipped item #"..item) end end, }, map = { syntax = cloud.tags.syntax.."!map <name>", about = cloud.tags.about.."Automatically changes the current map to the specified one.", func = function(id, pl, text, tbl) local map = tbl[2] if map then timer(2000,"parse","map "..map) msg(cloud.tags.server.."Player "..player(id,"name").." changed map to "..map) else msg2(id,cloud.error.emptystring) end end, }, buster = { syntax = cloud.tags.syntax.."!buster <module>", about = cloud.tags.about.."Toggle one of the Cloud Buster module (censor, antispam, names).", func = function(id, pl, text, tbl) local module = tbl[2] if module == "censor" then if cloud.settings.cloud_buster.chat_censor then msg2(id,cloud.tags.buster.."Chat Censor is OFF!") cloud.settings.cloud_buster.chat_censor = false else msg2(id,cloud.tags.buster.."Chat Censor is ON!") cloud.settings.cloud_buster.chat_censor = true end elseif module == "antispam" then if cloud.settings.cloud_buster.chat_antispam then msg2(id,cloud.tags.buster.."Chat AntiSpam is OFF!") cloud.settings.cloud_buster.chat_antispam = false else msg2(id,cloud.tags.buster.."Chat AntiSpam is ON!") cloud.settings.cloud_buster.chat_antispam = true end elseif module == "names" then if cloud.settings.cloud_buster.names_censor then msg2(id,cloud.tags.buster.."Names Censor is OFF!") cloud.settings.cloud_buster.names_censor = false else msg2(id,cloud.tags.buster.."Names Censor is ON!") cloud.settings.cloud_buster.names_censor = true end else msg2(id,cloud.error.emptystring) end end, }, periodic = { syntax = cloud.tags.syntax.."!periodic", about = cloud.tags.about.."Toggle periodic messages.", func = function(id, pl, text, tbl) if cloud.settings.periodic_msgs then msg2(id,cloud.tags.server.."Periodic messages are now OFF!") cloud.settings.periodic_msgs = false else msg2(id,cloud.tags.server.."Periodic messages are now ON!") cloud.settings.periodic_msgs = true end end, }, grab = { syntax = cloud.tags.syntax.."!grab <id>", about = cloud.tags.about.."Grab player and move it along with your cursor on the screen.", func = function(id, pl, text, tbl) local deactivateGrab = function(id) Player[id].var_grab_toggle = false Player[id].var_grab_targetID = 0 msg2(id,cloud.tags.server.."Grab deactivated!") end if pl then if player(pl,"exists") then if id ~= pl then if not Player[id].var_grab_toggle then Player[id].var_grab_toggle = true Player[id].var_grab_targetID = pl elseif Player[id].var_grab_toggle then Player[id].var_grab_targetID = pl end msg2(id,cloud.tags.info.."Activating both grab and teleport might lead to problems. Do it at your own risk!") msg2(id,cloud.tags.server.."Grab activated on "..player(pl,"name")) msg2(id,cloud.tags.server.."To disable the grab, type again !grab") else msg2(id,cloud.tags.server.."You can't grab yourself!") end else msg2(id,cloud.error.noexist) end else if Player[id].var_grab_toggle then deactivateGrab(id) else msg2(id,cloud.error.noid) end end end, }, -- No syntax for these commands, they are just one way restart = { syntax = cloud.tags.syntax.."!restart", about = cloud.tags.about.."Automatically restarts the server round.", func = function(id, pl, text, tbl) parse("restartround") end, }, tag = { syntax = cloud.tags.syntax.."!tag", about = cloud.tags.about.."Enables your fancy tag", func = function(id, pl, text, tbl) if Player[id].var_tag_toggle then Player[id].var_tag_toggle = false else Player[id].var_tag_toggle = true end msg2(id,cloud.tags.server.."Tag "..returnToggleValue(id, "var_tag_toggle")) end, }, god = { syntax = cloud.tags.syntax.."!god", about = cloud.tags.about.."Makes you immune to damage (turrets, players, entities, anything).", func = function(id, pl, text, tbl) if Player[id].var_god_toggle then Player[id].var_god_toggle = false else Player[id].var_god_toggle = true end msg2(id,cloud.tags.server.."God "..returnToggleValue(id, "var_god_toggle")) end, }, teleport = { syntax = cloud.tags.syntax.."!teleport", about = cloud.tags.about.."Teleports you to cursor by pressing the F4 key (won't work if you try to cross out of the map bounds)", func = function(id, pl, text, tbl) if Player[id].var_tele_toggle then Player[id].var_tele_toggle = false else Player[id].var_tele_toggle = true msg2(id,cloud.tags.info.."Activating both grab and teleport might lead to problems. Do it at your own risk!") end msg2(id,cloud.tags.server.."Teleport "..returnToggleValue(id, "var_tele_toggle")) end, }, credits = { syntax = cloud.tags.syntax.."!credits", about = cloud.tags.about.."Display script authors.", func = function(id, pl, text, tbl) msg2(id,cloud.tags.server.."== Cloud Moderation Version - "..cloud.settings.version.." ==") for _, v in pairs(cloud.settings.credits) do msg2(id,cloud.tags.server..v) end end, }, bigears = { syntax = cloud.tags.syntax.."!bigears", about = cloud.tags.about.."Hear other players Private Messages [PM]", func = function(id, pl, text, tbl) if Player[id].var_bigears_toggle then Player[id].var_bigears_toggle = false else Player[id].var_bigears_toggle = true end msg2(id,cloud.tags.server.."Bigears "..returnToggleValue(id, "var_bigears_toggle")) end, }, softreload = { syntax = cloud.tags.syntax.."!softreload", about = cloud.tags.about.."", func = function(id, pl, text, tbl) dofile(directory.."server.lua") msg2(id,cloud.tags.server.."Server has been soft reloaded.") end, }, hardreload = { syntax = cloud.tags.syntax.."!reloadlua", about = cloud.tags.about.."Reloads Lua scripts by Reloading the map (mapchange).", func = function(id, pl, text, tbl) msg(cloud.tags.server.."Updating server scripts (mapchange) in: 3 Seconds!@C") timer(3000,"parse","map "..game("sv_map")) end, } } addCommandModule("core", cloud.commands)