content
stringlengths
5
1.05M
pfUI:RegisterModule("easteregg", function () if date("%m%d") == "1224" or date("%m%d") == "1225" then -- merry x-mas! local title = (UnitFactionGroup("player") == "Horde") and PVP_RANK_18_0 or PVP_RANK_18_1 _G.CHAT_FLAG_AFK = title .. " " _G.MARKED_AFK = "|cff33ffccpf|cffffffffUI|r wishes you a merry christmas, |cff33ffcc" .. title .. "|r." _G.MARKED_AFK_MESSAGE = "|cff33ffccpf|cffffffffUI|r wishes you a merry christmas, |cff33ffcc" .. title .. "|r: %s" _G.CLEARED_AFK = "You are no longer |cff33ffcc" .. title .. "|r." end end)
--[[ Deep Convolutional Generative Adversarial Network (DCGAN). Using deep convolutional generative adversarial networks to generate face images from a noise distribution. References: - Generative Adversarial Nets. Goodfellow et al. arXiv: 1406.2661. - Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks. A Radford, L Metz, S Chintala. arXiv: 1511.06434. Links: - [GAN Paper](https://arxiv.org/pdf/1406.2661.pdf). - [DCGAN Paper](https://arxiv.org/abs/1511.06434.pdf). Author: Prabhsimran Singh Project: https://github.com/pskrunner14/face-DCGAN/tree/master/face-DCGAN.torch ]] local DCGAN = {} DCGAN.__index = DCGAN -- "Understanding the difficulty of training deep feedforward neural networks" -- Xavier Glorot, 2010 local function w_init_xavier(fan_in, fan_out) return math.sqrt(2/(fan_in + fan_out)) end -- Randomly initializes the weights and biases of a network module. local function weights_init(m) local name = torch.type(m) if name:find('Convolution') then m:reset(w_init_xavier(m.nInputPlane * m.kH * m.kW, m.nOutputPlane * m.kH * m.kW)) -- m.weight:normal(0.0, 0.02) m.bias:zero() elseif name:find('BatchNormalization') then if m.weight then m.weight:normal(1.0, 0.02) end if m.bias then m.bias:zero() end end end -- DCGAN Generator Network (different from paper) function DCGAN.generator(z_dim) local net = nn.Sequential() --[[ DENSE 1 ]]-- net:add(nn.Linear(z_dim, 8 * 8 * 10)) net:add(nn.BatchNormalization(8 * 8 * 10)) net:add(nn.LeakyReLU(0.2, true)) net:add(nn.View(-1, 10, 8, 8)) --[[ DECONV 1 ]]-- net:add(nn.SpatialFullConvolution(10, 64, 5, 5)) net:add(nn.SpatialBatchNormalization(64)) net:add(nn.LeakyReLU(0.2, true)) --[[ DECONV 2]]-- net:add(nn.SpatialFullConvolution(64, 64, 5, 5)) net:add(nn.SpatialBatchNormalization(64)) net:add(nn.LeakyReLU(0.2, true)) --[[ UPSAMPLING ]]-- net:add(nn.SpatialUpSamplingNearest(2)) --[[ DECONV 3 ]]-- net:add(nn.SpatialFullConvolution(64, 32, 7, 7)) net:add(nn.SpatialBatchNormalization(32)) net:add(nn.LeakyReLU(0.2, true)) --[[ FINAL CONV ]]-- net:add(nn.SpatialConvolution(32, 3, 3, 3)) net:add(nn.Tanh()) net:apply(weights_init) return net end -- DCGAN Discriminator Network (different from paper) function DCGAN.discriminator() local net = nn.Sequential() --[[ CONV 1 ]]-- net:add(nn.SpatialConvolution(3, 32, 3, 3, 1, 1, 1, 1)) -- same padding with stride 1 net:add(nn.SpatialBatchNormalization(32)) net:add(nn.LeakyReLU(0.2, true)) net:add(nn.SpatialAveragePooling(2, 2, 1, 1)) --[[ CONV 2 ]]-- net:add(nn.SpatialConvolution(32, 32, 3, 3, 2, 2, 1, 1)) -- same padding with stride 2 net:add(nn.SpatialBatchNormalization(32)) net:add(nn.LeakyReLU(0.2, true)) net:add(nn.SpatialAveragePooling(2, 2, 1, 1)) net:add(nn.SpatialDropout(0.5)) --[[ DENSE 1 ]]-- net:add(nn.View(-1):setNumInputDims(3)) -- flatten net:add(nn.Linear(9248, 256)) net:add(nn.BatchNormalization(256)) net:add(nn.LeakyReLU(0.2, true)) net:add(nn.Dropout(0.5)) --[[ FINAL DENSE ]]-- net:add(nn.Linear(256, 1)) net:add(nn.Sigmoid()) net:apply(weights_init) return net end return DCGAN
-------------------------------------------------------------------------------- -- 0205-tdeepequals-other-functions.lua: tests for other tdeepequals functions -- This file is a part of lua-nucleo library -- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license) -------------------------------------------------------------------------------- local make_suite = assert(loadfile('test/test-lib/init/strict.lua'))(...) local check_ok = import 'test/test-lib/tdeepequals-test-utils.lua' { 'check_ok' } -------------------------------------------------------------------------------- local less_kv, tless_kv, tsort_kv, ordered_pairs = import 'lua-nucleo/tdeepequals.lua' { 'less_kv', 'tless_kv', 'tsort_kv', 'ordered_pairs' } -------------------------------------------------------------------------------- local test = make_suite("tdeepequals-other-functions") -------------------------------------------------------------------------------- -- Test based on real bug scenario -- https://github.com/lua-nucleo/lua-nucleo/issues/31 test 'Test ordered_pairs()' (function() local t1 = {b = {}} local t2 = {a = {}} local test = {[t1] = '', [t2] = ''} local ordered = {t2, t1} local i = 1 for k, v in ordered_pairs(test) do check_ok(ordered[i], k, true) i = i + 1 end end) test:UNTESTED 'less_kv' test:UNTESTED 'tless_kv' test:UNTESTED 'tsort_kv'
#!/usr/bin/lua --[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uvl = require "luci.uvl" local util = require "luci.util" if not arg[1] then util.perror("Usage %s scheme_name" % arg[0]) os.exit(1) end local scheme, error = uvl.UVL():get_scheme(arg[1]) if not scheme then print( error:string() ) os.exit(1) end print('cbimap = Map(%q, %q, %q)\n' % { scheme.name, scheme.title or scheme.name, scheme.description or "" } ) for sn, sv in util.kspairs(scheme.sections) do print('%s = cbimap:section(TypedSection, %q, %q, %q)' % { sn, sn, sv.title or "", sv.description or "" } ) if not sv.named then print('%s.anonymous = true' % sn) end if not sv.unique then print('%s.addremove = true' % sn) end if sv.dynamic then print('%s.dynamic = true' % sn) end if sv.depends then for _, dep in ipairs(sv.depends) do print('%s:depends(%s)' % { sn, util.serialize_data(dep) } ) end end print('') for vn, vv in util.kspairs(scheme.variables[sn]) do if not vv.type or vv.type == "variable" then print('%s = %s:option(%s, %q, %q, %q)' % { vn, sn, vv.datatype == "boolean" and "Flag" or "Value", vn, vv.title or "", vv.description or "" } ) elseif vv.type == "enum" then print('%s = %s:option(%s, %q, %q, %q)' % { vn, sn, vv.multival and "MultiValue" or "ListValue", vn, vv.title or "", vv.description or "" } ) for _, val in ipairs(vv.valuelist or {}) do print('%s:value(%q, %q)' % { vn, val.value, val.title or val.value } ) end elseif vv.type == "list" or vv.type == "lazylist" then print('%s = %s:option(DynamicList, %q, %q, %q)' % { vn, sn, vn, vv.title or "", vv.description or "" } ) else print('-- option: type(%s) ?' % { vv.type or "" } ) end if vv.default then print('%s.default = %q' % { vn, vv.default } ) end if vv.required then print('%s.optional = false' % vn ) end if not vv.required then print('%s.rmempty = true' % vn ) end for _, dep in ipairs(vv.depends or {}) do print('%s:depends(%s)' % { vn, util.serialize_data(dep) } ) end print('') end print('\nreturn cbimap') end
local nbody = require(arg[1]) local N = tonumber(arg[2]) or 1000 -- or 50000000 local REP = tonumber(arg[3]) or 1 -- N-body benchmark from benchmarks game -- https://benchmarksgame-team.pages.debian.net/benchmarksgame/description/nbody.html -- -- Original code by Mike Pall and Geoff Leyland, with modifications by Hugo -- Gualandi for correctness, clarity, and compatibility with Pallene. -- * Fix implementation of advance() to use two outer loops. -- * Use #xs instead of passing "n" as a parameter to all the functions -- * Use math.sqrt instead of caching sqrt in a local variable -- * Use 0.0 instead of 0 where appropriate. -- * Don't use multiple assignments. -- -- Expected output (N = 1000): -- -0.169075164 -- -0.169087605 -- -- Expected output (N = 50000000): -- -0.169075164 -- -0.169059907 local PI = 3.141592653589793 local SOLAR_MASS = 4 * PI * PI local DAYS_PER_YEAR = 365.24 local bodies = { nbody.new_body( -- Sun 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, SOLAR_MASS), nbody.new_body( -- Jupiter 4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01, 1.66007664274403694e-03 * DAYS_PER_YEAR, 7.69901118419740425e-03 * DAYS_PER_YEAR, -6.90460016972063023e-05 * DAYS_PER_YEAR, 9.54791938424326609e-04 * SOLAR_MASS ), nbody.new_body( -- Saturn 8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01, -2.76742510726862411e-03 * DAYS_PER_YEAR, 4.99852801234917238e-03 * DAYS_PER_YEAR, 2.30417297573763929e-05 * DAYS_PER_YEAR, 2.85885980666130812e-04 * SOLAR_MASS ), nbody.new_body( -- Uranus 1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01, 2.96460137564761618e-03 * DAYS_PER_YEAR, 2.37847173959480950e-03 * DAYS_PER_YEAR, -2.96589568540237556e-05 * DAYS_PER_YEAR, 4.36624404335156298e-05 * SOLAR_MASS ), nbody.new_body( -- Neptune 1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01, 2.68067772490389322e-03 * DAYS_PER_YEAR, 1.62824170038242295e-03 * DAYS_PER_YEAR, -9.51592254519715870e-05 * DAYS_PER_YEAR, 5.15138902046611451e-05 * SOLAR_MASS ), } nbody.offset_momentum(bodies) print(string.format("%0.9f", nbody.energy(bodies))) for _ = 1, REP do nbody.advance_multiple_steps(N, bodies, 0.01) end print(string.format("%0.9f", nbody.energy(bodies)))
object_tangible_furniture_decorative_event_lifeday07_orb = object_tangible_furniture_decorative_shared_event_lifeday07_orb:new { } ObjectTemplates:addTemplate(object_tangible_furniture_decorative_event_lifeday07_orb, "object/tangible/furniture/decorative/event_lifeday07_orb.iff")
local _M = {} function _M.split(text, delimiter) if text.find(text, delimiter) == nil then return { text } end local splited_texts = {} local last_position for splited_text, position in text:gmatch("(.-)"..delimiter.."()") do table.insert(splited_texts, splited_text) last_position = position end table.insert(splited_texts, string.sub(text, last_position)) return splited_texts end function _M.split_lines(text) local lines = {} local function splitter(line) table.insert(lines, line) return "" end text:gsub("(.-\r?\n)", splitter) return lines end function _M.new(self) local object = {} setmetatable(object, object) object.__index = self return object end return _M
----------------------------------------------------------------------------------------- -- -- main.lua -- This is main screen of ----------------------------------------------------------------------------------------- -- TODO LIST --[[ * DO I REALLY NEED STOP MUSIC BUTTON? --]] -- Display background as white(1,1,1), (r,g,b). --display.setDefault( "background", 1, 1, 1 ) local composer = require( "composer" ) local scene = composer.newScene() -- Require the widget library local widget = require( "widget" ) local centerX = display.contentCenterX local centerY = display.contentCenterY local _W = display.contentWidth local _H = display.contentHeight --Hide the status bar display.setStatusBar( display.HiddenStatusBar ) --Require the widget library ( we will use this to create buttons and other gui elements ) local widget = require( "widget" ) -- The device will auto-select the theme or you can set it here widget.setTheme( "widget_theme_ios" ) -- iOS5/6 theme --widget.setTheme( "widget_theme_ios7" ) -- iOS7 theme -- widget.setTheme( "widget_theme_android" ) -- android theme --Box to underlay our audio status text local gradient = { type = 'gradient', color1 = {94/255,181/255,100/255}, color2 = { 20/255, 143/255, 17/255 }, direction = "down" } function backButtonRelease() print("backButtonRelease function") print("back to menu") composer.gotoScene( "mainmenu", "fade", 200 ) return true -- indicates successful touch end -- create all objects function scene:create( event ) local sceneGroup = self.view -- Display background image. display.setDefault( "background", 198/255, 198/255, 198/255 ) -- silver -- sellinne, et supportida ka nt S3 ja iphone 5 oskab scaleda paremini http://forums.coronalabs.com/topic/39290-modernizing-the-configlua-rob-miracle-article/ --local background = display.newImage("images/green_background.png",true) -- background.x = display.contentWidth / 2 -- center the image -- background.y = display.contentHeight / 2 local statusBoxHeight = 100 local statusBox = display.newRect( display.contentCenterX, display.screenOriginY, display.actualContentWidth, statusBoxHeight ) statusBox:setFillColor( gradient ) -- statusBox.fill = gradient statusBox.alpha = 0.9 local backButton = widget.newButton { defaultFile = "images/back_button.png", overFile = "images/back_buttonOver.png", label = "", --emboss = true, -- white and grey, default= normal. over= pressed labelColor = { default={ 1, 1, 1 }, over={ 0, 0, 0, 1 } }, onPress = backButtonPress, onRelease = backButtonRelease, } -- 20 on siis Y, et täpselt olla samas kohas. ja 30 selleks, et pilt ise on umbes 60 pixlit+paddingud ja seetõttu on selline arv. backButton.x = 30; backButton.y = statusBox.y+25 --Create a text object to show the current status local statusText = display.newText( "Audio Test", statusBox.x, statusBox.y+25, native.systemFontBold, 18 ) --Variable to store what platform we are on. local platform --Check what platform we are running this sample on if system.getInfo( "platformName" ) == "Android" then platform = "Android" elseif system.getInfo( "platformName" ) == "Mac OS X" then platform = "Mac" elseif system.getInfo( "platformName" ) == "Win" then platform = "Win" else platform = "IOS" end --[[] juhuks kui vaja kunagi muid faile panna ["Mac"] = { extensions = { ".aac", ".aif", ".caf", ".wav", ".mp3", ".ogg" } }, ["IOS"] = { extensions = { ".aac", ".aif", ".caf", ".wav", ".mp3" } }, ["Win"] = { extensions = { ".wav", ".mp3", ".ogg" } }, ["Android"] = { extensions = { ".wav", ".mp3", ".ogg" } }, } --]] --Create a table to store what types of audio are supported per platform local supportedAudio = { ["Mac"] = { extensions = {".mp3" } }, ["IOS"] = { extensions = { ".mp3" } }, ["Win"] = { extensions = { ".mp3"} }, ["Android"] = { extensions = {".mp3" } }, } --Create a table to store what types of audio files should be streamed or loaded fully into memory. local loadTypes = { ["sound"] = { extensions = { } }, ["stream"] = { extensions = { ".mp3"} } } --Forward references for our buttons/labels local volumeLabel local playButton, stopButton --Variables local audioFiles = { "Skisofreenia","Rõõmus" } --Table to store what audio files are available for playback. (ie included in the app). local audioLoaded, audioHandle = nil, nil --Variables to hold audio states. local audioLoops = 0 --Variables to hold audio states. local audioVolume = 0.5 --Variables to hold audio states. local audioWasStopped = false -- Variable to hold whether or not we have manually stopped the currently playing audio. --Set the initial volume to match our initial audio volume variable audio.setVolume( audioVolume, { channel = 1 } ) --Handle slider events local function sliderListener( event ) local value = event.value --Convert the value to a floating point number we can use it to set the audio volume audioVolume = value / 100 audioVolume = string.format('%.02f', audioVolume ) --Update the volume text to reflect the new value volumeLabel.text = "Volume: " .. string.format('%i', audioVolume*100 ) --Set the audio volume at the current level audio.setVolume( audioVolume, { channel = 1 } ) end --Create a slider to control the volume level local volumeSlider = widget.newSlider { --loopButton.x, loopButton.y = display.contentCenterX, stopButton.y + stopButton.contentHeight + loopButton.contentHeight * 0.5 - 10 left = 50, top = 160, -- X cordinate -- top = 210 width = _W - 80, orientation = "horizontal", listener = sliderListener } --Create our volume label to display the current volume on screen volumeLabel = display.newText( "Volume: " .. string.format('%i', audioVolume*10 ) .. "0", centerX, volumeSlider.y -40, native.systemFontBold, 18 ) volumeLabel:setFillColor( 0, 0, 0) -- Set up the Picker Wheel's columns local columnData = { { align = "center", width = 280, startIndex = 1, labels = audioFiles, } } --Create the picker which will display our audio files & extensions local audioPicker = widget.newPickerWheel { top = volumeSlider.y + 50, width = 360, font = native.systemFontBold, columns = columnData, } --Set the audio to loop forever in test screen audioLoops = -1 --Function to handle all button events local function manageButtonEvents( event ) local phase = event.phase local buttonPressed = event.target.id if phase == "began" then --Loop Button --Play button if buttonPressed == "PlayAudio" then --Toggle the buttons state ( 1 or 0 ) playButton.toggle = 1 - playButton.toggle --Function to reset the play button state when audio completes playback local function resetButtonState() playButton:setLabel( "Play" ); playButton.toggle = 0 --Only update the status text to finished if we didn't stop the audio manually if audioWasStopped == false then --Update status text end --Set the audioWasStopped flag back to false audioWasStopped = false end --Audio playback is set to paused if playButton.toggle == 0 then --Pause any currently playing audio if audio.isChannelPlaying( 1 ) then audio.pause( 1 ) end --Set the buttons label to "Resume" playButton:setLabel( "Resume" ) --Update status text --Audio playback is set to play else --If the audio is paused resume it if audio.isChannelPaused( 1 ) then audio.resume( 1 ) --Update status text --If not play it from scratch else local audioFileSelected = audioPicker:getValues()[1].index local audioExtensionSelected = ".mp3" --Print what sound we have loaded to the terminal -- print( "Loaded sound:", audioFiles[ audioFileSelected ] .. supportedAudio[ platform ].extensions[ audioExtensionSelected ] ) --If we are trying to load a sound, then use loadSound if supportedAudio[ platform ].extensions[ audioFileSelected ] == loadTypes[ "sound" ].extensions[ audioExtensionSelected ] then --Load the audio file fully into memory audioLoaded = audio.loadStream( audioFiles[ audioFileSelected ] .. ".mp3" ) -- loadsound too laggy -- audioLoaded = audio.loadSound( audioFiles[ audioFileSelected ] .. ".mp3" ) --Play audio file audioHandle = audio.play( audioLoaded, { channel = 1, loops = audioLoops, onComplete = resetButtonState } ) else --Load the audio file in chunks audioLoaded = audio.loadStream( audioFiles[ audioFileSelected ] .. ".mp3" ) --Play the audio file audioHandle = audio.play( audioLoaded, { channel = 1, loops = audioLoops, onComplete = resetButtonState } ) end end --Set the buttons label to "Pause" playButton:setLabel( "Pause" ) end --Stop button elseif buttonPressed == "StopAudio" then --If there is audio playing on channel 1 if audio.isChannelPlaying( 1 ) then --Stop the audio audio.stop( 1 ) --Let the system know we stopped the audio manually audioWasStopped = true --No audio currently playing else end end end return true end --Play/pause/resume Button playButton = widget.newButton{ id = "PlayAudio", style = "sheetBlack", label = "Play", yOffset = - 3, fontSize = 24, emboss = true, width = 140, onEvent = manageButtonEvents, } playButton.toggle = 0 playButton.x, playButton.y = playButton.contentWidth * 0.5 + 10, 80 --Stop button local stopButton stopButton = widget.newButton{ id = "StopAudio", style = "sheetBlack", label = "Stop", yOffset = - 3, fontSize = 24, emboss = true, width = 140, onEvent = manageButtonEvents, } stopButton.x, stopButton.y = display.contentWidth - stopButton.contentWidth * 0.5 - 10, 80 -- sceneGroup:insert(background) sceneGroup:insert(backButton) -- siin järjekorras, et tekiks teistsugune buttoni effekt. Saab mängida nii. sceneGroup:insert(statusBox) sceneGroup:insert(volumeSlider) sceneGroup:insert(volumeLabel) sceneGroup:insert(audioPicker) -- maybe disable this one sceneGroup:insert(playButton) sceneGroup:insert(stopButton) sceneGroup:insert(statusText) end function scene:show( event ) local sceneGroup = self.view local phase = event.phase if phase == "will" then -- Called when the scene is still off screen and is about to move on screen elseif phase == "did" then -- Called when the scene is now on screen -- -- INSERT code here to make the scene come alive -- e.g. start timers, begin animation, play audio, etc. end end function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if event.phase == "will" then audio.stop( 1 ) -- Called when the scene is on screen and is about to move off screen -- -- INSERT code here to pause the scene -- e.g. stop timers, stop animation, unload sounds, etc.) elseif phase == "did" then -- Called when the scene is now off screen end end function scene:destroy( event ) local sceneGroup = self.view audio.stop(backgroundSound) -- Called prior to the removal of scene's "view" (sceneGroup) -- -- INSERT code here to cleanup the scene -- e.g. remove display objects, remove touch listeners, save state, etc. -- -- Dispose the handles from memory and 'nil' out each reference --[[ audio.dispose( laserSound ) audio.dispose( backgroundMusic ) laserSound = nil --prevents the handle from being used again backgroundMusic = nil --prevents the handle from being used again --]] end --- MUSIC PART --------------------------------------------------------------------------------- -- Comments: -- Supports: .aac, .aif, .caf, .wav, .mp3 and .ogg audio formats -- Notes: -- iOS ( iPhone/iPad/iPod Touch ) doesn't support .ogg format audio. -- Android only supports .wav, .mp3 and .ogg format audio. -- -- -- Sample code is MIT licensed, see http://www.coronalabs.com/links/code/license -- Copyright (C) 2012 Corona Labs Inc. All Rights Reserved. -- -- Supports Graphics 2.0 --------------------------------------------------------------------------------------- --[[ function onKeyEvent( event ) local phase = event.phase local keyName = event.keyName print( event.phase, event.keyName ) if ( "back" == keyName and phase == "up" ) then print("backButtonRelease function") print("back to menu") composer.gotoScene( "mainmenu", "fade", 200 ) end return true -- to Override physical back button end Runtime:addEventListener( "key", onKeyEvent ) --]] --------------------------------------------------------------------------------- -- Listener setup scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) ----------------------------------------------------------------------------------------- return scene
local teams = { --{"Military Forces",0,110,0}, --{"GIGN",0,0,100}, } function getGroups() local official = {} for k,v in ipairs(teams) do if v then table.insert(official,v[1]) end end return official end function getFirstLaw() return "Military Forces" or "GIGN" end function getFirstLawColor() for k,v in ipairs(teams) do if v[1] == "Military Forces" then return v[2],v[3],v[4] elseif v[1] == "GIGN" then return v[2],v[3],v[4] end end end function isFirstLaw(p) if getPlayerTeam(p) then if getTeamName(getPlayerTeam(p)) == "Military Forces" then return true else return false end else return false end end
if game.SinglePlayer() then hook.Add("EntityTakeDamage", "ArcCW_ETD", function(npc, dmg) timer.Simple(0, function() if !IsValid(npc) then return end if npc:Health() <= 0 then net.Start("arccw_sp_health") net.WriteEntity(npc) net.Broadcast() end end) end) end
--[[ TermsitionTerminal.lua Copyright (C) 2016 Kano Computing Ltd. License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2 ]]-- return { type = "repeat", dialogues = { --- 1) Welcome dialogue ------------------------------------------------------------- { type = "copy", copy = { "termsitionTerminal1" }, arguments = {}, options = { { letsGo = "GAME_EVENT_MOVE_TO_OVERWORLD" } , }, }, } }
Locales['br'] = { ['911'] = '~g~Central~s~ : O alarme anti-roubo de um veículo foi disparado na area indicadas.', ['alarm1'] = '%s$ - sistema basico de alarme', ['alarm2'] = '%s$ - sistema de alarme com conexão a policia', ['alarm3'] = '%s$ - sistema de alarme de alta tecnologia com GPS', ['alarminterface'] = '%s$ - Interface do sistema de alarme', ['alarm1_install'] = 'O ~g~sistema basico de alarme~s~ foi ~r~instalado~s~', ['alarm2_install'] = 'O ~g~sistema de alarme com conexão a policia~s~ foi ~r~instalado~s~', ['alarm3_install'] = 'O ~g~sistema de alarme de alta tecnologia com GPS~s~ foi ~r~instalado~s~', ['alarm_max_lvl'] = 'O ~g~sistema de alarme~s~ instalado já é o melhor disponivél', ['alarm_not_install'] = 'O ~g~sistema de alarme~s~ não pode ser instalado.', ['checkvehicle'] = 'Um momento estamos checando o nosso estoque', ['hammerwirecutter'] = '%s$ - Kit para arrombamento basico', ['illegalusedetect'] = '~r~USO NÃO AUTORIZADO DETECTADO', ['inspect'] = '~b~Você observa se a chave está em contato..', ['jammer'] = '%s$ - Bloqueador de sinal (Ilegal)', ['jammeruse'] = 'Sinal mexido', ['max_item'] = 'Você não pode carregar mais disto com você.', ['memoryformating'] = 'O software da interface foi apagado.', ['no_cops'] = 'Para fazer é preciso mais policias na cidade', ['not_enough_money'] = 'você não tem dinheiro suficiente', ['not_work_with_npc'] = 'Nos não queremos este veículo no momento', ['pawn_shop_blip'] = 'Receptador de veículos', ['pawn_shop_menu'] = 'Pressione ~r~E~s~ para falar com o negociador', ['black_garage_menu'] = 'Press ~r~E~s~ to open Illegal Garage menu', ['pawnshop_buyitem'] = 'Comprar equipamento', ['pawnshop_menu_title'] = 'negociação com receptador', ['black_menu_title'] = 'Illegal Garage', ['pawnshop_rebuy'] = 'Comprar um veículo roubado', ['blackgarage_resell'] = 'Vender um veículo roubado', ['please_wait'] = 'Você está forçando a fechadura... ~b~%s minutos %s segundos~s~', ['resellcar'] = 'compre um veículo roubado', ['rucops'] = 'Checando sua identificação.........', ['stolen_car'] = 'Veículo ROUBADO', ['truecop'] = 'Use allow. Desligue o alarme', ['unlockingtool'] = '%s$ - Kit para arrombamento sofisticado (Ilegal)', ['vehicle_buy'] = 'pojazd został ~g~comprar~s~ for ~g~$%s~s~', ['vehicle_notunlocked'] = 'Você ~r~falhou~s~ em destrancar o veículo.', ['vehicle_sold'] = 'pojazd został ~g~sprzedany~s~ for ~g~$%s~s~', ['vehicle_unlocked'] = 'Veículo ~g~destrancado~s~', ['warning'] = '~r~Você se distanciou do receptador', ['we_r_busy'] = '~r~Desculpe~s~ , mas estamos ocupados com outro veículo, volte mais tarde.', }
object_draft_schematic_space_cargo_hold_crg_starfighter_small = object_draft_schematic_space_cargo_hold_shared_crg_starfighter_small:new { } ObjectTemplates:addTemplate(object_draft_schematic_space_cargo_hold_crg_starfighter_small, "object/draft_schematic/space/cargo_hold/crg_starfighter_small.iff")
--[[ This file is part of xmldom. It is subject to the licence terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/pallene-modules/xmldom/master/COPYRIGHT. No part of xmldom, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. Copyright © 2015 The developers of xmldom. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/pallene-modules/xmldom/master/COPYRIGHT. ]]-- local halimede = require('halimede') local xmldom = require('xmldom') local slaxml = xmldom.slaxml local Node = xmldom.Node local assert = halimede.assert local areInstancesEqual = halimede.table.equality.areInstancesEqual local ProcessingInstructionPseudoAttribute = xmldom.ProcessingInstructionPseudoAttribute local ProcessingInstructionNode = halimede.moduleclass('ProcessingInstructionNode', Node) module.static.isComment = false module.static.isElement = false module.static.isProcessingInstruction = true module.static.isText = false function module:initialize(name, value) assert.parameterTypeIsString('name', name) assert.parameterTypeIsString('value', value) self.name = name self.value = value end function module:__tostring() return ('<?%s %s?>'):format(self.name, self.value) end local simpleEqualityFieldNames = {'name', 'value'} local shallowArrayFieldNames = {} local potentiallyNilFieldNames = {} function module:__eq(right) return areInstancesEqual(self, right, simpleEqualityFieldNames, shallowArrayFieldNames, potentiallyNilFieldNames) end -- has pseudo attributes version="1.0" encoding="UTF-8" standalone="no" function module:isXmlDeclaration() return 'xml' == self.name end local XmlDeclarationPsuedoAttributeValidators = { version = function(value) if value == '1.0' or value == '1.1' then return tonumber(value) * 10 else return nil end end, encoding = function(value) -- Other values are valid but not supported if value == 'UTF-8' or value == 'US-ASCII' then return value else return nil end end, standalone = function(value) if value == 'yes' then return true elseif value == 'no' then return false else return nil end end, } local XmlDeclarationPsuedoAttributeDefaults = { version = 10, encoding = 'UTF-8', standalone = true, } function module:xmlDeclarationPseudoAttributes() if not self:isXmlDeclaration() then exception.throw('Not a XML declaration') end return self:parsePseudoAttributesAsATableWithDefaults(XmlDeclarationPsuedoAttributeValidators, XmlDeclarationPsuedoAttributeDefaults) end -- must appear in the prolog, before the document or root element function module:isXmlStyleSheet() -- Expected pseudo attributes: https://www.w3.org/TR/xml-stylesheet/#the-xml-stylesheet-processing-instruction return 'xml-stylesheet' == self.name end local XmlStyleSheetPsuedoAttributeValidators = { href = function(value) return value end, type = function(value) return value end, title = function(value) return value end, -- Could be stricter: See https://www.w3.org/TR/css3-mediaqueries/ media = function(value) return value end, charset = function(value) -- Other values are valid but not supported if value == 'UTF-8' or value == 'US-ASCII' then return value else return nil end end, alternate = function(value) if value == 'yes' then return true elseif value == 'no' then return false else return nil end end, } local XmlStyleSheetPseudoAttributeDefaults = { media = 'screen', charset = 'UTF-8', alternate = false, } function module:xmlStyleSheetPseudoAttributes() if not self:isXmlStyleSheet() then exception.throw('Not a XML style sheet') end return self:parsePseudoAttributesAsATableWithDefaults(XmlStyleSheetPsuedoAttributeValidators, XmlStyleSheetPseudoAttributeDefaults) end function module:parsePseudoAttributesAsATableWithDefaults(validPsuedoAttributeNamesTableOrNilIfAllAreValid, defaults) local table = {} self:parsePseudoAttributes(function(psuedoAttribute) psuedoAttribute:addValueUniquelyToTableWithValueValidationAndConversion(table, validPsuedoAttributeNamesTableOrNilIfAllAreValid) end) for defaultName, defaultValue in pairs(defaults) do if table[defaultName] == nil then table[defaultName] = defaultValue end end return table end function module:parsePseudoAttributesAsAnArray() local array = {} self:parsePseudoAttributes(function(psuedoAttribute) array[#array + 1] = psuedoAttribute end) end local fakeElementName = 'X' function module:parsePseudoAttributes(callback) local slaxmlParser = slaxml:parser{ startElement = function(uninternedSimpleName, potentiallyNilUninternedNamespaceUri, potentiallyNilNamespacePrefix) -- in theory, a psuedo-attribute could be named 'xmlns', so this test isn't perfect if uninternedSimpleName ~= fakeElementName or potentiallyNilUninternedNamespaceUri ~= nil or potentiallyNilNamespacePrefix ~= nil then exception.throw('Bad psuedo-attributes or a pseudo-attribute that is like a XML namespace xmlns is present') end end, attribute = function(uninternedSimpleName, value, potentiallyNilUninternedNamespaceUri, potentiallyNilNamespacePrefix) if potentiallyNilUninternedNamespaceUri ~= nil or potentiallyNilNamespacePrefix ~= nil then exception.throw("Bad psuedo-attribute '%s'", uninternedSimpleName) end callback(ProcessingInstructionPseudoAttribute:new(uninternedSimpleName, value)) end, closeElement = function(uninternedSimpleName, potentiallyNilUninternedNamespaceUri, potentiallyNilNamespacePrefix) if uninternedSimpleName ~= fakeElementName or potentiallyNilUninternedNamespaceUri ~= nil or potentiallyNilNamespacePrefix ~= nil then exception.throw('Bad psuedo-attributes') end end, text = function(text) exception.throw('Should not be parsing text in psuedo-attributes of a XML processing instruction') end, comment = function(comment) exception.throw('Should not be parsing comments in psuedo-attributes of a XML processing instruction') end, pi = function(uninternedName, unparsedAttributes) exception.throw('Should not be parsing processing instructions in psuedo-attributes of a XML processing instruction') end } slaxmlParser:parse(self.value, {}) collectgarbage() end
local def_pitch_range = range(20*60, 80*60) DefineClass.MDSLaser = { __parents = { "ElectricityConsumer", "OutsideBuildingWithShifts" }, properties = { { template = true, category = "MDSLaser", name = T{671, "Hit Chance"}, id = "hit_chance", editor = "number", default = 100, min = 0, max = 100, help = "The chance to hit a meteor" }, { template = true, category = "MDSLaser", name = T{672, "Fire Rate"}, id = "cooldown", editor = "number", default = 5 * 1000, scale = 1000, help = "cooldown between shots in seconds(only useful during a meteor storm)" }, { template = true, category = "MDSLaser", name = T{673, "Protect Range"}, id = "protect_range", editor = "number", default = 20, help = "If meteors would fall within dist range it can be destroyed by the laser (in hexes)" }, { template = true, category = "MDSLaser", name = T{674, "Shoot Range"}, id = "shoot_range", editor = "number", default = 30, scale = guim, help = "Range at which meteors can be destroyed. Should be greater than the protection range (in hexes)" }, { template = true, category = "MDSLaser", name = T{675, "Pitch Range"}, id = "pitch_range", editor = "range", default = def_pitch_range, scale = 60, help = "Range of the pitch angle for vertical adjustment (in Deg)" }, { template = true, category = "MDSLaser", name = T{676, "Rotate Speed"},id = "rot_speed", editor = "number", default = 45 * 60, scale = 60, help = "Platform's rotation speed to target meteor in Deg/Sec" }, { template = true, category = "MDSLaser", name = T{677, "Beam Time"}, id = "beam_time", editor = "number", default = 500, help = "For how long laser beam is visible(in ms)" }, { template = true, category = "MDSLaser", name = T{678, "Tilt Tolerance"},id = "tilt_tolerance",editor = "number", default = 2 * 60, scale = 60, help = "Allowed angle difference between the beam and shooting dir(in degrees)" }, }, platform = false, laser = false, beams = false, track_thread = false, cooldown_end = 0, meteor = false, } DefineClass.LaserBody = { __parents = { "Object" }, enum_flags = { efWalkable = false, efCollision = false, efApplyToGrids = false }, entity = "Shuttle", } function MDSLaser:GameInit() local platform = self:GetAttach("DefenceLaserPlatform") if not platform then assert(false, "Laser Platform for rotation not present") return end local tube = platform:GetAttach("DefenceLaserTube") if not tube then assert(false, "Laser Tube for firing not present") return end self.platform = platform self.tube = tube tube:SetAxis(axis_y) local starting_yaw = self:GetAngle() local starting_pitch = (self.pitch_range.to + self.pitch_range.from) / 2 local rot_time = MulDivRound(1000, starting_pitch, self.rot_speed) self:SetLaserOrientation(0, starting_yaw) self:SetLaserOrientation(starting_pitch, starting_yaw, rot_time) local meteor = self:GetSoonestMeteor() if meteor then self:Track(meteor) end end function MDSLaser:SetLaserOrientation(pitch, yaw, time) local tube = self.tube if not IsValid(tube) then return end time = time or 0 yaw = yaw - self:GetAngle() pitch = -pitch tube:SetAngle(pitch, time) self.platform:SetAngle(yaw, time) end function MDSLaser:GetLaserOrientation() local tube = self.tube if not IsValid(self.tube) then return 0, 0 end return -tube:GetVisualAngleLocal(), self.platform:GetVisualAngle() end function MDSLaser:Done() DeleteThread(self.track_thread) if self.beams then for i=1,#self.beams do DoneObject(self.beams[i]) end if IsValid(self.meteor) then PlayFX("Laser", "end", self, self.meteor) end end if self:GetCooldownLeft() > 0 then PlayFX("LaserCooldown", "end", self.tube) end end function MDSLaser:GetShootDir() local tube = self.tube if not IsValid(tube) then return self:GetPos(), axis_x -- savegame compatibility end local vertex = tube:GetSpotPos(tube:GetSpotBeginIndex("Conusvertex")) local target = tube:GetSpotPos(tube:GetSpotBeginIndex("Conusdirection")) return vertex, target end function MDSLaser:IsExecuting() return IsValid(self.meteor) end function MDSLaser:CanHit(meteor) if not IsValid(meteor) or not self:CanWork() or self:IsExecuting() or self:GetCooldownLeft() > 0 or IsValid(meteor.marked) and meteor.marked ~= self or HexAxialDistance(self, meteor.dest) > self.protect_range then return false end return true end function MDSLaser:GetSoonestMeteor() local soonest_time, soonest_meteor = max_int for _, meteor in ipairs(g_MeteorsPredicted) do local time = self:CanHit(meteor) and meteor:GetTimeToImpact() or max_int if soonest_time > time then soonest_time = time soonest_meteor = meteor end end for missile in pairs(g_IncomingMissiles or empty_table) do local time = self:CanHit(missile) and missile:GetTimeToImpact() or max_int if soonest_time > time then soonest_time = time soonest_meteor = missile end end return soonest_meteor, soonest_time end function MDSLaser:GetCooldownLeft() return Max(0, self.cooldown_end - GameTime()) end function MDSLaser:Track(meteor) meteor.marked = self self.meteor = meteor self.track_thread = CreateGameTimeThread(function(self, meteor) local min_picth, max_pitch = self.pitch_range.from, self.pitch_range.to local rot_speed = self.rot_speed local tilt_tolerance = self.tilt_tolerance local shoot_range = self.shoot_range * const.GridSpacing local reaction_time = 100 while true do local intercepted local pos = meteor:GetVisualPos() while IsValid(meteor) do local origin, target = self:GetShootDir() if self:IsCloser(pos, shoot_range) and CalcAngleBetween(pos - origin, target - origin) <= tilt_tolerance then intercepted = true break end pos = meteor:GetVisualPos(reaction_time) local vector = pos - origin local len = vector:Len() if len == 0 then break end local pitch0, yaw0 = self:GetLaserOrientation() local yaw1 = atan(vector) local yaw_rot = AngleDiff(yaw1, yaw0) local yaw_time = MulDivRound(1000, abs(yaw_rot), rot_speed) local pitch1 = Clamp(asin(MulDivRound(vector:z(), 4096, len)), min_picth, max_pitch) local pitch_rot = AngleDiff(pitch1, pitch0) local pitch_time = MulDivRound(1000, abs(pitch_rot), rot_speed) local time = Max(pitch_time, yaw_time) self:SetLaserOrientation(pitch1, yaw1, time) Sleep(reaction_time) end -- stop interpolation self:SetLaserOrientation(self:GetLaserOrientation()) if IsValid(meteor) and intercepted then -- fire local origin = self:GetShootDir() local vector = pos - origin local total_len = vector:Len() if total_len > 0 then PlayFX("Laser", "start", self, meteor, origin, vector) local beam = PlaceObject("DefenceLaserBeam") local beam_len = beam:GetEntityBBox():max():z() local beam_offset = point(0, 0, beam_len) local beams = {} self.beams = beams local added_len = 0 local next_pos = origin local axis, angle = GetAxisAngle(axis_z, vector) while true do beams[#beams + 1] = beam beam:SetPos(next_pos) beam:SetAxisAngle(axis, angle) added_len = added_len + beam_len if added_len >= total_len then beam:SetZClip(beam_len - (added_len - total_len)) break end next_pos = beam:GetRelativePoint(beam_offset) beam = PlaceObject("DefenceLaserBeam") end if self:Random(100) < self.hit_chance then Msg("MeteorIntercepted", meteor, self) meteor:ExplodeInAir() end Sleep(self.beam_time) for i=1,#beams do DoneObject(beams[i]) end self.beams = false PlayFX("Laser", "end", self, meteor) -- cooldown PlayFX("LaserCooldown", "start", self.tube) self.cooldown_end = GameTime() + self.cooldown Sleep(self.cooldown) PlayFX("LaserCooldown", "end", self.tube) end end self.meteor = false local new_meteor = self:GetSoonestMeteor() meteor.marked = nil meteor = new_meteor if not meteor then break end self.meteor = meteor meteor.marked = self end self.track_thread = false end, self, meteor) end function MDSLaser:GetSelectionRadiusScale() return self.protect_range end local function SeekAndDestroy(obj) assert(IsKindOf(obj, "BaseMeteor"), "Invalid object to track!") local lasers = UICity.labels.MDSLaser or empty_table local soonest_laser, min_rot_time = nil, max_int for _, laser in ipairs(lasers) do if laser:CanHit(obj) then local origin, target = laser:GetShootDir() local yaw_angle = CalcAngleBetween(obj.dest - origin, target - origin) local rot_time = MulDivTrunc(yaw_angle, 1000, laser.rot_speed) if min_rot_time > rot_time then soonest_laser = laser min_rot_time = rot_time end end end if not soonest_laser then local towers = UICity.labels.DefenceTower or empty_table for _, tower in ipairs(towers) do if tower:CanHit(obj) then soonest_laser = tower break end end end if not soonest_laser then local rovers = UICity.labels.Rover or empty_table for _, rover in ipairs(rovers) do if IsKindOf(rover, "AttackRover") and rover.reclaimed and rover:CanHit(obj) then soonest_laser = rover break end end end if soonest_laser then soonest_laser:Track(obj) end end function OnMsg.Meteor(meteor) SeekAndDestroy(meteor) end function OnMsg.IncomingMissile(missile) SeekAndDestroy(missile) end function OnMsg.GatherFXActors(list) list[#list + 1] = "MDSLaser" end function OnMsg.GatherFXActions(list) list[#list + 1] = "Laser" list[#list + 1] = "LaserCooldown" end
-- Dialogue for NPC "npc_vincent2" loadDialogue = function(DL) if (not DL:isConditionFulfilled("npc_vincent", "talked")) then DL:setRoot(1) elseif (DL:isQuestState("spoiled_fire", "started") and not DL:isConditionFulfilled("npc_rhendal", "spoiled_schnapps")) then DL:setRoot(9) elseif (DL:isQuestState("spoiled_fire", "started") and DL:isConditionFulfilled("npc_rhendal", "spoiled_schnapps")) then DL:setRoot(10) elseif (not DL:isConditionFulfilled("npc_vincent2", "talked") and DL:isQuestState("spoiled_fire", "completed")) then DL:setRoot(11) elseif (not DL:isConditionFulfilled("npc_vincent2", "talked") and DL:isConditionFulfilled("npc_vincent", "disgruntled")) then DL:setRoot(12) elseif (not DL:isConditionFulfilled("npc_vincent2", "talked")) then DL:setRoot(13) elseif (DL:isQuestState("elder_chest", "void")) then DL:setRoot(2) elseif (DL:isQuestState("elder_chest", "started")) then DL:setRoot(35) elseif (DL:isQuestState("elder_chest", "completed") and not DL:isConditionFulfilled("npc_vincent2", "second_quest")) then DL:setRoot(39) elseif (DL:isQuestState("invis_recipe", "void")) then DL:setRoot(41) elseif (DL:isQuestState("invis_recipe", "failed") and not DL:isConditionFulfilled("npc_vincent2", "trusted_failed")) then DL:setRoot(47) else DL:setRoot(45) end if (not DL:isConditionFulfilled("npc_vincent", "talked")) then DL:createNPCNode(1, -2, "DL_Vincent_NotTalked") -- Hey you, psst! You look like you could use some gold. Interested in a ... special job? DL:addConditionProgress("npc_vincent", "talked") DL:addConditionProgress("npc_vincent2", "talked") DL:addConditionProgress("npc_vincent2", "key_50") DL:addNode() end if (DL:isQuestState("spoiled_fire", "started") and not DL:isConditionFulfilled("npc_rhendal", "spoiled_schnapps")) then DL:createNPCNode(9, -1, "DL_Vincent_DoYourDuty") -- You remember that little deal we had in the tavern? You'd better do your job soon. DL:addNode() end if (DL:isQuestState("spoiled_fire", "started") and DL:isConditionFulfilled("npc_rhendal", "spoiled_schnapps")) then DL:createNPCNode(10, 14, "DL_NPC_TaskFulfilled") -- Oh, it's you. You have carried out my task. Very good. You might be of use. DL:changeQuestState("spoiled_fire", "completed") DL:addGold(50) DL:addReputationProgress("thief", 10) DL:addNode() DL:createNPCNode(14, -2, "DL_Vincent_FurtherJob") -- Interested in another job? DL:addConditionProgress("npc_vincent2", "talked") DL:addNode() end if (not DL:isConditionFulfilled("npc_vincent2", "talked") and DL:isQuestState("spoiled_fire", "completed")) then DL:createNPCNode(11, -2, "DL_Vincent_YouAgainGood") -- Hey. Good to see you here. My plan has worked out. Interested in another job? DL:addConditionProgress("npc_vincent2", "talked") DL:addNode() end if (not DL:isConditionFulfilled("npc_vincent2", "talked") and DL:isConditionFulfilled("npc_vincent", "disgruntled")) then DL:createNPCNode(12, -2, "DL_Vincent_Disgruntled") -- Oh... you again. Y'know, I would have offered you an awesome job, if you hadn't been so aggressive. If you want another chance, it will cost you something. DL:addConditionProgress("npc_vincent2", "talked") DL:addConditionProgress("npc_vincent2", "key_150") DL:addNode() end if (not DL:isConditionFulfilled("npc_vincent2", "talked")) then DL:createNPCNode(13, -2, "DL_Vincent_NotCooperated") -- Oh look. The boy who wasn't interested. Maybe a second chance for a job, huh? DL:addConditionProgress("npc_vincent2", "talked") DL:addConditionProgress("npc_vincent2", "key_100") DL:addNode() end if (DL:isQuestState("elder_chest", "void")) then DL:createChoiceNode(2) if (not DL:isConditionFulfilled("npc_vincent2", "job_talked")) then DL:addChoice(3, "DL_Choice_WhatDeal") -- Tell me more about that job. end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_50") and DL:hasItem("gold", 50)) then DL:addItemChoice(5, "DL_Choice_GimmeKey", "gold", 50) -- Give me that key, I'll do it. end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_50") and not DL:hasItem("gold", 50)) then DL:addItemChoice(15, "DL_Choice_GimmeKey", "gold", 50) -- end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_100") and DL:hasItem("gold", 100)) then DL:addItemChoice(16, "DL_Choice_GimmeKey", "gold", 100) -- end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_100") and not DL:hasItem("gold", 100)) then DL:addItemChoice(17, "DL_Choice_GimmeKey", "gold", 100) -- end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_150") and DL:hasItem("gold", 150)) then DL:addItemChoice(18, "DL_Choice_GimmeKey", "gold", 150) -- end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_150") and not DL:hasItem("gold", 150)) then DL:addItemChoice(19, "DL_Choice_GimmeKey", "gold", 150) -- end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and not (DL:isConditionFulfilled("npc_vincent2", "key_150") or DL:isConditionFulfilled("npc_vincent2", "key_100") or DL:isConditionFulfilled("npc_vincent2", "key_50")) ) then DL:addChoice(31, "DL_Choice_GimmeKey") -- end DL:addChoice(8, "DL_Choice_NotInterested") -- I'm not interested. DL:addChoice(-1, "") -- DL:addNode() if (not DL:isConditionFulfilled("npc_vincent2", "job_talked")) then DL:createNPCNode(3, 4, "DL_Vincent_ExplainDeal") -- (Smiles and pulls out a golden key) I got this small key here. It belongs to a treasure chest. I could give it to you, if you want... DL:addConditionProgress("npc_vincent2", "job_talked") DL:addNode() DL:createChoiceNode(4) if (DL:isConditionFulfilled("npc_vincent2", "key_150")) then DL:addChoice(6, "DL_Cendric_WhereCatch") -- And what is the catch? end if (DL:isConditionFulfilled("npc_vincent2", "key_100")) then DL:addChoice(7, "DL_Cendric_WhereCatch") -- end if (DL:isConditionFulfilled("npc_vincent2", "key_50")) then DL:addChoice(20, "DL_Cendric_WhereCatch") -- end if (not DL:isConditionFulfilled("npc_vincent2", "key_50") and not DL:isConditionFulfilled("npc_vincent2", "key_100") and not DL:isConditionFulfilled("npc_vincent2", "key_150")) then DL:addChoice(21, "DL_Cendric_WhereCatch") -- end DL:addNode() if (DL:isConditionFulfilled("npc_vincent2", "key_150")) then DL:createNPCNode(6, 22, "DL_Vincent_TheCatch") -- Hehe, I knew you would ask. Well, the treasure chest doesn't belong to me, so to speak - it belongs to the Elder Rhendal. DL:addNode() DL:createNPCNode(22, 23, "DL_Vincent_KeyCost150") -- I had to steal the key from him. It wasn't easy, as he was fully awake. DL:addNode() DL:createNPCNode(23, 49, "DL_Vincent_KeyCost150_2") -- It wouldn't have been a problem if you did what I told you before... Now, to compensate for my troubles, it will cost you 150 golden coins. DL:addNode() DL:createNPCNode(49, -2, "DL_Vincent_Treasure") -- I only want you to get a special blue stone from the Elder's chest for me. You can keep the rest for yourself. DL:addNode() end if (DL:isConditionFulfilled("npc_vincent2", "key_100")) then DL:createNPCNode(7, 24, "DL_Vincent_TheCatch") -- DL:addNode() DL:createNPCNode(24, 25, "DL_Vincent_KeyCost100") -- I had to steal the key from him. It wasn't easy, as he was fully awake. DL:addNode() DL:createNPCNode(25, 50, "DL_Vincent_KeyCost100_2") -- It wouldn't have been a problem if you did what I told you before... Now, to compensate for my troubles, it will cost you 100 golden coins. DL:addNode() DL:createNPCNode(50, -2, "DL_Vincent_Treasure") -- DL:addNode() end if (DL:isConditionFulfilled("npc_vincent2", "key_50")) then DL:createNPCNode(20, 26, "DL_Vincent_TheCatch") -- DL:addNode() DL:createNPCNode(26, 27, "DL_Vincent_KeyCost50") -- I had to steal the key from him. So, a small fee of 50 golden coins for the key would be a good compensation. DL:addNode() DL:createNPCNode(27, -2, "DL_Vincent_Treasure") -- DL:addNode() end if (not DL:isConditionFulfilled("npc_vincent2", "key_50") and not DL:isConditionFulfilled("npc_vincent2", "key_100") and not DL:isConditionFulfilled("npc_vincent2", "key_150")) then DL:createNPCNode(21, 28, "DL_Vincent_TheCatch") -- DL:addNode() DL:createNPCNode(28, 29, "DL_Vincent_KeyCost0") -- You remember the stuff I mixed into the schnapps you gave him? DL:addNode() DL:createNPCNode(29, 52, "DL_Vincent_KeyCost0_2") -- It was a sleeping powder. Getting the key from him was mere child's play. DL:addNode() DL:createNPCNode(52, -2, "DL_Vincent_Treasure") -- DL:addNode() end end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_50") and DL:hasItem("gold", 50)) then DL:createNPCNode(5, 30, "DL_Vincent_StartElderQuest") -- A good choice. Here you go. DL:removeGold(50) DL:addItem("ke_rhendal", 1) DL:addNode() DL:createNPCNode(30, 54, "DL_Vincent_ChestIsObserved") -- The chest is in a secret room in the Elder's house, behind the wall to the West. DL:changeQuestState("elder_chest", "started") DL:addNode() DL:createNPCNode(54, -2, "DL_Vincent_ChestIsObserved2") -- Oh, and it's most likely guarded by observer spells. Just make sure that they don't catch you. DL:addNode() end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_50") and not DL:hasItem("gold", 50)) then DL:createNPCNode(15, -1, "DL_Vincent_NotEnoughGold") -- Come back when you have enough gold. DL:addNode() end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_100") and DL:hasItem("gold", 100)) then DL:createNPCNode(16, 32, "DL_Vincent_StartElderQuest") -- DL:removeGold(100) DL:addItem("ke_rhendal", 1) DL:addNode() DL:createNPCNode(32, -2, "DL_Vincent_ChestIsObserved") -- DL:changeQuestState("elder_chest", "started") DL:addNode() end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_100") and not DL:hasItem("gold", 100)) then DL:createNPCNode(17, -1, "DL_Vincent_NotEnoughGold") -- DL:addNode() end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_150") and DL:hasItem("gold", 150)) then DL:createNPCNode(18, 33, "DL_Vincent_StartElderQuest") -- DL:removeGold(150) DL:addItem("ke_rhendal", 1) DL:addNode() DL:createNPCNode(33, -2, "DL_Vincent_ChestIsObserved") -- DL:changeQuestState("elder_chest", "started") DL:addNode() end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and DL:isConditionFulfilled("npc_vincent2", "key_150") and not DL:hasItem("gold", 150)) then DL:createNPCNode(19, -1, "DL_Vincent_NotEnoughGold") -- DL:addNode() end if (DL:isConditionFulfilled("npc_vincent2", "job_talked") and not (DL:isConditionFulfilled("npc_vincent2", "key_150") or DL:isConditionFulfilled("npc_vincent2", "key_100") or DL:isConditionFulfilled("npc_vincent2", "key_50")) ) then DL:createNPCNode(31, 34, "DL_Vincent_StartElderQuest") -- DL:addItem("ke_rhendal", 1) DL:addNode() DL:createNPCNode(34, -2, "DL_Vincent_ChestIsObserved") -- DL:changeQuestState("elder_chest", "started") DL:addNode() end DL:createNPCNode(8, -1, "DL_Vincent_Pity") -- What a pity. DL:addConditionProgress("npc_vincent", "talked") DL:addConditionProgress("npc_vincent2", "talked") DL:addNode() end if (DL:isQuestState("elder_chest", "started")) then DL:createChoiceNode(35) if (not DL:isConditionFulfilled("npc_vincent2", "observer_spells")) then DL:addChoice(36, "DL_Choice_ObserverSpells") -- What are "observer spells"? end if (DL:isQuestState("elder_chest", "started") and DL:isConditionFulfilled("npc_vincent2", "rhendal_chest_looted")) then DL:addChoice(37, "DL_Choice_FoundChest") -- I got the gem from the Elder's chest... end DL:addChoice(-1, "DL_Choice_CU") -- See you later. DL:addNode() if (not DL:isConditionFulfilled("npc_vincent2", "observer_spells")) then DL:createNPCNode(36, 48, "DL_Vincent_ObserverSpells") -- A nasty form of magic. People place it in their homes so that thieves won't be able to steal something. DL:addConditionProgress("npc_vincent2", "observer_spells") DL:addHint("ObserverSpell") DL:addNode() DL:createNPCNode(48, -2, "DL_Vincent_ObserverSpells2") -- But they can't see everything... (grins). But if they see you stealing something, they will put you in jail. It won't be a nice experience, I can tell you that. DL:addNode() end if (DL:isQuestState("elder_chest", "started") and DL:isConditionFulfilled("npc_vincent2", "rhendal_chest_looted")) then DL:createNPCNode(37, 38, "DL_Vincent_OpenedTheChest") -- Hehe, I knew you'd succeed. But I don't want that stone anyway, you can keep it as your reward. DL:addNode() DL:createNPCNode(38, -2, "DL_Vincent_StealingFitsYou") -- Taking belongings from other people doesn't seem to be a big deal for you. I could teach you how to get to even more valuables. DL:changeQuestState("elder_chest", "completed") DL:addReputationProgress("thief", 5) DL:addNode() end end if (DL:isQuestState("elder_chest", "completed") and not DL:isConditionFulfilled("npc_vincent2", "second_quest")) then DL:createChoiceNode(39) DL:addChoice(40, "DL_Choice_TeachMe") -- Teach me. DL:addChoice(-1, "") -- DL:addNode() DL:createNPCNode(40, -2, "DL_Vincent_TeachUnlock") -- Of course. Just read this scroll and I can offer you more work in this... domain. (Grins) DL:addItem("sp_unlock", 1) DL:addConditionProgress("npc_vincent2", "second_quest") DL:addNode() end if (DL:isQuestState("invis_recipe", "void")) then DL:createChoiceNode(41) if (DL:isSpellLearned(7)) then DL:addChoice(42, "DL_Choice_SecondQuest") -- I'm ready for your new job. end DL:addChoice(-1, "") -- DL:addNode() if (DL:isSpellLearned(7)) then DL:createNPCNode(42, 43, "DL_Vincent_SecondQuest") -- Good. This time, the stakes are a little bit higher. We know that the mage Syrah knows how to brew a potion that can render you invisible. DL:addNode() DL:createNPCNode(43, 44, "DL_Vincent_SecondQuest2") -- A very useful ability, isn't it? The only problem is, she won't tell us how it works. DL:addNode() DL:createNPCNode(44, 51, "DL_Vincent_SecondQuest3") -- She leaves us no choice but to abstract the recipe from her. DL:addNode() DL:createNPCNode(51, 53, "DL_Vincent_SecondQuest4") -- There must be a way to get into her basement - by taking a shortcut through the sewers. Find that way and get the recipe for us. DL:addNode() DL:createNPCNode(53, -2, "DL_Vincent_SecondQuest5") -- If you manage to do that, you might get to know what "us" really means. DL:changeQuestState("invis_recipe", "started") DL:addNode() end end if (DL:isQuestState("invis_recipe", "failed") and not DL:isConditionFulfilled("npc_vincent2", "trusted_failed")) then DL:createNPCNode(47, -2, "DL_Vincent2_Disappointed") -- Hm. I trusted you and you failed me. DL:addConditionProgress("npc_vincent2", "trusted_failed") DL:addNode() end DL:createChoiceNode(45) if (DL:isQuestState("invis_recipe", "started") and DL:isQuestComplete("invis_recipe")) then DL:addChoice(46, "DL_Choice_IGotRecipe") -- I got the recipe for you. end DL:addChoice(-1, "") -- DL:addNode() if (DL:isQuestState("invis_recipe", "started") and DL:isQuestComplete("invis_recipe")) then DL:createNPCNode(46, -1, "DL_Vincent_SecondQuestDone") -- Very well. I knew you had talent. Now, if you'd like to learn more of this useful magic, take this key and find the door it opens. DL:changeQuestState("invis_recipe", "completed") DL:removeItem("qe_invisrecipe", 1) DL:addItem("ke_thiefguild", 1) DL:addReputationProgress("thief", 10) DL:addConditionProgress("default", "thieves_open") DL:changeQuestState("rusty_key", "started") DL:addNode() end end
-- replaces md with html in links function Link(el) el.target = string.gsub(el.target, "%.md", ".html") return el end
local skynet = require "skynet" local group = require "mcgroup" --local group = require "localgroup" skynet.start(function() local gid = group.create() local gaddr = group.address(gid) local g = {} print("=== Create Group ===",gid,skynet.address(gaddr)) for i=1,10 do local address = skynet.newservice("testgroup_c", tostring(i)) table.insert(g, address) group.enter(gid , address) end skynet.cast(g,"text","Cast") skynet.sleep(1000) skynet.send(gaddr,"text","Hello World") skynet.exit() end)
local L = BigWigs:NewBossLocale("Ahn'kahet Trash", "ptBR") if not L then return end if L then L.spellflinger = "Sortílego Ahn'kahar" L.eye = "Olho de Taldaram" L.darkcaster = "Taumaturgo do Crepúsculo" end
local path = (...):sub(1, #(...) - #(".Framework"))
function widget:GetInfo() return { name = "Metalspot Finder", desc = "Finds metal spots for other widgets", author = "Niobium", version = "v1.1", date = "November 2010", license = "GNU GPL, v2 or later", layer = -30000, enabled = true } end ------------------------------------------------------------ -- Config ------------------------------------------------------------ local gridSize = 16 -- Resolution of metal map local buildGridSize = 8 -- Resolution of build positions ------------------------------------------------------------ -- Speedups ------------------------------------------------------------ local min, max = math.min, math.max local floor, ceil = math.floor, math.ceil local sqrt = math.sqrt local huge = math.huge local spGetGroundInfo = Spring.GetGroundInfo local spGetGroundHeight = Spring.GetGroundHeight local spTestBuildOrder = Spring.TestBuildOrder local extractorRadius = Game.extractorRadius local extractorRadiusSqr = extractorRadius * extractorRadius local buildmapSizeX = Game.mapSizeX - buildGridSize local buildmapSizeZ = Game.mapSizeZ - buildGridSize local buildmapStartX = buildGridSize local buildmapStartZ = buildGridSize local metalmapSizeX = Game.mapSizeX - 1.5 * gridSize local metalmapSizeZ = Game.mapSizeZ - 1.5 * gridSize local metalmapStartX = 1.5 * gridSize local metalmapStartZ = 1.5 * gridSize ------------------------------------------------------------ -- Callins ------------------------------------------------------------ function widget:Initialize() WG.metalSpots = GetSpots() WG.GetMexPositions = GetMexPositions WG.IsMexPositionValid = IsMexPositionValid widgetHandler:RemoveWidget(self) end ------------------------------------------------------------ -- Shared functions ------------------------------------------------------------ function GetMexPositions(spot, uDefID, facing, testBuild) local positions = {} local xoff, zoff local uDef = UnitDefs[uDefID] if facing == 0 or facing == 2 then xoff = (4 * uDef.xsize) % 16 zoff = (4 * uDef.zsize) % 16 else xoff = (4 * uDef.zsize) % 16 zoff = (4 * uDef.xsize) % 16 end if not spot.validLeft then GetValidStrips(spot) end local validLeft = spot.validLeft local validRight = spot.validRight for z, vLeft in pairs(validLeft) do if z % 16 == zoff then for x = gridSize * ceil((vLeft + xoff) / gridSize) - xoff, gridSize * floor((validRight[z] + xoff) / gridSize) - xoff, gridSize do local y = spGetGroundHeight(x, z) if not (testBuild and spTestBuildOrder(uDefID, x, y, z, facing) == 0) then positions[#positions + 1] = {x, y, z} end end end end return positions end function IsMexPositionValid(spot, x, z) if z <= spot.maxZ - extractorRadius or z >= spot.minZ + extractorRadius then -- Test for metal being included is dist < extractorRadius return false end local sLeft, sRight = spot.left, spot.right for sz = spot.minZ, spot.maxZ, gridSize do local dz = sz - z local maxXOffset = sqrt(extractorRadiusSqr - dz * dz) -- Test for metal being included is dist < extractorRadius if x <= sRight[sz] - maxXOffset or x >= sLeft[sz] + maxXOffset then return false end end return true end ------------------------------------------------------------ -- Mex finding ------------------------------------------------------------ function GetSpots() -- Main group collection local uniqueGroups = {} -- Strip info local nStrips = 0 local stripLeft = {} local stripRight = {} local stripGroup = {} -- Indexes local aboveIdx local workingIdx -- Strip processing function (To avoid some code duplication) local function DoStrip(x1, x2, z, worth) local assignedTo for i = aboveIdx, workingIdx - 1 do if stripLeft[i] > x2 + gridSize then break elseif stripRight[i] + gridSize >= x1 then local matchGroup = stripGroup[i] if assignedTo then if matchGroup ~= assignedTo then for iz = matchGroup.minZ, assignedTo.minZ - gridSize, gridSize do assignedTo.left[iz] = matchGroup.left[iz] end for iz = matchGroup.minZ, matchGroup.maxZ, gridSize do assignedTo.right[iz] = matchGroup.right[iz] end if matchGroup.minZ < assignedTo.minZ then assignedTo.minZ = matchGroup.minZ end assignedTo.maxZ = z assignedTo.worth = assignedTo.worth + matchGroup.worth uniqueGroups[matchGroup] = nil end else assignedTo = matchGroup assignedTo.left[z] = assignedTo.left[z] or x1 -- Only accept the first assignedTo.right[z] = x2 -- Repeated overwrite gives us result we want assignedTo.maxZ = z -- Repeated overwrite gives us result we want assignedTo.worth = assignedTo.worth + worth end else aboveIdx = aboveIdx + 1 end end nStrips = nStrips + 1 stripLeft[nStrips] = x1 stripRight[nStrips] = x2 if assignedTo then stripGroup[nStrips] = assignedTo else local newGroup = { left = {[z] = x1}, right = {[z] = x2}, minZ = z, maxZ = z, worth = worth } stripGroup[nStrips] = newGroup uniqueGroups[newGroup] = true end end -- Strip finding workingIdx = huge for mz = metalmapStartX, metalmapSizeZ, gridSize do aboveIdx = workingIdx workingIdx = nStrips + 1 local stripStart = nil local stripWorth = 0 for mx = metalmapStartZ, metalmapSizeX, gridSize do local _, _, groundMetal = spGetGroundInfo(mx, mz) if groundMetal > 0 then stripStart = stripStart or mx stripWorth = stripWorth + groundMetal elseif stripStart then DoStrip(stripStart, mx - gridSize, mz, stripWorth) stripStart = nil stripWorth = 0 end end if stripStart then DoStrip(stripStart, metalmapSizeX, mz, stripWorth) end end -- Final processing local spots = {} for g, _ in pairs(uniqueGroups) do local gMinX, gMaxX = huge, -1 local gLeft, gRight = g.left, g.right for iz = g.minZ, g.maxZ, gridSize do if gLeft[iz] < gMinX then gMinX = gLeft[iz] end if gRight[iz] > gMaxX then gMaxX = gRight[iz] end end g.minX = gMinX g.maxX = gMaxX g.x = (gMinX + gMaxX) * 0.5 g.z = (g.minZ + g.maxZ) * 0.5 g.y = spGetGroundHeight(g.x, g.z) spots[#spots + 1] = g end return spots end function GetValidStrips(spot) local sMinZ, sMaxZ = spot.minZ, spot.maxZ local sLeft, sRight = spot.left, spot.right local validLeft = {} local validRight = {} local maxZOffset = buildGridSize * ceil(extractorRadius / buildGridSize - 1) for mz = max(sMaxZ - maxZOffset, buildmapStartZ), min(sMinZ + maxZOffset, buildmapSizeZ), buildGridSize do local vLeft, vRight = buildmapStartX, buildmapSizeX for sz = sMinZ, sMaxZ, gridSize do local dz = sz - mz local maxXOffset = buildGridSize * ceil(sqrt(extractorRadiusSqr - dz * dz) / buildGridSize - 1) -- Test for metal being included is dist < extractorRadius local left, right = sRight[sz] - maxXOffset, sLeft[sz] + maxXOffset if left > vLeft then vLeft = left end if right < vRight then vRight = right end end validLeft[mz] = vLeft validRight[mz] = vRight end spot.validLeft = validLeft spot.validRight = validRight end
Locales['br'] = { ['Discord do servidor'] = 'Discord do servidor', ['Site do Servidor'] = 'Site do servidor', ['Servidor'] = 'Servidor', }
for i = 1, #KEYS-1 do local has = redis.call("sismember", KEYS[i], ARGV[1]) if has == 1 then return KEYS[i] == KEYS[#KEYS] end end redis.call("sadd", KEYS[#KEYS], ARGV[1]) return true
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --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 GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --Children folder includes -- Server Objects includeFile("tangible/loot/collectible/collectible_parts/blue_rug_adhesive.lua") includeFile("tangible/loot/collectible/collectible_parts/blue_rug_dye.lua") includeFile("tangible/loot/collectible/collectible_parts/blue_rug_patches.lua") includeFile("tangible/loot/collectible/collectible_parts/blue_rug_thread_01.lua") includeFile("tangible/loot/collectible/collectible_parts/blue_rug_thread_02.lua") includeFile("tangible/loot/collectible/collectible_parts/blue_rug_thread_03.lua") includeFile("tangible/loot/collectible/collectible_parts/blue_rug_thread_04.lua") includeFile("tangible/loot/collectible/collectible_parts/blue_rug_thread_05.lua") includeFile("tangible/loot/collectible/collectible_parts/blue_rug_thread_06.lua") includeFile("tangible/loot/collectible/collectible_parts/blue_rug_thread_07.lua") includeFile("tangible/loot/collectible/collectible_parts/fs_tracking_device_assembly_bracket_01.lua") includeFile("tangible/loot/collectible/collectible_parts/fs_tracking_device_assembly_bracket_02.lua") includeFile("tangible/loot/collectible/collectible_parts/fs_tracking_device_assembly_bracket_03.lua") includeFile("tangible/loot/collectible/collectible_parts/fs_tracking_device_case_01.lua") includeFile("tangible/loot/collectible/collectible_parts/fs_tracking_device_case_02.lua") includeFile("tangible/loot/collectible/collectible_parts/fs_tracking_device_case_03.lua") includeFile("tangible/loot/collectible/collectible_parts/gong_adhesive.lua") includeFile("tangible/loot/collectible/collectible_parts/gong_skin_back.lua") includeFile("tangible/loot/collectible/collectible_parts/gong_skin_front.lua") includeFile("tangible/loot/collectible/collectible_parts/gong_structure_01.lua") includeFile("tangible/loot/collectible/collectible_parts/gong_structure_02.lua") includeFile("tangible/loot/collectible/collectible_parts/gong_structure_03.lua") includeFile("tangible/loot/collectible/collectible_parts/gong_structure_04.lua") includeFile("tangible/loot/collectible/collectible_parts/gong_structure_05.lua") includeFile("tangible/loot/collectible/collectible_parts/gong_structure_06.lua") includeFile("tangible/loot/collectible/collectible_parts/gong_structure_07.lua") includeFile("tangible/loot/collectible/collectible_parts/light_table_adhesive.lua") includeFile("tangible/loot/collectible/collectible_parts/light_table_glasstop_01.lua") includeFile("tangible/loot/collectible/collectible_parts/light_table_glasstop_02.lua") includeFile("tangible/loot/collectible/collectible_parts/light_table_structure_01.lua") includeFile("tangible/loot/collectible/collectible_parts/light_table_structure_02.lua") includeFile("tangible/loot/collectible/collectible_parts/light_table_structure_03.lua") includeFile("tangible/loot/collectible/collectible_parts/light_table_structure_04.lua") includeFile("tangible/loot/collectible/collectible_parts/light_table_structure_05.lua") includeFile("tangible/loot/collectible/collectible_parts/light_table_structure_06.lua") includeFile("tangible/loot/collectible/collectible_parts/light_table_structure_07.lua") includeFile("tangible/loot/collectible/collectible_parts/orange_rug_adhesive.lua") includeFile("tangible/loot/collectible/collectible_parts/orange_rug_dye.lua") includeFile("tangible/loot/collectible/collectible_parts/orange_rug_patches.lua") includeFile("tangible/loot/collectible/collectible_parts/orange_rug_thread_01.lua") includeFile("tangible/loot/collectible/collectible_parts/orange_rug_thread_02.lua") includeFile("tangible/loot/collectible/collectible_parts/orange_rug_thread_03.lua") includeFile("tangible/loot/collectible/collectible_parts/orange_rug_thread_04.lua") includeFile("tangible/loot/collectible/collectible_parts/orange_rug_thread_05.lua") includeFile("tangible/loot/collectible/collectible_parts/orange_rug_thread_06.lua") includeFile("tangible/loot/collectible/collectible_parts/orange_rug_thread_07.lua") includeFile("tangible/loot/collectible/collectible_parts/sculpture_adhesive.lua") includeFile("tangible/loot/collectible/collectible_parts/sculpture_goldinlay_01.lua") includeFile("tangible/loot/collectible/collectible_parts/sculpture_goldinlay_02.lua") includeFile("tangible/loot/collectible/collectible_parts/sculpture_structure_01.lua") includeFile("tangible/loot/collectible/collectible_parts/sculpture_structure_02.lua") includeFile("tangible/loot/collectible/collectible_parts/sculpture_structure_03.lua") includeFile("tangible/loot/collectible/collectible_parts/sculpture_structure_04.lua") includeFile("tangible/loot/collectible/collectible_parts/sculpture_structure_05.lua") includeFile("tangible/loot/collectible/collectible_parts/sculpture_structure_06.lua") includeFile("tangible/loot/collectible/collectible_parts/sculpture_structure_07.lua")
-- Retrieve the project name newoption { trigger = "projectname", description = "Name of the generated project" } local projectName = _OPTIONS["projectname"] if projectName == nil then print("The project name was not specified! --projectname=YourApplication") os.exit(1) end if projectName == "BatteryEngine" then print("The project cannot be named 'BatteryEngine'!") os.exit(1) end -- Main Solution workspace (projectName) configurations { "Debug", "Release", "Deploy" } platforms { "x64" } defaultplatform "x64" startproject (projectName) -- The BatteryEngine Subproject batteryIncludeDirs = {} batteryLinkFiles = {} include "modules/BatteryEngine" -- Import the BatteryEngine's premake5.lua -- Actual application project project (projectName) language "C++" cppdialect "C++17" staticruntime "on" location "build" targetname (projectName) targetdir "bin" system "Windows" entrypoint "mainCRTStartup" architecture "x86_64" pchheader "pch.h" pchsource "src/pch.cpp" -- Configuration filters are active up to the next filter statement -- Indentation is purely visual filter "configurations:Debug" defines { "DEBUG", "_DEBUG", "NDEPLOY", "ALLEGRO_STATICLINK" } kind "ConsoleApp" runtime "Debug" symbols "On" linkoptions { '/NODEFAULTLIB:libcmt.lib', '/NODEFAULTLIB:msvcrt.lib', '/NODEFAULTLIB:msvcrtd.lib' } filter "configurations:Release" defines { "NDEBUG", "NDEPLOY", "ALLEGRO_STATICLINK" } kind "ConsoleApp" runtime "Release" optimize "On" linkoptions { '/NODEFAULTLIB:libcmtd.lib', '/NODEFAULTLIB:msvcrt.lib', '/NODEFAULTLIB:msvcrtd.lib' } filter "configurations:Deploy" defines { "NDEBUG", "DEPLOY", "ALLEGRO_STATICLINK" } kind "WindowedApp" runtime "Release" optimize "On" linkoptions { '/NODEFAULTLIB:libcmtd.lib', '/NODEFAULTLIB:msvcrt.lib', '/NODEFAULTLIB:msvcrtd.lib' } filter {} -- Include directories for the compiler includedirs { "include" } -- Main source files (all files in the project view) files { "include/**" } files { "src/**" } -- Load the BatteryEngine dependency dependson("BatteryEngine"); includedirs { batteryIncludeDirs } links { batteryLinkFiles } --linkoptions { "/IGNORE:4099" } -- Ignore warning that no .pdb file is found for debugging
-- helper file to be able to debug the simple menu on PC -- without messing around with actual menu code! PLATFORM="Android" dofile("builtin/mainmenu/init.lua")
my_table = {} my_table.sub = {} function my_table.sub.change_owner_and_spawn_stuff(planet) planet.Change_Owner(Find_Player("Empire")) Spawn_Unit(Find_Object_Type("Star_Destroyer"), planet, Find_Player("Empire")) end
local COLOR = FindMetaTable("Color") -- negate a color/return the opposite of a color function COLOR:Negate() return Color( 255 - self.r, 255 - self.g, 255 - self.b, self.a ) end --increment/decrement a color function COLOR:Increment( am ) return Color( self.r + am, self.g + am, self.b + am, self.a ) end -- random color with optional alpha declaration function randomColor( al ) return Color( math.random( 0, 255 ), math.random( 0, 255 ), math.random( 0, 255 ), al or 255 ) end
--data.lua require("calcui-prototypes") require("calcui-styles") require("calcui-hotkey")
--- === WindowManager === --- --- Moves and resizes windows. --- Features: --- * Every window can be resized to be a quarter, half or the whole of the screen. --- * Every window can be positioned anywhere on the screen, WITHIN the constraints of a grid. The grids are 1x1, 2x2 and 4x4 for maximized, half-sized and quarter-sized windows, respectively. --- * Any given window can be cycled through all sizes and locations with just 4 keys. For example: northwest quarter → northeast quarter → right half ↓ southeast quarter ↓ bottom half ↓ full-screen. local Window = require("hs.window") local Screen = require("hs.screen") local Geometry = require("hs.geometry") local Spoons = require("hs.spoons") local obj = {} obj.__index = obj obj.name = "WindowManager" obj.version = "1.0" obj.author = "roeybiran <roeybiran@icloud.com>" obj.homepage = "https://github.com/Hammerspoon/Spoons" obj.license = "MIT - https://opensource.org/licenses/MIT" -- second window resize suggestion a-la Windows -- TODO -- obj.overlay = { -- fill = Drawing.rectangle({0, 0, 0, 0}):setLevel(Drawing.windowLevels["_MaximumWindowLevelKey"]):setFill(true):setFillColor( -- getSystemBlueColor() -- ):setAlpha(0.2):setRoundedRectRadii(3, 3), -- stroke = Drawing.rectangle({0, 0, 0, 0}):setLevel(Drawing.windowLevels["_MaximumWindowLevelKey"]):setFill(false):setStrokeWidth( -- 15 -- ):setStrokeColor(getSystemBlueColor()):setStroke(true):setRoundedRectRadii(3, 3), -- show = function(dimensions) -- for _, v in ipairs({obj.overlay.fill, obj.overlay.stroke}) do -- if v and v.hide then -- v:setFrame(dimensions):show(0.2) -- end -- end -- end, -- hide = function() -- for _, v in ipairs({obj.overlay.fill, obj.overlay.stroke}) do -- if v and v.hide then -- v:setFrame({0, 0, 0, 0}):hide(0.2) -- end -- end -- end -- } -- local function getSystemBlueColor() -- return Drawing.color.lists()["System"]["systemBlueColor"] -- end -- hs.timer.doAfter(0.5, function() tabBind:disable() end) -- end local mainScreen = Screen.mainScreen() local usableFrame = mainScreen:frame() local menuBarHeight = mainScreen:fullFrame().h - usableFrame.h local minX = 0 local midX = usableFrame.w / 2 local maxX = usableFrame.w local minY = usableFrame.y -- not a simple zero because of the menu bar local midY = usableFrame.h / 2 local maxY = usableFrame.h local possibleCells = { northWest = { rect = Geometry.rect({minX, minY, midX, midY}), onLeft = "west", onRight = "northEast", onUp = "north", onDown = "southWest" }, northEast = { rect = Geometry.rect({midX, minY, midX, midY}), onLeft = "northWest", onRight = "east", onUp = "north", onDown = "southEast" }, southWest = { rect = Geometry.rect({minX, midY, midX, midY + menuBarHeight}), onLeft = "west", onRight = "southEast", onUp = "northWest", onDown = "south" }, southEast = { rect = Geometry.rect({midX, midY, midX, midY + menuBarHeight}), onLeft = "southWest", onRight = "east", onUp = "northEast", onDown = "south" }, west = { rect = Geometry.rect({minX, minY, midX, maxY}), onLeft = "fullScreen", onRight = "east", onUp = "northWest", onDown = "southWest" }, east = { rect = Geometry.rect({midX, minY, midX, maxY}), onLeft = "west", onRight = "fullScreen", onUp = "northEast", onDown = "southEast" }, south = { rect = Geometry.rect({minX, midY, maxX, midY + menuBarHeight}), onLeft = "southWest", onRight = "southEast", onUp = "north", onDown = "fullScreen" }, north = { rect = Geometry.rect({minX, minY, maxX, midY}), onLeft = "northWest", onRight = "northEast", onUp = "fullScreen", onDown = "south" }, fullScreen = { rect = Geometry.rect({minX, minY, maxX, maxY}), onLeft = "west", onRight = "east", onUp = "north", onDown = "south" } } local fallbacks = {Up = "north", Down = "south", Right = "east", Left = "west"} local function pushToCell(direction) local frontWindow = Window.frontmostWindow() local frontWindowFrame = frontWindow:frame() for _, cellProperties in pairs(possibleCells) do if frontWindowFrame:equals(cellProperties.rect) then local targetCellName = cellProperties["on" .. direction] local targetCell = possibleCells[targetCellName].rect frontWindow:setFrame(targetCell) return end end local targetCellName = fallbacks[direction] frontWindow:setFrame(possibleCells[targetCellName].rect) end local function maximize() local frontWindow = Window.frontmostWindow() local frontWindowFrame = frontWindow:frame() if frontWindowFrame:equals(possibleCells.fullScreen.rect) then frontWindow:setFrame(possibleCells.northWest.rect) frontWindow:centerOnScreen() else frontWindow:setFrame(possibleCells.fullScreen.rect) end end local function center() Window.frontmostWindow():centerOnScreen() end --- WindowManager:bindHotKeys(_mapping) --- Method --- This module offers the following functionalities: --- * `maximize` - maximizes the frontmost window. If it's already maximized, it will be centered and resized to be a quarter of the screen. --- * `pushLeft` - moves and/or resizes a window towards the left of the screen. --- * `pushRight` - moves and/or resizes a window towards the right of the screen. --- * `pushDown` - moves and/or resizes a window towards the bottom of the screen. --- * `pushUp` - moves and/or resizes a window towards the top of the screen. --- * `pushLeft` - moves and/or resizes a window towards the left of the screen. --- * `center` - centers the frontmost window. --- Parameters: --- * `_mapping` - A table that conforms to the structure described in the Spoon plugin documentation. function obj:bindHotKeys(_mapping) local def = { maximize = function() maximize() end, pushLeft = function() pushToCell("Left") end, pushRight = function() pushToCell("Right") end, pushDown = function() pushToCell("Down") end, pushUp = function() pushToCell("Up") end, center = function() center() end } Spoons.bindHotkeysToSpec(def, _mapping) end return obj
-- This will load the new copy of the library on Unix systems where it's built -- with libtool. package.cpath = ".libs/liblua-?.so;" .. package.cpath local Tmpl = require 'smpltmpl' local TmplPriv = require 'smpltmpl_priv' -- File existence testing. assert(TmplPriv._file_exists("test"), "_file_exists(test)") assert(not TmplPriv._file_exists("xyzzy"), "_file_exists(xyzzy)") local proc = Tmpl.new({ dirs = { 'test' } }) local tmpl, code = proc:compile_template('foo') local tmpl2, code2 = proc:compile_template('foo') assert(tmpl2 == tmpl) assert(code2 == nil) -- Write out compiled template for debugging. do local fh = assert(io.open("test/foo.st.lua", "wb")) fh:write(code) fh:close() end local info = { hello = "Hello &<world>\"'", list = { "foo", "bar", "baz" }, } local out = assert(io.open("test/out.got", "wb")) tmpl:generate(out, info) out:close()
local context = {} function context:create() -- debug options self.debug = false; -- get device info self.device = require("device"); -- initiate Flurry analytics self:startAnalytics(self.debug); -- image module initialization self.img =require("img.img"); self:createDisplayBounds(); -- settings self.settingsIO = require("io.settingsIO"); self.settings = self.settingsIO.getSettings(); -- increase run count if(self.settings.runCount) then self.settings.runCount = self.settings.runCount + 1; else self.settings.runCount = 1; end -- add canShowRateMeWin if needed if(self.settings.canShowRateMeWin== nil) then self.settings.canShowRateMeWin = true; end -- save settings to persistent memory self.settingsIO:persistSettings(); -- sounds local soundSettings = self.settings.soundSettings --{sound=true, soundVolume = 0.5, music=true, musicVolume=0.3}; self.soundManager = require("sound.soundManager"):create(soundSettings, self.displayBounds); self.uiConst = require("ui.uiConst"); --self.textSource = require("i18n.textSource"):create("en_us") self.textSource = require("i18n.textSource"):create(self.settings.language) if(self.settings.language == nil) then self:determineLanguage(); end self.systemEventsHandler = require("systemEventsHandler"):create(self); -- not tested !! self:checkGooglePlayLinence(); return self; end function context:createDisplayBounds() -- calc display bounds local displayBounds = { minX=display.screenOriginX , minY= display.screenOriginY, maxX=display.viewableContentWidth + math.abs(display.screenOriginX),--display.contentWidth+math.abs(display.screenOriginX), maxY=display.viewableContentHeight + math.abs(display.screenOriginY)--display.contentHeight + math.abs(display.screenOriginY) }; displayBounds.width = displayBounds.maxX - displayBounds.minX; displayBounds.height = displayBounds.maxY - displayBounds.minY; displayBounds.centerX = displayBounds.minX + displayBounds.width*0.5; displayBounds.centerY = displayBounds.minY + displayBounds.height*0.5; self.displayBounds = displayBounds; end function context:determineLanguage() local prefLanguage = system.getPreference( "locale", "language"); --system.getPreference( "ui", "language" )) if(type(prefLanguage) ~= "string") then return; end prefLanguage = string.lower(prefLanguage); --prefLanguage = " čeština (česká republika)" --print("pref lang: " .. prefLanguage) local langCode = nil local find = string.find; if( find(prefLanguage,"en",1,true) or find(prefLanguage,"english",1,true))then langCode = "en_us"; elseif(find(prefLanguage,"cz",1,true) or find(prefLanguage, "cs",1,true) or find(prefLanguage,"czech",1,true) or find(prefLanguage,"čeština",1,true))then langCode = "cs_cz"; end if(langCode) then print("detected language: " .. langCode ) self:setLanguage(langCode); --else -- print("Language not recognized automatically.") end end function context:setLanguage(langCode) --print("language set to:".. langCode); self.settings.language = langCode; self.textSource:setLanguage(langCode); -- save settings to persistent memory self.settingsIO:persistSettings(); end function context:startAnalytics(devel) local appKey = nil; local device = self.device; -- true only in the Corona Simulator not for example in Xcode iOS Simulator or Android emulator or and Windows Phone emulator if(device.isSimulator) then --print("no analytics in simulator ...") return; end -- get platform name name ---local platformName = system.getInfo( "platformName" ); if( device.isApple) then if(devel) then appKey = nil; else appKey = "supply-key-of-your-own"; -- Diptera iOS key end elseif(device.isGoogle) then if(devel) then appKey = "supply-key-of-your-own"; -- Android development project key else appKey = "supply-key-of-your-own"; -- Diptera android key end end if(appKey) then local analytics = require "analytics"; self.analytics = analytics; analytics.init( appKey ); end end function context:analyticslogEvent(eventName, params) if(not self.analytics) then return; -- analytics off end self.analytics.logEvent( eventName, params ); end function context:checkGooglePlayLinence() -- check licensing local device = require("device"); if(device.isSimulator) then return; end if(device.isGoogle) then local licensing = require( "licensing" ) licensing.init( "google" ) local function licensingListener( event ) local verified = event.isVerified if not verified then --failed verify app from the play store, we print a message --print( "Pirates: Walk the Plank!!!" ) --native.requestExit() --assuming this is how we handle pirates if self.analytics then self.analytics.logEvent("failed to verify licence"); end end end licensing.verify( licensingListener ) end end return context;
vim.g.translator_default_engines = { "bing", "youdao", "haici" } vim.g.translator_window_type = "preview"
--#selene: allow(unused_variable) --[[ kinda complex reactive graph, stress test. ]] local ReplicatedStorage = game:GetService("ReplicatedStorage") local Fusion = require(ReplicatedStorage.DevPackages.Fusion) local ReactiveGraph = require(ReplicatedStorage.DevPackages.ReactiveGraph) local FusionState = Fusion.State local ReactiveGraphState = ReactiveGraph.State local Computed = Fusion.Computed local StaticEffect = ReactiveGraph.StaticEffect return { ParameterGenerator = function() return math.random(), math.random(), math.random() end; Functions = { Fusion = function(Profiler: BenchmarkerProfiler, value1: number, value2: number, value3: number) local state1 = FusionState(value1) local state2 = FusionState(value2) local state3 = FusionState(value3) local effect1 = Computed(function() return state1:get() + 1 end) local effect2 = Computed(function() return effect1:get() + state2:get() end) local effect3 = Computed(function() return effect2:get() + effect1:get() + state3:get() end) for _ = 1, 128 do value1 += 1 value2 += 1 value3 += 1 state1:set(value1) state2:set(value2) state3:set(value3) effect3:get() end end; ReactiveGraph = function(Profiler: BenchmarkerProfiler, value1: number, value2: number, value3: number) local state1 = ReactiveGraphState(value1) local state2 = ReactiveGraphState(value2) local state3 = ReactiveGraphState(value3) local effect1 = StaticEffect(function() return state1:get() + 1 end) local effect2 = StaticEffect(function() return effect1:get() + state2:get() + 1 end) local effect3 = StaticEffect(function() return effect2:get() + effect1:get() + state3:get() + 1 end) for _ = 1, 128 do value1 += 1 value2 += 1 value3 += 1 state1:set(value1) state2:set(value2) state3:set(value3) effect3:get() end end; }; }
--!nonstrict --[[ Constructs a new state object which can listen for updates on another state object. FIXME: enabling strict types here causes free types to leak ]] local runService = game:GetService("RunService") -- Used to create a tunnel between client and server local src = script.Parent.Parent local packages = src.Parent local maidConstructor = require(packages:WaitForChild("maid")) local Observe = require(src.State.Observe) local remotes = game.ReplicatedStorage:FindFirstChild("FusionRemotes") if not remotes then if runService:IsClient() then remotes = game.ReplicatedStorage:WaitForChild("FusionRemotes") else remotes = Instance.new("Folder", game.ReplicatedStorage) remotes.Name = "FusionRemotes" end end function getRemoteEvent(key, clientWaitDuration) if runService:IsClient() then return remotes:WaitForChild(key, clientWaitDuration) else if remotes:FindFirstChild(key) then return remotes:FindFirstChild(key) else local newRemote = Instance.new("RemoteEvent", remotes) newRemote.Name = key return newRemote end end end local fusion = script.Parent.Parent local PubTypes = require(fusion.PubTypes) local Types = require(fusion.Types) local initDependency = require(fusion.Dependencies.initDependency) type Set<T> = {[T]: any} local class = {} local CLASS_METATABLE = {__index = class} -- Table used to hold Observe objects in memory. local strongRefs: Set<Types.Observe> = {} --[[ Called when the watched state changes value. ]] function class:Fire() local t = tick() if t - self._lastFire < 1/self._rate then return end self._lastFire = t local event = getRemoteEvent(self._key) local value = self._state:get() if runService:IsServer() then if self._player then event:FireClient(self._player, value) else event:FireAllClients(value) end else event:FireServer(value) end end function class:fire() return self:Fire() end function class:Destroy(destroyValue: boolean) if destroyValue then if self._value ~= nil and (type(self._value) == "table" or typeof(self._value) == "Instance") then if self._value.Destroy then self._value:Destroy() end end end if self._Maid then self._Maid:Destroy() end for k, v in pairs(self) do self[k] = nil end setmetatable(self, nil) end function class:update(): boolean self:fire() return false end local function Transmit(watchedState, key: string, lockedPlayer: Player | nil, rate: number | nil) -- print("I") if runService:IsClient() then lockedPlayer = game.Players.LocalPlayer end local self = setmetatable({ type = "State", kind = "Transmit", dependencySet = {[watchedState] = true}, dependentSet = {}, _lastFire = 0, _Maid = maidConstructor.new(), _state = watchedState, _player = lockedPlayer, _key = key, _rate = rate or 40, _changeListeners = {}, _numChangeListeners = 0, _cleanUp = false, --whether it cleans up old value when changing it }, CLASS_METATABLE) -- print("II") local event = getRemoteEvent(self._key) -- print("III") if runService:IsClient() then self._Maid:GiveTask(event.OnClientEvent:Connect(function(newVal) self:Fire() end)) else self._Maid:GiveTask(event.OnServerEvent:Connect(function(plr, newVal) if self._player == nil or self._player == plr then self:Fire() end end)) end self._Maid:GiveTask(Observe(watchedState):Connect(function() self:Fire() end)) -- print("IV") initDependency(self) -- print("V") return self end return Transmit
local PANEL = {} function PANEL:Init() local scrw, scrh = ScrW(), ScrH() self.player_list = vgui.create('DListView', self) self.player_list:DockMargin(4, 4, 2, 4) self.player_list:Dock(LEFT) self.player_list:AddColumn(t'ui.admin.players') self.player_list:SetWide(scrw / 6) for k, v in ipairs(player.all()) do self.player_list:AddLine(v:steam_name(true)..' ('..v:name(true)..')').player = v end self.player_list.OnRowSelected = function(list, index, panel) if self:get_player() != panel.player then self:set_player(panel.player) end end self.player_info = vgui.create('fl_player_info', self) self.player_info:SetVisible(false) self.perm_editor = vgui.create('fl_permissions_editor', self) self.perm_editor:SetVisible(false) end function PANEL:on_opened() local scrw, scrh = ScrW(), ScrH() self.player_info:DockMargin(2, 4, 4, 2) self.player_info:Dock(TOP) self.player_info:SetTall(scrh / 6) self.perm_editor:DockMargin(2, 2, 4, 4) self.perm_editor:Dock(FILL) self.perm_editor:SetSize(self:GetWide() - self.player_list:GetWide() - 12, self:GetTall() - self.player_info:GetTall() - 12) end function PANEL:set_player(player) if !self:get_player() then self.player_info:SetVisible(true) self.perm_editor:SetVisible(true) end self.active_player = player self.player_info:set_player(player) self.perm_editor:set_player(player) end function PANEL:get_player() return self.active_player end vgui.Register('fl_player_management', PANEL, 'fl_base_panel') PANEL = {} function PANEL:Init() self.avatar = vgui.create('fl_avatar_panel', self) self.name_label = vgui.create('DLabel', self) self.name_label:SetFont(Theme.get_font('text_normal_large')) self.name_label:SetTextColor(color_white) self.role_label = vgui.create('DLabel', self) self.role_label:SetFont(Theme.get_font('text_normal')) self.role_label:SetTextColor(color_white) self.role_edit = vgui.create('fl_button', self) self.role_edit:set_icon('fa-edit') self.role_edit:set_centered(true) self.role_edit:SetDrawBackground(false) self.role_edit.DoClick = function(btn) local selector = vgui.create('fl_selector') selector:set_title(t'ui.admin.selector.title') selector:set_text(t'ui.admin.selector.message') selector:set_value(t'ui.admin.selector.roles') for k, v in pairs(Bolt:get_roles()) do selector:add_choice(v.name, function() Cable.send('fl_bolt_set_role', self.player, v.role_id) timer.simple(0.05, function() self:rebuild() end) end) end end end function PANEL:PerformLayout(w, h) self.avatar:SetSize(h - 16, h - 16) self.avatar:SetPos(w - self.avatar:GetWide() - 8, 8) self.name_label:SetPos(4, 4) self.role_label:SetPos(4, 4 + self.name_label:GetTall()) self.role_edit:set_icon_size(self.role_label:GetTall()) self.role_edit:SetSize(self.role_label:GetTall(), self.role_label:GetTall()) self.role_edit:SetPos(8 + self.role_label:GetWide(), 4 + self.name_label:GetTall()) end function PANEL:set_player(player) self.player = player self:rebuild() end function PANEL:rebuild() local player = self.player self.avatar:set_player(player, 128) self.name_label:SetText(player:steam_name(true)..' ('..player:name(true)..')') self.name_label:SizeToContents() self.role_label:SetText(t'ui.admin.role'..': '..player:GetUserGroup():upper()) self.role_label:SizeToContents() self:InvalidateLayout() end vgui.Register('fl_player_info', PANEL, 'fl_base_panel')
--[===[ This file is part of https://github.com/MarcGamesons/factoriomod-cheaper-landfill which is released under MIT License. Go to https://opensource.org/licenses/MIT for full license details. === For support open a new issue at https://github.com/MarcGamesons/factoriomod-cheaper-landfill/issues/new or visit https://forums.factorio.com/viewtopic.php?f=93&t=44991. ]===] data:extend({ { type = "bool-setting", name = "cheaper-landfill-enabled", setting_type = "startup", default_value = true }, { type = "int-setting", name = "cheaper-landfill-stone-cost", setting_type = "startup", minimum_value = 1, default_value = 20 }, { type = "int-setting", name = "cheaper-landfill-crafted-amount", setting_type = "startup", minimum_value = 1, default_value = 20 } })
Player = baseCharacter:new() function Player:load() baseCharacter.load(self, { scale = 0.035 * utils.vh, xCenter = 20 * utils.vw, -- uhh vai ter q calcular como q fica certo antes era 15.5 * utils.vw yCenter = love.graphics.getHeight() / 2, }) -- flap sound self.flap = love.audio.newSource("assets/wing-flap.wav", "static") self.flap:setVolume(0.5) self.shape = shapes.newPolygonShape( self.x, self.y, self.x + self.width * 0.85, self.y, self.x + self.width * 0.85, self.y + self.height * 0.775, self.x, self.y + self.height * 0.775 ) end function Player:update(dt) objectGravity(Player, dt) self:playerScreenCollision() self:playerCoinCollision() self.shape:moveTo(self.x + self.width / 2, self.y + self.height * 0.775 / 2) if not self.wings.isAnimating then self:animateWings() end if gameState:getName() == "classic" then objectRotation(Player, dt) self.shape:setRotation(self.rotation) self:playerObstacleCollision() elseif gameState:getName() == "gameOver" then self.crying.currentTime = self.crying.currentTime + dt if self.crying.currentTime >= self.crying.duration then self.crying.currentTime = math.fmod(self.crying.currentTime, self.crying.duration) end end end function objectGravity(object, dt) object.ySpeed = object.ySpeed + object.yAcceleration * dt object.y = object.y + object.ySpeed * dt end function objectRotation(object, dt) object.rotationSpeed = object.rotationSpeed + object.rotationAcceleration * dt object.rotation = clamp(-math.pi / 4, object.rotation + object.rotationSpeed * dt, math.pi / 2) if Player.rotation == (-math.pi / 4) then Player.rotationSpeed = math.max(-1.5, Player.rotationSpeed) end end function Player:reset() self.rotation = 0 self.y = love.graphics.getHeight() / 2 - self.height / 2 self.ySpeed = -3 * utils.vh -- 20 self.rotationSpeed = 0 end function Player:playerScreenCollision() if Player.y <= 0 then Player.y = 0 Player.ySpeed = 0 elseif Player.y + Player.height >= love.graphics.getHeight() then Player.y = love.graphics.getHeight() - Player.height GameOver:gameOver() end end function Player:changesColor(color) self.changeColorShader = newColoredPlayerShader(color) end function Player:draw() local crying = gameState:getName() == "gameOver" self:drawPlayerModel(crying) end function Player:jump() self.flap:stop() self.flap:play() Player.ySpeed = -52 * utils.vh -- -375 Player.rotationSpeed = -2.5 end function Player:updateWings() self.wings.front.rotation = self.rotation + self.animationRotation self.wings.back.rotation = self.rotation + self.animationRotation end function Player:animateWings() if self.ySpeed <= 0 then self.wings.isAnimating = true Timer.after(0.1, function() self.wings.back.rotation = math.pi / 6 self.wings.front.rotation = math.pi / 6 Timer.after(0.1, function() self.wings.back.rotation = 0 self.wings.front.rotation = 0 Timer.after(0.1, function() self.wings.back.rotation = -math.pi / 6 self.wings.front.rotation = -math.pi / 6 Timer.after(0.1, function() self.wings.back.rotation = 0 self.wings.front.rotation = 0 self.wings.isAnimating = false end) end) end) end) else self.wings.isAnimating = false end end function Player:playerObstacleCollision() for i, obstacle in ipairs(obstacles.obstacles) do if Obstacle.checkObstacleCollision(Player, obstacle) then GameOver:gameOver() end end end function Player:playerCoinCollision() for i, coin in ipairs(Coin.coins) do return Coin:checkCoinCollision(Player, i, coin) end end
return function() local class = require(script.Parent) it("should create a unique new table", function() local Class = class("Class") expect(Class).to.be.a("table") expect(Class).to.never.equal(class("Foo")) end) it("should error when a name isn't supplied", function() expect(function() class() end).to.throw() end) it("should instantiate a new class with new()", function() local Class = class("Class") function Class:foo() return "foo" end local instance = Class.new() expect(instance:foo()).to.equal("foo") end) it("should optionally allow parameters to be assigned in __init()", function() local Person = class("Person") function Person:__init(name, age) self.name = name self.age = age end local person = Person.new("John", 18) expect(person.name).to.equal("John") expect(person.age).to.equal(18) end) it("should allow static functions", function() local Class = class("Class") function Class.staticFunction() return true end local instance = Class.new() expect(Class.staticFunction()).to.equal(true) expect(instance.staticFunction()).to.equal(true) end) it("should have a ClassName property set to the name of the class", function() local Class = class("Class") expect(Class.ClassName).to.equal("Class") end) it("should reuse the metatable for each instance of a class", function() local Class = class("Class") local inst1 = Class.new() local inst2 = Class.new() expect(inst1).to.never.equal(inst2) expect(getmetatable(inst1)).to.equal(getmetatable(inst2)) end) describe("subclasses", function() it("should return the superclass for easy referencing", function() local Base = class("Base") local Sub, super = class("Sub", Base) expect(super).to.equal(Base) expect(Sub).to.never.equal(Base) end) it("should allow two classes to define the properties they take", function() local Base = class("Base") function Base:__init(foo) self.foo = foo end local Sub, super = class("Sub", Base) function Sub:__init(foo, bar) super.__init(self, foo) self.bar = bar end local instance = Sub.new("foo", "bar") expect(instance.foo).to.equal("foo") expect(instance.bar).to.equal("bar") end) it("should look up methods in the superclass", function() local Base = class("Base") function Base:foo() return "foo" end local Sub = class("Sub", Base) local instance = Sub.new() expect(instance:foo()).to.equal("foo") end) it("should use the __init method of the superclass", function() local Base = class("Base") function Base:__init(foo) self.foo = foo end local Sub = class("Sub", Base) local instance = Sub.new("foo") expect(instance.foo).to.equal("foo") end) -- Be aware that if you're getting down to 3+ levels of inheritance, -- your objects are going to be very complex and hard to reason about. -- Consider using composition instead. it("should support multiple levels of inheritance", function() local Base = class("Base") function Base:__init(arg) self.arg = arg end local Sub1 = class("Sub1", Base) function Sub1:foo() return "foo" end local Sub2 = class("Sub2", Sub1) local instance = Sub2.new("arg") expect(instance.arg).to.equal("arg") expect(instance:foo()).to.equal("foo") end) it("should inheret metamethods", function() local Base = class("Base") function Base:__tostring() return self.ClassName end function Base:__call() return 1 end local Sub = class("Sub", Base) local instance = Sub.new() expect(tostring(instance)).to.equal("Sub") expect(instance()).to.equal(1) end) end) end
-- file: 'BrokeTimerCountDown.lua' -- Description: 倒计时 动画 ; -- 接口说明: -- play "播放"提示 动画.(允许多次调用) -- reset "隐藏"提示 动画.(允许多次调用 , 如果播放期间隐藏,则附加执行中断动画) -- release "删除"相关资源 -- 可能的调用情景: -- 动画模式; -- (1) 播放一次(调play) -> (调release) -- (2) 播放和隐藏多次(在同一请求页面时播放动画) (模式:play->reset->play->reset ... ) -> (调release) -- (3) 播放和隐藏多次但中途直接调release(在同一请求页面时播放动画)(模式:play->reset->play ... ->release) -- 其他要求: -- 调用例子 BrokeTimerCountDown.play(drawingText); require("core/anim"); require("animation/animBase"); require("util/log") BrokeTimerCountDown = class(AnimBase); -- 动画总时常 BrokeTimerCountDown.countStart = 0; BrokeTimerCountDown.s_countMax = 0; BrokeTimerCountDown.countEnd = 0; BrokeTimerCountDown.msTimer = 1000; BrokeTimerCountDown.loaded=false; BrokeTimerCountDown.type_going=1; BrokeTimerCountDown.type_stop=2; BrokeTimerCountDown.interval=1; --[[ public [METHOD] getCountStart [ACTION] Parameters:nil ]] BrokeTimerCountDown.getCountStart = function() return BrokeTimerCountDown.countStart; end --[[ public [METHOD] play [ACTION] BrokeTimerCountDown 动画 入口 Parameters: startTime -- 开始时间 endTime -- 结束时间 ]] BrokeTimerCountDown.play = function(startTime , endTime , obj,objCallBack,speed,interval) if not obj or not objCallBack or not number.isNum(startTime) or not number.isNum(endTime) then return; end BrokeTimerCountDown.obj = obj; BrokeTimerCountDown.objCallBack = objCallBack; if startTime<= endTime then objCallBack(obj, BrokeTimerCountDown.type_stop, endTime); return; end BrokeTimerCountDown.interval= interval or 1; BrokeTimerCountDown.msTimer = speed or 1000; Log.v("---------BrokeTimerCountDown.play ----------",BrokeTimerCountDown.msTimer ); BrokeTimerCountDown.countStart = startTime; BrokeTimerCountDown.countEnd = endTime; BrokeTimerCountDown.onBrokeTimerCountDownStart(); end BrokeTimerCountDown.load = function() end --private BrokeTimerCountDown.creatAnim = function () BrokeTimerCountDown.onBrokeTimerCountDownStop(false, BrokeTimerCountDown.type_going, BrokeTimerCountDown.countStart); BrokeTimerCountDown.animCount = AnimFactory.createAnimDouble(kAnimRepeat, 0, 1 , BrokeTimerCountDown.msTimer, -1); BrokeTimerCountDown.animCount:setEvent(BrokeTimerCountDown.animCount , BrokeTimerCountDown.onTimer); ToolKit.setDebugName(BrokeTimerCountDown.animCount , "AnimInt|BrokeTimerCountDown.animCount"); end --private BrokeTimerCountDown.onTimer = function (self,anim_type, anim_id, repeat_or_loop_num) BrokeTimerCountDown.countStart = BrokeTimerCountDown.countStart - BrokeTimerCountDown.interval; if BrokeTimerCountDown.countStart > BrokeTimerCountDown.countEnd then -- BrokeTimerCountDown.drawingText:setText(BrokeTimerCountDown.changeCount()); BrokeTimerCountDown.onBrokeTimerCountDownStop(false, BrokeTimerCountDown.type_going, BrokeTimerCountDown.countStart); else -- BrokeTimerCountDown.drawingText:setText(BrokeTimerCountDown.changeCount()); BrokeTimerCountDown.onBrokeTimerCountDownStop(true, BrokeTimerCountDown.type_stop, BrokeTimerCountDown.countStart); end end --计算倒计时间 BrokeTimerCountDown.changeCount = function () return BrokeTimerCountDown.countStart < 10 and string.format("0%d",BrokeTimerCountDown.countStart) or BrokeTimerCountDown.countStart; end --倒计时继续 BrokeTimerCountDown.onBrokeTimerCountDownStart = function () BrokeTimerCountDown.reset(); BrokeTimerCountDown.creatAnim(); end --停止倒计时 BrokeTimerCountDown.onBrokeTimerCountDownStop = function (isstop, dtype, time) if isstop then BrokeTimerCountDown.reset(); end BrokeTimerCountDown.onCallBack(BrokeTimerCountDown.obj,BrokeTimerCountDown.objCallBack, dtype,time) end --停止倒计时 BrokeTimerCountDown.onCallBack = function (obj,objCallBack, dtype, time) if obj and objCallBack then objCallBack(obj, dtype, time); end end --[[ public [METHOD] reset [ACTION] 中断或复位动画 Parameters: 无 ]] BrokeTimerCountDown.reset=function() BrokeTimerCountDown.stop(); end --[[ private [METHOD] stop [ACTION] 执行 删除赋给prop的anim ; 删除赋给drawing的prop 复位动画 Parameters: 无 ]] BrokeTimerCountDown.stop =function() --删除anim delete(BrokeTimerCountDown.animCount); BrokeTimerCountDown.animCount = nil; end --[[ public [METHOD] release [ACTION] 动画结束 释放资源 Parameters: 无 ]] BrokeTimerCountDown.dtor = function() Log.d("BrokeTimerCountDown dtor start ..."); BrokeTimerCountDown.stop(); end
--[[ MIT License Copyright (c) 2021 Michael Wiesendanger 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 mod = rgpvpw local me = {} mod.testSoundRogueEn = me me.tag = "TestSoundRogueEn" local testGroupName = "SoundRogueEn" local testCategory = "rogue" function me.Test() mod.testReporter.StartTestGroup(testGroupName) me.CollectTestCases() mod.testReporter.PlayTestQueueWithDelay(function() mod.testReporter.StopTestGroup() -- asyncron finish of testgroup end) end function me.CollectTestCases() mod.testReporter.AddToTestQueueWithDelay(me.TestSoundKick) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundBlind) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundSprint) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundDownSprint) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundEvasion) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundDownEvasion) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundKidneyShot) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundCheapShot) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundAdrenalineRush) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundDownAdrenalineRush) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundBladeFlurry) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundDownBladeFlurry) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundColdBlood) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundDownColdBlood) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundPreparation) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundVanish) mod.testReporter.AddToTestQueueWithDelay(me.TestSoundStealth) end function me.TestSoundBlind() mod.testHelper.TestSoundApplied( "TestSoundBlind", testCategory, "Blind" ) end function me.TestSoundKick() mod.testHelper.TestSoundSuccess( "TestSoundKick", testCategory, "Kick" ) end function me.TestSoundSprint() mod.testHelper.TestSoundApplied( "TestSoundSprint", testCategory, "Sprint" ) end function me.TestSoundDownSprint() mod.testHelper.TestSoundRemoved( "TestSoundDownSprint", testCategory, "Sprint" ) end function me.TestSoundEvasion() mod.testHelper.TestSoundApplied( "TestSoundEvasion", testCategory, "Evasion" ) end function me.TestSoundDownEvasion() mod.testHelper.TestSoundRemoved( "TestSoundDownEvasion", testCategory, "Evasion" ) end function me.TestSoundKidneyShot() mod.testHelper.TestSoundSuccess( "TestSoundKidneyShot", testCategory, "Kidney Shot" ) end function me.TestSoundCheapShot() mod.testHelper.TestSoundSuccess( "TestSoundCheapShot", testCategory, "Cheap Shot" ) end function me.TestSoundAdrenalineRush() mod.testHelper.TestSoundApplied( "TestSoundAdrenalineRush", testCategory, "Adrenaline Rush" ) end function me.TestSoundDownAdrenalineRush() mod.testHelper.TestSoundRemoved( "TestSoundDownAdrenalineRush", testCategory, "Adrenaline Rush" ) end function me.TestSoundBladeFlurry() mod.testHelper.TestSoundApplied( "TestSoundBladeFlurry", testCategory, "Blade Flurry" ) end function me.TestSoundDownBladeFlurry() mod.testHelper.TestSoundRemoved( "TestSoundDownBladeFlurry", testCategory, "Blade Flurry" ) end function me.TestSoundColdBlood() mod.testHelper.TestSoundApplied( "TestSoundColdBlood", testCategory, "Cold Blood" ) end function me.TestSoundDownColdBlood() mod.testHelper.TestSoundRemoved( "TestSoundDownColdBlood", testCategory, "Cold Blood" ) end function me.TestSoundPreparation() mod.testHelper.TestSoundSuccess( "TestSoundPreparation", testCategory, "Preparation" ) end function me.TestSoundVanish() mod.testHelper.TestSoundSuccess( "TestSoundVanish", testCategory, "Vanish" ) end function me.TestSoundStealth() mod.testHelper.TestSoundSuccess( "TestSoundStealth", testCategory, "Stealth" ) end
-------------------------------- -- @module EventListenerPhysicsContactWithShapes -- @extend EventListenerPhysicsContact -- @parent_module cc -------------------------------- -- @function [parent=#EventListenerPhysicsContactWithShapes] hitTest -- @param self -- @param #cc.PhysicsShape physicsshape -- @param #cc.PhysicsShape physicsshape -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#EventListenerPhysicsContactWithShapes] create -- @param self -- @param #cc.PhysicsShape physicsshape -- @param #cc.PhysicsShape physicsshape -- @return EventListenerPhysicsContactWithShapes#EventListenerPhysicsContactWithShapes ret (return value: cc.EventListenerPhysicsContactWithShapes) -------------------------------- -- @function [parent=#EventListenerPhysicsContactWithShapes] clone -- @param self -- @return EventListenerPhysicsContactWithShapes#EventListenerPhysicsContactWithShapes ret (return value: cc.EventListenerPhysicsContactWithShapes) return nil
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// enginelessVehicle = { [510]=true, [509]=true, [481]=true } lightlessVehicle = { [592]=true, [577]=true, [511]=true, [548]=true, [512]=true, [593]=true, [425]=true, [520]=true, [417]=true, [487]=true, [553]=true, [488]=true, [497]=true, [563]=true, [476]=true, [447]=true, [519]=true, [460]=true, [469]=true, [513]=true, [472]=true, [473]=true, [493]=true, [595]=true, [484]=true, [430]=true, [453]=true, [452]=true, [446]=true, [454]=true } locklessVehicle = { [472]=true, [473]=true, [493]=true, [595]=true, [484]=true, [430]=true, [453]=true, [452]=true, [446]=true, [454]=true, [581]=true, [509]=true, [481]=true, [462]=true, [521]=true, [463]=true, [510]=true, [522]=true, [461]=true, [448]=true, [468]=true, [586]=true } armoredCars = { [427]=true, [528]=true, [432]=true, [601]=true, [428]=true, [597]=true } -- Enforcer, FBI Truck, Rhino, SWAT Tank, Securicar, SFPD Car -- Events addEvent("onVehicleSpawn", false) -- /makeveh function createPermVehicle(thePlayer, commandName, id, col1, col2, userName, factionVehicle, cost) if (exports.global:isPlayerLeadAdmin(thePlayer)) then if not (id) or not (col1) or not (col2) or not (userName) or not (factionVehicle) or not (cost) then outputChatBox("SYNTAX: /" .. commandName .. " [id] [color1 (-1 for random)] [color2 (-1 for random)] [Owner Partial Username] [Faction Vehicle (1/0)] [Cost] [Tinted Windows] ", thePlayer, 255, 194, 14) outputChatBox("NOTE: If it is a faction vehicle, Username is the owner of the faction.", thePlayer, 255, 194, 14) outputChatBox("NOTE: If it is a faction vehicle, The cost is taken from the faction fund, rather than the player.", thePlayer, 255, 194, 14) else local r = getPedRotation(thePlayer) local x, y, z = getElementPosition(thePlayer) x = x + ( ( math.cos ( math.rad ( r ) ) ) * 5 ) y = y + ( ( math.sin ( math.rad ( r ) ) ) * 5 ) if (tonumber(col1)==-1) then col1 = math.random(0, 126) end if (tonumber(col2)==-1) then col2 = math.random(0, 126) end local targetPlayer = exports.global:findPlayerByPartialNick(userName) if not (targetPlayer) then outputChatBox("No such player found.", thePlayer, 255, 0, 0) else local username = getPlayerName(targetPlayer) local dbid = getElementData(targetPlayer, "dbid") cost = tonumber(cost) if (tonumber(factionVehicle)==1) then factionVehicle = tonumber(getElementData(targetPlayer, "faction")) local theTeam = getPlayerTeam(targetPlayer) local money = getElementData(theTeam, "money") if (cost>money) then outputChatBox("This faction cannot afford this vehicle.", thePlayer, 255, 0, 0) else setElementData(theTeam, "money", money-tonumber(cost)) mysql_query(handler, "UPDATE factions SET money='" .. money-tonumber(cost) .. "' WHERE id='" .. factionVehicle .. "'") end else factionVehicle = -1 local money = getElementData(targetPlayer, "money") if (cost>money) then outputChatBox("This player cannot afford this vehicle.", thePlayer, 255, 0, 0) else exports.global:takePlayerSafeMoney(targetPlayer, cost) end end local letter1 = exports.global:randChar() local letter2 = exports.global:randChar() local plate = letter1 .. letter2 .. math.random(0, 9) .. " " .. math.random(1000, 9999) local veh = createVehicle(id, x, y, z, 0, 0, r, plate) exports.pool:allocateElement(veh) if not (veh) then outputChatBox("Invalid Vehicle ID.", thePlayer, 255, 0, 0) else setElementData(veh, "fuel", 100) local rx, ry, rz = getVehicleRotation(veh) setVehicleRespawnPosition(veh, x, y, z, rx, ry, rz) setVehicleLocked(veh, true) local locked = 1 setVehicleColor(veh, col1, col2, col1, col2) setVehicleOverrideLights(veh, 1) setVehicleEngineState(veh, false) setVehicleFuelTankExplodable(veh, false) -- faction vehicles are unlocked if (factionVehicle~=-1) then locked = 0 setVehicleLocked(veh, false) end -- Set the vehicle armored if it is armored if (armoredCars[tonumber(id)]) then setVehicleDamageProof(veh, true) end local query = mysql_query(handler, "INSERT INTO vehicles SET model='" .. id .. "', x='" .. x .. "', y='" .. y .. "', z='" .. z .. "', rotx='" .. rx .. "', roty='" .. ry .. "', rotz='" .. rz .. "', color1='" .. col1 .. "', color2='" .. col2 .. "', faction='" .. factionVehicle .. "', owner='" .. dbid .. "', plate='" .. plate .. "', currx='" .. x .. "', curry='" .. y .. "', currz='" .. z .. "', currrx='0', currry='0', currrz='" .. r .. "', locked='" .. locked .. "'") if (query) then mysql_free_result(query) local id = mysql_insert_id(handler) if (factionVehicle==-1) then exports.global:givePlayerItem(targetPlayer, 3, tonumber(id)) end setElementData(veh, "dbid", tonumber(id)) setElementData(veh, "fuel", 100) setElementData(veh, "engine", 0) setElementData(veh, "oldx", x) setElementData(veh, "oldy", y) setElementData(veh, "oldz", z) setElementData(veh, "faction", factionVehicle) setElementData(veh, "owner", dbid) setElementData(veh, "job", 0) outputChatBox(getVehicleName(veh) .. " spawned with ID #" .. id .. ".", thePlayer, 255, 194, 14) triggerEvent("onVehicleSpawn", veh) end end end end end end addCommandHandler("makeveh", createPermVehicle, false, false) -- /makecivveh function createCivilianPermVehicle(thePlayer, commandName, id, col1, col2, userName, factionVehicle, cost) if (exports.global:isPlayerLeadAdmin(thePlayer)) then if not (id) or not (col1) or not (col2) then outputChatBox("SYNTAX: /" .. commandName .. " [id] [color1 (-1 for random)] [color2 (-1 for random)]", thePlayer, 255, 194, 14) else local r = getPedRotation(thePlayer) local x, y, z = getElementPosition(thePlayer) x = x + ( ( math.cos ( math.rad ( r ) ) ) * 5 ) y = y + ( ( math.sin ( math.rad ( r ) ) ) * 5 ) if (tonumber(col1)==-1) then col1 = math.random(0, 126) end if (tonumber(col2)==-1) then col2 = math.random(0, 126) end local letter1 = exports.global:randChar() local letter2 = exports.global:randChar() local plate = letter1 .. letter2 .. math.random(0, 9) .. " " .. math.random(1000, 9999) local veh = createVehicle(id, x, y, z, 0, 0, r, plate) exports.pool:allocateElement(veh) if not (veh) then outputChatBox("Invalid Vehicle ID.", thePlayer, 255, 0, 0) else setElementData(veh, "fuel", 100) local rx, ry, rz = getVehicleRotation(veh) setVehicleRespawnPosition(veh, x, y, z, rx, ry, rz) setVehicleLocked(veh, false) setVehicleColor(veh, col1, col2, col1, col2) setVehicleOverrideLights(veh, 1) setVehicleEngineState(veh, false) setVehicleFuelTankExplodable(veh, false) -- Set the vehicle armored if it is armored if (armoredCars[tonumber(id)]) then setVehicleDamageProof(veh, true) end local query = mysql_query(handler, "INSERT INTO vehicles SET model='" .. id .. "', x='" .. x .. "', y='" .. y .. "', z='" .. z .. "', rotx='" .. rx .. "', roty='" .. ry .. "', rotz='" .. rz .. "', color1='" .. col1 .. "', color2='" .. col2 .. "', faction='-1', owner='-2', plate='" .. plate .. "', currx='" .. x .. "', curry='" .. y .. "', currz='" .. z .. "', currrx='0', currry='0', currrz='" .. r .. "'") if (query) then mysql_free_result(query) local id = mysql_insert_id(handler) setElementData(veh, "dbid", tonumber(id)) setElementData(veh, "fuel", 100) setElementData(veh, "engine", 0) setElementData(veh, "oldx", x) setElementData(veh, "oldy", y) setElementData(veh, "oldz", z) setElementData(veh, "faction", -1) setElementData(veh, "owner", -2) setElementData(veh, "job", 0) outputChatBox(getVehicleName(veh) .. " (Civilian) spawned with ID #" .. id .. ".", thePlayer, 255, 194, 14) triggerEvent("onVehicleSpawn", veh) end end end end end addCommandHandler("makecivveh", createCivilianPermVehicle, false, false) function loadAllVehicles(res) if (res==getThisResource()) then -- Reset player in vehicle states local players = exports.pool:getPoolElementsByType("player") for key, value in ipairs(players) do setElementData(value, "realinvehicle", 0) end local result = mysql_query(handler, "SELECT currx, curry, currz, currrx, currry, currrz, x, y, z, rotx, roty, rotz, id, model, upgrade0, upgrade1, upgrade2, upgrade3, upgrade4, upgrade5, upgrade6, upgrade7, upgrade8, upgrade9, upgrade10, upgrade11, upgrade12, upgrade13, upgrade14, upgrade15, upgrade16 FROM vehicles") local resultext = mysql_query(handler, "SELECT fuel, engine, locked, lights, sirens, paintjob, wheel1, wheel2, wheel3, wheel4, panel0, panel1, panel2, panel3, panel4, panel5, panel6, door1, door2, door3, door4, door5, door6, hp, color1, color2, plate, faction, owner, job FROM vehicles") local counter = 0 local rowc = 1 if (result) then for result, row in mysql_rows(result) do local x = tonumber(row[1]) local y = tonumber(row[2]) local z = tonumber(row[3]) local rx = tonumber(row[4]) local ry = tonumber(row[5]) local rz = tonumber(row[6]) local respawnx = tonumber(row[7]) local respawny = tonumber(row[8]) local respawnz = tonumber(row[9]) local respawnrx = tonumber(row[10]) local respawnry = tonumber(row[11]) local respawnrz = tonumber(row[12]) local id = tonumber(row[13]) local vehid = tonumber(row[14]) local upgrade0 = row[15] local upgrade1 = row[16] local upgrade2 = row[17] local upgrade3 = row[18] local upgrade4 = row[19] local upgrade5 = row[20] local upgrade6 = row[21] local upgrade7 = row[22] local upgrade8 = row[23] local upgrade9 = row[24] local upgrade10 = row[25] local upgrade11 = row[26] local upgrade12 = row[27] local upgrade13 = row[28] local upgrade14 = row[29] local upgrade15 = row[30] local upgrade16 = row[31] local fuel = tonumber(mysql_result(resultext, rowc, 1)) local engine = tonumber(mysql_result(resultext, rowc, 2)) local locked = tonumber(mysql_result(resultext, rowc, 3)) local lights = tonumber(mysql_result(resultext, rowc, 4)) local sirens = tonumber(mysql_result(resultext, rowc, 5)) local paintjob = tonumber(mysql_result(resultext, rowc, 6)) local wheel1 = mysql_result(resultext, rowc, 7) local wheel2 = mysql_result(resultext, rowc, 8) local wheel3 = mysql_result(resultext, rowc, 9) local wheel4 = mysql_result(resultext, rowc, 10) local panel0 = mysql_result(resultext, rowc, 11) local panel1 = mysql_result(resultext, rowc, 12) local panel2 = mysql_result(resultext, rowc, 13) local panel3 = mysql_result(resultext, rowc, 14) local panel4 = mysql_result(resultext, rowc, 15) local panel5 = mysql_result(resultext, rowc, 16) local panel6 = mysql_result(resultext, rowc, 17) local door1 = mysql_result(resultext, rowc, 18) local door2 = mysql_result(resultext, rowc, 19) local door3 = mysql_result(resultext, rowc, 20) local door4 = mysql_result(resultext, rowc, 21) local door5 = mysql_result(resultext, rowc, 22) local door6 = mysql_result(resultext, rowc, 23) local hp = mysql_result(resultext, rowc, 24) local col1 = mysql_result(resultext, rowc, 25) local col2 = mysql_result(resultext, rowc, 26) local plate = mysql_result(resultext, rowc, 27) local faction = tonumber(mysql_result(resultext, rowc, 28)) local owner = tonumber(mysql_result(resultext, rowc, 29)) if (faction~=-1) then locked = 0 end local job = mysql_result(resultext, rowc, 30) -- Spawn the vehicle local veh = createVehicle(vehid, x, y, z, rx, ry, rz, plate) exports.pool:allocateElement(veh) -- Set the vehicle armored if it is armored if (armoredCars[tonumber(vehid)]) then setVehicleDamageProof(veh, true) end -- Set the lights to undamaged, currently we cannot load light states as the MTA function is bugged setVehicleLightState(veh, 0, 0) setVehicleLightState(veh, 1, 0) setVehicleLightState(veh, 2, 0) setVehicleLightState(veh, 3, 0) -- Add the vehicle upgrades addVehicleUpgrade(veh, upgrade0) addVehicleUpgrade(veh, upgrade1) addVehicleUpgrade(veh, upgrade2) addVehicleUpgrade(veh, upgrade3) addVehicleUpgrade(veh, upgrade4) addVehicleUpgrade(veh, upgrade5) addVehicleUpgrade(veh, upgrade6) addVehicleUpgrade(veh, upgrade7) addVehicleUpgrade(veh, upgrade8) addVehicleUpgrade(veh, upgrade9) addVehicleUpgrade(veh, upgrade10) addVehicleUpgrade(veh, upgrade11) addVehicleUpgrade(veh, upgrade12) addVehicleUpgrade(veh, upgrade13) addVehicleUpgrade(veh, upgrade14) addVehicleUpgrade(veh, upgrade15) addVehicleUpgrade(veh, upgrade16) -- Paint job setVehiclePaintjob(veh, paintjob) -- Vehicle wheel states setVehicleWheelStates(veh, wheel1, wheel2, wheel3, wheel4) -- Vehicle panel states setVehiclePanelState(veh, 0, panel0) setVehiclePanelState(veh, 1, panel1) setVehiclePanelState(veh, 2, panel2) setVehiclePanelState(veh, 3, panel3) setVehiclePanelState(veh, 4, panel4) setVehiclePanelState(veh, 5, panel5) setVehiclePanelState(veh, 6, panel6) -- Door states setVehicleDoorState(veh, 0, door1) setVehicleDoorState(veh, 1, door2) setVehicleDoorState(veh, 2, door3) setVehicleDoorState(veh, 3, door4) setVehicleDoorState(veh, 4, door5) setVehicleDoorState(veh, 5, door6) -- Car HP setElementHealth(veh, hp) -- Lock the vehicle if locked if (locked==1) then setVehicleLocked(veh, true) else setVehicleLocked(veh, false) end -- Set the siren status if (sirens==1) then setVehicleSirensOn(veh, true) else setVehicleSirensOn(veh, false) end -- Set the vehicles color setVehicleColor(veh, col1, col2, col1, col2) -- Fix rz rz = -rz --respawnrz = -respawnrz respawnry = 0 -- Where the vehicle will respawn on explode/idle setVehicleRespawnPosition(veh, respawnx, respawny, respawnz, respawnrx, respawnry, respawnrz) -- Vehicles element data setElementData(veh, "dbid", id) setElementData(veh, "fuel", fuel) setElementData(veh, "engine", engine) setElementData(veh, "oldx", x) setElementData(veh, "oldy", y) setElementData(veh, "oldz", z) setElementData(veh, "faction", faction) setElementData(veh, "owner", owner) setElementData(veh, "job", tonumber(job)) -- Set the lights if (lights==0 or lights==1) then setVehicleOverrideLights(veh, 1) else setVehicleOverrideLights(veh, 2) end -- Set the sirens setVehicleSirensOn(veh, false) -- Set the engine if (engine==0) then setVehicleEngineState(veh, false) else setVehicleEngineState(veh, true) end -- Set the fuel tank non explodable setVehicleFuelTankExplodable(veh, false) triggerEvent("onVehicleSpawn", veh) counter = counter + 1 rowc = rowc + 1 end end exports.irc:sendMessage("[SCRIPT] Loaded " .. counter .. " vehicles.") end end addEventHandler("onResourceStart", getRootElement(), loadAllVehicles) function vehicleExploded() setTimer(respawnVehicle, 180000, 1, source) end addEventHandler("onVehicleExplode", getRootElement(), vehicleExploded) function vehicleRespawn(exploded) local id = getElementData(source, "dbid") local faction = getElementData(source, "faction") local owner = getElementData(source, "owner") -- Set the vehicle armored if it is armored local vehid = getElementModel(source) if (armoredCars[tonumber(vehid)]) then setVehicleDamageProof(source, true) end setVehicleFuelTankExplodable(source, false) setVehicleEngineState(source, false) setVehicleLandingGearDown(source, true) setElementData(source, "dbid", id) setElementData(source, "fuel", 100) setElementData(source, "engine", 0) local x, y, z = getElementPosition(source) setElementData(source, "oldx", x) setElementData(source, "oldy", y) setElementData(source, "oldz", z) setElementData(source, "faction", faction) setElementData(source, "owner", owner) setVehicleOverrideLights(source, 1) setVehicleFrozen(source, false) -- Set the sirens off setVehicleSirensOn(source, false) setVehicleLightState(source, 0, 0) setVehicleLightState(source, 1, 0) if (faction==-1) then setVehicleLocked(source, true) end end addEventHandler("onVehicleRespawn", getRootElement(), vehicleRespawn) function setEngineStatusOnEnter(thePlayer, seat, jacked) local engine = getElementData(source, "engine") if (seat==0) then local model = getElementModel(source) if not (enginelessVehicle[model]) then if (engine==0) then toggleControl(thePlayer, "accelerate", false) toggleControl(thePlayer, "brake_reverse", false) toggleControl(thePlayer, "vehicle_fire", false) setVehicleEngineState(source, false) else setVehicleEngineState(source, true) end else toggleControl(thePlayer, "accelerate", true) toggleControl(thePlayer, "brake_reverse", true) toggleControl(thePlayer, "vehicle_fire", true) setVehicleEngineState(source, true) setElementData(source, "engine", 1) end end end addEventHandler("onVehicleEnter", getRootElement(), setEngineStatusOnEnter) function vehicleExit(thePlayer, seat) toggleControl(thePlayer, "accelerate", true) toggleControl(thePlayer, "brake_reverse", true) toggleControl(thePlayer, "vehicle_fire", true) -- For oldcar local vehid = getElementData(source, "dbid") setElementData(thePlayer, "lastvehid", vehid) end addEventHandler("onVehicleExit", getRootElement(), vehicleExit) function destroyTyre(veh, tyre) if (tyre==1) then setVehicleWheelStates(veh, 2, -1, -1, -1) elseif (tyre==2) then setVehicleWheelStates(veh, -1, 2, -1, -1) elseif (tyre==3) then setVehicleWheelStates(veh, -1, -1, 2, -1) elseif (tyre==4) then setVehicleWheelStates(veh, -1, -1, -1, 2) end end function damageTyres() local tyre1, tyre2, tyre3, tyre4 = getVehicleWheelStates(source) if (tyre1==1) then local randTime = math.random(10, 30) randTime = randTime * 1000 setTimer(destroyTyre, randTime, 1, source, 1) end if (tyre2==1) then local randTime2 = math.random(10, 30) randTime2 = randTime2 * 1000 setTimer(destroyTyre, randTime2, 1, source, 2) end if (tyre3==1) then local randTime3 = math.random(10, 30) randTime3 = randTime3 * 1000 setTimer(destroyTyre, randTime3, 1, source, 3) end if (tyre4==1) then local randTime4 = math.random(10, 30) randTime4 = randTime4 * 1000 setTimer(destroyTyre, randTime4, 1, source, 4) end end addEventHandler("onVehicleDamage", getRootElement(), damageTyres) -- Bind Keys required function bindKeys() local players = exports.pool:getPoolElementsByType("player") for k, arrayPlayer in ipairs(players) do if not(isKeyBound(arrayPlayer, "j", "down", toggleEngine)) then bindKey(arrayPlayer, "j", "down", toggleEngine) end if not(isKeyBound(arrayPlayer, "l", "down", toggleLights)) then bindKey(arrayPlayer, "l", "down", toggleLights) end if not(isKeyBound(arrayPlayer, "k", "down", toggleLock)) then bindKey(arrayPlayer, "k", "down", toggleLock) end end end function bindKeysOnJoin() bindKey(source, "j", "down", toggleEngine) bindKey(source, "l", "down", toggleLights) bindKey(source, "k", "down", toggleLock) end addEventHandler("onResourceStart", getRootElement(), bindKeys) addEventHandler("onPlayerJoin", getRootElement(), bindKeysOnJoin) function toggleEngine(source, key, keystate) local veh = getPedOccupiedVehicle(source) local inVehicle = getElementData(source, "realinvehicle") if (veh) and (inVehicle==1) then local model = getElementModel(veh) if not (enginelessVehicle[model]) then local engine = getElementData(veh, "engine") local fuel = getElementData(veh, "fuel") local seat = getPedOccupiedVehicleSeat(source) if (seat==0) then if (engine==0) and (fuel>0) then -- Bike fix toggleControl(source, "accelerate", true) toggleControl(source, "brake_reverse", true) toggleControl(source, "vehicle_fire", true) setVehicleEngineState(veh, true) setElementData(veh, "engine", 1) elseif (engine==0) and (fuel<1) then -- Bike fix toggleControl(source, "accelerate", false) toggleControl(source, "brake_reverse", false) toggleControl(source, "vehicle_fire", false) exports.global:sendLocalMeAction(source, "attempts to turn the engine on and fails.") outputChatBox("This vehicle has no fuel.", source) else -- Bike fix toggleControl(source, "accelerate", false) toggleControl(source, "brake_reverse", false) toggleControl(source, "vehicle_fire", false) setVehicleEngineState(veh, false) setElementData(veh, "engine", 0) end end end end end function toggleLock(source, key, keystate) local veh = getPedOccupiedVehicle(source) local inVehicle = getElementData(source, "realinvehicle") if (veh) and (inVehicle==1) then local model = getElementModel(veh) --if not (locklessVehicle[model]) then local locked = isVehicleLocked(veh) local seat = getPedOccupiedVehicleSeat(source) if (seat==0) then if (locked) then setVehicleLocked(veh, false) exports.global:sendLocalMeAction(source, "unlocks the vehicle doors.") else setVehicleLocked(veh, true) exports.global:sendLocalMeAction(source, "locks the vehicle doors.") end end --end end end function checkLock(thePlayer) local locked = isVehicleLocked(source) if (locked) then cancelEvent() outputChatBox("The door is locked.", thePlayer) end end addEventHandler("onVehicleStartExit", getRootElement(), checkLock) function toggleLights(source, key, keystate) local veh = getPedOccupiedVehicle(source) local inVehicle = getElementData(source, "realinvehicle") if (veh) and (inVehicle==1) then local model = getElementModel(veh) if not (lightlessVehicle[model]) then local lights = getVehicleOverrideLights(veh) local seat = getPedOccupiedVehicleSeat(source) if (seat==0) then if (lights~=2) then setVehicleOverrideLights(veh, 2) setElementData(veh, "lights", 1) elseif (lights~=1) then setVehicleOverrideLights(veh, 1) setElementData(veh, "lights", 0) end end end end end --///////////////////////////////////////////////////////// --Fix for spamming keys to unlock etc on entering --///////////////////////////////////////////////////////// -- bike lock fix function checkBikeLock(thePlayer) if (isVehicleLocked(source)) then outputChatBox("That bike is locked.", source, 255, 194, 15) cancelEvent() end end addEventHandler("onVehicleStartEnter", getRootElement(), checkBikeLock) function setRealInVehicle(thePlayer) setElementData(thePlayer, "realinvehicle", 1) end addEventHandler("onVehicleEnter", getRootElement(), setRealInVehicle) function setRealNotInVehicle(thePlayer) local locked = isVehicleLocked(source) if not (locked) then setElementData(thePlayer, "realinvehicle", 0) end end addEventHandler("onVehicleStartExit", getRootElement(), setRealNotInVehicle) -- Faction vehicles removal script function removeFromFactionVehicle(thePlayer) local faction = getElementData(thePlayer, "faction") local vfaction = tonumber(getElementData(source, "faction")) if (vfaction~=-1) then local seat = getPedOccupiedVehicleSeat(thePlayer) if (faction~=vfaction) and (seat==0) then local factionName = "this faction" for key, value in ipairs(exports.pool:getPoolElementsByType("team")) do local id = tonumber(getElementData(value, "id")) if (id==vfaction) then factionName = getTeamName(value) break end end outputChatBox("You are not a member of '" .. factionName .. "'.", thePlayer, 255, 194, 14) removePedFromVehicle(thePlayer) local x, y, z = getElementPosition(thePlayer) setElementPosition(thePlayer, x, y, z) end end end addEventHandler("onVehicleEnter", getRootElement(), removeFromFactionVehicle)
local rdebug = require 'remotedebug.visitor' local NEWLINE <const> = '\n' local INDENT <const> = ' ' local DEPTH <const> = 10 local level local out local visited local putValue local function floatToString(x) if x ~= x then return '0/0' end if x == math.huge then return 'math.huge' end if x == -math.huge then return '-math.huge' end local g = ('%.16g'):format(x) if tonumber(g) == x then return g end return ('%.17g'):format(x) end local function isIdentifier(str) return type(str) == 'string' and str:match( "^[_%a][_%a%d]*$" ) end local TypeOrders = { ['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4, ['function'] = 5, ['userdata'] = 6, ['thread'] = 7 } local function sortKeys(a, b) a, b = a[1], b[1] local ta, tb = type(a), type(b) if ta == tb and (ta == 'string' or ta == 'number') then return a < b end local dta, dtb = TypeOrders[ta], TypeOrders[tb] if dta and dtb then return TypeOrders[ta] < TypeOrders[tb] elseif dta then return true elseif dtb then return false end return ta < tb end local function puts(text) out[#out+1] = text end local function newline() puts(NEWLINE) puts(INDENT:rep(level)) end local function putKey(k) if isIdentifier(k) then return puts(k) end puts("[") putValue(k) puts("]") end local function putTable(t) local uniquekey = rdebug.value(t) if visited[uniquekey] then puts('<table>') elseif level >= DEPTH then puts('{...}') else visited[uniquekey] = true puts('{') level = level + 1 local count = 0 local asize = rdebug.tablesize(t) for i=1, asize do if count > 0 then puts(',') end puts(' ') putValue(rdebug.index(t, i)) count = count + 1 end local loct = rdebug.tablehashv(t) local kvs = {} for i = 1, #loct, 2 do local key, value = loct[i], loct[i+1] kvs[#kvs + 1] = { key, value } end table.sort(kvs, sortKeys) for i=1, #kvs do local kv = kvs[i] if count > 0 then puts(',') end newline() putKey(kv[1]) puts(' = ') putValue(kv[2]) count = count + 1 end local metatable = rdebug.getmetatablev(t) if metatable then if count > 0 then puts(',') end newline() puts('<metatable> = ') putValue(metatable) end level = level - 1 if #kvs > 0 or metatable then newline() elseif asize > 0 then puts(' ') end puts('}') end end function putValue(v) local tv = rdebug.type(v) if tv == 'string' then puts(("%q"):format(rdebug.value(v))) elseif tv == 'float' then puts(floatToString(rdebug.value(v))) elseif tv == 'integer' or tv == 'boolean' or tv == 'nil' then puts(tostring(rdebug.value(v))) elseif tv == 'table' then putTable(v) else puts('<'..tv..'>') end end return function (root) level = 0 out = {} visited = {} putValue(root) return table.concat(out) end
Tests = {} Lester = {} if not GetGameTimer then GetGameTimer = function() return os.time() end end --- @class Context Context = setmetatable({}, Context) Context.__index = Context Context.__call = function() return "Context" end function Context.new(parent) local _Context = { _Parent = parent, Tests ={}, Cleaner = function() end } return setmetatable(_Context, Context) end ---@param description string ---@param handler fun(context: Context): void ---@return Context function Context:Should(description, handler) table.insert(self.Tests, { description = description, handler = handler }) return self end function Context:Clean(handler) self.Cleaner = handler end function Context:Assert(val1, val2) return val1 == val2 end ---@param description string ---@param handler fun(context: Context): void ---@return Context function Lester.Describe(description, handler) table.insert(Tests, { description = description, handler = handler }) end function Lester.Assert(val, check) return val == check end function Lester.Run() for k,v in pairs(Tests) do local context = v.handler(Context.new()) local testStr = ColorString.new():LightGreen("Testing: "):LightBlue(v.description):End() print(testStr) local passed = 0 local failed = 0 if type(context) == "table" then if context.__call() == "Context" then for b,z in pairs(context.Tests) do local startTime = GetGameTimer() local res = z.handler() local endTime = GetGameTimer() local diff = endTime - startTime local seconds = math.floor(diff / 1000) local rawRemainder = diff % 1000 local remainder if rawRemainder < 10 then remainder = "00" .. rawRemainder elseif rawRemainder < 100 then remainder = "0" .. rawRemainder end if res == true then if not ColorString then print(" ✅ should " .. z.description .. " ⏱️: " .. diff) else local output = ColorString.new():LightGreen("+ " .. z.description):LightBlue(" => " .. seconds .. "." .. remainder .. "s"):End() print(output) end passed = passed + 1 else if not ColorString then print(" ❌ should " .. z.description .. " ⏱️: " .. diff) else local output = ColorString.new():RedOrange("!" .. z.description):LightBlue(" => " .. seconds .. "." .. remainder .. "s"):End() print(output) end failed = failed + 1 end end context.Cleaner() else print(ColorString.new():LightYellow("Skipping because of invalid config")) end else print(ColorString.new():LightYellow("Skipping because of invalid config")) end print("Passed: " .. passed .. " - Failed: " .. failed .. " - " .. (passed / (passed + failed) * 100) .. " % of tests passed") end end if not Vehicle then --- @class Vehicle Vehicle = setmetatable({}, Vehicle) Vehicle.__index = Vehicle Vehicle.__call = function() return "Vehicle" end function Vehicle.new() local _Vehicle = {} return setmetatable(_Vehicle, Vehicle) end end function CreateTruck() local veh = World:CreateVehicle("panto", Player:ForwardVector(3), 0, true) print("Created vehicle", veh) Citizen.Wait(2000) return veh end Lester.Describe("CreateTruck()", function(context) local val = CreateTruck() context:Should("return an instance of the Vehicle class", function() local response = context:Assert(val.__call(), "Vehicle") Citizen.Wait(2000) return response end) val:Model("sultan") context:Should("have a model equal to 'sultan'", function() local response = context:Assert(val:Model(), GetHashKey("sultan")) return response end) context:Clean(function() val:Delete() end) print("Returning ", context) return context end) Lester.Describe("Getting net player name", function(context) local testVehicle = World:CreateVehicle("zentorno",Player:ForwardVector(5), 0, true) local owner = testVehicle:GetNetworkOwner():Name() print("Owner is", owner) context:Should("be owned by Cyntaax", function() return context:Assert(owner, "Cyntaax") end) context:Clean(function() testVehicle:Delete() end) return context end)
-- ===== ===== ===== ===== ===== -- Copyright (c) 2017 Lukas Grünwald -- License MIT License -- ===== ===== ===== ===== ===== --- {abstract} Event base class. -- All event inherit their functionality from this. -- Import new functions: require( "libErrorFunctions" ) require( "libDebugFunctions" ) cEvent = {} cEvent.__index = cEvent --- {abstract} Constructor. -- @tparam cEventHandler parentEventHandler Needs the access to the event handler, so it can communicate with all objects. -- @within Constructor function cEvent.New( parentEventHandler ) local self = setmetatable( {}, cEvent ) self.Parent = parentEventHandler self.Type = "TEXT_LUA_OBJECT_TYPE_EVENT_BASIC" self.IsTimed = false self.RegisteredTimestamp = false self.Timer = false return self end --- Returns the IsTimed attribute. -- @treturn bool -- @within Getter Functions function cEvent:IsTimedEvent() return self.IsTimed end --- Returns the event type. -- @treturn string -- @within Getter Functions function cEvent:GetObjectType() return self.Type end --- Returns the event delay. -- @treturn float -- @within Getter Functions function cEvent:GetTimer() return self.Timer end --- Returns the event registered timestamp. -- @treturn int (I think; could be game cycles too, not sure.) -- @within Getter Functions function cEvent:GetRegisteredTimestamp() return self.RegisteredTimestamp end --- Calculates whether a timed event is allowed to be executed. -- Uses the vanilla GetCurrenttime() function. This should return the seconds passed since the GC has been started. -- @treturn bool -- @within Getter Functions function cEvent:IsReadyToExecute() if self:GetRegisteredTimestamp() + self:GetTimer() <= GetCurrentTime() then return true end return false end --- {abstract} Executes the event. function cEvent:Execute() return false end return cEvent
local Errors = require "kong.dao.errors" return { no_consumer = true, -- this plugin is available on APIs as well as on Consumers, fields = { -- Describe your plugin's configuration's schema here. domain = {type = "string", required=true}, secret = {type = "string", required=true }, required_headers = {type="array"} }, self_check = function(schema, plugin_t, dao, is_updating) -- perform any custom verification if not plugin_t.domain then return false, Errors.schema("domain is required") end if not plugin_t.secret then return false, Errors.schema("secret is required") end return true end }
local gsrTimer = 0 local gsrPositive = false local plyPed = PlayerPedId() local gsrTestDistance = 5 Citizen.CreateThread(function() while true do Citizen.Wait(1) plyPed = PlayerPedId() if IsPedSwimmingUnderWater(plyPed) then Citizen.Wait(10000) if gsrPositive then chance = math.random(1, 3) if chance ~= 1 then Notify("~g~Success! ~w~Residue ~g~was ~w~cleaned off.") gsrTimer = 0 gsrPositive = false; else Notify("~r~Failed! ~w~Residue was ~r~not ~w~cleaned off.") gsrTimer = Config.GSRAutoClean Citizen.CreateThread(GSRThreadTimer) end end end if IsPedShooting(plyPed) then if gsrPositive then gsrTimer = Config.GSRAutoClean else gsrPositive = true gsrTimer = Config.GSRAutoClean Citizen.CreateThread(GSRThreadTimer) end end end end) RegisterCommand(Config.TestGSR, function() local playerCoords = GetEntityCoords(plyPed) for _, player in ipairs(GetActivePlayers()) do local targetPed = GetPlayerPed(player) local targetId = GetPlayerServerId(player) local distance = #(playerCoords-GetEntityCoords(targetPed)) if targetPed ~= plyPed then if distance <= gsrTestDistance then TriggerServerEvent('GSR:PlayerTest', targetId) else Notify("~r~Could Not Find Subject") end end end end) RegisterCommand(Config.cleargsr, function() if gsrPositive then Notify("~b~Cleaning...") Citizen.Wait(10000) chance = math.random(1, 3) if chance ~= 1 then Notify("~g~Success! ~w~Residue ~g~was ~w~cleaned off.") gsrTimer = 0 gsrPositive = false; else Notify("~r~Failed! ~w~Residue was ~r~not ~w~cleaned off.") gsrTimer = Config.GSRAutoClean Citizen.CreateThread(GSRThreadTimer) end end end) RegisterCommand(Config.forceclean, function() if Config.Perms.restricted then if TriggerServerEvent('GSR:PermCheck') then Notify("~g~Success! ~w~Residue ~g~was ~w~cleaned off.") gsrTimer = 0 gsrPositive = false; TriggerServerEvent("GSR:ForceClean") else Notify('~r~Failed! You do not have permission to do that!') end else Notify("~g~Success! ~w~Residue ~g~was ~w~cleaned off.") gsrTimer = 0 gsrPositive = false; TriggerServerEvent("GSR:ForceClean") end end) RegisterNetEvent("GSR:Not1fy") AddEventHandler("GSR:Not1fy", function(notHandler) Notify(notHandler) end) RegisterNetEvent("GSR:TestHandler") AddEventHandler("GSR:TestHandler", function(tester) if gsrPositive then TriggerServerEvent("GSR:TestCallback", tester, true) elseif not gsrPositive then TriggerServerEvent("GSR:TestCallback", tester, false) end end) function GSRThreadTimer() while gsrPositive do Citizen.Wait(1000) if gsrTimer == 0 then gsrPositive = false else gsrTimer = gsrTimer - 1 end end end -- Jordan's Notify System function Notify(string) SetNotificationTextEntry("STRING") AddTextComponentString('~y~[ROCKET_GSR] ' .. string) DrawNotification(false, true) end
--[[ Boss -- Slad'ran.lua This script was written and is protected by the GPL v2. This script was released by Bapes of the Blua Scripting Project. Please give proper accredidations when re-releasing or sharing this script with others in the emulation community. ~~End of License Agreement -- Bapes, November 03, 2008. ]] -- Adds: http://wotlk.wowhead.com/?npc=29713 & http://wotlk.wowhead.com/?npc=29680 --local Slad'ranConstrictor = 29713 --local Slad'ranViper = 29680 -- 99% Blizzlike, just need exact times for spells. function Sladran_OnCombat(pUnit, Event) pUnit:SendChatMessage(14, 0, "Drakkari gonna kill anybody who trespass on these lands!") pUnit:RegisterEvent("Sladran_PoisonNova", math.random(15000, 17000), 0) pUnit:RegisterEvent("Sladran_PowerfulBite", math.random(22000, 24000), 0) pUnit:RegisterEvent("Sladran_VenomBolt", math.random(29000, 34000), 0) end function Sladran_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function Sladran_OnKillTarget(pUnit, Event) -- Around 80% chance to use text. local Text = math.random(1, 4) if Text == 1 then pUnit:SendChatMessage(14, 0, "Ye not breathin'! Good.") elseif Text == 2 then pUnit:SendChatMessage(14, 0, "You scared now?") elseif Text == 3 then pUnit:SendChatMessage(14, 0, "I'll eat you next, mon!") end end function Sladran_OnDeath(pUnit, Event) pUnit:RemoveEvents() pUnit:SendChatMessage(14, 0, "I see now... Scourge was not our greatest enemy.") end RegisterUnitEvent(29304, 1, "Sladran_OnCombat") RegisterUnitEvent(29304, 2, "Sladran_OnLeaveCombat") RegisterUnitEvent(29304, 3, "Sladran_OnKillTarget") RegisterUnitEvent(29304, 4, "Sladran_OnDeath") function Sladran_PhaseTwo(pUnit, Event) if pUnit:GetHealthPct() <= 30 then pUnit:RegisterEvent("Sladran_SummonAdds", math.random(40000, 42000), 0) pUnit:RegisterEvent("Sladran_PoisonNova", math.random(15000, 17000), 0) pUnit:RegisterEvent("Sladran_PowerfulBite", math.random(22000, 24000), 0) pUnit:RegisterEvent("Sladran_VenomBolt", math.random(29000, 34000), 0) end end function Sladran_SummonAdds(pUnit, Event) pUnit:SendChatMessage(14, 0, "Minions of the scale, heed my call!") local x,y,z,o = pUnit:GetX(),pUnit:GetY(),pUnit:GetZ(),pUnit:GetO() pUnit:SpawnCreature(29713, x, y, z, o, 14, 0) pUnit:SpawnCreature(29713, x, y, z, o, 14, 0) pUnit:SpawnCreature(29680, x, y, z, o, 14, 0) pUnit:SpawnCreature(29680, x, y, z, o, 14, 0) end function Sladran_PoisonNova(pUnit, Event) -- http://wotlk.wowhead.com/?spell=55081 pUnit:FullCastSpell(55081) end function Sladran_PowerfulBite(pUnit, Event) -- http://wotlk.wowhead.com/?spell=48287 pUnit:FullCastSpellOnTarget(48287, pUnit:GetMainTank()) end function Sladran_VenomBolt(pUnit, Event) -- http://wotlk.wowhead.com/?spell=54970 pUnit:FullCastSpellOnTarget(54970, pUnit:GetRandomPlayer(0)) end
return { metadata = { {scaling_used = {"Exo_3D"}, subject_age = {30.0}, subject_height = {1.70}, subject_weight = {80.00}, subject_gender = {"male"}, subject_pelvisWidth = {0.2400}, subject_hipCenterWidth = {0.1700}, subject_shoulderCenterWidth = {0.4000}, subject_heelAnkleXOffset = {0.0800}, subject_heelAnkleZOffset = {0.0900}, subject_shoulderNeckZOffset = {0.0700}, subject_footWidth = {0.0900}, }, }, gravity = { 0, 0, -9.81,}, configuration = { axis_front = { 1, 0, 0,}, axis_right = { 0, -1, 0,}, axis_up = { 0, 0, 1,}, }, points = { {name = "ExoPelvis_L", body = "Exo_PelvisModule", point = {0.000000, 0.150000, 0.000000,},}, {name = "ExoPelvis_R", body = "Exo_PelvisModule", point = {0.000000, -0.150000, 0.000000,},}, {name = "ExoPelvis_Back", body = "Exo_PelvisModule", point = {-0.112500, 0.000000, 0.000000,},}, {name = "ExoThigh_R", body = "Exo_ThighModule_R", point = {0.000000, -0.000000, 0.000000,},}, {name = "ExoThigh_L", body = "Exo_ThighModule_L", point = {0.000000, 0.000000, 0.000000,},}, {name = "ExoUpperTrunk_Front", body = "Exo_UpperTrunkModule", point = {0.275400, 0.000000, -0.033660,},}, {name = "ExoUpperTrunk_Back", body = "Exo_UpperTrunkModule", point = {-0.010200, 0.000000, 0.000000,},}, }, constraint_sets = { }, frames = { {name = "Exo_PelvisModule", parent = "ROOT", joint_frame = { r = { 0.000000, 0.000000, 0.105000,}, E = {{ 1.000000, 0.000000, 0.000000,}, { 0.000000, 1.000000, 0.000000,}, { 0.000000, 0.000000, 1.000000,},}, }, body = { mass = 2.617337, com = { 0.001012, -0.000922, -0.000114,}, inertia = {{ 0.021193, -0.000003, 0.000000,}, { -0.000003, 0.017238, -0.000001,}, { 0.000000, -0.000001, 0.035733,},}, }, joint = {{ 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000,}, { 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000,}, { 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000,}, { 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000,},}, markers = {}, visuals = {{ src = "exo_pelvisModule.obj", dimensions = { 0.288000, 0.360000, 0.075000,}, mesh_center = { 0.000000, 0.000000, 0.000000,}, color = { 0.000000, 0.407843, 0.545098,}, },}, }, {name = "Exo_ThighBar_R", parent = "Exo_PelvisModule", joint_frame = { r = { 0.080000, -0.085000, 0.000000,}, E = {{ 1.000000, 0.000000, 0.000000,}, { 0.000000, 1.000000, 0.000000,}, { 0.000000, 0.000000, 1.000000,},}, }, body = { mass = 0.440265, com = { 0.030000, 0.000000, -0.250747,}, inertia = {{ 0.006909, 0.000000, 0.000000,}, { 0.000000, 0.006882, 0.000000,}, { 0.000000, 0.000000, 0.000039,},}, }, joint = {{ 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000,},}, markers = {}, visuals = {{ src = "exo_bar.obj", dimensions = { 0.015000, 0.030000, 0.501494,}, mesh_center = { 0.030000, 0.000000, -0.250747,}, color = { 0.000000, 0.407843, 0.545098,}, },}, }, {name = "Exo_ThighModule_R", parent = "Exo_ThighBar_R", joint_frame = { r = { 0.000000, 0.000000, -0.405000,}, E = {{ 1.000000, 0.000000, 0.000000,}, { 0.000000, 1.000000, 0.000000,}, { 0.000000, 0.000000, 1.000000,},}, }, body = { mass = 1.071810, com = { -0.070000, 0.004000, 0.000000,}, inertia = {{ 0.001903, 0.000000, 0.000000,}, { 0.000000, 0.004787, 0.000000,}, { 0.000000, 0.000000, 0.005763,},}, }, joint = {{ 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000,},}, markers = {}, visuals = {{ src = "exo_thighModule.obj", dimensions = { 0.220000, 0.150000, 0.072000,}, mesh_center = { -0.070000, 0.004000, 0.000000,}, color = { 0.000000, 0.407843, 0.545098,}, },}, }, {name = "Exo_ThighBar_L", parent = "Exo_PelvisModule", joint_frame = { r = { 0.080000, 0.085000, 0.000000,}, E = {{ 1.000000, 0.000000, 0.000000,}, { 0.000000, 1.000000, 0.000000,}, { 0.000000, 0.000000, 1.000000,},}, }, body = { mass = 0.440265, com = { 0.030000, 0.000000, -0.250747,}, inertia = {{ 0.006909, -0.000000, 0.000000,}, { -0.000000, 0.006882, -0.000000,}, { 0.000000, -0.000000, 0.000039,},}, }, joint = {{ 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000,},}, markers = {}, visuals = {{ src = "exo_bar.obj", dimensions = { 0.015000, 0.030000, 0.501494,}, mesh_center = { 0.030000, 0.000000, -0.250747,}, color = { 0.000000, 0.407843, 0.545098,}, },}, }, {name = "Exo_ThighModule_L", parent = "Exo_ThighBar_L", joint_frame = { r = { 0.000000, 0.000000, -0.405000,}, E = {{ 1.000000, 0.000000, 0.000000,}, { 0.000000, 1.000000, 0.000000,}, { 0.000000, 0.000000, 1.000000,},}, }, body = { mass = 1.071810, com = { -0.070000, -0.004000, 0.000000,}, inertia = {{ 0.001903, 0.000000, 0.000000,}, { 0.000000, 0.004787, 0.000000,}, { 0.000000, 0.000000, 0.005763,},}, }, joint = {{ 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000,},}, markers = {}, visuals = {{ src = "exo_thighModule.obj", dimensions = { 0.220000, 0.150000, 0.072000,}, mesh_center = { -0.070000, -0.004000, 0.000000,}, color = { 0.000000, 0.407843, 0.545098,}, },}, }, {name = "Exo_TorsoBar", parent = "Exo_PelvisModule", joint_frame = { r = { -0.105000, 0.000000, 0.000000,}, E = {{ 1.000000, 0.000000, 0.000000,}, { 0.000000, 1.000000, 0.000000,}, { 0.000000, 0.000000, 1.000000,},}, }, body = { mass = 0.651290, com = { -0.020000, 0.000000, 0.208650,}, inertia = {{ 0.007130, -0.000000, 0.000000,}, { -0.000000, 0.007059, 0.000000,}, { 0.000000, 0.000000, 0.000103,},}, }, joint = { { 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000,},}, markers = {}, visuals = {{ src = "exo_bar.obj", dimensions = { 0.020000, 0.040000, 0.417300,}, mesh_center = { -0.020000, 0.000000, 0.208650,}, color = { 0.000000, 0.407843, 0.545098,}, },}, }, {name = "Exo_UpperTrunkModule", parent = "Exo_TorsoBar", joint_frame = { r = { 0.000000, 0.000000, 0.321000,}, E = {{ 1.000000, 0.000000, 0.000000,}, { 0.000000, 1.000000, 0.000000,}, { 0.000000, 0.000000, 1.000000,},}, }, body = { mass = 1.424113, com = { 0.105000, -0.013005, 0.068569,}, inertia = {{ 0.021507, -0.000000, 0.000000,}, { -0.000000, 0.010778, -0.000070,}, { 0.000000, -0.000070, 0.022159,},}, }, joint = {{ 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000,}, { 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000,},}, markers = {}, visuals = {{ src = "exo_upperTrunkModule.obj", dimensions = { 0.231000, 0.440000, 0.224400,}, mesh_center = { 0.105000, 0.000000, 0.068000,}, color = { 0.000000, 0.407843, 0.545098,}, },}, }, }, }
if (SERVER) then -- CreateConVar('sbox_maxkeypads', 10) -- Handled by keypad_willox.lua end TOOL.Category = "Construction" TOOL.Name = "Keypad - Wire" TOOL.Command = nil TOOL.ClientConVar['weld'] = '1' TOOL.ClientConVar['freeze'] = '1' TOOL.ClientConVar['password'] = '1234' TOOL.ClientConVar['secure'] = '0' TOOL.ClientConVar['repeats_granted'] = '0' TOOL.ClientConVar['repeats_denied'] = '0' TOOL.ClientConVar['length_granted'] = '0.1' TOOL.ClientConVar['length_denied'] = '0.1' TOOL.ClientConVar['delay_granted'] = '0' TOOL.ClientConVar['delay_denied'] = '0' TOOL.ClientConVar['init_delay_granted'] = '0' TOOL.ClientConVar['init_delay_denied'] = '0' TOOL.ClientConVar['output_on'] = '1' TOOL.ClientConVar['output_off'] = '0' -- cleanup.Register("keypads") -- Handled by keypad_willox.lua if CLIENT then language.Add("tool.keypad_willox_wire.name", "Keypad - Wire") language.Add("tool.keypad_willox_wire.0", "Left Click: Create, Right Click: Update") language.Add("tool.keypad_willox_wire.desc", "Creates Keypads for secure access") --[[ language.Add("Undone_Keypad", "Undone Keypad") language.Add("Cleanup_keypads", "Keypads") language.Add("Cleaned_keypads", "Cleaned up all Keypads") language.Add("SBoxLimit_keypads", "You've hit the Keypad limit!") ]] -- Handled by keypad_willox.lua end function TOOL:SetupKeypad(ent, pass) local data = { Password = pass, RepeatsGranted = self:GetClientNumber("repeats_granted"), RepeatsDenied = self:GetClientNumber("repeats_denied"), LengthGranted = self:GetClientNumber("length_granted"), LengthDenied = self:GetClientNumber("length_denied"), DelayGranted = self:GetClientNumber("delay_granted"), DelayDenied = self:GetClientNumber("delay_denied"), InitDelayGranted = self:GetClientNumber("init_delay_granted"), InitDelayDenied = self:GetClientNumber("init_delay_denied"), OutputOn = self:GetClientNumber("output_on"), OutputOff = self:GetClientNumber("output_off"), Secure = util.tobool(self:GetClientNumber("secure")) } ent:SetData(data) end function TOOL:RightClick(tr) if not WireLib then return false end if not IsValid(tr.Entity) or not tr.Entity:GetClass():lower() == "keypad_wire" then return false end if CLIENT then return true end local ply = self:GetOwner() local password = tonumber(ply:GetInfo("keypad_willox_wire_password")) local spawn_pos = tr.HitPos local trace_ent = tr.Entity if password == nil or (string.len(tostring(password)) > 4) or (string.find(tostring(password), "0")) then ply:PrintMessage(3, "Invalid password!") return false end self:SetupKeypad(trace_ent, password) return true end function TOOL:LeftClick(tr) if not WireLib then return false end if IsValid(tr.Entity) and tr.Entity:GetClass() == "player" then return false end if CLIENT then return true end local ply = self:GetOwner() local password = self:GetClientNumber("password") local spawn_pos = tr.HitPos + tr.HitNormal local trace_ent = tr.Entity if password == nil or (string.len(tostring(password)) > 4) or (string.find(tostring(password), "0")) then ply:PrintMessage(3, "Invalid password!") return false end if not self:GetWeapon():CheckLimit("keypads") then return false end local ent = ents.Create("keypad_wire") ent:SetPos(spawn_pos) ent:SetAngles(tr.HitNormal:Angle()) ent:Spawn() ent:SetPlayer(ply) local freeze = util.tobool(self:GetClientNumber("freeze")) local weld = util.tobool(self:GetClientNumber("weld")) if freeze or weld then local phys = ent:GetPhysicsObject() if IsValid(phys) then phys:EnableMotion(false) end end if weld then local weld = constraint.Weld(ent, trace_ent, 0, 0, 0, true, false) end self:SetupKeypad(ent, password) undo.Create("Keypad") undo.AddEntity(ent) undo.SetPlayer(ply) undo.Finish() ply:AddCount("keypads", ent) ply:AddCleanup("keypads", ent) return true end if CLIENT then local function ResetSettings(ply) ply:ConCommand("keypad_willox_wire_repeats_granted 0") ply:ConCommand("keypad_willox_wire_repeats_denied 0") ply:ConCommand("keypad_willox_wire_length_granted 0.1") ply:ConCommand("keypad_willox_wire_length_denied 0.1") ply:ConCommand("keypad_willox_wire_delay_granted 0") ply:ConCommand("keypad_willox_wire_delay_denied 0") ply:ConCommand("keypad_willox_wire_init_delay_granted 0") ply:ConCommand("keypad_willox_wire_init_delay_denied 0") ply:ConCommand("keypad_willox_wire_output_on 1") ply:ConCommand("keypad_willox_wire_output_off 0") end concommand.Add("keypad_willox_wire_reset", ResetSettings) function TOOL.BuildCPanel(CPanel) if not WireLib then CPanel:Help("This tool requires Wiremod to function") CPanel:Help("http://wiremod.com/") CPanel:Help("Workshop Addon #160250458") else local r, l = CPanel:TextEntry("Access Password", "keypad_willox_wire_password") r:SetTall(22) CPanel:ControlHelp("Max Length: 4\nAllowed Digits: 1-9") CPanel:CheckBox("Secure Mode", "keypad_willox_wire_secure") CPanel:CheckBox("Weld", "keypad_willox_wire_weld") CPanel:CheckBox("Freeze", "keypad_willox_wire_freeze") CPanel:NumSlider("Output On:", "keypad_willox_wire_output_on", -10, 10, 0) CPanel:NumSlider("Output Off:", "keypad_willox_wire_output_off", -10, 10, 0) local granted = vgui.Create("DForm") granted:SetName("Access Granted Settings") granted:NumSlider("Hold Length", "keypad_willox_wire_length_granted", 0.1, 10, 2) granted:NumSlider("Initial Delay", "keypad_willox_wire_init_delay_granted", 0, 10, 2) granted:NumSlider("Multiple Press Delay", "keypad_willox_wire_delay_granted", 0, 10, 2) granted:NumSlider("Additional Repeats", "keypad_willox_wire_repeats_granted", 0, 5, 0) CPanel:AddItem(granted) local denied = vgui.Create("DForm") denied:SetName("Access Denied Settings") denied:NumSlider("Hold Length", "keypad_willox_wire_length_denied", 0.1, 10, 2) denied:NumSlider("Initial Delay", "keypad_willox_wire_init_delay_denied", 0, 10, 2) denied:NumSlider("Multiple Press Delay", "keypad_willox_wire_delay_denied", 0, 10, 2) denied:NumSlider("Additional Repeats", "keypad_willox_wire_repeats_denied", 0, 5, 0) CPanel:AddItem(denied) CPanel:Button("Default Settings", "keypad_willox_wire_reset") CPanel:Help("") local faq = CPanel:Help("Information") faq:SetFont("GModWorldtip") CPanel:Help("You can enter your password with your numpad when numlock is enabled!") end end end
#!/usr/bin/env lua header = [[ (set-logic QF_UFDT) (declare-datatypes ((t 0)) (((T0) (T1 (prev1 t)) (T2 (prev2 t))))) ]] footer = [[ (check-sat) (exit) ]] function printf(...) print(string.format(...)) end function mkdiamond(n) -- decls for i=1,n do printf("(declare-const c%d t)", i) end printf("(assert (= c1 c%d))", n) -- now for the diamond itself for i=1,n do printf("(assert (not (= c%d T0)))",i) end for i=1, n-1 do local s = "c" .. i local next_ = "c" .. (i+1) printf("(assert (or (= %s (T1 %s)) (= %s (T2 %s))))", s, next_, s, next_) end end n = tonumber(arg[1]) print(header) mkdiamond(n) print(footer)
data:extend( { { type = "technology", name = "cement-shoes-equipment", icon = "__Cement Shoes__/graphics/technology/cement-shoes-equipment.png", icon_size = 128, prerequisites = {"modular-armor"}, effects = { { type = "unlock-recipe", recipe = "cement-shoes" }, { type = "unlock-recipe", recipe = "brick-shoes" }, { type = "unlock-recipe", recipe = "landfill-shoes", }, }, unit = { count = 50, ingredients = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, }, time = 15 }, }, } )
local Tunnel = module("_core", "lib/Tunnel") local Proxy = module("_core", "lib/Proxy") cAPI = Proxy.getInterface("API") API = Tunnel.getInterface("API") cam = nil hided = false spawnedCamera = nil choosePed = {} pedSelected = nil sex = nil zoom = 4.0 offset = 0.2 DeleteeEntity = true local InterP = true local adding = true local showroomHorse_entity local showroomHorse_model local MyHorse_entity local IdMyHorse cameraUsing = { { name = "Horse", x = 0.2, y = 0.0, z = 1.8 }, { name = "Olhos", x = 0.0, y = -0.4, z = 0.65 } } local saddlecloths = {} local acshorn = {} local bags = {} local horsetails = {} local manes = {} local saddles = {} local stirrups = {} local acsluggage = {} Citizen.CreateThread( function() while adding do Citizen.Wait(0) for i, v in ipairs(HorseComp) do if v.category == "Saddlecloths" then table.insert(saddlecloths, v.Hash) elseif v.category == "AcsHorn" then table.insert(acshorn, v.Hash) elseif v.category == "Bags" then table.insert(bags, v.Hash) elseif v.category == "HorseTails" then table.insert(horsetails, v.Hash) elseif v.category == "Manes" then table.insert(manes, v.Hash) elseif v.category == "Saddles" then table.insert(saddles, v.Hash) elseif v.category == "Stirrups" then table.insert(stirrups, v.Hash) elseif v.category == "AcsLuggage" then table.insert(acsluggage, v.Hash) end end adding = false end end ) RegisterCommand( "estabulo", function() OpenStable() end ) function passBagTable() return bag end function OpenStable() inCustomization = true horsesp = true local playerHorse = MyHorse_entity SetEntityHeading(playerHorse, 334) DeleteeEntity = true SetNuiFocus(true, true) InterP = true local hashm = GetEntityModel(playerHorse) if hashm ~= nil and IsPedOnMount(PlayerPedId()) then createCamera(PlayerPedId()) else createCamera(PlayerPedId()) end SetEntityVisible(PlayerPedId(), false) if not alreadySentShopData then SendNUIMessage( { action = "show", shopData = getShopData() } ) else SendNUIMessage( { action = "show" } ) end TriggerServerEvent("FRP:STABLE:AskForMyHorses") end local promptGroup local varStringCasa = CreateVarString(10, "LITERAL_STRING", "Estabulo") local blip local prompts = {} local SpawnPoint = {} local StablePoint = {} local HeadingPoint local CamPos = {} Citizen.CreateThread( function() while true do Wait(1) local coords = GetEntityCoords(PlayerPedId()) for _, prompt in pairs(prompts) do if PromptIsJustPressed(prompt) then for k, v in pairs(Config.Stables) do if GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < 7 then HeadingPoint = v.Heading StablePoint = {v.Pos.x, v.Pos.y, v.Pos.z} CamPos = {v.SpawnPoint.CamPos.x, v.SpawnPoint.CamPos.y} SpawnPoint = {x = v.SpawnPoint.Pos.x, y = v.SpawnPoint.Pos.y, z = v.SpawnPoint.Pos.z, h = v.SpawnPoint.Heading} Wait(300) end end OpenStable() end end end end ) Citizen.CreateThread( function() for _, v in pairs(Config.Stables) do -- blip = N_0x554d9d53f696d002(1664425300, v.Pos.x, v.Pos.y, v.Pos.z) SetBlipSprite(blip, -145868367, 1) Citizen.InvokeNative(0x9CB1A1623062F402, blip, "Lovarda") local prompt = PromptRegisterBegin() PromptSetActiveGroupThisFrame(promptGroup, varStringCasa) PromptSetControlAction(prompt, 0xE8342FF2) PromptSetText(prompt, CreateVarString(10, "LITERAL_STRING", "Lovarda megnyitása")) PromptSetStandardMode(prompt, true) PromptSetEnabled(prompt, 1) PromptSetVisible(prompt, 1) PromptSetHoldMode(prompt, 1) PromptSetPosition(prompt, v.Pos.x, v.Pos.y, v.Pos.z) N_0x0c718001b77ca468(prompt, 3.0) PromptSetGroup(prompt, promptGroup) PromptRegisterEnd(prompt) table.insert(prompts, prompt) end end ) AddEventHandler( "onResourceStop", function(resourceName) if resourceName == GetCurrentResourceName() then for _, prompt in pairs(prompts) do PromptDelete(prompt) RemoveBlip(blip) end end end ) -- function deletePrompt() -- if prompt ~= nil then -- PromptSetVisible(prompt, false) -- PromptSetEnabled(prompt, false) -- PromptDelete(prompt) -- prompt = nil -- promptGroup = nil -- end -- end function rotation(dir) local playerHorse = MyHorse_entity local pedRot = GetEntityHeading(playerHorse) + dir SetEntityHeading(playerHorse, pedRot % 360) end RegisterNUICallback( "rotate", function(data, cb) if (data["key"] == "left") then rotation(20) elseif (data["key"] == "right") then rotation(-20) end cb("ok") end ) -- AddEventHandler( -- 'onResourceStop', -- function(resourceName) -- if resourceName == GetCurrentResourceName() then -- for _, prompt in pairs(prompts) do -- PromptDelete(prompt) -- end -- end -- end -- ) AddEventHandler( "onResourceStop", function(resourceName) if (GetCurrentResourceName() ~= resourceName) then return end SetNuiFocus(false, false) SendNUIMessage( { action = "hide" } ) end ) function createCam(creatorType) for k, v in pairs(cams) do if cams[k].type == creatorType then cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", cams[k].x, cams[k].y, cams[k].z, cams[k].rx, cams[k].ry, cams[k].rz, cams[k].fov, false, 0) -- CAMERA COORDS SetCamActive(cam, true) RenderScriptCams(true, false, 3000, true, false) createPeds() end end end RegisterNUICallback( "Nyergek", function(data) zoom = 4.0 offset = 0.2 if tonumber(data.id) == 0 then num = 0 SaddlesUsing = num local playerHorse = MyHorse_entity Citizen.InvokeNative(0xD710A5007C2AC539, playerHorse, 0xBAA7E618, 0) -- HAT REMOVE Citizen.InvokeNative(0xCC8CA3E88256E58F, playerHorse, 0, 1, 1, 1, 0) -- Actually remove the component else local num = tonumber(data.id) hash = ("0x" .. saddles[num]) setcloth(hash) SaddlesUsing = ("0x" .. saddles[num]) end end ) RegisterNUICallback( "Takarok", function(data) zoom = 4.0 offset = 0.2 if tonumber(data.id) == 0 then num = 0 SaddleclothsUsing = num local playerHorse = MyHorse_entity Citizen.InvokeNative(0xD710A5007C2AC539, playerHorse, 0x17CEB41A, 0) -- HAT REMOVE Citizen.InvokeNative(0xCC8CA3E88256E58F, playerHorse, 0, 1, 1, 1, 0) -- Actually remove the component else local num = tonumber(data.id) hash = ("0x" .. saddlecloths[num]) setcloth(hash) SaddleclothsUsing = ("0x" .. saddlecloths[num]) end end ) RegisterNUICallback( "Kengyelek", function(data) zoom = 4.0 offset = 0.2 if tonumber(data.id) == 0 then num = 0 StirrupsUsing = num local playerHorse = MyHorse_entity Citizen.InvokeNative(0xD710A5007C2AC539, playerHorse, 0xDA6DADCA, 0) -- HAT REMOVE Citizen.InvokeNative(0xCC8CA3E88256E58F, playerHorse, 0, 1, 1, 1, 0) -- Actually remove the component else local num = tonumber(data.id) hash = ("0x" .. stirrups[num]) setcloth(hash) StirrupsUsing = ("0x" .. stirrups[num]) end end ) RegisterNUICallback( "Taskak", function(data) zoom = 4.0 offset = 0.2 if tonumber(data.id) == 0 then num = 0 BagsUsing = num local playerHorse = MyHorse_entity Citizen.InvokeNative(0xD710A5007C2AC539, playerHorse, 0x80451C25, 0) -- HAT REMOVE Citizen.InvokeNative(0xCC8CA3E88256E58F, playerHorse, 0, 1, 1, 1, 0) -- Actually remove the component else local num = tonumber(data.id) hash = ("0x" .. bags[num]) setcloth(hash) BagsUsing = ("0x" .. bags[num]) end end ) RegisterNUICallback( "Soreny fajtai", function(data) zoom = 4.0 offset = 0.2 if tonumber(data.id) == 0 then num = 0 ManesUsing = num local playerHorse = MyHorse_entity Citizen.InvokeNative(0xD710A5007C2AC539, playerHorse, 0xAA0217AB, 0) -- HAT REMOVE Citizen.InvokeNative(0xCC8CA3E88256E58F, playerHorse, 0, 1, 1, 1, 0) -- Actually remove the component else local num = tonumber(data.id) hash = ("0x" .. manes[num]) setcloth(hash) ManesUsing = ("0x" .. manes[num]) end end ) RegisterNUICallback( "Farok fajtai", function(data) zoom = 4.0 offset = 0.2 if tonumber(data.id) == 0 then num = 0 HorseTailsUsing = num local playerHorse = MyHorse_entity Citizen.InvokeNative(0xD710A5007C2AC539, playerHorse, 0x17CEB41A, 0) -- HAT REMOVE Citizen.InvokeNative(0xCC8CA3E88256E58F, playerHorse, 0, 1, 1, 1, 0) -- Actually remove the component else local num = tonumber(data.id) hash = ("0x" .. horsetails[num]) setcloth(hash) HorseTailsUsing = ("0x" .. horsetails[num]) end end ) RegisterNUICallback( "Szarvak", function(data) zoom = 4.0 offset = 0.2 if tonumber(data.id) == 0 then num = 0 AcsHornUsing = num local playerHorse = MyHorse_entity Citizen.InvokeNative(0xD710A5007C2AC539, playerHorse, 0x5447332, 0) -- HAT REMOVE Citizen.InvokeNative(0xCC8CA3E88256E58F, playerHorse, 0, 1, 1, 1, 0) -- Actually remove the component else local num = tonumber(data.id) hash = ("0x" .. acshorn[num]) setcloth(hash) AcsHornUsing = ("0x" .. acshorn[num]) end end ) RegisterNUICallback( "Lepedok", function(data) zoom = 4.0 offset = 0.2 if tonumber(data.id) == 0 then num = 0 AcsLuggageUsing = num local playerHorse = MyHorse_entity Citizen.InvokeNative(0xD710A5007C2AC539, playerHorse, 0xEFB31921, 0) -- HAT REMOVE Citizen.InvokeNative(0xCC8CA3E88256E58F, playerHorse, 0, 1, 1, 1, 0) -- Actually remove the component else print(data.id) local num = tonumber(data.id) hash = ("0x" .. acsluggage[num]) setcloth(hash) AcsLuggageUsing = ("0x" .. acsluggage[num]) end end ) myHorses = {} function setcloth(hash) local model2 = GetHashKey(tonumber(hash)) if not HasModelLoaded(model2) then Citizen.InvokeNative(0xFA28FE3A6246FC30, model2) end Citizen.InvokeNative(0xD3A7B003ED343FD9, MyHorse_entity, tonumber(hash), true, true, true) end RegisterNUICallback( "selectHorse", function(data) print(data.horseID) TriggerServerEvent("FRP:STABLE:SelectHorseWithId", tonumber(data.horseID)) end ) RegisterNUICallback( "sellHorse", function(data) print(data.horseID) DeleteEntity(showroomHorse_entity) TriggerServerEvent("FRP:STABLE:SellHorseWithId", tonumber(data.horseID)) TriggerServerEvent("FRP:STABLE:AskForMyHorses") end ) RegisterNetEvent("FRP:STABLE:ReceiveHorsesData") AddEventHandler( "FRP:STABLE:ReceiveHorsesData", function(dataHorses) SendNUIMessage( { myHorsesData = dataHorses } ) end ) SaddlesUsing = nil SaddleclothsUsing = nil StirrupsUsing = nil BagsUsing = nil ManesUsing = nil HorseTailsUsing = nil AcsHornUsing = nil AcsLuggageUsing = nil --- /// ARRASTAR CAVALO local alreadySentShopData = false function getShopData() alreadySentShopData = true local ret = { { name = "Haszon lovak", ["A_C_HORSEMULE_01"] = {"Öszvér", 5, 17}, ["A_C_Horse_KentuckySaddle_Grey"] = {"Kentucky Saddle (Szürke)", 20, 50}, ["A_C_Horse_Morgan_Palomino"] = {"Morgan", 21, 55}, }, { name = "Verseny lovak", ["A_C_Horse_Thoroughbred_DappleGrey"] = {"Thoroughbred", 47, 130}, ["A_C_Horse_Nokota_ReverseDappleRoan"] = {"Nokota", 135, 450}, ["A_C_Horse_AmericanStandardbred_Buckskin"] = {"Standardbred Americano", 47, 130}, }, { name = "Szívós lovak", ["A_C_Horse_Andalusian_DarkBay"] = {"Andalusian (Csillogó fekete)", 50, 140}, ["A_C_Horse_Andalusian_Perlino"] = {"Andalusian (Mennyei)", 50, 140}, }, { name = "Szallítós lovak", ["A_C_Horse_AmericanPaint_Overo"] = {"American Paint (Foltos)", 47, 130}, ["A_C_Horse_AmericanPaint_Tobiano"] = {"American Paint (Foltos)", 50, 140}, ["A_C_Horse_Appaloosa_Blanket"] = {"Appaloosa", 73, 200}, }, { name = "Ledönthetetlen lovak", ["A_C_Horse_Belgian_BlondChestnut"] = {"Belga (Világos-barna)", 30, 120}, ["A_C_Horse_Belgian_MealyChestnut"] = {"Belga (Szőke)", 30, 120}, ["A_C_Horse_Shire_LightGrey"] = {"Shire (Szürkés-fehér)", 35, 130}, ["A_C_Horse_SuffolkPunch_RedChestnut"] = {"Suffolk Punch (Pirosas-barna)", 55, 150}, }, { name = "Tehetős emberek lovai", ["A_C_Horse_Turkoman_Gold"] = {"Turkoman (Szikrázó arany)", 470, 950}, } } return ret end RegisterNUICallback( "loadHorse", function(data) local horseModel = data.horseModel if showroomHorse_model == horseModel then return end if showroomHorse_entity ~= nil then DeleteEntity(showroomHorse_entity) showroomHorse_entity = nil end if MyHorse_entity ~= nil then DeleteEntity(MyHorse_entity) MyHorse_entity = nil end showroomHorse_model = horseModel local modelHash = GetHashKey(showroomHorse_model) if not HasModelLoaded(modelHash) then RequestModel(modelHash) while not HasModelLoaded(modelHash) do Citizen.Wait(10) end end showroomHorse_entity = CreatePed(modelHash, SpawnPoint.x, SpawnPoint.y, SpawnPoint.z - 0.98, SpawnPoint.h, false, 0) Citizen.InvokeNative(0x283978A15512B2FE, showroomHorse_entity, true) Citizen.InvokeNative(0x58A850EAEE20FAA3, showroomHorse_entity) NetworkSetEntityInvisibleToNetwork(showroomHorse_entity, true) SetVehicleHasBeenOwnedByPlayer(showroomHorse_entity, true) -- SetModelAsNoLongerNeeded(modelHash) interpCamera("Horse", showroomHorse_entity) end ) RegisterNUICallback( "loadMyHorse", function(data) local horseModel = data.horseModel IdMyHorse = data.IdHorse if showroomHorse_model == horseModel then return end if showroomHorse_entity ~= nil then DeleteEntity(showroomHorse_entity) showroomHorse_entity = nil end if MyHorse_entity ~= nil then DeleteEntity(MyHorse_entity) MyHorse_entity = nil end showroomHorse_model = horseModel local modelHash = GetHashKey(showroomHorse_model) if not HasModelLoaded(modelHash) then RequestModel(modelHash) while not HasModelLoaded(modelHash) do Citizen.Wait(10) end end MyHorse_entity = CreatePed(modelHash, SpawnPoint.x, SpawnPoint.y, SpawnPoint.z - 0.98, SpawnPoint.h, false, 0) Citizen.InvokeNative(0x283978A15512B2FE, MyHorse_entity, true) Citizen.InvokeNative(0x58A850EAEE20FAA3, MyHorse_entity) NetworkSetEntityInvisibleToNetwork(MyHorse_entity, true) SetVehicleHasBeenOwnedByPlayer(MyHorse_entity, true) local componentsHorse = json.decode(data.HorseComp) if componentsHorse ~= '[]' then for _, Key in pairs(componentsHorse) do local model2 = GetHashKey(tonumber(Key)) if not HasModelLoaded(model2) then Citizen.InvokeNative(0xFA28FE3A6246FC30, model2) end Citizen.InvokeNative(0xD3A7B003ED343FD9, MyHorse_entity, tonumber(Key), true, true, true) end end -- SetModelAsNoLongerNeeded(modelHash) interpCamera("Horse", MyHorse_entity) end ) RegisterNUICallback( "BuyHorse", function(data) local HorseName = cAPI.prompt("A ló neve:", "") if HorseName == "" then return end SetNuiFocus(true, true) TriggerServerEvent('FRP:STABLE:BuyHorse', data, HorseName) end ) RegisterNUICallback( "CloseStable", function() SetNuiFocus(false, false) SendNUIMessage( { action = "hide" } ) SetEntityVisible(PlayerPedId(), true) showroomHorse_model = nil if showroomHorse_entity ~= nil then DeleteEntity(showroomHorse_entity) end if MyHorse_entity ~= nil then DeleteEntity(MyHorse_entity) end DestroyAllCams(true) showroomHorse_entity = nil CloseStable() end ) function CloseStable() local dados = { -- ['saddles'] = SaddlesUsing, -- ['saddlescloths'] = SaddleclothsUsing, -- ['stirrups'] = StirrupsUsing, -- ['bags'] = BagsUsing, -- ['manes'] = ManesUsing, -- ['horsetails'] = HorseTailsUsing, -- ['acshorn'] = AcsHornUsing, -- ['ascluggage'] = AcsLuggageUsing SaddlesUsing, SaddleclothsUsing, StirrupsUsing, BagsUsing, ManesUsing, HorseTailsUsing, AcsHornUsing, AcsLuggageUsing } local DadosEncoded = json.encode(dados) if DadosEncoded ~= "[]" then TriggerServerEvent("FRP:STABLE:UpdateHorseComponents", dados, IdMyHorse ) end end Citizen.CreateThread( function() while true do Citizen.Wait(100) if MyHorse_entity ~= nil then SendNUIMessage( { EnableCustom = "true" } ) else SendNUIMessage( { EnableCustom = "false" } ) end end end ) function interpCamera(cameraName, entity) for k, v in pairs(cameraUsing) do if cameraUsing[k].name == cameraName then tempCam = CreateCam("DEFAULT_SCRIPTED_CAMERA") AttachCamToEntity(tempCam, entity, cameraUsing[k].x + CamPos[1], cameraUsing[k].y + CamPos[2], cameraUsing[k].z) SetCamActive(tempCam, true) SetCamRot(tempCam, -30.0, 0, HeadingPoint + 50.0) if InterP then SetCamActiveWithInterp(tempCam, fixedCam, 1200, true, true) InterP = false end end end end function createCamera(entity) groundCam = CreateCam("DEFAULT_SCRIPTED_CAMERA") SetCamCoord(groundCam, StablePoint[1] + 0.5, StablePoint[2] - 3.6, StablePoint[3] ) SetCamRot(groundCam, -20.0, 0.0, HeadingPoint + 20) SetCamActive(groundCam, true) RenderScriptCams(true, false, 1, true, true) --Wait(3000) -- last camera, create interpolate fixedCam = CreateCam("DEFAULT_SCRIPTED_CAMERA") SetCamCoord(fixedCam, StablePoint[1] + 0.5, StablePoint[2] - 3.6, StablePoint[3] +1.8) SetCamRot(fixedCam, -20.0, 0, HeadingPoint + 50.0) SetCamActive(fixedCam, true) SetCamActiveWithInterp(fixedCam, groundCam, 3900, true, true) Wait(3900) DestroyCam(groundCam) end
local E, C, L, ET, _ = select(2, shCore()):unpack() if C.main.restyleUI ~= true then return end local _G = _G local select = select local function LoadSkin() ArenaRegistrarFrame:StripLayout(true) ArenaRegistrarFrame:SetLayout() ArenaRegistrarFrame.bg:SetAnchor('TOPLEFT', 14, -18) ArenaRegistrarFrame.bg:SetAnchor('BOTTOMRIGHT', -30, 67) ArenaRegistrarFrame:SetShadow() ArenaRegistrarFrame.shadow:SetAnchor('TOPLEFT', 12, -16) ArenaRegistrarFrame.shadow:SetAnchor('BOTTOMRIGHT', -26, 63) ArenaRegistrarFrameCloseButton:CloseTemplate() ArenaRegistrarGreetingFrame:StripLayout() select(1, ArenaRegistrarGreetingFrame:GetRegions()):SetTextColor(1, 0.80, 0.10) RegistrationText:SetTextColor(1, 0.80, 0.10) ET:HandleButton(ArenaRegistrarFrameGoodbyeButton) for i = 1, MAX_TEAM_BORDERS do local button = _G['ArenaRegistrarButton'..i] local obj = select(3, button:GetRegions()) ET:HandleButtonHighlight(button) obj:SetTextColor(1, 1, 1) end ArenaRegistrarPurchaseText:SetTextColor(1, 1, 1) ET:HandleButton(ArenaRegistrarFrameCancelButton) ET:HandleButton(ArenaRegistrarFramePurchaseButton) select(6, ArenaRegistrarFrameEditBox:GetRegions()):dummy() select(7, ArenaRegistrarFrameEditBox:GetRegions()):dummy() ET:HandleEditBox(ArenaRegistrarFrameEditBox) ArenaRegistrarFrameEditBox:Height(18) PVPBannerFrame:SetLayout() PVPBannerFrame.bg:SetAnchor('TOPLEFT', 10, -12) PVPBannerFrame.bg:SetAnchor('BOTTOMRIGHT', -33, 73) PVPBannerFrame:StripLayout() PVPBannerFramePortrait:dummy() PVPBannerFrameCustomizationFrame:StripLayout() local customization, customizationLeft, customizationRight for i = 1, 2 do customization = _G['PVPBannerFrameCustomization'..i] customizationLeft = _G['PVPBannerFrameCustomization'..i..'LeftButton'] customizationRight = _G['PVPBannerFrameCustomization'..i..'RightButton'] customization:StripLayout() customizationLeft:ButtonPrevLeft() customizationRight:ButtonNextRight() end local pickerButton for i = 1, 3 do pickerButton = _G['PVPColorPickerButton'..i] ET:HandleButton(pickerButton) if i == 2 then pickerButton:SetAnchor('TOP', PVPBannerFrameCustomization2, 'BOTTOM', 0, -33) elseif i == 3 then pickerButton:SetAnchor('TOP', PVPBannerFrameCustomization2, 'BOTTOM', 0, -59) end end ET:HandleButton(PVPBannerFrameAcceptButton) ET:HandleButton(PVPBannerFrameCancelButton) ET:HandleButton(select(4, PVPBannerFrame:GetChildren())) PVPBannerFrameCloseButton:CloseTemplate() end table.insert(ET['SohighUI'], LoadSkin)
-- Dialogue for NPC "npc_cat" loadDialogue = function(DL) DL:setRoot(1) DL:createNPCNode(1, -1, "DL_Cat_Meow") -- Meow! DL:addNode() end
-- This file is generated by proto-gen-lua. DO NOT EDIT. -- The protoc version is 'v3.19.2' -- The proto-gen-lua version is 'Develop' return { name = [[google/protobuf/type.proto]], package = [[google.protobuf]], dependency = { [[google/protobuf/any.proto]], [[google/protobuf/source_context.proto]], }, message_type = { { name = [[Type]], field = { { name = [[name]], number = 1, label = [[LABEL_OPTIONAL]], type = [[TYPE_STRING]], json_name = [[name]], }, { name = [[fields]], number = 2, label = [[LABEL_REPEATED]], type = [[TYPE_MESSAGE]], type_name = [[.google.protobuf.Field]], json_name = [[fields]], }, { name = [[oneofs]], number = 3, label = [[LABEL_REPEATED]], type = [[TYPE_STRING]], json_name = [[oneofs]], }, { name = [[options]], number = 4, label = [[LABEL_REPEATED]], type = [[TYPE_MESSAGE]], type_name = [[.google.protobuf.Option]], json_name = [[options]], }, { name = [[source_context]], number = 5, label = [[LABEL_OPTIONAL]], type = [[TYPE_MESSAGE]], type_name = [[.google.protobuf.SourceContext]], json_name = [[sourceContext]], }, { name = [[syntax]], number = 6, label = [[LABEL_OPTIONAL]], type = [[TYPE_ENUM]], type_name = [[.google.protobuf.Syntax]], json_name = [[syntax]], }, }, }, { name = [[Field]], field = { { name = [[kind]], number = 1, label = [[LABEL_OPTIONAL]], type = [[TYPE_ENUM]], type_name = [[.google.protobuf.Field.Kind]], json_name = [[kind]], }, { name = [[cardinality]], number = 2, label = [[LABEL_OPTIONAL]], type = [[TYPE_ENUM]], type_name = [[.google.protobuf.Field.Cardinality]], json_name = [[cardinality]], }, { name = [[number]], number = 3, label = [[LABEL_OPTIONAL]], type = [[TYPE_INT32]], json_name = [[number]], }, { name = [[name]], number = 4, label = [[LABEL_OPTIONAL]], type = [[TYPE_STRING]], json_name = [[name]], }, { name = [[type_url]], number = 6, label = [[LABEL_OPTIONAL]], type = [[TYPE_STRING]], json_name = [[typeUrl]], }, { name = [[oneof_index]], number = 7, label = [[LABEL_OPTIONAL]], type = [[TYPE_INT32]], json_name = [[oneofIndex]], }, { name = [[packed]], number = 8, label = [[LABEL_OPTIONAL]], type = [[TYPE_BOOL]], json_name = [[packed]], }, { name = [[options]], number = 9, label = [[LABEL_REPEATED]], type = [[TYPE_MESSAGE]], type_name = [[.google.protobuf.Option]], json_name = [[options]], }, { name = [[json_name]], number = 10, label = [[LABEL_OPTIONAL]], type = [[TYPE_STRING]], json_name = [[jsonName]], }, { name = [[default_value]], number = 11, label = [[LABEL_OPTIONAL]], type = [[TYPE_STRING]], json_name = [[defaultValue]], }, }, enum_type = { { name = [[Kind]], value = { { name = [[TYPE_UNKNOWN]], number = 0, }, { name = [[TYPE_DOUBLE]], number = 1, }, { name = [[TYPE_FLOAT]], number = 2, }, { name = [[TYPE_INT64]], number = 3, }, { name = [[TYPE_UINT64]], number = 4, }, { name = [[TYPE_INT32]], number = 5, }, { name = [[TYPE_FIXED64]], number = 6, }, { name = [[TYPE_FIXED32]], number = 7, }, { name = [[TYPE_BOOL]], number = 8, }, { name = [[TYPE_STRING]], number = 9, }, { name = [[TYPE_GROUP]], number = 10, }, { name = [[TYPE_MESSAGE]], number = 11, }, { name = [[TYPE_BYTES]], number = 12, }, { name = [[TYPE_UINT32]], number = 13, }, { name = [[TYPE_ENUM]], number = 14, }, { name = [[TYPE_SFIXED32]], number = 15, }, { name = [[TYPE_SFIXED64]], number = 16, }, { name = [[TYPE_SINT32]], number = 17, }, { name = [[TYPE_SINT64]], number = 18, }, }, }, { name = [[Cardinality]], value = { { name = [[CARDINALITY_UNKNOWN]], number = 0, }, { name = [[CARDINALITY_OPTIONAL]], number = 1, }, { name = [[CARDINALITY_REQUIRED]], number = 2, }, { name = [[CARDINALITY_REPEATED]], number = 3, }, }, }, }, }, { name = [[Enum]], field = { { name = [[name]], number = 1, label = [[LABEL_OPTIONAL]], type = [[TYPE_STRING]], json_name = [[name]], }, { name = [[enumvalue]], number = 2, label = [[LABEL_REPEATED]], type = [[TYPE_MESSAGE]], type_name = [[.google.protobuf.EnumValue]], json_name = [[enumvalue]], }, { name = [[options]], number = 3, label = [[LABEL_REPEATED]], type = [[TYPE_MESSAGE]], type_name = [[.google.protobuf.Option]], json_name = [[options]], }, { name = [[source_context]], number = 4, label = [[LABEL_OPTIONAL]], type = [[TYPE_MESSAGE]], type_name = [[.google.protobuf.SourceContext]], json_name = [[sourceContext]], }, { name = [[syntax]], number = 5, label = [[LABEL_OPTIONAL]], type = [[TYPE_ENUM]], type_name = [[.google.protobuf.Syntax]], json_name = [[syntax]], }, }, }, { name = [[EnumValue]], field = { { name = [[name]], number = 1, label = [[LABEL_OPTIONAL]], type = [[TYPE_STRING]], json_name = [[name]], }, { name = [[number]], number = 2, label = [[LABEL_OPTIONAL]], type = [[TYPE_INT32]], json_name = [[number]], }, { name = [[options]], number = 3, label = [[LABEL_REPEATED]], type = [[TYPE_MESSAGE]], type_name = [[.google.protobuf.Option]], json_name = [[options]], }, }, }, { name = [[Option]], field = { { name = [[name]], number = 1, label = [[LABEL_OPTIONAL]], type = [[TYPE_STRING]], json_name = [[name]], }, { name = [[value]], number = 2, label = [[LABEL_OPTIONAL]], type = [[TYPE_MESSAGE]], type_name = [[.google.protobuf.Any]], json_name = [[value]], }, }, }, }, enum_type = { { name = [[Syntax]], value = { { name = [[SYNTAX_PROTO2]], number = 0, }, { name = [[SYNTAX_PROTO3]], number = 1, }, }, }, }, options = { java_package = [[com.google.protobuf]], java_outer_classname = [[TypeProto]], java_multiple_files = true, go_package = [[google.golang.org/protobuf/types/known/typepb]], cc_enable_arenas = true, objc_class_prefix = [[GPB]], csharp_namespace = [[Google.Protobuf.WellKnownTypes]], }, syntax = [[proto3]], }
return function(p, o, sw, sh) local pc, cx, cy = o / sw, sw / 2, sh / 2 local prog = math.min(1, math.abs(16 * pc)) for i, ic in subviews(p) do local result = dofile("includes/formula.lua")("math.abs(-400 * math.sin(x)) - 150", pc, i, #p, sw / (2 * math.pi), sw, sh, ic.width) ic:translate(prog * (result.x - ic.x), prog * (result.y - ic.y), 0) ic:rotate(prog * result.r, 0, 0, 1) end p:translate(o, 0, 0) end
--[[ Grupy: Praca jako DJ @author Jakub 'XJMLN' Starzak <jack@pszmta.pl @package PSZMTA.psz-grupy @copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl> Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie. ]]-- C_DJ = 0 local napisy = { {476.65,-12.49,1004,17,0, fid=6},-- DJ } for i,v in ipairs(napisy) do v.napis = createElement("ctext") setElementPosition(v.napis,v[1],v[2],v[3]+0.4) setElementData(v.napis,"ctext",setTxtByGID(v.fid)) setElementData(v.napis,"f:text",v.fid) setElementDimension(v.napis,v[5]) setElementInterior(v.napis,v[4]) end local DJ_info = createElement("text") setElementPosition(DJ_info, 487.45,-6.16,1004.5) setElementInterior(DJ_info,17) setElementDimension(DJ_info,0) setElementData(DJ_info, "text","Aktualnie gra DJ:\n --") setElementData(DJ_info, "scale", 1.5) function grupy_playerStopJob(plr, fid) if (not fid or not plr) then return end local fr = getElementData(plr,"faction:data") if (not fr) then return end if fid == 6 then C_DJ = C_DJ - 1 if C_DJ < 0 then C_DJ = 0 end updateAllTxt(fid,C_DJ) restoreSavedData(plr,fr) setElementData(DJ_info,"text","Aktualnie gra DJ:\n --") outputChatBox("* Zakończyłeś pracę jako DJ!", plr, 255, 0, 0) end end function grupy_playerStartJob(plr,fid) if (not plr or not fid) then return end local fr = getElementData(plr,"faction:data") if (fr) then return end if fid == 6 then if C_DJ == 1 then return end C_DJ = C_DJ + 1 if C_DJ > 1 then C_DJ = 1 end updateAllTxt(fid, C_DJ) setElementData(plr,"faction:data",{ ["id"]=fid, ["nick"]=getPlayerName(plr), }) string.gsub(getPlayerName(plr),"|DJ|","") setPlayerName(plr,"|DJ|"..getPlayerName(plr)) setElementData(DJ_info,"text","Aktualnie gra DJ:\n "..string.gsub(getPlayerName(plr),"#%x%x%x%x%x%x","")) outputChatBox("* Rozpoczęto pracę jako DJ!", plr, 255,0,0) end end function grupy_playerJoinToJob(plr,fid) if (not plr or not fid) then return end local fr = getElementData(plr,"faction:data") local blokada = getElementData(plr,"banned_jobs") if fid == 6 then if C_DJ>=2 then return end if fr and fr.id ~= 6 then outputChatBox('Najpierw zakończ aktualną pracę aby rozpocząć kolejna.',plr,255,0,0) return elseif fr and fr.id == 6 then grupy_playerStopJob(plr,fid) return elseif not fr and not blokada then grupy_playerStartJob(plr,fid) return end end end function grupy_checkJob(v) if (not v) then return end grupy_playerJoinToJob(source,v) end function grupy_quitJob(reason,plr) if reason ~= 'bpracy' then plr = source end local fr = getElementData(plr,"faction:data") if (not fr) then return end grupy_playerStopJob(plr,fr.id) end addEventHandler("onPlayerQuit",getRootElement(),grupy_quitJob) addEvent("grupy_playerHasJoinToJob", true) addEventHandler("grupy_playerHasJoinToJob", root, grupy_checkJob)
local M = {} M.config = { goimport = "gopls", -- if set to 'gopls' will use golsp format gofmt = "gopls", -- if set to gopls will use golsp format tag_transform = false, test_dir = "", comment_placeholder = "  ", lsp_cfg = false, -- false: use your own lspconfig lsp_on_attach = false, -- use on_attach from go.nvim dap_debug = true, } M.setup = function() local status_ok, go = pcall(require, "go") if not status_ok then return end go.setup(M.config) end return M
local discordia = require('discordia') local client = discordia.Client() local E = io.open("Test.lua"):read() local tk = 'NzcxNDY0MjQ0MzQzODY1Mzc2.X5sgEA.3_xGyXHsbcCXmIRUzg0Gk2tMOFc' local pf = '!' client:on('ready', function() print('Logged in as '.. client.user.username) end) client:on('messageCreate', function(message) local content = message.content local member = message.member local memberid = message.member.id if content:lower():sub(1,#"!gay") == "!gay" then local mentioned = message.mentionedUsers if #mentioned == 1 then local member = message.guild:getMember(mentioned[1][1]) message:reply{ embed = { fields = { {name = "Gay Detected"; value = member.username.." is "..math.random(1,100).."% Gay!"} }; color = discordia.Color.fromRGB(255,0,0).value; }; } elseif #mentioned == 0 then message:reply{ embed = { fields = { {name = "Gay Detected"; value = message.member.username.." is "..math.random(1,100).."% Gay!"} }; color = discordia.Color.fromRGB(255,0,0).value; }; } end end end) client:run("Bot "..tk)
BigButton = class() function BigButton:init(t, x, y) self.text = t self.frame = Frame(x, y, x + 140, y + 80) self.active = true end function BigButton:draw() if self.active then stroke(255, 255, 255, 255) else stroke(93, 95, 125, 255) end strokeWidth(2) noFill() self.frame:draw() if self.active then fill(255, 255, 255, 255) else fill(98, 100, 134, 255) end fontSize(24) textMode(CORNER) text(self.text, self.frame.left + 20, self.frame.top - 40) end function BigButton:touched(touch) return self.frame:touched(touch) end
Class = require 'class' Menu = Class{} function Menu:init() -- one indexed arrays in Lua self.options = { 'Single Player (PvsAI)', 'Multi Player (PvsP)', 'Settings', 'Exit' } self.optionsSize = 4 self.selection = 0 end function Menu:changeSelection(key) if key ~= 'up' and key ~= 'down' then return false end if key == 'down' then self.selection = (self.selection+1)%self.optionsSize elseif key == 'up' then self.selection = (self.selection-1)%self.optionsSize end sounds['menuOption']:play() return true end function Menu:performSelection() if self.selection == 0 then -- single player currentState = gameState.setAi elseif self.selection == 1 then -- multi player currentState = gameState.setPlayer elseif self.selection == 2 then -- settings elseif self.selection == 3 then -- exit love.event.quit() end end function Menu:render() love.graphics.setFont(fonts['retroL']) love.graphics.setColor(220/255, 220/255, 220/255, 0.7) frameWidth = WINDOW_WIDTH frameHeight = WINDOW_HEIGHT/3 frameX = WINDOW_WIDTH/2-frameWidth/2 frameY = WINDOW_HEIGHT/2-frameHeight/2 love.graphics.rectangle('fill', frameX, frameY, frameWidth, frameHeight) love.graphics.setColor(0, 0, 0, 0.5) -- love.graphics.polygon('fill', , 200, 100, 400, 300, 400) -- love.graphics.print(self.options[self.selection+1], frameX+frameWidth/2, frameY+frameHeight/2) love.graphics.print(self.options[(self.selection-1)%self.optionsSize+1], frameWidth/3+frameX+20, frameY+2*frameHeight/6-15) love.graphics.print(self.options[(self.selection+1)%self.optionsSize+1], frameWidth/3+frameX+20, frameY+4*frameHeight/6-15) love.graphics.setColor(0, 0, 0, 1) love.graphics.print(self.options[self.selection+1], frameWidth/3+frameX+20, frameY+3*frameHeight/6-15) love.graphics.setColor(1, 1, 1, 1) love.graphics.setFont(fonts.retroS) love.graphics.printf('<Up> and <Down> arrow-keys to control the right paddle.\n<W> and <S> keys to control the left paddle (multiplayer).\n<Esc> to pause game. <Enter> or <Space> to select option.', 115, 440, 800, 'center') triangleX1 = WINDOW_WIDTH/2-30 triangleX2 = WINDOW_WIDTH/2+30 love.graphics.setColor(0, 0, 0, 1) love.graphics.polygon('fill', WINDOW_WIDTH/2, WINDOW_HEIGHT/3+15, triangleX1, WINDOW_HEIGHT/3+40, triangleX2, WINDOW_HEIGHT/3+40) love.graphics.polygon('fill', WINDOW_WIDTH/2, 2*WINDOW_HEIGHT/3-10, triangleX1, 2*WINDOW_HEIGHT/3-35, triangleX2, 2*WINDOW_HEIGHT/3-35) love.graphics.setColor(1, 1, 1, 1) love.graphics.polygon('fill', WINDOW_WIDTH/2, WINDOW_HEIGHT/3+20, triangleX1+10, WINDOW_HEIGHT/3+36, triangleX2-10, WINDOW_HEIGHT/3+36) love.graphics.polygon('fill', WINDOW_WIDTH/2, 2*WINDOW_HEIGHT/3-15, triangleX1+10, 2*WINDOW_HEIGHT/3-31, triangleX2-10, 2*WINDOW_HEIGHT/3-31) end
-- This file is subject to copyright - contact swampservers@gmail.com for more information. -- INSTALL: CINEMA -- autorun/client/cl_vapeswep.lua -- Defines shared globals for Vape SWEP -- Vape SWEP by Swamp Onions - http://steamcommunity.com/id/swamponions/ CreateConVar("vape_block_sounds", "0", FCVAR_REPLICATED, "Set to 1 to disable Vape SWEP speech sounds") --override Entity:SetMaterial to make sure vape shows for ponies meta = FindMetaTable("Entity") if meta.VapeOrigSetMaterial == nil then meta.VapeOrigSetMaterial = meta.SetMaterial meta.SetMaterial = function(self, materialName, forceMaterial) if self:GetClass():sub(1, 11) == "weapon_vape" and materialName == "Models/effects/vol_light001" then return end self:VapeOrigSetMaterial(materialName, forceMaterial) end end
---------------- Require ----------------------- require 'image' if opt.cuda then require 'cutorch' cutorch.setDevice(opt.gpuID) -- goes after cutorch and before nn end require 'nn' if opt.cuda then require 'cudnn' require 'cunn' end require 'stn' require 'util/nn/WarpFlowNew' require 'util/nn/ShuffleTable' require 'optim' require 'util/ut' ----------------------- Set cuda ---------------------- if opt.cuda then cudnn.fastest = true cudnn.benchmark = true end
local string = require"string" local path = require"minipath" local str_fmt = string.format local dir_envir = "D:\\Mirserver\\Mir200\\Envir" -- local dir_mirserver = [[E:\clear\Envir]] function trim(s) return s:match("^%s*(.-)%s*$") end local doc = App.active_doc local fullpath = doc.fullpath or "" if string.contains(fullpath, "Envir") then local parts = string.explode(fullpath, [[\]], true) local out = {} for i, v in ipairs(parts) do table.insert(out, v) if v == "Envir" then break end end dir_envir = table.concat(out, [[\]]) end local text = trim(doc:getline(".")) local parts = string.explode(text, "[%s]+") if #parts >= 7 then local npc_fn = path.join(dir_envir, "Market_Def", str_fmt("%s-%s.txt", parts[1], parts[2])) -- App:output_line(str_fmt("npc_fn: %s", npc_fn)) App:open_doc(npc_fn, 936) elseif #parts >= 2 and parts[1]:upper() == "#CALL" then local script_name = parts[2]:sub(2, -2) local script_fn = path.join(dir_envir, "QuestDiary", script_name) -- App:output_line(str_fmt("script_fn: %s", script_fn)) App:open_doc(script_fn, 936) elseif #parts >= 2 then for _, val in ipairs(parts) do if string.contains(val, "QuestDiary") or string.contains(val, "questdiary") then local fn = path.join(dir_envir, "Market_Def", val) fn = path.getabsolute(fn) App:open_doc(fn, 936) break end end end
dofile("./opensimplex2s.lua") local function fbm2Loop( gen, vx, vy, cosa, sina, octaves, lacunarity, gain) local freq = 1.0 local amp = 0.5 local vinx = 0.0 local viny = 0.0 local vinz = 0.0 local vinw = 0.0 local sum = 0.0 local oct = octaves or 8 local lac = lacunarity or 1.0 local gn = gain or 1.0 for i = 0, oct - 1, 1 do vinx = vx * freq viny = vy * freq vinz = sina * freq vinw = cosa * freq -- This noise variety is recommmended for this trick. -- https://necessarydisorder.wordpress.com/2017/11/15/ -- drawing-from-noise-and-then-making-animated- -- loopy-gifs-from-there/ sum = sum + amp * gen:noise4_XYBeforeZW( vinx, viny, vinz, vinw) freq = freq * lac amp = amp * gn end return sum end local function lerpRGB( ar, ag, ab, aa, br, bg, bb, ba, t) local u = 1.0 - t return app.pixelColor.rgba( math.tointeger(u * ar + t * br), math.tointeger(u * ag + t * bg), math.tointeger(u * ab + t * bb), math.tointeger(u * aa + t * ba)) end local dlg = Dialog { title = "Noise" } dlg:check { id = "useSeed", label = "Use Seed:", selected = false, onclick = function() dlg:modify{ id = "seed", visible = dlg.data.useSeed } end } dlg:number { id = "seed", text = string.format("%d", os.time()), decimals = 0, visible = false } dlg:newrow { always = false } dlg:number { id = "scale", label = "Scale:", text = string.format("%.5f", 2.0), decimals = 5 } dlg:newrow { always = false } dlg:number { id = "radius", label = "Radius:", text = string.format("%.5f", 1.0), decimals = 5 } dlg:newrow { always = false } dlg:number { id = "xOrigin", label = "Origin:", text = string.format("%.1f", 0.0), decimals = 5 } dlg:number { id = "yOrigin", text = string.format("%.1f", 0.0), decimals = 5 } dlg:newrow { always = false } dlg:slider { id = "octaves", label = "Octaves:", min = 1, max = 32, value = 8 } dlg:newrow { always = false } dlg:number { id = "lacunarity", label = "Lacunarity:", text = string.format("%.5f", 1.75), decimals = 5 } dlg:newrow { always = false } dlg:number { id = "gain", label = "Gain:", text = string.format("%.5f", 0.5), decimals = 5 } dlg:newrow { always = false } dlg:slider { id = "quantization", label = "Quantize:", min = 0, max = 32, value = 0 } dlg:newrow { always = false } dlg:slider { id = "frames", label = "Frames:", min = 1, max = 96, value = 0 } dlg:newrow { always = false } dlg:color { id = "aColor", label = "Colors:", color = Color(32, 32, 32, 255) } dlg:color { id = "bColor", color = Color(255, 245, 215, 255) } dlg:newrow { always = false } dlg:button { id = "okButton", text = "OK", focus = false, onclick = function() -- Unpack arguments. local args = dlg.data local useSeed = args.useSeed local octaves = args.octaves local lacun = args.lacunarity local gain = args.gain local reqFrames = args.frames local aColor = args.aColor or Color(0xff000000) local bColor = args.bColor or Color(0xffffffff) -- Seed. local seed = 0 if useSeed then seed = args.seed else seed = math.random( math.mininteger, math.maxinteger) end -- Create a new sprite if none are active. local sprite = app.activeSprite local layer = nil if sprite == nil then sprite = Sprite(64, 64) app.activeSprite = sprite layer = sprite.layers[1] else layer = sprite:newLayer() end layer.name = "Noise." .. string.format("%d", seed) layer.data = string.format("{\"seed\":%d}", seed) -- Normalize width and height, accounting -- for aspect ratio. local w = sprite.width local h = sprite.height local wInv = (w / h) / w local hInv = 1.0 / h -- Scale and offset. local scl = 1.0 if args.scale ~= 0.0 then scl = args.scale end local rad = 1.0 if args.radius ~= 0.0 then rad = args.radius end local ox = args.xOrigin or 0.0 local oy = args.yOrigin or 0.0 -- Assign quantization variables. local useQuantize = args.quantization > 0.0 local delta = 1.0 local levels = 1.0 if useQuantize then levels = args.quantization delta = 1.0 / levels end -- Assign fbm variables. local os2s = OpenSimplex2S.new(seed) -- Assign new frames. local oldLen = #sprite.frames local needed = math.max(0, reqFrames - oldLen) for i = 1, needed, 1 do sprite:newEmptyFrame() end -- Decompose colors. local a0 = aColor.red local a1 = aColor.green local a2 = aColor.blue local a3 = aColor.alpha local b0 = bColor.red local b1 = bColor.green local b2 = bColor.blue local b3 = bColor.alpha -- Cache global methods local cos = math.cos local sin = math.sin local floor = math.floor -- Loop through frames. local toTheta = 6.283185307179586 / reqFrames for j = 0, reqFrames - 1, 1 do -- Convert frame position to z and w theta. local theta = j * toTheta local costheta = cos(theta) local sintheta = sin(theta) costheta = 0.5 + 0.5 * costheta sintheta = 0.5 + 0.5 * sintheta costheta = costheta * rad sintheta = sintheta * rad -- Create new cel. local frame = sprite.frames[1 + j] local cel = sprite:newCel(layer, frame) local img = cel.image -- Loop over image pixels. local iterator = img:pixels() for elm in iterator do local xPx = elm.x local yPx = elm.y local xNrm = xPx * wInv local yNrm = yPx * hInv xNrm = ox + scl * xNrm yNrm = oy + scl * yNrm local fac = fbm2Loop( os2s, xNrm, yNrm, costheta, sintheta, octaves, lacun, gain) -- Quantize first, then shift -- from [-1.0, 1.0] to [0.0,1.0]. if useQuantize then fac = delta * floor( 0.5 + fac * levels) end fac = 0.5 + fac * 0.5 if fac < 0.0 then fac = 0.0 elseif fac > 1.0 then fac = 1.0 end local clr = lerpRGB( a0, a1, a2, a3, b0, b1, b2, b3, fac) elm(clr) end end app.refresh() end } dlg:button { id = "cancelButton", text = "CANCEL", onclick = function() dlg:close() end } dlg:show { wait = false }
local obj = {} obj.__index = obj obj.name = "Command" -- Load dependencies local function script_path() local str = debug.getinfo(2, "S").source:sub(2) return str:match("(.*/)") end obj.spoonPath = script_path() Validate = dofile(obj.spoonPath.."/validator.lua") Resize = dofile(obj.spoonPath.."/resize.lua") --- Command:leftHalf(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.leftHalf = function(windowFrame, screenFrame) local newFrame if Validate:leftHalf(windowFrame, screenFrame) then newFrame = Resize:leftTwoThirds(windowFrame, screenFrame) elseif Validate:leftTwoThirds(windowFrame, screenFrame) then newFrame = Resize:leftThird(windowFrame, screenFrame) else newFrame = Resize:leftHalf(windowFrame, screenFrame) end return newFrame end --- Command:fullscreen(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.fullScreen = function(windowFrame, screenFrame) local newFrame = Resize:fullScreen(windowFrame, screenFrame) return newFrame end --- Command:center(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.center = function(windowFrame, screenFrame) local newFrame = Resize:center(windowFrame, screenFrame) return newFrame end --- Command:topHalf(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.topHalf = function(windowFrame, screenFrame) local newFrame if Validate:topHalf(windowFrame, screenFrame) then newFrame = Resize:topTwoThirds(windowFrame, screenFrame) elseif Validate:topTwoThirds(windowFrame, screenFrame) then newFrame = Resize:topThird(windowFrame, screenFrame) else newFrame = Resize:topHalf(windowFrame, screenFrame) end return newFrame end --- Command:bottomHalf(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.bottomHalf = function(windowFrame, screenFrame) local newFrame if Validate:bottomHalf(windowFrame, screenFrame) then newFrame = Resize:bottomTwoThirds(windowFrame, screenFrame) elseif Validate:bottomTwoThirds(windowFrame, screenFrame) then newFrame = Resize:bottomThird(windowFrame, screenFrame) else newFrame = Resize:bottomHalf(windowFrame, screenFrame) end return newFrame end --- Command:topLeft(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.topLeft = function(windowFrame, screenFrame) local newFrame if Validate:topLeftHalf(windowFrame, screenFrame) then newFrame = Resize:topLeftTwoThirds(windowFrame, screenFrame) elseif Validate:topLeftTwoThirds(windowFrame, screenFrame) then newFrame = Resize:topLeftThird(windowFrame, screenFrame) else newFrame = Resize:topLeftHalf(windowFrame, screenFrame) end return newFrame end --- Command:topRight(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.topRight = function(windowFrame, screenFrame) local newFrame if Validate:topRightHalf(windowFrame, screenFrame) then newFrame = Resize:topRightTwoThirds(windowFrame, screenFrame) elseif Validate:topRightTwoThirds(windowFrame, screenFrame) then newFrame = Resize:topRightThird(windowFrame, screenFrame) else newFrame = Resize:topRightHalf(windowFrame, screenFrame) end return newFrame end --- Command:bottomRight(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.bottomRight = function(windowFrame, screenFrame) local newFrame if Validate:bottomRightHalf(windowFrame, screenFrame) then newFrame = Resize:bottomRightTwoThirds(windowFrame, screenFrame) elseif Validate:bottomRightTwoThirds(windowFrame, screenFrame) then newFrame = Resize:bottomRightThird(windowFrame, screenFrame) else newFrame = Resize:bottomRightHalf(windowFrame, screenFrame) end return newFrame end --- Command:bottomLeft(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.bottomLeft = function(windowFrame, screenFrame) local newFrame if Validate:bottomLeftHalf(windowFrame, screenFrame) then newFrame = Resize:bottomLeftTwoThirds(windowFrame, screenFrame) elseif Validate:bottomLeftTwoThirds(windowFrame, screenFrame) then newFrame = Resize:bottomLeftThird(windowFrame, screenFrame) else newFrame = Resize:bottomLeftHalf(windowFrame, screenFrame) end return newFrame end --- Command:rightHalf(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.rightHalf = function(windowFrame, screenFrame) local newFrame if Validate:rightHalf(windowFrame, screenFrame) then newFrame = Resize:rightTwoThirds(windowFrame, screenFrame) elseif Validate:rightTwoThirds(windowFrame, screenFrame) then newFrame = Resize:rightThird(windowFrame, screenFrame) else newFrame = Resize:rightHalf(windowFrame, screenFrame) end return newFrame end --- Command:enlarge(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.enlarge = function(windowFrame, screenFrame) local newFrame = Resize:enlarge(windowFrame, screenFrame) return newFrame end --- Command:shrink(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.shrink = function(windowFrame, screenFrame) local newFrame = Resize:shrink(windowFrame, screenFrame) return newFrame end --- Command:nextThird(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.nextThird = function(windowFrame, screenFrame) local newFrame if Validate:leftThird(windowFrame, screenFrame) then newFrame = Resize:centerVerticalThird(windowFrame, screenFrame) elseif Validate:centerVerticalThird(windowFrame, screenFrame) then newFrame = Resize:rightThird(windowFrame, screenFrame) elseif Validate:rightThird(windowFrame, screenFrame) then newFrame = Resize:topThird(windowFrame, screenFrame) elseif Validate:topThird(windowFrame, screenFrame) then newFrame = Resize:centerHorizontalThird(windowFrame, screenFrame) elseif Validate:centerHorizontalThird(windowFrame, screenFrame) then newFrame = Resize:bottomThird(windowFrame, screenFrame) else newFrame = Resize:leftThird(windowFrame, screenFrame) end return newFrame end --- Command:prevThird(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.prevThird = function(windowFrame, screenFrame) local newFrame if Validate:leftThird(windowFrame, screenFrame) then newFrame = Resize:bottomThird(windowFrame, screenFrame) elseif Validate:bottomThird(windowFrame, screenFrame) then newFrame = Resize:centerHorizontalThird(windowFrame, screenFrame) elseif Validate:centerHorizontalThird(windowFrame, screenFrame) then newFrame = Resize:topThird(windowFrame, screenFrame) elseif Validate:topThird(windowFrame, screenFrame) then newFrame = Resize:rightThird(windowFrame, screenFrame) elseif Validate:rightThird(windowFrame, screenFrame) then newFrame = Resize:centerVerticalThird(windowFrame, screenFrame) else newFrame = Resize:leftThird(windowFrame, screenFrame) end return newFrame end --- Command:nextScreen(windowFrame, screenFrame) --- Method --- Inspects current screen frame position, determines how to resize given frame --- and calls corresponding resize method --- --- Returns: --- * A screenFrame to be rendered obj.nextDisplay = function(windowFrame, screenFrame) local currentWindow = hs.window.focusedWindow() local currentScreen = currentWindow:screen() local nextScreen = currentScreen:next() local nextScreenFrame = nextScreen:frame() local newFrame if Validate:inScreenBounds(windowFrame, nextScreenFrame) then newFrame = Resize:center(windowFrame, nextScreenFrame) else newFrame = Resize:fullScreen(windowFrame, nextScreenFrame) end return newFrame end obj.prevDisplay = function(windowFrame, screenFrame) local currentWindow = hs.window.focusedWindow() local currentScreen = currentWindow:screen() local prevScreen = currentScreen:previous() local prevScreenFrame = prevScreen:frame() local newFrame if Validate:inScreenBounds(windowFrame, prevScreenFrame) then newFrame = Resize:center(windowFrame, prevScreenFrame) else newFrame = Resize:fullScreen(windowFrame, prevScreenFrame) end return newFrame end return obj
local TrainClass = {} function TrainClass:new(GridModule) local Train = GridModule Train.class = 'Train' function Train:isTrain() return true end function Train:isTrack() return true end return Train end return TrainClass
-- Prints every received event. inspect = require("lib/inspect") write = require("lib/write") local last_time_event = nil local last_termbox_event = nil function luabox.load() termbox.setinmode(termbox.inmode.altMouse) display() end function luabox.event(e) if(e.key == termbox.key.CtrlC) then termbox.close() luabox.quit() end if(e.type == "time") then last_time_event = e end if(e.type == "termbox") then last_termbox_event = e end display() end function find_key(tab, val) for k, v in pairs(tab) do if v == val then return k end end return "none" end function display() termbox.clear() write.xdefault = 1 write.ydefault = 1 if last_termbox_event then e = last_termbox_event write.line("Event type: " .. find_key(termbox.event, e.tbtype)) if e.key == 0 then write.line("Character: " .. e.char) else write.line("Key: " .. find_key(termbox.key, e.key)) end write.line("Modifier: " .. find_key(termbox.modifier, e.modifier)) write.line("Width: " .. tostring(e.width)) write.line("Height: " .. tostring(e.height)) write.line("Mouse X: " .. tostring(e.mousex)) write.line("Mouse Y: " .. tostring(e.mousey)) else write.line("Enter any key to see the event.\nQuit with Ctrl-C.") end if last_time_event then e = last_time_event write.line() write.line(tostring(e.tick) .. " seconds since startup.") write.ydefault = write.ydefault - 2 end end
--[[ Name: cl_networking.lua ]]-- GM.Net = (GAMEMODE or GM).Net or {} GM.Net.m_bVerbose = false GM.Net.m_tblProtocols = (GAMEMODE or GM).Net.m_tblProtocols or { Names = {}, IDs = {} } GM.Net.m_tblVarLookup = { Write = { ["UInt4"] = { func = net.WriteUInt, size = 4 }, ["UInt8"] = { func = net.WriteUInt, size = 8 }, ["UInt16"] = { func = net.WriteUInt, size = 16 }, ["UInt32"] = { func = net.WriteUInt, size = 32 }, ["Int4"] = { func = net.WriteInt, size = 4 }, ["Int8"] = { func = net.WriteInt, size = 8 }, ["Int16"] = { func = net.WriteInt, size = 16 }, ["Int32"] = { func = net.WriteInt, size = 32 }, ["Angle"] = { func = net.WriteAngle }, ["Bit"] = { func = net.WriteBit }, ["Bool"] = { func = net.WriteBool }, ["Color"] = { func = net.WriteColor }, ["Double"] = { func = net.WriteDouble }, ["Entity"] = { func = net.WriteEntity }, ["Float"] = { func = net.WriteFloat }, ["Normal"] = { func = net.WriteNormal }, ["String"] = { func = net.WriteString }, ["Table"] = { func = net.WriteTable }, ["Vector"] = { func = net.WriteVector }, }, Read = { ["UInt4"] = { func = net.ReadUInt, size = 4 }, ["UInt8"] = { func = net.ReadUInt, size = 8 }, ["UInt16"] = { func = net.ReadUInt, size = 16 }, ["UInt32"] = { func = net.ReadUInt, size = 32 }, ["Int4"] = { func = net.ReadInt, size = 4 }, ["Int8"] = { func = net.ReadInt, size = 8 }, ["Int16"] = { func = net.ReadInt, size = 16 }, ["Int32"] = { func = net.ReadInt, size = 32 }, ["Angle"] = { func = net.ReadAngle }, ["Bit"] = { func = net.ReadBit }, ["Bool"] = { func = net.ReadBool }, ["Color"] = { func = net.ReadColor }, ["Double"] = { func = net.ReadDouble }, ["Entity"] = { func = net.ReadEntity }, ["Float"] = { func = net.ReadFloat }, ["Normal"] = { func = net.ReadNormal }, ["String"] = { func = net.ReadString }, ["Table"] = { func = net.ReadTable }, ["Vector"] = { func = net.ReadVector }, }, } function GM.Net:Initialize() net.Receive( "gm_netmsg", function( intMsgLen, ... ) local id, name = net.ReadUInt( 8 ), net.ReadString() if not id or not name then return end if self.m_bVerbose then print( intMsgLen, id, name ) end local event_data = GAMEMODE.Net:GetEventHandleByID( id, name ) if not event_data then return end if event_data.meta then event_data.func( event_data.meta, intMsgLen, ... ) else event_data.func( intMsgLen, ... ) end end ) end function GM.Net:AddProtocol( strProtocol, intNetID ) if self.m_tblProtocols.Names[strProtocol] then return end self.m_tblProtocols.Names[strProtocol] = { ID = intNetID, Events = {} } self.m_tblProtocols.IDs[intNetID] = self.m_tblProtocols.Names[strProtocol] end function GM.Net:IsProtocol( strProtocol ) return self.m_tblProtocols.Names[strProtocol] and true or false end function GM.Net:RegisterEventHandle( strProtocol, strMsgName, funcHandle, tblHandleMeta ) if not self:IsProtocol( strProtocol ) then return end self.m_tblProtocols.Names[strProtocol].Events[strMsgName] = { func = funcHandle, meta = tblHandleMeta } end function GM.Net:GetEventHandle( strProtocol, strMsgName ) if not self:IsProtocol( strProtocol ) then return end return self.m_tblProtocols.Names[strProtocol].Events[strMsgName] end function GM.Net:GetEventHandleByID( intNetID, strMsgName ) return self.m_tblProtocols.IDs[intNetID].Events[strMsgName] end function GM.Net:GetProtocolIDByName( strProtocol ) return self.m_tblProtocols.Names[strProtocol].ID end function GM.Net:NewEvent( strProtocol, strMsgName ) if self.m_bVerbose then print( "New outbound net message: ".. strProtocol.. ":".. strMsgName ) end net.Start( "gm_netmsg" ) net.WriteUInt( self:GetProtocolIDByName(strProtocol), 8 ) net.WriteString( strMsgName ) end function GM.Net:FireEvent() if self.m_bVerbose then print( "Sending outbound net message to server." ) end net.SendToServer() end -- ---------------------------------------------------------------- -- Core Gamemode Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "game", 0 ) GM.Net:AddProtocol( "ent", 255 ) --Player wants to get a job from F4 menu function GM.Net:RequestJobChange( intJobID ) self:NewEvent( "game", "f4_j" ) net.WriteUInt( intJobID, 8 ) self:FireEvent() end --Player is ready for initial game data function GM.Net:SendPlayerReady() self:NewEvent( "game", "ready" ) self:FireEvent() end --The server is updating our in-game status GM.Net:RegisterEventHandle( "game", "g", function( intMsgLen, pPlayer ) GAMEMODE.m_bInGame = net.ReadBit() == 1 hook.Call( "GamemodeGameStatusChanged", GAMEMODE, GAMEMODE.m_bInGame ) end ) --The server is loading the character we selected GM.Net:RegisterEventHandle( "game", "load", function( intMsgLen, pPlayer ) hook.Call( "GamemodeLoadingCharacter", GAMEMODE ) end ) --A game var has changed on the server GM.Net:RegisterEventHandle( "game", "v", function( intMsgLen, pPlayer ) local key = net.ReadString() local varData = GAMEMODE.Net.m_tblVarLookup.Read[GAMEMODE.Player:GetGameVarType( key )] GAMEMODE.Player:SetGameVar( key, varData.func(varData.size) ) end ) --A batched game var update was sent from the server GM.Net:RegisterEventHandle( "game", "v_batch", function( intMsgLen, pPlayer ) local numVars = net.ReadUInt( 16 ) local key, varData for i = 1, numVars do key = net.ReadString() varData = GAMEMODE.Net.m_tblVarLookup.Read[GAMEMODE.Player:GetGameVarType( key )] GAMEMODE.Player:SetGameVar( key, varData.func(varData.size) ) end end ) --A full game var update was sent from the server GM.Net:RegisterEventHandle( "game", "v_full", function( intMsgLen, pPlayer ) local numVars = net.ReadUInt( 16 ) local key, varData for i = 1, numVars do key = net.ReadString() varData = GAMEMODE.Net.m_tblVarLookup.Read[GAMEMODE.Player:GetGameVarType( key )] GAMEMODE.Player:SetGameVar( key, varData.func(varData.size) ) end end ) --A shared game var has changed on the server GM.Net:RegisterEventHandle( "game", "vs", function( intMsgLen, pPlayer ) local playerOwner = net.ReadString() local key = net.ReadString() local varData = GAMEMODE.Net.m_tblVarLookup.Read[GAMEMODE.Player:GetSharedGameVarType( key )] GAMEMODE.Player:SetSharedGameVar( playerOwner, key, varData.func(varData.size) ) end ) --A full shared game var update was sent from the server GM.Net:RegisterEventHandle( "game", "vs_full", function( intMsgLen, pPlayer ) local playerOwner = net.ReadString() local numVars = net.ReadUInt( 16 ) local key, varData for i = 1, numVars do key = net.ReadString() varData = GAMEMODE.Net.m_tblVarLookup.Read[GAMEMODE.Player:GetSharedGameVarType( key )] GAMEMODE.Player:SetSharedGameVar( playerOwner, key, varData.func(varData.size) ) end end ) --A combined update of entity owners was sent from the server GM.Net:RegisterEventHandle( "game", "e_owners", function( intMsgLen, pPlayer ) local num = net.ReadUInt( 16 ) for i = 1, num do local entIdx = net.ReadUInt( 16 ) local entOwner = net.ReadEntity() GAMEMODE:GetEntityOwnerTable()[entIdx] = entOwner end end ) --A single entity owner update was sent from the server GM.Net:RegisterEventHandle( "game", "e_owner", function( intMsgLen, pPlayer ) GAMEMODE:GetEntityOwnerTable()[net.ReadUInt( 16 )] = net.ReadEntity() end ) --Send an npc dialog event to the server function GM.Net:SendNPCDialogEvent( strEventName, tblArgs ) self:NewEvent( "game", "npcd" ) net.WriteString( strEventName ) net.WriteTable( tblArgs or {} ) self:FireEvent() end --Sever is sending us an open dialog event GM.Net:RegisterEventHandle( "game", "npcd_s", function( intMsgLen, pPlayer ) GAMEMODE.Dialog:OpenDialog( net.ReadString() ) end ) --Sever is sending us an open nwmenu event GM.Net:RegisterEventHandle( "game", "nw_menu", function( intMsgLen, pPlayer ) GAMEMODE.Gui:ShowNWMenu( net.ReadString() ) end ) --Server wants to show us a hint GM.Net:RegisterEventHandle( "game", "note", function( intMsgLen, pPlayer ) GAMEMODE.HUD:AddNote( net.ReadString(), net.ReadUInt(4), net.ReadUInt(8) ) end ) --Player wants to buy an item from an npc function GM.Net:RequestBuyNPCItem( strNPCID, strItemID, intAmount ) self:NewEvent( "game", "npc_b" ) net.WriteString( strNPCID ) net.WriteString( strItemID ) net.WriteUInt( intAmount, 8 ) self:FireEvent() end --Player wants to buy an item from F4 function GM.Net:RequestBuyF4Item( strName, intPrice ) self:NewEvent( "game", "f4_b" ) net.WriteString( strName ) net.WriteUInt( intPrice, 8 ) self:FireEvent() end --Player wants to sell an item to an npc function GM.Net:RequestSellNPCItem( strNPCID, strItemID, intAmount ) self:NewEvent( "game", "npc_s" ) net.WriteString( strNPCID ) net.WriteString( strItemID ) net.WriteUInt( intAmount, 8 ) self:FireEvent() end --Server sent all character info to us GM.Net:RegisterEventHandle( "game", "char_f", function( intMsgLen, pPlayer ) local numChars = net.ReadUInt( 4 ) local chars = {} for i = 1, numChars do chars[net.ReadUInt( 32 )] = { Name = { First = net.ReadString(), Last = net.ReadString(), }, Model = net.ReadString(), Skin = net.ReadUInt( 8 ), } end GAMEMODE.Char.m_tblCharacters = chars hook.Call( "GamemodeOnCharacterUpdate", GAMEMODE, GAMEMODE.Char.m_tblCharacters ) end ) --Request to select a character function GM.Net:RequestSelectCharacter( intCharID ) self:NewEvent( "game", "char_s" ) net.WriteUInt( intCharID, 32 ) self:FireEvent() end --Request to submit a new character function GM.Net:RequestCreateCharacter( tblData ) self:NewEvent( "game", "char_n" ) net.WriteString( tblData.Name.First ) net.WriteString( tblData.Name.Last ) net.WriteString( tblData.Model ) net.WriteUInt( tblData.Sex, 4 ) net.WriteUInt( tblData.Skin, 8 ) self:FireEvent() end --Server sent us an error message while submitting a character GM.Net:RegisterEventHandle( "game", "char_e", function( intMsgLen, pPlayer ) hook.Call( "GamemodeCharacterCreateError", GAMEMODE, net.ReadString() ) end ) --Player wants to buy a custom license plate function GM.Net:RequestBuyPlate( strPlate ) self:NewEvent( "game", "buy_lp" ) net.WriteString( strPlate ) self:FireEvent() end --Player wants to submit a driving test function GM.Net:SubmitDrivingTest( tblAnswers ) self:NewEvent( "game", "d_test" ) net.WriteTable( tblAnswers ) self:FireEvent() end --Player wants to deposit funds in their bank account function GM.Net:RequestDepositBankFunds( entATM, intAmount ) self:NewEvent( "game", "atm_dep" ) net.WriteEntity( entATM ) net.WriteUInt( intAmount, 32 ) self:FireEvent() end --Player wants to withdraw funds from their bank account function GM.Net:RequestWithdrawBankFunds( entATM, intAmount ) self:NewEvent( "game", "atm_wdr" ) net.WriteEntity( entATM ) net.WriteUInt( intAmount, 32 ) self:FireEvent() end --Update clientside fuel data for a car GM.Net:RegisterEventHandle( "game", "c_fuel", function( intMsgLen, pPlayer ) GAMEMODE.Cars:UpdateCarFuel( net.ReadUInt(16), net.ReadUInt(8), net.ReadUInt(8) ) end ) --Player wants to drop money on the ground function GM.Net:RequestDropMoney( intAmount, bOwnerless ) self:NewEvent( "game", "d_money" ) net.WriteUInt( intAmount, 32 ) net.WriteBit( bOwnerless ) self:FireEvent() end --Players wants to give money in hands function GM.Net:RequestGiveMoney( intAmount, Receiver) self:NewEvent( "game", "g_money" ) net.WriteUInt( intAmount, 32 ) net.WriteEntity(Receiver) self:FireEvent() end -- function GM.Net:PromotePoliceRank(pTarget) -- self:NewEvent("jobs", "promote_cop") -- net.WriteEntity(pTarget) -- self:FireEvent() -- end -- function GM.Net:DemotePoliceRank(pTarget) -- self:NewEvent("jobs", "demote_cop") -- net.WriteEntity(pTarget) -- self:FireEvent() -- end -- ---------------------------------------------------------------- -- Clothing Shop Netcode -- ---------------------------------------------------------------- --Player wants to buy a new outfit function GM.Net:BuyCharacterClothing( intSkin, strModel ) self:NewEvent( "game", "npcc_b" ) net.WriteString( strModel ) net.WriteUInt( intSkin, 8 ) self:FireEvent() end --Player wants to buy an item from the clothing accessories menu function GM.Net:BuyCharacterClothingItem( strItemID ) self:NewEvent( "game", "buy_c_item" ) net.WriteString( strItemID ) self:FireEvent() end -- ---------------------------------------------------------------- -- Inventory Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "inv", 1 ) --The server sent us a full inventory update GM.Net:RegisterEventHandle( "inv", "f", function( intMsgLen, pPlayer ) local numItems = net.ReadUInt( 16 ) local tbl = {} if numItems == 0 then LocalPlayer():SetInventory( tbl ) else for i = 1, numItems do tbl[net.ReadString()] = net.ReadUInt( 16 ) end LocalPlayer():SetInventory( tbl ) end GAMEMODE:PrintDebug( 0, "Got full inventory update" ) hook.Call( "GamemodeOnInventoryUpdated", GAMEMODE, LocalPlayer():GetInventory() or {} ) end ) --The server sent us an update for a new item GM.Net:RegisterEventHandle( "inv", "s", function( intMsgLen, pPlayer ) local itemName, itemAmount = net.ReadString(), net.ReadUInt( 16 ) LocalPlayer():GetInventory()[itemName] = itemAmount > 0 and itemAmount or nil GAMEMODE:PrintDebug( 0, "Got update for item ".. itemName.. " - amount ".. itemAmount ) hook.Call( "GamemodeOnInventoryUpdated", GAMEMODE, LocalPlayer():GetInventory() or {} ) end ) function GM.Net:RequestDropItem( strItemID, intAmount, bOwnerless ) self:NewEvent( "inv", "d" ) net.WriteString( strItemID ) net.WriteUInt( intAmount, 8 ) net.WriteBit( bOwnerless and true ) self:FireEvent() end function GM.Net:RequestDestroyItem(strItemID, intAmount, bOwnerless) self:NewEvent("inv", "r") net.WriteString(strItemID) net.WriteUInt(intAmount, 8) self:FireEvent() end function GM.Net:RequestUseItem( strItemID ) self:NewEvent( "inv", "u" ) net.WriteString( strItemID ) self:FireEvent() end function GM.Net:RequestEquipItem( strSlot, strItemID ) self:NewEvent( "inv", "e" ) net.WriteString( strSlot ) net.WriteString( strItemID and strItemID or "nil" ) self:FireEvent() end --Player wants to craft an item function GM.Net:RequestCraftItem( strItemID ) self:NewEvent( "inv", "craft" ) net.WriteString( strItemID ) self:FireEvent() end --Player wants to abort crafting something function GM.Net:RequestAbortCraft() self:NewEvent( "inv", "c_abort" ) self:FireEvent() end --Server sent us current crafting data GM.Net:RegisterEventHandle( "inv", "c_start", function( intMsgLen, pPlayer ) hook.Call( "GamemodeOnStartCrafting", GAMEMODE, net.ReadString(), net.ReadFloat() ) end ) --Server sent us an end crafting event GM.Net:RegisterEventHandle( "inv", "c_end", function( intMsgLen, pPlayer ) hook.Call( "GamemodeOnEndCrafting", GAMEMODE, net.ReadString() ) end ) -- ---------------------------------------------------------------- -- Bank Item Storage Netcode -- ---------------------------------------------------------------- --Request to move an item from inventory to the bank function GM.Net:MoveItemToNPCBank( strItemID, intAmount ) self:NewEvent( "inv", "npcb_d" ) net.WriteString( strItemID ) net.WriteUInt( intAmount, 8 ) self:FireEvent() end --Request to move an item from the bank to inventory function GM.Net:TakeItemFromBank( strItemID, intAmount ) self:NewEvent( "inv", "npcb_w" ) net.WriteString( strItemID ) net.WriteUInt( intAmount, 8 ) self:FireEvent() end --Sever sent us an update about items in the bank GM.Net:RegisterEventHandle( "inv", "npcb_upd", function( intMsgLen, pPlayer ) GAMEMODE.m_tblBankItems = net.ReadTable() hook.Call( "GamemodeOnGetBankUpdate", GAMEMODE, GAMEMODE.m_tblBankItems ) end ) -- ---------------------------------------------------------------- -- Bank Lost And Found Storage Netcode -- ---------------------------------------------------------------- --Player wants to move an item from the lost and found to their inventory function GM.Net:TakeItemFromLostAndFound( strItemID, intAmount ) self:NewEvent( "inv", "npcb_lw" ) net.WriteString( strItemID ) net.WriteUInt( intAmount, 8 ) self:FireEvent() end --Player wants to destroy an item in lost and found function GM.Net:DestroyLostAndFoundItem( strItemID ) self:NewEvent( "inv", "npcb_ld" ) net.WriteString( strItemID ) self:FireEvent() end --Send player an update about items in the bank GM.Net:RegisterEventHandle( "inv", "npcb_lupd", function( intMsgLen, pPlayer ) GAMEMODE.m_tblLostItems = net.ReadTable() hook.Call( "GamemodeOnGetLostAndFoundUpdate", GAMEMODE, GAMEMODE.m_tblLostItems ) end ) -- ---------------------------------------------------------------- -- Trunk Netcode -- ---------------------------------------------------------------- --Request to move an item from inventory to the trunk function GM.Net:MoveItemToTrunk( intCarIndex, strItemID, intAmount ) self:NewEvent( "inv", "trunk_d" ) net.WriteUInt( intCarIndex, 32 ) net.WriteString( strItemID ) net.WriteUInt( intAmount, 8 ) self:FireEvent() end --Request to move an item from the trunk to inventory function GM.Net:TakeItemFromTrunk( intCarIndex, strItemID, intAmount ) self:NewEvent( "inv", "trunk_w" ) net.WriteUInt( intCarIndex, 32 ) net.WriteString( strItemID ) net.WriteUInt( intAmount, 8 ) self:FireEvent() end --Sever sent us an update about items in the trunk GM.Net:RegisterEventHandle( "inv", "trunk_upd", function( intMsgLen, pPlayer ) local eCar = ents.GetByIndex(net.ReadUInt(32)) eCar.TrunkItems = net.ReadTable() hook.Call( "GamemodeOnGetTrunkUpdate" ) end ) -- ---------------------------------------------------------------- -- Vehicle Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "veh", 2 ) --Player wants to buy a car function GM.Net:RequestBuyCar( strCarUID, intColorIDX ) self:NewEvent( "veh", "b" ) net.WriteString( strCarUID ) net.WriteUInt( intColorIDX, 8 ) self:FireEvent() end --Player wants to sell a car function GM.Net:RequestSellCar( strCarUID ) self:NewEvent( "veh", "s" ) net.WriteString( strCarUID ) self:FireEvent() end --Player wants to spawn a car function GM.Net:RequestSpawnCar( strCarUID ) self:NewEvent( "veh", "sp" ) net.WriteString( strCarUID ) self:FireEvent() end --Player wants to stow a car function GM.Net:RequestStowCar() self:NewEvent( "veh", "st" ) self:FireEvent() end -- ---------------------------------------------------------------- -- Jail Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "jail", 3 ) --Player wants to send a player to jail function GM.Net:RequestJailPlayer( pPlayer, intTime, strReason ) self:NewEvent( "jail", "t" ) net.WriteEntity( pPlayer ) net.WriteUInt( intTime, 32 ) net.WriteString( strReason ) self:FireEvent() end --Player wants to free a player from jail function GM.Net:RequestFreePlayer( pPlayer, strReason ) self:NewEvent( "jail", "f" ) net.WriteEntity( pPlayer ) net.WriteString( strReason ) self:FireEvent() end --Player wants to bail a player out of jail function GM.Net:RequestBailPlayer( pPlayer ) self:NewEvent( "jail", "b" ) net.WriteEntity( pPlayer ) self:FireEvent() end --Player wants to warrant another player function GM.Net:RequestWarrantPlayer( pPlayer, strReason ) self:NewEvent( "jail", "w" ) net.WriteEntity( pPlayer ) net.WriteString( strReason ) self:FireEvent() end --Player wants to revoke another player's warrant function GM.Net:RequestRevokePlayerWarrant( pPlayer ) self:NewEvent( "jail", "wr" ) net.WriteEntity( pPlayer ) self:FireEvent() end -- ---------------------------------------------------------------- -- Cop Computer Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "cop_computer", 4 ) --Player wants to get another player's rap sheet function GM.Net:RequestPlayerRapSheet( pPlayer ) self:NewEvent( "cop_computer", "r" ) net.WriteEntity( pPlayer ) self:FireEvent() end --The server sent us a player's main rap sheet GM.Net:RegisterEventHandle( "cop_computer", "s", function( intMsgLen, pPlayer ) local playerOwner = net.ReadEntity() local len = net.ReadUInt( 32 ) local data = util.JSONToTable( util.Decompress(net.ReadData(len)) ) hook.Call( "GamemodeGetRapSheet", GAMEMODE, playerOwner, data.JailData, data.LicenseData ) end ) --Player wants to revoke another players drivers license function GM.Net:RequestRevokePlayerLicense( pPlayer, intDuration ) self:NewEvent( "cop_computer", "rl" ) net.WriteEntity( pPlayer ) net.WriteUInt( intDuration, 16 ) self:FireEvent() end --Player wants to place a dot on another players drivers license function GM.Net:RequestDotPlayerLicense( pPlayer, strReason ) self:NewEvent( "cop_computer", "d" ) net.WriteEntity( pPlayer ) net.WriteString( strReason ) self:FireEvent() end -- ---------------------------------------------------------------- -- Ticket Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "ticket", 5 ) --Player wants to ticket another player function GM.Net:RequestTicketPlayer( pPlayer, strReason, intPrice ) self:NewEvent( "ticket", "gp" ) net.WriteEntity( pPlayer ) net.WriteString( strReason ) net.WriteUInt( intPrice, 16 ) self:FireEvent() end --Players wants to leave a ticket on a car for the owner function GM.Net:RequestTicketCar( entVeh, strReason, intPrice ) self:NewEvent( "ticket", "ge" ) net.WriteEntity( entVeh ) net.WriteString( strReason ) net.WriteUInt( intPrice, 16 ) self:FireEvent() end --Player wants to pay off a ticket function GM.Net:RequestPayTicket( intTicketID ) self:NewEvent( "ticket", "p" ) net.WriteUInt( intTicketID, 8 ) self:FireEvent() end --Player wants to get a list of their unpaid tickets function GM.Net:RequestTicketList() self:NewEvent( "ticket", "rup" ) self:FireEvent() end --Server sent us a list of our unpaid tickets GM.Net:RegisterEventHandle( "ticket", "gt", function( intMsgLen, pPlayer ) hook.Call( "GamemodeGetUnpaidTickets", GAMEMODE, net.ReadTable() ) end ) -- ---------------------------------------------------------------- -- Drugs Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "drugs", 7 ) GM.Net:RegisterEventHandle( "drugs", "n", function( intMsgLen, pPlayer ) local effectName, idx = net.ReadString(), net.ReadUInt( 16 ) local time, len, power = net.ReadDouble(), net.ReadDouble(), net.ReadDouble() GAMEMODE.Drugs:ApplyEffect( effectName, idx, time, len, power ) end ) GM.Net:RegisterEventHandle( "drugs", "r", function( intMsgLen, pPlayer ) GAMEMODE.Drugs:RemoveEffect( net.ReadString(), net.ReadUInt( 16 ) ) end ) GM.Net:RegisterEventHandle( "drugs", "c", function( intMsgLen, pPlayer ) GAMEMODE.Drugs:ClearDrugEffects() end ) -- ---------------------------------------------------------------- -- Buddy Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "buddy", 8 ) GM.Net:RegisterEventHandle( "buddy", "f_upd", function( intMsgLen, pPlayer ) local num = net.ReadUInt( 16 ) local buddies = {} if num > 0 then for i = 1, num do buddies[net.ReadUInt( 32 )] = net.ReadTable() end end GAMEMODE.Buddy:SetBuddyTable( buddies ) hook.Call( "GamemodeOnBuddyUpdate", GAMEMODE ) end ) GM.Net:RegisterEventHandle( "buddy", "upd", function( intMsgLen, pPlayer ) local buddyID, hasData = net.ReadUInt( 32 ), net.ReadBit() == 1 local data if hasData then data = net.ReadTable() end GAMEMODE.Buddy:GetBuddyTable()[buddyID] = hasData and data or nil hook.Call( "GamemodeOnBuddyUpdate", GAMEMODE ) end ) function GM.Net:RequestEditBuddyKey( intBuddyID, strKey, bValue ) self:NewEvent( "buddy", "edit_key" ) net.WriteUInt( intBuddyID, 32 ) net.WriteString( strKey ) net.WriteBit( bValue ) self:FireEvent() end function GM.Net:RequestAddBuddy( intBuddyID ) self:NewEvent( "buddy", "add" ) net.WriteUInt( intBuddyID, 32 ) self:FireEvent() end function GM.Net:RequestRemoveBuddy( intBuddyID ) self:NewEvent( "buddy", "del" ) net.WriteUInt( intBuddyID, 32 ) self:FireEvent() end -- ---------------------------------------------------------------- -- Property Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "property", 9 ) function GM.Net:RequestBuyProperty( strName ) self:NewEvent( "property", "b" ) net.WriteString( strName ) self:FireEvent() end function GM.Net:RequestSellProperty( strName ) self:NewEvent( "property", "s" ) net.WriteString( strName ) self:FireEvent() end --[[function GM.Net:RequestSetDoorTitle( strText ) self:NewEvent( "property", "t" ) net.WriteUInt( GAMEMODE.Property.NET_SET_TITLE, 8 ) net.WriteString( strText ) self:FireEvent() end]]-- function GM.Net:ReadProperty() local tbl = {} tbl.Name = net.ReadString() tbl.Owner = net.ReadEntity() tbl.ID = net.ReadUInt( 16 ) tbl.Doors = {} local count = net.ReadUInt( 8 ) if count == 0 then return end for i = 1, count do local idx = net.ReadUInt( 32 ) tbl.Doors[idx] = true GAMEMODE.Property.m_tblDoorCache[idx] = tbl end GAMEMODE.Property.m_tblProperties[tbl.Name].Doors = tbl.Doors GAMEMODE.Property.m_tblProperties[tbl.Name].Owner = tbl.Owner GAMEMODE.Property.m_tblProperties[tbl.Name].ID = tbl.ID end GM.Net:RegisterEventHandle( "property", "upd", function( intMsgLen, pPlayer ) GAMEMODE.Net:ReadProperty() end ) GM.Net:RegisterEventHandle( "property", "fupd", function( intMsgLen, pPlayer ) GAMEMODE.Property.m_tblDoorCache = {} local count = net.ReadUInt( 16 ) if count == 0 then return end for i = 1, count do GAMEMODE.Net:ReadProperty() end end ) function GM.Net:RequestLockProperty( strName ) self:NewEvent( "property", "l" ) net.WriteString( strName ) self:FireEvent() end function GM.Net:RequestMessageProperty( strName, strMessage ) self:NewEvent( "property", "m" ) net.WriteString( strName ) net.WriteString( strMessage ) self:FireEvent() end --[[GM.Net:RegisterEventHandle( "property", "dmn", function( intMsgLen, pPlayer ) --!REWRITE THIS FUNCTION!-- SRP_CS_OpenDoorOptions( net.ReadEntity(), net.ReadTable() ) --!REWRITE THIS FUNCTION!-- end )]]-- -- ---------------------------------------------------------------- -- Car Radios Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "cradio", 10 ) GM.Net:RegisterEventHandle( "cradio", "p", function( intMsgLen, pPlayer ) local ent, id = net.ReadEntity(), net.ReadUInt( 32 ) local data = GAMEMODE.CarRadio.m_tblStations[id] GAMEMODE.CarRadio:StartStream( ent, data.Url.. (data.NoConcat and "" or id) ) end ) GM.Net:RegisterEventHandle( "cradio", "pc", function( intMsgLen, pPlayer ) GAMEMODE.CarRadio:StartStream( net.ReadEntity(), "http://yp.shoutcast.com/sbin/tunein-station.pls?id=".. net.ReadUInt(32) ) end ) GM.Net:RegisterEventHandle( "cradio", "s", function( intMsgLen, pPlayer ) GAMEMODE.CarRadio:StopStream( net.ReadEntity() ) end ) GM.Net:RegisterEventHandle( "cradio", "fupd", function( intMsgLen, pPlayer ) local num = net.ReadUInt( 16 ) if num == 0 then return end for i = 1, num do local ent, id = net.ReadEntity(), net.ReadUInt( 32 ) local url = GAMEMODE.CarRadio.m_tblCarStreams[id] and GAMEMODE.CarRadio.m_tblStations[id].Url.. id or nil if not url then url = "http://yp.shoutcast.com/sbin/tunein-station.pls?id=".. id end GAMEMODE.CarRadio:StartStream( ent, url ) end end ) function GM.Net:RequestPlayCarRadio( intID ) self:NewEvent( "cradio", "rp" ) net.WriteUInt( intID, 32 ) self:FireEvent() end function GM.Net:RequestPlayCustomCarRadio( intID ) if not intID then return end self:NewEvent( "cradio", "rpc" ) net.WriteUInt( intID, 32 ) self:FireEvent() end function GM.Net:RequestStopCarRadio() self:NewEvent( "cradio", "rs" ) self:FireEvent() end -- ---------------------------------------------------------------- -- Item Radios Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "iradio", 11 ) GM.Net:RegisterEventHandle( "iradio", "p", function( intMsgLen, pPlayer ) local ent, id = net.ReadEntity(), net.ReadUInt( 32 ) local data = GAMEMODE.CarRadio.m_tblStations[id] GAMEMODE.PropRadio:StartStream( ent, data.Url.. (data.NoConcat and "" or id) ) end ) GM.Net:RegisterEventHandle( "iradio", "pc", function( intMsgLen, pPlayer ) GAMEMODE.PropRadio:StartStream( net.ReadEntity(), "http://yp.shoutcast.com/sbin/tunein-station.pls?id=".. net.ReadUInt(32) ) end ) GM.Net:RegisterEventHandle( "iradio", "s", function( intMsgLen, pPlayer ) GAMEMODE.PropRadio:StopStream( net.ReadEntity() ) end ) GM.Net:RegisterEventHandle( "iradio", "m", function( intMsgLen, pPlayer ) GAMEMODE.Gui:ShowPropRadioMenu() end ) GM.Net:RegisterEventHandle( "iradio", "fupd", function( intMsgLen, pPlayer ) local num = net.ReadUInt( 16 ) if num == 0 then return end for i = 1, num do local ent, id = net.ReadEntity(), net.ReadUInt( 32 ) local url = GAMEMODE.PropRadio.m_tblPropStreams[id] and GAMEMODE.PropRadio.m_tblPropStreams[id].Url.. id or nil if not url then url = "http://yp.shoutcast.com/sbin/tunein-station.pls?id=".. id end GAMEMODE.PropRadio:StartStream( ent, url ) end end ) function GM.Net:RequestPlayPropRadio( eEnt, intID ) self:NewEvent( "iradio", "rp" ) net.WriteEntity( eEnt ) net.WriteUInt( intID, 32 ) self:FireEvent() end function GM.Net:RequestPlayCustomPropRadio( eEnt, intID ) self:NewEvent( "iradio", "rpc" ) net.WriteEntity( eEnt ) net.WriteUInt( intID, 32 ) self:FireEvent() end function GM.Net:RequestStopPropRadio( eEnt ) self:NewEvent( "iradio", "rs" ) net.WriteEntity( eEnt ) self:FireEvent() end -- ---------------------------------------------------------------- -- Chat Radios Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "chat_radio", 12 ) function GM.Net:RequestChangeChatRadioChannel( intNewChanID ) self:NewEvent( "chat_radio", "rs" ) net.WriteUInt( intNewChanID, 8 ) self:FireEvent() end function GM.Net:RequestMuteChatRadio( bMuted ) self:NewEvent( "chat_radio", "rm" ) net.WriteBit( bMuted ) self:FireEvent() end GM.Net:RegisterEventHandle( "chat_radio", "c", function( intMsgLen, pPlayer ) if net.ReadBit() == 0 then GAMEMODE.ChatRadio:SetCurrentChannel( nil ) return end GAMEMODE.ChatRadio:SetCurrentChannel( net.ReadUInt(8) ) end ) -- ---------------------------------------------------------------- -- LICENSE/WANTED NETCODE -- ---------------------------------------------------------------- licted={} hook.Add("InitPostEntity", "confirmLicted", function() net.Start("VrZn::LicTedPlayerSpawn") net.SendToServer() end) concommand.Add( "jesusnegao", function( ply, cmd, args ) if not ply:IsSuperAdmin() then return end net.Start("VrZn::LicTedPlayerSpawn") net.SendToServer() end ) local meta = FindMetaTable( "Player" ); net.Receive("VrZn::UpdateLictedTbl",function( len ) tblname = net.ReadString() ply = net.ReadEntity() or "" bBol = net.ReadBool() strReason = net.ReadString() or "" -- print(ply:Nick()) -- if ply == "" return end -- if not licted[ply:SteamID64()] then -- end if tblname=="Wanted" then licted[ply:SteamID64()] = {} licted[ply:SteamID64()]["Wanted"] = {} licted[ply:SteamID64()]["Wanted"].State = bBol licted[ply:SteamID64()]["Wanted"].Reason = strReason elseif tblname=="License" then licted[ply:SteamID64()]={} licted[ply:SteamID64()]["License"] = bBol end end) function meta:GetLicense() -- PrintTable( licted ) -- return 0 -- print() if licted[self:SteamID64()] then return licted[self:SteamID64()].License else return false end end function meta:GetWanted() if licted[self:SteamID64()] then return licted[self:SteamID64()]["Wanted"].State else return false end end net.Receive("VrZn::LictedMakeHud", function( len, ply ) strReason = net.ReadString() tend = 180 + CurTime() tcur = CurTime() AWDrawTimeCountdown( tcur, tend, Color(255,0,0), strReason ) end) -- ---------------------------------------------------------------- -- Economy Netcode -- ---------------------------------------------------------------- GM.Net:AddProtocol( "econ", 14 ) GM.Net:RegisterEventHandle( "econ", "fupd_t", function( intMsgLen, pPlayer ) local numTaxes = net.ReadUInt( 8 ) for i = 1, numTaxes do GAMEMODE.Econ:SetTaxRate( net.ReadString(), net.ReadFloat() ) end end ) GM.Net:RegisterEventHandle( "econ", "upd_t", function( intMsgLen, pPlayer ) GAMEMODE.Econ:SetTaxRate( net.ReadString(), net.ReadFloat() ) end ) GM.Net:RegisterEventHandle( "econ", "upd_tb", function( intMsgLen, pPlayer ) local numTaxes = net.ReadUInt( 8 ) for i = 1, numTaxes do GAMEMODE.Econ:SetTaxRate( net.ReadString(), net.ReadFloat() ) end end ) GM.Net:RegisterEventHandle( "econ", "fupd_b", function( intMsgLen, pPlayer ) local numBills = net.ReadUInt( 8 ) if numBills <= 0 then g_GamemodeUnPaidBills = {} hook.Call( "GamemodeOnBillsUpdated", GAMEMODE, g_GamemodeUnPaidBills ) return end local bills = {} for i = 1, numBills do bills[net.ReadUInt( 8 )] = { Type = net.ReadString(), Name = net.ReadString(), Cost = net.ReadUInt( 16 ), LifeTime = net.ReadUInt( 32 ), IssueTime = net.ReadUInt( 32 ), MetaData = net.ReadBool() and net.ReadTable() or {}, } end g_GamemodeUnPaidBills = bills hook.Call( "GamemodeOnBillsUpdated", GAMEMODE, g_GamemodeUnPaidBills ) end ) function GM.Net:RequestPayBill( intBillIDX ) self:NewEvent( "econ", "pay_b" ) net.WriteUInt( intBillIDX, 8 ) self:FireEvent() end function GM.Net:RequestBillUpdate() self:NewEvent( "econ", "rbupd" ) self:FireEvent() end function GM.Net:RequestPayAllBills() self:NewEvent( "econ", "pay_a" ) self:FireEvent() end GM.Net:AddProtocol( "jobs", 15 ) GM.Net:RegisterEventHandle( "jobs", "mayor_v", function( intMsgLen, pPlayer ) local participants = net.ReadTable() GAMEMODE.Gui:ShowMayorVoteWheel(participants) end ) function GM.Net:SendVote(participant) self:NewEvent( "jobs", "mayor_sv" ) net.WriteEntity(participant) self:FireEvent() end
DefineClass.ResourceItems = { __parents = {"ItemMenuBase"}, hide_single_category = true, align_pos = false, ScaleModifier = point(750,750), lines_stretch_time_init = 350, } function ResourceItems:Init() self.align_pos = GetUIStyleGamepad() and self.desktop.box:Center() or terminal:GetMousePos() self:SetModal() PlayFX("ItemSelectorIn", "start") UICity:Gossip("ItemSelector", "open") end function ResourceItems:Close() ItemMenuBase.Close(self) PlayFX("ItemSelectorOut", "start") UICity:Gossip("ItemSelector", "close") if self.context.on_close_callback then self.context.on_close_callback() end local igi = GetInGameInterface() if igi then if igi.mode_dialog then igi.mode_dialog:SetFocus() else igi:SetMode("selection") end end end function ResourceItems:UpdateLayout() local margins_x1, margins_y1, margins_x2, margins_y2 = ScaleXY(self.scale, self.Margins:xyxy()) local anchor = sizebox(self.align_pos, 1, 1) local safe_area_box = GetSafeAreaBox() local x, y = self.box:minxyz() local width, height = self.measure_width - margins_x1 - margins_x2, self.measure_height - margins_y1 - margins_y2 x = anchor:minx() + ((anchor:maxx() - anchor:minx()) - width)/2 y = anchor:miny() - height - margins_y2 if y<safe_area_box:miny() then x = anchor:minx() + ((anchor:maxx() - anchor:minx()) - width)/2 y = anchor:maxy() + margins_y2 end -- fit window to safe_area_box if x + width + margins_x2 > safe_area_box:maxx() then x = safe_area_box:maxx() - width - margins_x2 elseif x < safe_area_box:minx() then x = safe_area_box:minx() end if y + height + margins_y2 > safe_area_box:maxy() then y = safe_area_box:maxy() - height - margins_y2 elseif y < safe_area_box:miny() then y = safe_area_box:miny() end -- layout self:SetBox(x, y, width, height) return XControl.UpdateLayout(self) end function ResourceItems:GetCategories() return empty_table end function ResourceItems:GetItems(category_id) local buttons = {} local items = self.context.object:GetSelectorItems(self.context) if #items<=0 then self:delete() end for i=1, #items do local item = items[i] item.ButtonAlign = i%2==1 and "top" or "bottom" item.hint = item.hint or false item.gamepad_hint = item.gamepad_hint or false local button = HexButtonResource:new(item, self.idButtonsList) buttons[#buttons + 1] = button end return buttons end function ResourceItems:OpenItemsInterpolation(bFirst, set_focus) ItemMenuBase.OpenItemsInterpolation(self, bFirst, set_focus) self:CreateThread(function() local items = self.items local offs = self.idBottomBackWnd.box:miny() - self.idTopBackWnd.box:maxy() local item_pop_time = self.lines_stretch_time_init/#items local duration = item_pop_time for i = 1, #items do items[i]:SetVisible(true, "instant") if duration > 0 then if i % 2 == 0 then EdgeAnimation(true, items[i], 0, offs / 4, duration) else EdgeAnimation(true, items[i], 0, -offs / 4, duration) end end end self:SetInitFocus(set_focus) end) end function ResourceItems:OnXButtonDown(button, source) if button == "ButtonA" then local focus = self.desktop and self.desktop.keyboard_focus if focus then if focus:GetEnabled() then focus.idButton:Press() end end return "break" elseif button == "ButtonX" and self.context.meta_key then local focus = self.desktop and self.desktop.keyboard_focus if focus then if focus:GetEnabled() then focus.idButton:Press(nil, false, true) end end return "break" end return ItemMenuBase.OnXButtonDown(self, button, source) end function OpenResourceSelector(object, context) local dlg = GetXDialog("ResourceItems") if dlg then if dlg.context.object~=object then CloseXDialog("ResourceItems") else return end end context.object = object return OpenXDialog("ResourceItems", GetInGameInterface(), context) end function CloseResourceSelector() CloseXDialog("ResourceItems") end function OnMsg.UIModeChange(mode) CloseResourceSelector() end function OnMsg.SelectionChange() CloseResourceSelector() end
-- mydoors mod by don -- DO WHAT YOU WANT TO PUBLIC LICENSE -- or abbreviated DWYWPL -- December 2nd 2015 -- License Copyright (C) 2015 Michael Tomaino (PlatinumArts@gmail.com) -- www.sandboxgamemaker.com/DWYWPL/ -- DO WHAT YOU WANT TO PUBLIC LICENSE -- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION -- 1. You are allowed to do whatever you want to with what content is using this license. -- 2. This content is provided 'as-is', without any express or implied warranty. In no event -- will the authors be held liable for any damages arising from the use of this content. -- Retrieving mod settings local scifi_nodes = {} scifi_nodes.doors_open_with_mesecon_only = minetest.settings:get_bool("scifi_nodes.doors_open_with_mesecon_only", true) print("Ici !"..dump(scifi_nodes)) -- Some aliases to deal with old namming policy -- minetest.register_alias("scifi_nodes:doors_1a","scifi_nodes:Doom_door_closed") minetest.register_alias("scifi_nodes:doors_1b","scifi_nodes:Doom_door_closed_top") minetest.register_alias("scifi_nodes:doors_1c","scifi_nodes:Doom_door_opened") minetest.register_alias("scifi_nodes:doors_1d","scifi_nodes:Doom_door_opened_top") minetest.register_alias("scifi_nodes:doors_2a","scifi_nodes:black_door_closed") minetest.register_alias("scifi_nodes:doors_2b","scifi_nodes:black_door_closed_top") minetest.register_alias("scifi_nodes:doors_2c","scifi_nodes:black_door_opened") minetest.register_alias("scifi_nodes:doors_2d","scifi_nodes:black_door_opened_top") minetest.register_alias("scifi_nodes:doors_3a","scifi_nodes:white_door_closed") minetest.register_alias("scifi_nodes:doors_3b","scifi_nodes:white_door_closed_top") minetest.register_alias("scifi_nodes:doors_3c","scifi_nodes:white_door_opened") minetest.register_alias("scifi_nodes:doors_3d","scifi_nodes:white_door_opened_top") minetest.register_alias("scifi_nodes:doors_4a","scifi_nodes:green_door_closed") minetest.register_alias("scifi_nodes:doors_4b","scifi_nodes:green_door_closed_top") minetest.register_alias("scifi_nodes:doors_4c","scifi_nodes:green_door_opened") minetest.register_alias("scifi_nodes:doors_4d","scifi_nodes:green_door_opened_top") -- This table now uses named parameters and more convenient variables names local doors = { {base_name = "Doom", base_ingredient = "doors:door_obsidian_glass", sound = "scifi_nodes_door_mechanic"}, {base_name = "black", base_ingredient = "doors:door_steel", sound = "scifi_nodes_door_mechanic"}, {base_name = "white", base_ingredient = "doors:door_glass", sound = "scifi_nodes_door_normal"}, {base_name = "green", base_ingredient = "doors:door_wood", sound = "scifi_nodes_door_mechanic"}, {base_name = "blue", base_ingredient = "default:steel_block", sound = "scifi_nodes_door_normal"} } for _, current_door in ipairs(doors) do local closed = "scifi_nodes:"..current_door.base_name.."_door_closed" local closed_top = "scifi_nodes:"..current_door.base_name.."_door_closed_top" local opened = "scifi_nodes:"..current_door.base_name.."_door_opened" local opened_top = "scifi_nodes:"..current_door.base_name.."_door_opened_top" local base_name = current_door.base_name local base_ingredient = current_door.base_ingredient local sound = current_door.sound local doors_rightclick minetest.register_craft({ output = closed .. " 2", recipe = { {"scifi_nodes:white2", base_ingredient, "scifi_nodes:white2"}, {"scifi_nodes:black", base_ingredient, "scifi_nodes:black"} } }) function onplace(itemstack, placer, pointed_thing) -- Is there room enough ? local pos1 = pointed_thing.above local pos2 = {x=pos1.x, y=pos1.y, z=pos1.z} pos2.y = pos2.y+1 -- 2 nodes above if not minetest.registered_nodes[minetest.get_node(pos1).name].buildable_to or not minetest.registered_nodes[minetest.get_node(pos2).name].buildable_to or not placer or not placer:is_player() or minetest.is_protected(pos1, placer:get_player_name()) or minetest.is_protected(pos2, placer:get_player_name()) then return end local pt = pointed_thing.above local pt2 = {x=pt.x, y=pt.y, z=pt.z} pt2.y = pt2.y+1 -- Player look dir is converted to node rotation ? local p2 = minetest.dir_to_facedir(placer:get_look_dir()) -- Where to look for another door ? local pt3 = {x=pt.x, y=pt.y, z=pt.z} -- Door param2 depends of placer's look dir local p4 = 0 if p2 == 0 then pt3.x = pt3.x-1 p4 = 2 elseif p2 == 1 then pt3.z = pt3.z+1 p4 = 3 elseif p2 == 2 then pt3.x = pt3.x+1 p4 = 0 elseif p2 == 3 then pt3.z = pt3.z-1 p4 = 1 end -- First door of a pair is already there if minetest.get_node(pt3).name == closed then minetest.set_node(pt, {name=closed, param2=p4,}) minetest.set_node(pt2, {name=closed_top, param2=p4}) -- Placed door is the first of a pair else minetest.set_node(pt, {name=closed, param2=p2,}) minetest.set_node(pt2, {name=closed_top, param2=p2}) end itemstack:take_item(1) return itemstack; end function afterdestruct(pos, oldnode) minetest.set_node({x=pos.x,y=pos.y+1,z=pos.z},{name="air"}) end function open_door(pos, node, player, itemstack, pointed_thing) -- play sound minetest.sound_play(sound,{ max_hear_distance = 16, pos = pos, gain = 1.0 }) local timer = minetest.get_node_timer(pos) local a = minetest.get_node({x=pos.x, y=pos.y, z=pos.z-1}) local b = minetest.get_node({x=pos.x, y=pos.y, z=pos.z+1}) local c = minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z}) local d = minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z}) local e = minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z-1}) local f = minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z-1}) local g = minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z+1}) local h = minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z+1}) minetest.set_node(pos, {name=opened, param2=node.param2}) minetest.set_node({x=pos.x,y=pos.y+1,z=pos.z}, {name=opened_top, param2=node.param2}) if a.name == closed then minetest.set_node({x=pos.x, y=pos.y, z=pos.z-1}, {name=opened, param2=a.param2}) minetest.set_node({x=pos.x,y=pos.y+1,z=pos.z-1}, {name=opened_top, param2=a.param2}) end if b.name == closed then minetest.set_node({x=pos.x, y=pos.y, z=pos.z+1}, {name=opened, param2=b.param2}) minetest.set_node({x=pos.x,y=pos.y+1,z=pos.z+1}, {name=opened_top, param2=b.param2}) end if c.name == closed then minetest.set_node({x=pos.x+1, y=pos.y, z=pos.z}, {name=opened, param2=c.param2}) minetest.set_node({x=pos.x+1,y=pos.y+1,z=pos.z}, {name=opened_top, param2=c.param2}) end if d.name == closed then minetest.set_node({x=pos.x-1, y=pos.y, z=pos.z}, {name=opened, param2=d.param2}) minetest.set_node({x=pos.x-1,y=pos.y+1,z=pos.z}, {name=opened_top, param2=d.param2}) end if e.name == closed then minetest.set_node({x=pos.x+1, y=pos.y, z=pos.z-1}, {name=opened, param2=e.param2}) minetest.set_node({x=pos.x+1, y=pos.y+1, z=pos.z-1}, {name=opened_top, param2=e.param2}) end if f.name == closed then minetest.set_node({x=pos.x-1, y=pos.y, z=pos.z-1}, {name=opened, param2=f.param2}) minetest.set_node({x=pos.x-1, y=pos.y+1, z=pos.z-1}, {name=opened_top, param2=f.param2}) end if g.name == closed then minetest.set_node({x=pos.x+1, y=pos.y, z=pos.z+1}, {name=opened, param2=g.param2}) minetest.set_node({x=pos.x+1, y=pos.y+1, z=pos.z+1}, {name=opened_top, param2=g.param2}) end if h.name == closed then minetest.set_node({x=pos.x-1, y=pos.y, z=pos.z+1}, {name=opened, param2=h.param2}) minetest.set_node({x=pos.x-1, y=pos.y+1, z=pos.z+1}, {name=opened_top, param2=h.param2}) end timer:start(3) end if scifi_nodes.doors_open_with_mesecon_only then rightclick = nil end function afterplace(pos, placer, itemstack, pointed_thing) minetest.set_node({x=pos.x,y=pos.y+1,z=pos.z},{name=opened_top,param2=nodeu.param2}) end function ontimer(pos, elapsed) -- play sound minetest.sound_play(sound,{ max_hear_distance = 16, pos = pos, gain = 1.0 }) local node = minetest.get_node(pos) local a = minetest.get_node({x=pos.x, y=pos.y, z=pos.z-1}) local b = minetest.get_node({x=pos.x, y=pos.y, z=pos.z+1}) local c = minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z}) local d = minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z}) local e = minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z-1}) local f = minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z-1}) local g = minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z+1}) local h = minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z+1}) minetest.set_node(pos, {name=closed, param2=node.param2}) minetest.set_node({x=pos.x,y=pos.y+1,z=pos.z}, {name=closed_top, param2=node.param2}) if a.name == opened then minetest.set_node({x=pos.x, y=pos.y, z=pos.z-1}, {name=closed, param2=a.param2}) minetest.set_node({x=pos.x,y=pos.y+1,z=pos.z-1}, {name=closed_top, param2=a.param2}) end if b.name == opened then minetest.set_node({x=pos.x, y=pos.y, z=pos.z+1}, {name=closed, param2=b.param2}) minetest.set_node({x=pos.x,y=pos.y+1,z=pos.z+1}, {name=closed_top, param2=b.param2}) end if c.name == opened then minetest.set_node({x=pos.x+1, y=pos.y, z=pos.z}, {name=closed, param2=c.param2}) minetest.set_node({x=pos.x+1,y=pos.y+1,z=pos.z}, {name=closed_top, param2=c.param2}) end if d.name == opened then minetest.set_node({x=pos.x-1, y=pos.y, z=pos.z}, {name=closed, param2=d.param2}) minetest.set_node({x=pos.x-1,y=pos.y+1,z=pos.z}, {name=closed_top, param2=d.param2}) end if e.name == opened then minetest.set_node({x=pos.x+1, y=pos.y, z=pos.z-1}, {name=closed, param2=e.param2}) minetest.set_node({x=pos.x+1, y=pos.y+1, z=pos.z-1}, {name=closed_top, param2=e.param2}) end if f.name == opened then minetest.set_node({x=pos.x-1, y=pos.y, z=pos.z-1}, {name=closed, param2=f.param2}) minetest.set_node({x=pos.x-1, y=pos.y+1, z=pos.z-1}, {name=closed_top, param2=f.param2}) end if g.name == opened then minetest.set_node({x=pos.x+1, y=pos.y, z=pos.z+1}, {name=closed, param2=g.param2}) minetest.set_node({x=pos.x+1, y=pos.y+1, z=pos.z+1}, {name=closed_top, param2=g.param2}) end if h.name == opened then minetest.set_node({x=pos.x-1, y=pos.y, z=pos.z+1}, {name=closed, param2=h.param2}) minetest.set_node({x=pos.x-1, y=pos.y+1, z=pos.z+1}, {name=closed_top, param2=h.param2}) end end local mesecons_doors_rules = { -- get signal from pressure plate {x=-1, y=0, z=0}, {x=0, y=0, z=1}, {x=0, y=0, z=-1}, {x=1, y=0, z=0}, -- get signal from wall mounted button {x=-1, y=1, z=-1}, {x=-1, y=1, z=1}, {x=0, y=1, z=-1}, {x=0, y=1, z=1}, {x=1, y=1, z=-1}, {x=1, y=1, z=1}, {x=-1, y=1, z=0}, {x=1, y=1, z=0}, } local mesecons_doors_def = { effector = { action_on = open_door, rules = mesecons_doors_rules }, } local doors_rightclick if scifi_nodes.doors_open_with_mesecon_only then doors_rightclick = {} else doors_rightclick = open_door end minetest.register_node(closed, { description = current_door.base_name.." sliding door", inventory_image = "scifi_nodes_door_"..base_name.."_inv.png", wield_image = "scifi_nodes_door_"..base_name.."_inv.png", tiles = { "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_rbottom.png", "scifi_nodes_door_"..base_name.."_bottom.png" }, drawtype = "nodebox", paramtype = "light", paramtype2 = "facedir", groups = {cracky = 3, oddly_breakable_by_hand = 1}, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.0625, 0.5, 0.5, 0.0625} } }, selection_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.0625, 0.5, 1.5, 0.0625} } }, mesecons = mesecons_doors_def, on_place = onplace, after_destruct = afterdestruct, on_rightclick = rightclick, }) minetest.register_node(closed_top, { tiles = { "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_rtop.png", "scifi_nodes_door_"..base_name.."_top.png" }, drawtype = "nodebox", paramtype = "light", paramtype2 = "facedir", groups = {cracky = 1}, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.0625, 0.5, 0.5, 0.0625} } }, selection_box = { type = "fixed", fixed = { {0, 0, 0, 0, 0, 0}, } }, }) minetest.register_node(opened, { tiles = { "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_rbottom0.png", "scifi_nodes_door_"..base_name.."_bottom0.png" }, drawtype = "nodebox", paramtype = "light", paramtype2 = "facedir", drop = closed, groups = {cracky = 1}, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.0625, -0.25, 0.5, 0.0625}, } }, selection_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.0625, -0.25, 1.5, 0.0625}, } }, after_place_node = afterplace, after_destruct = afterdestruct, on_timer = ontimer, }) minetest.register_node(opened_top, { tiles = { "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_edge.png", "scifi_nodes_door_"..base_name.."_rtopo.png", "scifi_nodes_door_"..base_name.."_topo.png" }, drawtype = "nodebox", paramtype = "light", paramtype2 = "facedir", groups = {cracky = 1}, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.0625, -0.25, 0.5, 0.0625}, } }, selection_box = { type = "fixed", fixed = { {0, 0, 0, 0, 0, 0}, } }, }) end -- end of doors table browsing
return { source = { type = 'dist', location = 'https://download.samba.org/pub/rsync/rsync-3.1.2.tar.gz', sha256sum = 'ecfa62a7fa3c4c18b9eccd8c16eaddee4bd308a76ea50b5c02a5840f09c0a1c2' }, build = { type = 'gnu' } }
package.path = './?.lua;' .. package.path local generator = require("bin.scaffold.generator") local lor = require("bin.scaffold.launcher") local version = require("lor.version") local usages = [[lor v]] .. version .. [[, a Lua web framework based on OpenResty. Usage: lord COMMAND [OPTIONS] Commands: new [name] Create a new application start Start running app server stop Stop the server restart Restart the server version Show version of lor help Show help tips path Show install path ]] local function exec(args) local arg = table.remove(args, 1) -- parse commands and options if arg == 'new' and args[1] then generator.new(args[1]) -- generate example code elseif arg == 'start' then lor.start() -- start application elseif arg == 'stop' then lor.stop() -- stop application elseif arg == 'restart' then lor.stop() lor.start() elseif arg == 'reload' then lor.reload() elseif arg == 'help' or arg == '-h' then print(usages) elseif arg == 'version' or arg == '-v' then print(version) -- show lor framework version elseif arg == nil then print(usages) else print("[lord] unsupported commands or options, `lord -h` to check usages.") end end return exec
return { variables = { {name = "random-splitter", type = "entity-expression", value = {type = "random-of-entity-type", entity_type = "splitter"}} }, entities = { {{type = "variable", name = "random-splitter"}, {x = 0, y = -1.5}, {dir = "south", dmg = {dmg = {type = "random", min = 30, max = 300}}}}, {{type = "variable", name = "random-splitter"}, {x = 1, y = -0.5}, {dir = "south", dmg = {dmg = {type = "random", min = 30, max = 300}}}}, {{type = "variable", name = "random-splitter"}, {x = 2, y = -1.5}, {dir = "south", dmg = {dmg = {type = "random", min = 30, max = 300}}}}, {{type = "variable", name = "random-splitter"}, {x = 0, y = 0.5}, {dir = "south", dmg = {dmg = {type = "random", min = 30, max = 300}}}}, {{type = "variable", name = "random-splitter"}, {x = 1, y = 1.5}, {dir = "south", dmg = {dmg = {type = "random", min = 30, max = 300}}}}, {{type = "variable", name = "random-splitter"}, {x = 2, y = 0.5}, {dir = "south", dmg = {dmg = {type = "random", min = 30, max = 300}}}}, }, }
-- -- Majordomo Protocol worker example -- Uses the mdwrk API to hide all MDP aspects -- -- Author: Robert G. Jakabosky <bobby@sharedrealm.com> -- require"mdwrkapi" require"zmsg" local verbose = (arg[1] == "-v") local session = mdwrkapi.new("tcp://localhost:5555", "echo", verbose) local reply while true do local request = session:recv(reply) if not request then break -- Worker was interrupted end reply = request -- Echo is complex... :-) end session:destroy()
Map = Object:extend() require "tilemap/tiledmap" function Map:new() _G.map = loadTiledMap('tilemap/map_data'); end function Map:update(dt) end function Map.draw() _G.map:draw() end
--- The player library is used to get the Lua objects that represent players in-game. _G.player = {} --- Similar to the serverside command "bot", this function creates a new Player bot with the given name. This bot will not obey to the usual "bot_*" commands, and it's the same bot base used in TF2 and CS:S. --- The best way to control the behaviour of a Player bot right now is to use the GM:StartCommand hook and modify its input serverside. --- ℹ **NOTE**: Despite this Player being fake, it has to be removed from the server by using Player:Kick and **NOT** Entity:Remove. --- Also keep in mind that these bots still use player slots, so you won't be able to spawn them in singleplayer! --- ℹ **NOTE**: Any Bot created using this method will be considered UnAuthed by Garry's Mod --- @param botName string @The name of the bot, using an already existing name will append brackets at the end of it with a number pertaining it --- @return GPlayer @The newly created Player bot function player.CreateNextBot(botName) end --- Gets all the current players in the server (not including connecting clients). --- ℹ **NOTE**: This function returns bots as well as human players. See player.GetBots and player.GetHumans. --- ℹ **NOTE**: This function returns sequential table, this means it should be looped with Global.ipairs instead of Global.pairs for efficiency reasons! --- @return table @All Players currently in the server. function player.GetAll() end --- Returns a table of all bots on the server. --- @return table @A table only containing bots ( AI / non human players ) function player.GetBots() end --- Gets the player with the specified AccountID. --- @param accountID string @The Player:AccountID to find the player by. --- @return GPlayer @Player if one is found, false otherwise. function player.GetByAccountID(accountID) end --- Gets the player with the specified connection ID. --- Connection ID can be retrieved via gameevent.Listen events. --- 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 Player:UserID, see Global.Player. --- @param connectionID number @The connection ID to find the player by. --- @return GPlayer @Player if one is found, nil otherwise function player.GetByID(connectionID) end --- Gets the player with the specified SteamID. --- @param steamID string @The Player:SteamID to find the player by. --- @return GPlayer @Player if one is found, false otherwise. function player.GetBySteamID(steamID) end --- Gets the player with the specified SteamID64. --- @param steamID64 string @The Player:SteamID64 to find the player by --- @return GPlayer @Player if one is found, false otherwise. function player.GetBySteamID64(steamID64) end --- Gets the player with the specified uniqueID (not recommended way to identify players). --- ⚠ **WARNING**: It is highly recommended to use player.GetByAccountID, player.GetBySteamID or player.GetBySteamID64 instead as this function can have collisions ( be same for different people ) while SteamID is guaranteed to unique to each player. --- @param uniqueID string @The Player:UniqueID to find the player by. --- @return GPlayer @Player if one is found, false otherwise. function player.GetByUniqueID(uniqueID) end --- Gives you the player count. Similar to **#**player.GetAll but with much better performance. --- @return number @Number of players function player.GetCount() end --- Returns a table of all human ( non bot/AI ) players. --- Unlike player.GetAll, this does not include bots. --- @return table @A table of all human ( non bot/AI ) players. function player.GetHumans() end
local t = ...; t = Def.ActorFrame{ Def.Sprite { Texture="ScreenPlayerOptions LineHighlight P2 1x2"; Frame0000=0; Delay0000=0.5; Frame0001=1; Delay0001=0.5; InitCommand=cmd(addx,458); }; LoadActor("Colour.png")..{ InitCommand=cmd(addx,458-100+2;addy,1;zoomy,0.98;zoomx,1.007); }; }; return t;
function getRun(i, param) local i = i local param = param return function () --print("test"); --[[if i == 1 then i = 0 print "aqui" print(io.read()) end]] --luajava.bindClass("java.lang.String") print("teste2 "..i); --luajava.bindClass("java.lang.Thread"):sleep(100) luajava.newInstance("java.lang.String", "lalala"); --print("fim thread"); print(gcinfo()); print(param:toString()); end end for i=0,100 do f = luajava.createProxy("java.lang.Runnable",{run=getRun(i, luajava.newInstance("java.lang.String", "str param"))}); --print(f:toString()) t = luajava.newInstance("java.lang.Thread", f); print(t:toString()) t:start() --t:run() --t:join() end for i=0,5000 do --luajava.bindClass("java.lang.String") end print("fim main"); --luajava.bindClass("java.lang.Thread"):sleep(100)
local Types = require('orgmode.parser.types') local parser = require('orgmode.parser') local Range = require('orgmode.parser.range') local Date = require('orgmode.objects.date') local config = require('orgmode.config') describe('Parser', function() it('should parse filetags headline', function() local lines = { '#+FILETAGS: :Tag1:Tag2:', '* TODO Something with a lot of tags :WORK:', } local parsed = parser.parse(lines, 'todos') assert.are.same(parsed.tags, { 'Tag1', 'Tag2' }) assert.are.same(false, parsed.is_archive_file) assert.are.same({ content = {}, dates = {}, headlines = {}, level = 1, line = '* TODO Something with a lot of tags :WORK:', id = 2, range = Range.from_line(2), parent = parsed, type = 'HEADLINE', archived = false, title = 'Something with a lot of tags', priority = '', properties = { items = {} }, todo_keyword = { type = 'TODO', value = 'TODO', range = Range:new({ start_line = 2, end_line = 2, start_col = 3, end_col = 6, }), }, tags = { 'Tag1', 'Tag2', 'WORK' }, category = 'todos', file = '', }, parsed:get_item( 2 )) end) it('should parse lines', function() local lines = { 'Top level content', '* TODO Test orgmode', '** TODO [#A] Test orgmode level 2 :PRIVATE:', 'Some content for level 2', '*** TODO [#1] Level 3', 'Content Level 3', '* DONE top level todo :WORK:', 'content for top level todo', '* TODO top level todo with multiple tags :OFFICE:PROJECT:', 'multiple tags content, tags not read from content :FROMCONTENT:', '** TODO Working on this now :OFFICE:NESTED:', '* NOKEYWORD Headline with wrong todo keyword and wrong tag format :WORK : OFFICE:', } local parsed = parser.parse(lines, 'todos') assert.are.same({ level = 0, line = 'Top level content', range = Range.from_line(1), id = 1, parent = parsed, dates = {}, type = 'CONTENT', }, parsed:get_item( 1 )) assert.are.same({ content = {}, dates = {}, headlines = { parsed:get_item(3) }, level = 1, line = '* TODO Test orgmode', range = Range:new({ start_line = 2, end_line = 6 }), id = 2, parent = parsed, priority = '', properties = { items = {} }, title = 'Test orgmode', type = 'HEADLINE', archived = false, category = 'todos', file = '', todo_keyword = { value = 'TODO', type = 'TODO', range = Range:new({ start_line = 2, end_line = 2, start_col = 3, end_col = 6, }), }, tags = {}, }, parsed:get_item( 2 )) assert.are.same({ content = { parsed:get_item(4) }, dates = {}, headlines = { parsed:get_item(5) }, level = 2, line = '** TODO [#A] Test orgmode level 2 :PRIVATE:', range = Range:new({ start_line = 3, end_line = 6 }), id = 3, parent = parsed:get_item(2), priority = 'A', properties = { items = {} }, title = '[#A] Test orgmode level 2', type = 'HEADLINE', archived = false, category = 'todos', file = '', todo_keyword = { value = 'TODO', type = 'TODO', range = Range:new({ start_line = 3, end_line = 3, start_col = 4, end_col = 7, }), }, tags = { 'PRIVATE' }, }, parsed:get_item( 3 )) assert.are.same({ level = 2, line = 'Some content for level 2', id = 4, range = Range.from_line(4), dates = {}, parent = parsed:get_item(3), type = 'CONTENT', }, parsed:get_item( 4 )) assert.are.same({ content = { parsed:get_item(6) }, dates = {}, headlines = {}, level = 3, line = '*** TODO [#1] Level 3', id = 5, range = Range:new({ start_line = 5, end_line = 6 }), parent = parsed:get_item(3), priority = '1', properties = { items = {} }, title = '[#1] Level 3', type = 'HEADLINE', archived = false, category = 'todos', file = '', todo_keyword = { value = 'TODO', type = 'TODO', range = Range:new({ start_line = 5, end_line = 5, start_col = 5, end_col = 8, }), }, tags = { 'PRIVATE' }, }, parsed:get_item( 5 )) assert.are.same({ level = 3, line = 'Content Level 3', id = 6, range = Range.from_line(6), dates = {}, parent = parsed:get_item(5), type = 'CONTENT', }, parsed:get_item( 6 )) assert.are.same({ content = { parsed:get_item(8) }, dates = {}, headlines = {}, level = 1, line = '* DONE top level todo :WORK:', id = 7, priority = '', properties = { items = {} }, range = Range:new({ start_line = 7, end_line = 8 }), title = 'top level todo', parent = parsed, type = 'HEADLINE', archived = false, category = 'todos', file = '', todo_keyword = { value = 'DONE', type = 'DONE', range = Range:new({ start_line = 7, end_line = 7, start_col = 3, end_col = 6, }), }, tags = { 'WORK' }, }, parsed:get_item( 7 )) assert.are.same({ level = 1, line = 'content for top level todo', id = 8, range = Range.from_line(8), parent = parsed:get_item(7), dates = {}, type = 'CONTENT', }, parsed:get_item( 8 )) assert.are.same({ content = { parsed:get_item(10) }, dates = {}, headlines = { parsed:get_item(11) }, level = 1, line = '* TODO top level todo with multiple tags :OFFICE:PROJECT:', id = 9, range = Range:new({ start_line = 9, end_line = 11 }), parent = parsed, priority = '', properties = { items = {} }, title = 'top level todo with multiple tags', type = 'HEADLINE', archived = false, category = 'todos', file = '', todo_keyword = { value = 'TODO', type = 'TODO', range = Range:new({ start_line = 9, end_line = 9, start_col = 3, end_col = 6, }), }, tags = { 'OFFICE', 'PROJECT' }, }, parsed:get_item( 9 )) assert.are.same({ level = 1, line = 'multiple tags content, tags not read from content :FROMCONTENT:', id = 10, range = Range.from_line(10), dates = {}, parent = parsed:get_item(9), type = 'CONTENT', }, parsed:get_item( 10 )) assert.are.same({ content = {}, dates = {}, headlines = {}, level = 2, line = '** TODO Working on this now :OFFICE:NESTED:', id = 11, range = Range.from_line(11), parent = parsed:get_item(9), type = 'HEADLINE', archived = false, category = 'todos', file = '', priority = '', properties = { items = {} }, title = 'Working on this now', todo_keyword = { value = 'TODO', type = 'TODO', range = Range:new({ start_line = 11, end_line = 11, start_col = 4, end_col = 7, }), }, tags = { 'OFFICE', 'PROJECT', 'NESTED' }, }, parsed:get_item( 11 )) assert.are.same({ content = {}, dates = {}, headlines = {}, level = 1, line = '* NOKEYWORD Headline with wrong todo keyword and wrong tag format :WORK : OFFICE:', id = 12, range = Range.from_line(12), parent = parsed, priority = '', properties = { items = {} }, title = 'NOKEYWORD Headline with wrong todo keyword and wrong tag format :WORK : OFFICE:', type = 'HEADLINE', archived = false, category = 'todos', file = '', todo_keyword = { value = '', type = '' }, tags = {}, }, parsed:get_item( 12 )) assert.are.same(0, parsed.level) assert.are.same(0, parsed.id) assert.are.same(lines, parsed.lines) assert.are.same(false, parsed.is_archive_file) assert.are.same( Range:new({ start_line = 1, end_line = 12, }), parsed.range ) assert.are.same(4, #parsed.headlines) assert.are.same(parsed.headlines[1], parsed.items[2]) assert.are.same(parsed.headlines[2], parsed.items[7]) assert.are.same(parsed.headlines[3], parsed.items[9]) assert.are.same(parsed.headlines[4], parsed.items[12]) end) it('should parse headline and its planning dates', function() local lines = { '* TODO Test orgmode <2021-05-15 Sat> :WORK:', 'DEADLINE: <2021-05-20 Thu> SCHEDULED: <2021-05-18> CLOSED: <2021-05-21 Fri>', '* TODO get deadline only if first line after headline', 'Some content', 'DEADLINE: <2021-05-22 Sat>', } local parsed = parser.parse(lines, 'work') assert.are.same({ content = { parsed:get_item(2) }, dates = { Date.from_string('2021-05-15 Sat', { active = true, range = Range:new({ start_line = 1, end_line = 1, start_col = 21, end_col = 36, }), }), Date.from_string('2021-05-20 Thu', { type = 'DEADLINE', active = true, range = Range:new({ start_line = 2, end_line = 2, start_col = 11, end_col = 26, }), }), Date.from_string('2021-05-18', { type = 'SCHEDULED', active = true, range = Range:new({ start_line = 2, end_line = 2, start_col = 39, end_col = 50, }), }), Date.from_string('2021-05-21 Fri', { type = 'CLOSED', active = true, range = Range:new({ start_line = 2, end_line = 2, start_col = 60, end_col = 75, }), }), }, headlines = {}, level = 1, line = '* TODO Test orgmode <2021-05-15 Sat> :WORK:', id = 1, range = Range:new({ start_line = 1, end_line = 2, }), parent = parsed, priority = '', properties = { items = {} }, title = 'Test orgmode <2021-05-15 Sat>', type = 'HEADLINE', archived = false, category = 'work', file = '', todo_keyword = { value = 'TODO', type = 'TODO', range = Range:new({ start_line = 1, end_line = 1, start_col = 3, end_col = 6, }), }, tags = { 'WORK' }, }, parsed:get_item( 1 )) assert.are.same({ level = 1, line = 'DEADLINE: <2021-05-20 Thu> SCHEDULED: <2021-05-18> CLOSED: <2021-05-21 Fri>', id = 2, range = Range:new({ start_line = 2, end_line = 2, }), parent = parsed:get_item(1), type = 'PLANNING', dates = { Date.from_string('2021-05-20 Thu', { type = 'DEADLINE', active = true, range = Range:new({ start_line = 2, end_line = 2, start_col = 11, end_col = 26, }), }), Date.from_string('2021-05-18', { type = 'SCHEDULED', active = true, range = Range:new({ start_line = 2, end_line = 2, start_col = 39, end_col = 50, }), }), Date.from_string('2021-05-21 Fri', { type = 'CLOSED', active = true, range = Range:new({ start_line = 2, end_line = 2, start_col = 60, end_col = 75, }), }), }, }, parsed:get_item( 2 )) assert.are.same({ content = { parsed:get_item(4), parsed:get_item(5) }, dates = { Date.from_string('2021-05-22 Sat', { active = true, type = 'NONE', range = Range:new({ start_line = 5, end_line = 5, start_col = 11, end_col = 26, }), }), }, headlines = {}, level = 1, line = '* TODO get deadline only if first line after headline', id = 3, range = Range:new({ start_line = 3, end_line = 5, }), parent = parsed, priority = '', properties = { items = {} }, title = 'get deadline only if first line after headline', type = 'HEADLINE', archived = false, category = 'work', file = '', todo_keyword = { value = 'TODO', type = 'TODO', range = Range:new({ start_line = 3, end_line = 3, start_col = 3, end_col = 6, }), }, tags = {}, }, parsed:get_item( 3 )) assert.are.same({ level = 1, line = 'Some content', range = Range:new({ start_line = 4, end_line = 4, }), id = 4, dates = {}, parent = parsed:get_item(3), type = 'CONTENT', }, parsed:get_item( 4 )) assert.are.same({ level = 1, line = 'DEADLINE: <2021-05-22 Sat>', dates = { Date.from_string('2021-05-22 Sat', { type = 'DEADLINE', active = true, range = Range:new({ start_line = 5, end_line = 5, start_col = 11, end_col = 26, }), }), }, range = Range:new({ start_line = 5, end_line = 5, }), id = 5, parent = parsed:get_item(3), type = Types.PLANNING, }, parsed:get_item( 5 )) end) it('should parse properties drawer', function() local lines = { '* TODO Test orgmode :WORK:', 'DEADLINE: <2021-05-10 11:00>', ':PROPERTIES:', ':SOME_PROP: some value', ':END:', '* TODO Another todo', } local parsed = parser.parse(lines, 'work') assert.are.same({ content = { parsed:get_item(2), parsed:get_item(3), parsed:get_item(4), parsed:get_item(5), }, dates = { Date.from_string('2021-05-10 11:00', { type = 'DEADLINE', active = true, range = Range:new({ start_line = 2, end_line = 2, start_col = 11, end_col = 28, }), }), }, headlines = {}, level = 1, line = '* TODO Test orgmode :WORK:', id = 1, range = Range:new({ start_line = 1, end_line = 5, }), parent = parsed, type = 'HEADLINE', archived = false, title = 'Test orgmode', priority = '', properties = { items = { SOME_PROP = 'some value', }, range = Range:new({ start_line = 3, end_line = 5, }), valid = true, }, todo_keyword = { value = 'TODO', type = 'TODO', range = Range:new({ start_line = 1, end_line = 1, start_col = 3, end_col = 6, }), }, tags = { 'WORK' }, category = 'work', file = '', }, parsed:get_item( 1 )) assert.are.same({ level = 1, line = 'DEADLINE: <2021-05-10 11:00>', dates = { Date.from_string('2021-05-10 11:00', { type = 'DEADLINE', active = true, range = Range:new({ start_line = 2, end_line = 2, start_col = 11, end_col = 28, }), }), }, range = Range:new({ start_line = 2, end_line = 2, }), id = 2, parent = parsed:get_item(1), type = Types.PLANNING, }, parsed:get_item( 2 )) assert.are.same({ level = 1, line = ':PROPERTIES:', dates = {}, range = Range:new({ start_line = 3, end_line = 3, }), id = 3, parent = parsed:get_item(1), type = Types.DRAWER, drawer = { name = 'PROPERTIES', }, }, parsed:get_item( 3 )) assert.are.same({ level = 1, line = ':SOME_PROP: some value', dates = {}, range = Range:new({ start_line = 4, end_line = 4, }), id = 4, parent = parsed:get_item(1), type = Types.DRAWER, drawer = { properties = { SOME_PROP = 'some value', }, }, }, parsed:get_item( 4 )) assert.are.same({ level = 1, line = ':END:', dates = {}, range = Range:new({ start_line = 5, end_line = 5, }), id = 5, parent = parsed:get_item(1), type = Types.DRAWER, drawer = { ended = true, }, }, parsed:get_item( 5 )) end) it('should not parse properties that are not in the :PROPERTIES: drawer', function() local lines = { '* TODO Test orgmode :WORK:', 'DEADLINE: <2021-05-10 11:00>', ':SOME_PROP: some value', ':END:', '* TODO Another todo', } local parsed = parser.parse(lines, 'work') assert.are.same({ items = {} }, parsed:get_item(1).properties) end) it('should parse properties only if its positioned after headline or planning date', function() local lines = { '* TODO Test orgmode :WORK:', 'DEADLINE: <2021-05-10 11:00>', 'Some content in between', ':PROPERTIES:', ':SOME_PROP: some value', ':END:', '* TODO Another todo', } local parsed = parser.parse(lines, 'work') local headline = parsed:get_item(1) assert.are.same({}, headline.properties.items) lines = { '* TODO Test orgmode :WORK:', 'Some content in between', ':PROPERTIES:', ':SOME_PROP: some value', ':END:', '* TODO Another todo', } parsed = parser.parse(lines, 'work') headline = parsed:get_item(1) assert.are.same({}, headline.properties.items) lines = { '* TODO Test orgmode :WORK:', ':PROPERTIES:', ':SOME_PROP: some value', ':END:', '* TODO Another todo', } parsed = parser.parse(lines, 'work') headline = parsed:get_item(1) assert.are.same({ SOME_PROP = 'some value' }, headline.properties.items) lines = { '* TODO Test orgmode :WORK:', 'DEADLINE: <2021-05-10 11:00>', ':PROPERTIES:', ':SOME_PROP: some value', ':END:', '* TODO Another todo', } parsed = parser.parse(lines, 'work') headline = parsed:get_item(1) assert.are.same({ SOME_PROP = 'some value' }, headline.properties.items) end) it('should override headline category from property', function() local lines = { '* TODO Test orgmode :WORK:', 'DEADLINE: <2021-05-10 11:00>', ':PROPERTIES:', ':SOME_PROP: some value', ':END:', '* TODO Another todo', } local parsed = parser.parse(lines, 'work') assert.are.same('work', parsed:get_item(1):get_category()) lines = { '* TODO Test orgmode :WORK:', 'DEADLINE: <2021-05-10 11:00>', ':PROPERTIES:', ':SOME_PROP: some value', ':CATEGORY: my-category', ':END:', '* TODO Another todo', } parsed = parser.parse(lines, 'work') assert.are.same('my-category', parsed:get_item(1):get_category()) end) it('should parse source code #BEGIN_SRC filetype', function() local lines = { '* TODO Test orgmode :WORK:', 'DEADLINE: <2021-05-10 11:00>', '#+BEGIN_SRC javascript', 'console.log("test");', '#+END_SRC', '* TODO Another todo', } local parsed = parser.parse(lines, 'work') assert.are.same({ 'javascript' }, parsed.source_code_filetypes) end) it('should consider file archived if file name is matching org-archive-location setting', function() local lines = { '* TODO Test orgmode :WORK:', 'DEADLINE: <2021-05-10 11:00>', '#+BEGIN_SRC javascript', 'console.log("test");', '#+END_SRC', '* TODO Another todo', } local parsed = parser.parse(lines, 'work', '/tmp/my-work.org_archive', true) assert.are.same(parsed.is_archive_file, true) end) it('should properly handle tag inheritance', function() local lines = { '#+FILETAGS: TOPTAG', '', '* TODO Test orgmode :WORK:MYPROJECT:', ' First level content', '** TODO Level 2 todo :CHILDPROJECT:', ' Second level content', '*** TODO Child todo', } local parsed = parser.parse(lines, 'work', '') assert.are.same({ 'TOPTAG', 'WORK', 'MYPROJECT' }, parsed:get_item(3).tags) assert.are.same({ 'TOPTAG', 'WORK', 'MYPROJECT', 'CHILDPROJECT' }, parsed:get_item(5).tags) assert.are.same({ 'TOPTAG', 'WORK', 'MYPROJECT', 'CHILDPROJECT' }, parsed:get_item(7).tags) config:extend({ org_use_tag_inheritance = false }) parsed = parser.parse(lines, 'work', '') assert.are.same({ 'WORK', 'MYPROJECT' }, parsed:get_item(3).tags) assert.are.same({ 'CHILDPROJECT' }, parsed:get_item(5).tags) assert.are.same({}, parsed:get_item(7).tags) config:extend({ org_use_tag_inheritance = true, org_tags_exclude_from_inheritance = { 'MYPROJECT' } }) parsed = parser.parse(lines, 'work', '') assert.are.same({ 'TOPTAG', 'WORK', 'MYPROJECT' }, parsed:get_item(3).tags) assert.are.same({ 'TOPTAG', 'WORK', 'CHILDPROJECT' }, parsed:get_item(5).tags) assert.are.same({ 'TOPTAG', 'WORK', 'CHILDPROJECT' }, parsed:get_item(7).tags) end) end)
-- TODO: actually implement this later, for now ripple works fine with just name swaps on top of it for naming consistency. Sound = function(asset_name, options) return ripple.newSound(love.audio.newSource('assets/sounds/' .. asset_name, 'static'), options) end SoundTag = ripple.newTag Effect = love.audio.setEffect
local Class = require "Base.Class" local Object = require "Base.Object" local Env = require "Env" local FileSystem = require "Card.FileSystem" local Serialization = require "Persist.Serialization" local Utils = require "Utils" local Path = require "Path" local Preset = Class {} Preset:include(Object) function Preset:init(data) self:setClassName("Preset") self.data = data end function Preset:write(fullpath) local data = self.data if data then data.firmwareVersion = app.FIRMWARE_VERSION return Serialization.writeTable(fullpath, data) end end function Preset:read(fullpath) self.data = Serialization.readTable(fullpath) return self.data ~= nil end function Preset:get(xpath) return self.data and Serialization.get(xpath, self.data) end -- This routine is trying to cover the different ways version info was encoded in presets in the past. function Preset:getVersionString() local defaultVersion = "0.0.00" if self.data == nil then return defaultVersion end local V = self.data.firmwareVersion or self.data.version if V == nil then return defaultVersion end if type(V) == "string" then return V end if type(V) == "table" then if V.SimpleString then return V.SimpleString elseif V.Major and V.Minor and V.Build then return string.format("%d.%d.%02d", V.Major, V.Minor, V.Build) end end return defaultVersion end local function walkHelper(value, path, callback) for k, v in pairs(value) do if type(v) == "table" then walkHelper(v, path .. "." .. k, callback) else callback(path, k, v) end end end -- Traverse the preset data executing the callback on each non-table element. -- callback(path, key, value) function Preset:walk(callback) walkHelper(self.data, "", callback) end return Preset
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:25' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] local GAMEPAD_AVA_ROOT_SCENE_NAME = "gamepad_campaign_root" local CAMPAIGN_BROWSER_MODES = { CAMPAIGNS = 1, BONUSES = 2, CAMPAIGN_RULESET_TYPES = 3, } local ENTRY_TYPES = { CAMPAIGN = 1, BONUSES = 2, SCORING = 3, EMPERORSHIP = 4, ENTER_CAMPAIGN = 5, TRAVEL_TO_CAMPAIGN = 6, LEAVE_QUEUE = 7, SET_HOME = 8, ABANDON_CAMPAIGN = 9, CAMPAIGN_RULESET_TYPE = 10, } local CONTENT_TYPES = { BONUSES = 1, SCORING = 2, EMPERORSHIP = 3, CAMPAIGN = 4, CAMPAIGN_RULESET_TYPE = 5, } local ICON_ENTER = "EsoUI/Art/Campaign/Gamepad/gp_campaign_menuIcon_enter.dds" local ICON_TRAVEL = "EsoUI/Art/Campaign/Gamepad/gp_campaign_menuIcon_travel.dds" local ICON_LEAVE = "EsoUI/Art/Campaign/Gamepad/gp_campaign_menuIcon_leave.dds" local ICON_ABANDON = "EsoUI/Art/Campaign/Gamepad/gp_campaign_menuIcon_abandon.dds" local ICON_HOME = "EsoUI/Art/Campaign/Gamepad/gp_overview_menuIcon_home.dds" local ICON_BONUS = "EsoUI/Art/Campaign/Gamepad/gp_overview_menuIcon_bonus.dds" local ICON_SCORING = "EsoUI/Art/Campaign/Gamepad/gp_overview_menuIcon_scoring.dds" local ICON_EMPEROR = "EsoUI/Art/Campaign/Gamepad/gp_overview_menuIcon_emperor.dds" ZO_CampaignBrowser_Gamepad = ZO_Gamepad_ParametricList_Screen:Subclass() function ZO_CampaignBrowser_Gamepad:New(...) return ZO_Gamepad_ParametricList_Screen.New(self, ...) end function ZO_CampaignBrowser_Gamepad:Initialize(control) GAMEPAD_AVA_ROOT_SCENE = ZO_Scene:New(GAMEPAD_AVA_ROOT_SCENE_NAME, SCENE_MANAGER) local ACTIVATE_LIST_ON_SHOW = true ZO_Gamepad_ParametricList_Screen.Initialize(self, control, ZO_GAMEPAD_HEADER_TABBAR_DONT_CREATE, ACTIVATE_LIST_ON_SHOW, GAMEPAD_AVA_ROOT_SCENE) end -- Override function ZO_CampaignBrowser_Gamepad:SetupList(list) list:AddDataTemplate("ZO_GamepadNewMenuEntryTemplate", ZO_SharedGamepadEntry_OnSetup, ZO_GamepadMenuEntryTemplateParametricListFunction) list:AddDataTemplateWithHeader("ZO_GamepadNewMenuEntryTemplate", ZO_SharedGamepadEntry_OnSetup, ZO_GamepadMenuEntryTemplateParametricListFunction, nil, "ZO_GamepadMenuEntryHeaderTemplate") end function ZO_CampaignBrowser_Gamepad:OnShowing() ZO_Gamepad_ParametricList_Screen.OnShowing(self) self:SetCurrentMode(CAMPAIGN_BROWSER_MODES.CAMPAIGN_RULESET_TYPES) -- need to update the content here because all the fragments have been removed, -- so we need to add the appropriate fragment back self:UpdateContentPane() self:RegisterEvents() self.dataRegistration:Refresh() QueryCampaignSelectionData() end function ZO_CampaignBrowser_Gamepad:OnHiding() ZO_Gamepad_ParametricList_Screen.OnHiding(self) self.dataRegistration:Refresh() self:UnregisterEvents() end ------------ -- Update -- ------------ function ZO_CampaignBrowser_Gamepad:PerformUpdate() if self.currentMode == CAMPAIGN_BROWSER_MODES.CAMPAIGN_RULESET_TYPES then self:BuildCampaignRulesetTypeList() else self:BuildCampaignList() end self:UpdateContentPane() self:RefreshScreenHeader() end function ZO_CampaignBrowser_Gamepad:GetCampaignQueryType(campaignId) if campaignId == GetAssignedCampaignId() then return BGQUERY_ASSIGNED_CAMPAIGN else return BGQUERY_LOCAL end end function ZO_CampaignBrowser_Gamepad:HasCampaignInformation(campaignId) return campaignId == GetAssignedCampaignId() or campaignId == GetCurrentCampaignId() end function ZO_CampaignBrowser_Gamepad:UpdateContentPane(updateFromTimer) local hideContent = true local hideScoring = true local hideEmperor = true local hideBonuses = true local targetData = self:GetTargetData() if targetData ~= nil then local displayContentType = targetData.displayContentType local queryType if displayContentType == CONTENT_TYPES.SCORING or displayContentType == CONTENT_TYPES.EMPERORSHIP or displayContentType == CONTENT_TYPES.BONUSES then queryType = self:GetCampaignQueryType(targetData.id) end if displayContentType == CONTENT_TYPES.CAMPAIGN then if not updateFromTimer then SCENE_MANAGER:AddFragment(GAMEPAD_AVA_CAMPAIGN_INFO_FRAGMENT) end self:RefreshCampaignInfoContent() hideContent = false elseif displayContentType == CONTENT_TYPES.SCORING then if not updateFromTimer then CAMPAIGN_SCORING_GAMEPAD:SetCampaignAndQueryType(targetData.id, queryType) SCENE_MANAGER:AddFragment(CAMPAIGN_SCORING_GAMEPAD_FRAGMENT) end hideScoring = false elseif displayContentType == CONTENT_TYPES.EMPERORSHIP then if not updateFromTimer then CAMPAIGN_EMPEROR_GAMEPAD:SetCampaignAndQueryType(targetData.id, queryType) SCENE_MANAGER:AddFragment(CAMPAIGN_EMPEROR_GAMEPAD_FRAGMENT) end hideEmperor = false elseif displayContentType == CONTENT_TYPES.BONUSES then if not updateFromTimer then CAMPAIGN_BONUSES_GAMEPAD:SetCampaignAndQueryType(targetData.id, queryType) SCENE_MANAGER:AddFragment(CAMPAIGN_BONUSES_GAMEPAD_FRAGMENT) end hideBonuses = false end end if hideContent then SCENE_MANAGER:RemoveFragment(GAMEPAD_AVA_CAMPAIGN_INFO_FRAGMENT) end if hideScoring then SCENE_MANAGER:RemoveFragment(CAMPAIGN_SCORING_GAMEPAD_FRAGMENT) end if hideEmperor then SCENE_MANAGER:RemoveFragment(CAMPAIGN_EMPEROR_GAMEPAD_FRAGMENT) end if hideBonuses then SCENE_MANAGER:RemoveFragment(CAMPAIGN_BONUSES_GAMEPAD_FRAGMENT) end local hideBackgroundAndHeader = hideScoring and hideContent and hideEmperor and hideBonuses if hideBackgroundAndHeader then GAMEPAD_AVA_ROOT_SCENE:RemoveFragment(GAMEPAD_NAV_QUADRANT_2_3_BACKGROUND_FRAGMENT) self.contentHeader:SetHidden(true) else GAMEPAD_AVA_ROOT_SCENE:AddFragment(GAMEPAD_NAV_QUADRANT_2_3_BACKGROUND_FRAGMENT) self.contentHeader:SetHidden(false) self:RefreshContentHeader() end KEYBIND_STRIP:UpdateCurrentKeybindButtonGroups() end local POPULATION_ICONS = { [CAMPAIGN_POP_LOW] = "EsoUI/Art/AvA/Gamepad/Server_Empty.dds", [CAMPAIGN_POP_MEDIUM] = "EsoUI/Art/AvA/Gamepad/Server_One.dds", [CAMPAIGN_POP_HIGH] = "EsoUI/Art/AvA/Gamepad/Server_Two.dds", [CAMPAIGN_POP_FULL] = "EsoUI/Art/AvA/Gamepad/Server_Full.dds", } local function GetPopulationIcon(population) return POPULATION_ICONS[population] end local function SetupPopulationIcon(control, data) control.populationControl:SetTexture(GetPopulationIcon(data.population)) local isFull = data.population == CAMPAIGN_POP_FULL control.lockedIconControl:SetHidden(not isFull) control.fullTextControl:SetHidden(not isFull) local queueWaitSeconds = GetSelectionCampaignQueueWaitTime(data.selectionIndex) if data.alliance == GetUnitAlliance("player") and queueWaitSeconds > 0 then --We don't want to show an estimate for seconds if queueWaitSeconds < 60 then queueWaitSeconds = 60 end local queueWaitMs = queueWaitSeconds * 1000 local textEstimatedTime = ZO_GetSimplifiedTimeEstimateText(queueWaitMs, TIME_FORMAT_STYLE_SHOW_LARGEST_UNIT, nil, ZO_TIME_ESTIMATE_STYLE.ARITHMETIC) control.estimatedWaitValueControl:SetText(textEstimatedTime) control.estimatedWaitControl:SetHidden(false) else control.estimatedWaitControl:SetHidden(true) end if isFull then control.factionControl:SetAlpha(0.5) else control.factionControl:SetAlpha(1.0) end end function ZO_CampaignBrowser_Gamepad:SetupStateMessage(stateMessageLabel, campaignData) local shouldHideStateMessage = false local queueData = campaignData.queue if queueData.isQueued and queueData.state ~= CAMPAIGN_QUEUE_REQUEST_STATE_FINISHED then local isLoading, message, messageIcon = CAMPAIGN_BROWSER_MANAGER:GetQueueMessage(queueData.id, queueData.isGroup, queueData.state) if not isLoading then message = message .. zo_iconFormat(messageIcon, 32, 32) end stateMessageLabel:SetText(ZO_SUCCEEDED_TEXT:Colorize(message)) elseif not ZO_CampaignBrowser_DoesPlayerMatchAllianceLock(campaignData) then stateMessageLabel:SetText(CAMPAIGN_BROWSER_MANAGER:GenerateAllianceLockStatusMessage(campaignData)) else shouldHideStateMessage = true end if shouldHideStateMessage then stateMessageLabel:SetHidden(true) self.campaignInfoRules:ClearAnchors() self.campaignInfoRules:SetAnchor(TOPLEFT, self.campaignInfoRulesContainer, TOPLEFT, 0, 0) self.campaignInfoRules:SetAnchor(TOPRIGHT, self.campaignInfoRulesContainer, TOPRIGHT, 0, 0) else stateMessageLabel:SetHidden(false) self.campaignInfoRules:ClearAnchors() self.campaignInfoRules:SetAnchor(TOPLEFT, stateMessageLabel, BOTTOMLEFT, 0, ZO_GAMEPAD_CONTENT_VERT_OFFSET_PADDING) self.campaignInfoRules:SetAnchor(TOPRIGHT, stateMessageLabel, BOTTOMRIGHT, 0, ZO_GAMEPAD_CONTENT_VERT_OFFSET_PADDING) end end function ZO_CampaignBrowser_Gamepad:RefreshCampaignInfoContent() local targetData = self:GetTargetData() if targetData and targetData.entryType ~= ENTRY_TYPES.CAMPAIGN_RULESET_TYPE then self:SetupStateMessage(self.campaignStateMessage, targetData) self.campaignInfoRules:SetText(GetCampaignRulesetDescription(targetData.rulesetId)) local selectionIndex = targetData.selectionIndex SetupPopulationIcon(self.campaignInfoStats:GetNamedChild("AldmeriDominion"), {population = targetData.alliancePopulation1, selectionIndex = selectionIndex, alliance = ALLIANCE_ALDMERI_DOMINION}) SetupPopulationIcon(self.campaignInfoStats:GetNamedChild("EbonheartPact"), {population = targetData.alliancePopulation2, selectionIndex = selectionIndex, alliance = ALLIANCE_EBONHEART_PACT}) SetupPopulationIcon(self.campaignInfoStats:GetNamedChild("DaggerfallCovenant"), {population = targetData.alliancePopulation3, selectionIndex = selectionIndex, alliance = ALLIANCE_DAGGERFALL_COVENANT}) end end ------------------- -- Deferred Init -- ------------------- function ZO_CampaignBrowser_Gamepad:OnDeferredInitialize() local campaignInfo = self.control:GetNamedChild("CampaignInfo") local campaignRules = campaignInfo:GetNamedChild("Rules") self.campaignInfoStats = campaignInfo:GetNamedChild("Stats") self.campaignInfoRulesContainer = campaignRules self.campaignInfoRules = campaignRules:GetNamedChild("RulesContent") self.campaignStateMessage = campaignRules:GetNamedChild("StateMessage") self.dataRegistration = ZO_CampaignDataRegistration:New("CampaignSelectorData", function() return GAMEPAD_AVA_ROOT_SCENE:IsShowing() end) ZO_CampaignDialogGamepad_Initialize(self) self.campaignList = self:GetMainList() self.campaignEntries = {} self.campaignRulesetTypeList = self:AddList("CampaignRulesetTypes") self.campaignRulesetTypes = {} self:InitializeHeader() -- These events need to be listened for whether we are showing or not -- If we are hidden, Update() will set the dirty flag and we will update when we next show CAMPAIGN_BROWSER_MANAGER:RegisterCallback("OnCampaignDataUpdated", function() self:Update() end) CAMPAIGN_BROWSER_MANAGER:RegisterCallback("OnCampaignQueueStateUpdated", function() self:Update() KEYBIND_STRIP:UpdateCurrentKeybindButtonGroups() end) EVENT_MANAGER:RegisterForEvent("ZO_CampaignBrowser_Gamepad", EVENT_ASSIGNED_CAMPAIGN_CHANGED, function() self:Update() end) EVENT_MANAGER:RegisterForEvent("ZO_CampaignBrowser_Gamepad", EVENT_PLAYER_DEAD, function() self:Update() end) EVENT_MANAGER:RegisterForEvent("ZO_CampaignBrowser_Gamepad", EVENT_PLAYER_ALIVE, function() self:Update() end) --Only the group leader can leave when group queued. We add or remove the leave entry through this update EVENT_MANAGER:RegisterForEvent("ZO_CampaignBrowser_Gamepad", EVENT_LEADER_UPDATE, function() self:Update() end) self:SetCurrentMode(CAMPAIGN_BROWSER_MODES.CAMPAIGN_RULESET_TYPES) end function ZO_CampaignBrowser_Gamepad:OnSelectionChanged(list, selectedData, oldSelectedData) if selectedData then self:UpdateContentPane() end end ------------ -- Header -- ------------ function ZO_CampaignBrowser_Gamepad:SetCampaignRulesetTypeFilter(campaignRulesetTypeFilter) self.campaignRulesetTypeFilter = campaignRulesetTypeFilter end function ZO_CampaignBrowser_Gamepad:SetCurrentMode(mode) self.currentMode = mode if mode == CAMPAIGN_BROWSER_MODES.CAMPAIGN_RULESET_TYPES then self:SetCurrentList(self.campaignRulesetTypeList) else self:SetCurrentList(self.campaignList) end self:Update() end function ZO_CampaignBrowser_Gamepad:InitializeHeader() local IS_PLURAL = false local IS_UPPER = false self.headerData = { titleText = GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_CAMPAIGNS_HEADER), data1HeaderText = GetCurrencyName(CURT_ALLIANCE_POINTS, IS_PLURAL, IS_UPPER), data1Text = function(control) ZO_CurrencyControl_SetSimpleCurrency(control, CURT_ALLIANCE_POINTS, GetCurrencyAmount(CURT_ALLIANCE_POINTS, CURRENCY_LOCATION_CHARACTER), ZO_GAMEPAD_CURRENCY_OPTIONS_LONG_FORMAT) return true end, } local rightPane = self.control:GetNamedChild("RightPane") local contentContainer = rightPane:GetNamedChild("ContentContainer") self.contentHeader = contentContainer:GetNamedChild("Header") self.contentHeaderData = {} ZO_GamepadGenericHeader_Initialize(self.contentHeader, ZO_GAMEPAD_HEADER_TABBAR_DONT_CREATE, ZO_GAMEPAD_HEADER_LAYOUTS.CONTENT_HEADER_DATA_PAIRS_LINKED) end function ZO_CampaignBrowser_Gamepad:RefreshScreenHeader() ZO_GamepadGenericHeader_Refresh(self.header, self.headerData) end local function GetCampaignEndsHeaderText(targetData) local headerDataText = GetString(SI_GAMEPAD_CAMPAIGN_SCORING_DURATION_REMAINING) local dataText local _, secondsRemaining = GetSelectionCampaignTimes(targetData.selectionIndex) if secondsRemaining > 0 then dataText = ZO_FormatTime(secondsRemaining, TIME_FORMAT_STYLE_SHOW_LARGEST_UNIT_DESCRIPTIVE, TIME_FORMAT_PRECISION_TWELVE_HOUR) else dataText = GetString(SI_GAMEPAD_CAMPAIGN_SCORING_DURATION_REMAINING_DONE) end return headerDataText, dataText end function ZO_CampaignBrowser_Gamepad:RefreshContentHeader() local targetData = self:GetTargetData() local headerData = self.contentHeaderData if targetData and not self.contentHeader:IsHidden() then -- Title if targetData.contentHeaderTitle then headerData.titleText = targetData.contentHeaderTitle else headerData.titleText = targetData.text end headerData.data1HeaderText = nil headerData.data1Text = nil headerData.data2HeaderText = nil headerData.data2Text = nil headerData.data3HeaderText = nil headerData.data3Text = nil headerData.data4HeaderText = nil headerData.data4Text = nil if targetData.entryType == ENTRY_TYPES.SCORING then -- Data 1 headerData.data1HeaderText = GetString(SI_GAMEPAD_CAMPAIGN_NEXT_SCORING_EVALUATION) headerData.data1Text = function(control) ZO_CampaignScoring_TimeUpdate(control, GetSecondsUntilCampaignScoreReevaluation) return true end -- Data 2 headerData.data2HeaderText, headerData.data2Text = GetCampaignEndsHeaderText(targetData) elseif targetData.entryType == ENTRY_TYPES.BONUSES then -- Data 1 headerData.data1HeaderText = GetString(SI_GAMEPAD_CAMPAIGN_BONUSES_HOME_KEEPS_HEADER) headerData.data1Text = function(control) local _, _, numHomeHeld, numTotalHome = GetAvAKeepScore(CAMPAIGN_BONUSES_GAMEPAD.campaignId, GetUnitAlliance("player")) return zo_strformat(GetString(SI_GAMEPAD_CAMPAIGN_BONUSES_HOME_KEEPS_HEADER_INFO), numHomeHeld, numTotalHome) end -- Data 2 headerData.data2HeaderText = GetString(SI_GAMEPAD_CAMPAIGN_BONUSES_ENEMY_KEEPS_HEADER) headerData.data2Text = function(control) local _, enemyKeepsHeld = GetAvAKeepScore(CAMPAIGN_BONUSES_GAMEPAD.campaignId, GetUnitAlliance("player")) return enemyKeepsHeld end -- Data 3 headerData.data3HeaderText = GetString(SI_GAMEPAD_CAMPAIGN_BONUSES_DEFENSIVE_SCROLLS_HEADER) headerData.data3Text = function(control) local _, enemyScrollsHeld = GetAvAArtifactScore(CAMPAIGN_BONUSES_GAMEPAD.campaignId, GetUnitAlliance("player"), OBJECTIVE_ARTIFACT_DEFENSIVE) return enemyScrollsHeld end -- Data 4 headerData.data4HeaderText = GetString(SI_GAMEPAD_CAMPAIGN_BONUSES_OFFENSIVE_SCROLLS_HEADER) headerData.data4Text = function(control) local _, enemyScrollsHeld = GetAvAArtifactScore(CAMPAIGN_BONUSES_GAMEPAD.campaignId, GetUnitAlliance("player"), OBJECTIVE_ARTIFACT_OFFENSIVE) return enemyScrollsHeld end elseif targetData.entryType == ENTRY_TYPES.EMPERORSHIP then -- Data 1 headerData.data1HeaderText = GetString(SI_CAMPAIGN_EMPEROR_NAME_HEADER) headerData.data1Text = function(control) if DoesCampaignHaveEmperor(targetData.id) then local alliance, characterName, displayName = GetCampaignEmperorInfo(targetData.id) local userFacingName = ZO_GetPlatformUserFacingName(characterName, displayName) return zo_strformat(GetString(SI_GAMEPAD_CAMPAIGN_EMPEROR_HEADER_NAME), GetLargeAllianceSymbolIcon(alliance), userFacingName) else return GetString(SI_CAMPAIGN_NO_EMPEROR) end end -- Data 2 headerData.data2HeaderText = GetString(SI_GAMEPAD_CAMPAIGN_EMPEROR_REIGN_DURATION_HEADER) headerData.data2Text = function(control) local duration = GetCampaignEmperorReignDuration(targetData.id) return ZO_FormatTime(duration, TIME_FORMAT_STYLE_COLONS, TIME_FORMAT_PRECISION_TWELVE_HOUR) end elseif self:DoesCampaignHaveSocialInfo(targetData) then -- Data 1 headerData.data1HeaderText = GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_TOOLTIP_GROUP_MEMBERS) headerData.data1Text = zo_strformat(SI_GAMEPAD_CAMPAIGN_BROWSER_PEOPLE_AMOUNT, targetData.numGroupMembers) -- Data 2 headerData.data2HeaderText = GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_TOOLTIP_FRIENDS) headerData.data2Text = zo_strformat(SI_GAMEPAD_CAMPAIGN_BROWSER_PEOPLE_AMOUNT, targetData.numFriends) -- Data 3 headerData.data3HeaderText = GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_TOOLTIP_GUILD_MEMBERS) headerData.data3Text = zo_strformat(SI_GAMEPAD_CAMPAIGN_BROWSER_PEOPLE_AMOUNT, targetData.numGuildMembers) -- Data 4 headerData.data4HeaderText, headerData.data4Text = GetCampaignEndsHeaderText(targetData) end ZO_GamepadGenericHeader_Refresh(self.contentHeader, headerData) end end -------------- -- Key Bind -- -------------- function ZO_CampaignBrowser_Gamepad:InitializeKeybindStripDescriptors() self.keybindStripDescriptor = { alignment = KEYBIND_STRIP_ALIGN_LEFT, { -- select keybind = "UI_SHORTCUT_PRIMARY", name = function() local targetData = self:GetTargetData() -- Contextual campaign action if targetData and targetData.entryType == ENTRY_TYPES.CAMPAIGN then if self:CanEnter(targetData) then -- enter campaign after queue return GetString(SI_CAMPAIGN_BROWSER_ENTER_CAMPAIGN) elseif self:CanQueueForCampaign(targetData) then -- enter campaign queue return GetString(SI_CAMPAIGN_BROWSER_QUEUE_CAMPAIGN) end end return GetString(SI_GAMEPAD_SELECT_OPTION) end, callback = function() local targetData = self:GetTargetData() local entryType = targetData.entryType -- Contextual campaign action if entryType == ENTRY_TYPES.CAMPAIGN then if self:CanEnter(targetData) then entryType = ENTRY_TYPES.TRAVEL_TO_CAMPAIGN elseif self:CanQueueForCampaign(targetData) then entryType = ENTRY_TYPES.ENTER_CAMPAIGN end end if entryType == ENTRY_TYPES.ENTER_CAMPAIGN then self:DoQueueForCampaign(targetData) elseif entryType == ENTRY_TYPES.TRAVEL_TO_CAMPAIGN then ConfirmCampaignEntry(targetData.id, targetData.isGroup, true) elseif entryType == ENTRY_TYPES.LEAVE_QUEUE then self:DoLeaveCampaignQueue(targetData) elseif entryType == ENTRY_TYPES.SET_HOME then self:DoSetHomeCampaign(targetData) elseif entryType == ENTRY_TYPES.BONUSES then self:DeactivateCurrentList() CAMPAIGN_BONUSES_GAMEPAD:Activate() self:SetCurrentMode(CAMPAIGN_BROWSER_MODES.BONUSES) PlaySound(SOUNDS.GAMEPAD_MENU_FORWARD) elseif entryType == ENTRY_TYPES.ABANDON_CAMPAIGN then self:DoAbandon(targetData) elseif entryType == ENTRY_TYPES.CAMPAIGN_RULESET_TYPE then self:SetCampaignRulesetTypeFilter(targetData.rulesetType) self:SetCurrentMode(CAMPAIGN_BROWSER_MODES.CAMPAIGNS) PlaySound(SOUNDS.GAMEPAD_MENU_FORWARD) end end, visible = function() local targetData = self:GetTargetData() if not targetData then return false end if targetData.entryType == ENTRY_TYPES.CAMPAIGN then return self:CanQueueForCampaign(targetData) or self:CanEnter(targetData) elseif targetData.entryType == ENTRY_TYPES.ENTER_CAMPAIGN then return self:CanQueueForCampaign(targetData) or self:IsQueuedForCampaign(targetData) elseif targetData.entryType == ENTRY_TYPES.TRAVEL_TO_CAMPAIGN then return self:CanEnter(targetData) elseif targetData.entryType == ENTRY_TYPES.LEAVE_QUEUE then return self:CanLeaveCampaignQueue(targetData) elseif targetData.entryType == ENTRY_TYPES.SET_HOME then return self:CanSetHomeCampaign(targetData) elseif targetData.entryType == ENTRY_TYPES.BONUSES then return self.currentMode == CAMPAIGN_BROWSER_MODES.CAMPAIGNS and self:HasCampaignInformation(targetData.id) elseif targetData.entryType == ENTRY_TYPES.ABANDON_CAMPAIGN then return true elseif targetData.entryType == ENTRY_TYPES.CAMPAIGN_RULESET_TYPE then return true else return false end end, enabled = function() local targetData = self:GetTargetData() if targetData then if targetData.entryType == ENTRY_TYPES.ENTER_CAMPAIGN then return not self:IsQueuedForCampaign(targetData) elseif targetData.entryType == ENTRY_TYPES.ABANDON_CAMPAIGN then return not self:IsQueuedForCampaign(targetData) end end return true end }, { -- back name = GetString(SI_GAMEPAD_BACK_OPTION), keybind = "UI_SHORTCUT_NEGATIVE", callback = function() if self.currentMode == CAMPAIGN_BROWSER_MODES.BONUSES then CAMPAIGN_BONUSES_GAMEPAD:Deactivate() self:ActivateCurrentList() self:SetCurrentMode(CAMPAIGN_BROWSER_MODES.CAMPAIGNS) PlaySound(SOUNDS.GAMEPAD_MENU_BACK) elseif self.currentMode == CAMPAIGN_BROWSER_MODES.CAMPAIGNS then self:SetCurrentMode(CAMPAIGN_BROWSER_MODES.CAMPAIGN_RULESET_TYPES) PlaySound(SOUNDS.GAMEPAD_MENU_BACK) else SCENE_MANAGER:Hide(GAMEPAD_AVA_ROOT_SCENE_NAME) end end, }, { -- set home campaign keybind = "UI_SHORTCUT_SECONDARY", name = GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_CHOOSE_HOME_CAMPAIGN), visible = function() local targetData = self:GetTargetData() if not targetData then return end if self.currentMode == CAMPAIGN_BROWSER_MODES.CAMPAIGNS and targetData.entryType == ENTRY_TYPES.CAMPAIGN then return self:CanSetHomeCampaign(targetData) end return false end, callback = function() local targetCampaignData = self:GetTargetData() self:DoSetHomeCampaign(targetCampaignData) end, }, { -- Leave a non-home/local campaign keybind = "UI_SHORTCUT_RIGHT_STICK", name = GetString(SI_CAMPAIGN_BROWSER_LEAVE_QUEUE), callback = function() local targetData = self:GetTargetData() if targetData.entryType == ENTRY_TYPES.CAMPAIGN then self:DoLeaveCampaignQueue(targetData) end end, visible = function() local targetData = self:GetTargetData() if targetData and targetData.entryType == ENTRY_TYPES.CAMPAIGN then return self:CanLeaveCampaignQueue(targetData) end return false end, }, } local function GetActiveList() if self.currentMode == CAMPAIGN_BROWSER_MODES.BONUSES then return CAMPAIGN_BONUSES_GAMEPAD.abilityList elseif self.currentMode == CAMPAIGN_BROWSER_MODES.CAMPAIGN_RULESET_TYPES then return self.campaignRulesetTypeList elseif self.currentMode == CAMPAIGN_BROWSER_MODES.CAMPAIGNS then return self.campaignList end end ZO_Gamepad_AddListTriggerKeybindDescriptors(self.keybindStripDescriptor, GetActiveList) end ------------ -- Events -- ------------ function ZO_CampaignBrowser_Gamepad:RegisterEvents() self.control:SetHandler("OnUpdate", function(control, seconds) self:OnUpdate(control, seconds) end) self.nextUpdateTimeSeconds = 0 EVENT_MANAGER:RegisterForEvent("ZO_CampaignBrowser_Gamepad", EVENT_CAMPAIGN_QUEUE_POSITION_CHANGED, function() self:OnCampaignQueuePositionChanged() end) end function ZO_CampaignBrowser_Gamepad:UnregisterEvents() self.control:SetHandler("OnUpdate", nil) EVENT_MANAGER:UnregisterForEvent("ZO_CampaignBrowser_Gamepad", EVENT_CAMPAIGN_QUEUE_POSITION_CHANGED) end function ZO_CampaignBrowser_Gamepad:OnUpdate(control, seconds) -- Many content pages contain countdown timers on them, so update every second to keep those fresh if seconds > self.nextUpdateTimeSeconds then self.nextUpdateTimeSeconds = zo_floor(seconds + 1) local UPDATE_FROM_TIMER = true self:UpdateContentPane(UPDATE_FROM_TIMER) end end ------------------------------------------------------------------------------------------------------------ function ZO_CampaignBrowser_Gamepad:GetTargetData() local currentList = self:GetCurrentList() if currentList then return currentList:GetTargetData() end return nil end function ZO_CampaignBrowser_Gamepad:IsQueuedForCampaign(data) return IsQueuedForCampaign(data.id, CAMPAIGN_QUEUE_INDIVIDUAL) end function ZO_CampaignBrowser_Gamepad:CanEnter(data) return data.queue.state == CAMPAIGN_QUEUE_REQUEST_STATE_CONFIRMING end do local PENDING_QUEUE_STATES = { [CAMPAIGN_QUEUE_REQUEST_STATE_PENDING_JOIN] = true, [CAMPAIGN_QUEUE_REQUEST_STATE_PENDING_LEAVE] = true, [CAMPAIGN_QUEUE_REQUEST_STATE_PENDING_ACCEPT] = true, } function ZO_CampaignBrowser_Gamepad:IsPendingQueueState(data) return PENDING_QUEUE_STATES[data.queue.state] end end function ZO_CampaignBrowser_Gamepad:CanSetHomeCampaign(data) return CAMPAIGN_BROWSER_MANAGER:CanSetHomeCampaign(data) end function ZO_CampaignBrowser_Gamepad:DoSetHomeCampaign(data) return CAMPAIGN_BROWSER_MANAGER:DoSetHomeCampaign(data) end function ZO_CampaignBrowser_Gamepad:CanLeaveCampaignQueue(data) return CAMPAIGN_BROWSER_MANAGER:CanLeaveCampaignQueue(data) end function ZO_CampaignBrowser_Gamepad:DoLeaveCampaignQueue(data) return CAMPAIGN_BROWSER_MANAGER:DoLeaveCampaignQueue(data) end function ZO_CampaignBrowser_Gamepad:DoAbandon(data) if internalassert(data.id == GetAssignedCampaignId()) then local lockTimeLeft = GetCampaignUnassignCooldown() if lockTimeLeft > 0 then ZO_Dialogs_ShowGamepadDialog(ZO_GAMEPAD_CAMPAIGN_LOCKED_DIALOG, { isAbandoning = true, id = data.id } ) else ZO_Dialogs_ShowGamepadDialog(ZO_GAMEPAD_CAMPAIGN_ABANDON_HOME_CONFIRM_DIALOG, { id = data.id }, { mainTextParams = self:GetTextParamsForAbandonHomeDialog() }) end end end function ZO_CampaignBrowser_Gamepad:CanQueueForCampaign(data) return CAMPAIGN_BROWSER_MANAGER:CanQueueForCampaign(data) end function ZO_CampaignBrowser_Gamepad:DoQueueForCampaign(data) CAMPAIGN_BROWSER_MANAGER:DoQueueForCampaign(data.dataSource) end do local DEFAULT_GAMEPAD_CAMPAIGN_ITEM_SORT = { campaignSort = { tiebreaker = "name", isNumeric = true }, name = { tiebreaker = "id" }, id = { isId64 = true }, } local HOME_CAMPAIGN_SORT_ID = -2 -- sort first, before campaign ruleset ids local LOCAL_CAMPAIGN_SORT_ID = -1 -- sort second, before campaign ruleset ids and after home campaign function ZO_CampaignBrowser_Gamepad:CreateAndSortCampaignEntries() local campaignDataList = CAMPAIGN_BROWSER_MANAGER:GetCampaignDataList() local assignedCampaign = GetAssignedCampaignId() local currentCampaign = GetCurrentCampaignId() ZO_ClearNumericallyIndexedTable(self.campaignEntries) for _, campaignData in ipairs(campaignDataList) do local campaignEntry = ZO_GamepadEntryData:New(campaignData.name) campaignEntry:SetDataSource(campaignData) campaignEntry.displayContentType = CONTENT_TYPES.CAMPAIGN campaignEntry.entryType = ENTRY_TYPES.CAMPAIGN local campaignRulesetName = GetCampaignRulesetName(campaignData.rulesetId) campaignEntry.contentHeaderTitle = zo_strformat(SI_GAMEPAD_CAMPAIGN_BROWSER_CONTENT_TITLE, campaignData.name, campaignRulesetName) if assignedCampaign == campaignData.id then if currentCampaign == campaignData.id then campaignEntry.campaignAssignmentType = BGQUERY_ASSIGNED_AND_LOCAL else campaignEntry.campaignAssignmentType = BGQUERY_ASSIGNED_CAMPAIGN end campaignEntry.campaignSort = HOME_CAMPAIGN_SORT_ID campaignEntry.headerText = GetString("SI_BATTLEGROUNDQUERYCONTEXTTYPE", BGQUERY_ASSIGNED_CAMPAIGN) elseif currentCampaign == campaignData.id then campaignEntry.campaignAssignmentType = BGQUERY_LOCAL campaignEntry.campaignSort = LOCAL_CAMPAIGN_SORT_ID campaignEntry.headerText = GetString("SI_BATTLEGROUNDQUERYCONTEXTTYPE", BGQUERY_LOCAL) else campaignEntry.campaignSort = campaignData.rulesetId campaignEntry.headerText = campaignRulesetName end campaignEntry.queue = CAMPAIGN_BROWSER_MANAGER:CreateCampaignQueueData(campaignEntry, CAMPAIGN_QUEUE_INDIVIDUAL) campaignEntry:SetLocked(not ZO_CampaignBrowser_DoesPlayerMatchAllianceLock(campaignEntry)) table.insert(self.campaignEntries, campaignEntry) end table.sort(self.campaignEntries, function(left, right) return ZO_TableOrderingFunction(left, right, "campaignSort", DEFAULT_GAMEPAD_CAMPAIGN_ITEM_SORT, ZO_SORT_ORDER_UP) end) end end function ZO_CampaignBrowser_Gamepad:CreateAndSortCampaignRulesetTypes() local campaignDataList = CAMPAIGN_BROWSER_MANAGER:GetCampaignDataList() ZO_ClearNumericallyIndexedTable(self.campaignRulesetTypes) for _, campaignData in ipairs(campaignDataList) do if not ZO_IsElementInNumericallyIndexedTable(self.campaignRulesetTypes, campaignData.rulesetType) then table.insert(self.campaignRulesetTypes, campaignData.rulesetType) end end table.sort(self.campaignRulesetTypes) -- sort by enum order end function ZO_CampaignBrowser_Gamepad:IsHomeCampaign(campaignEntry) return campaignEntry.campaignAssignmentType == BGQUERY_ASSIGNED_CAMPAIGN or campaignEntry.campaignAssignmentType == BGQUERY_ASSIGNED_AND_LOCAL end function ZO_CampaignBrowser_Gamepad:IsLocalCampaign(campaignEntry) return campaignEntry.campaignAssignmentType == BGQUERY_LOCAL or campaignEntry.campaignAssignmentType == BGQUERY_ASSIGNED_AND_LOCAL end function ZO_CampaignBrowser_Gamepad:DoesCampaignHaveScoreInfo(campaignEntry) return campaignEntry.campaignAssignmentType ~= nil and not campaignEntry.isImperialCityCampaign end function ZO_CampaignBrowser_Gamepad:DoesCampaignHaveSocialInfo(campaignEntry) -- IC can't be assigned, so there will never be any friends/guild members/group members to display return not campaignEntry.isImperialCityCampaign end function ZO_CampaignBrowser_Gamepad:IsHomeAndNotLocalCampaign(campaignEntry) return campaignEntry.campaignAssignmentType == BGQUERY_ASSIGNED_CAMPAIGN or campaignEntry.campaignAssignmentType == BGQUERY_ASSIGNED_AND_LOCAL end function ZO_CampaignBrowser_Gamepad:CreateCampaignRulesetTypeEntry(campaignRulesetType) local rulesetTypeName = GetString("SI_CAMPAIGNRULESETTYPE", campaignRulesetType) local rulesetTypeIcon = ZO_CampaignBrowser_GetGamepadIconForRulesetType(campaignRulesetType) local campaignTypeEntry = ZO_GamepadEntryData:New(rulesetTypeName, rulesetTypeIcon) campaignTypeEntry:SetIconTintOnSelection(true) campaignTypeEntry.rulesetType = campaignRulesetType campaignTypeEntry.displayContentType = CONTENT_TYPES.CAMPAIGN_RULESET_TYPE campaignTypeEntry.entryType = ENTRY_TYPES.CAMPAIGN_RULESET_TYPE return campaignTypeEntry end function ZO_CampaignBrowser_Gamepad:AddExpandedCampaignEntryToList(entries, sourceCampaignEntry, name, icon, contentType, entryType) local expandedEntry = ZO_GamepadEntryData:New(name, icon) expandedEntry:SetIconTintOnSelection(true) expandedEntry:SetDataSource(sourceCampaignEntry) expandedEntry.displayContentType = contentType expandedEntry.entryType = entryType table.insert(entries, expandedEntry) end function ZO_CampaignBrowser_Gamepad:CreateExpandedCampaignEntries(campaignEntry) local entries = {} -- ENTER CAMPAIGN if self:CanQueueForCampaign(campaignEntry) or (self:IsQueuedForCampaign(campaignEntry) and not self:CanEnter(campaignEntry)) then self:AddExpandedCampaignEntryToList(entries, campaignEntry, GetString(SI_CAMPAIGN_BROWSER_QUEUE_CAMPAIGN), ICON_ENTER, CONTENT_TYPES.CAMPAIGN, ENTRY_TYPES.ENTER_CAMPAIGN) end -- TRAVEL TO / LEAVE CAMPAIGN if self:CanEnter(campaignEntry) then self:AddExpandedCampaignEntryToList(entries, campaignEntry, GetString(SI_CAMPAIGN_BROWSER_ENTER_CAMPAIGN), ICON_TRAVEL, CONTENT_TYPES.CAMPAIGN, ENTRY_TYPES.TRAVEL_TO_CAMPAIGN) self:AddExpandedCampaignEntryToList(entries, campaignEntry, GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_LEAVE_CAMPAIGN), ICON_LEAVE, CONTENT_TYPES.CAMPAIGN, ENTRY_TYPES.LEAVE_QUEUE) elseif self:CanLeaveCampaignQueue(campaignEntry) and not self:IsPendingQueueState(campaignEntry) then -- LEAVE QUEUE self:AddExpandedCampaignEntryToList(entries, campaignEntry, GetString(SI_CAMPAIGN_BROWSER_LEAVE_QUEUE), ICON_LEAVE, CONTENT_TYPES.CAMPAIGN, ENTRY_TYPES.LEAVE_QUEUE) end -- SET HOME if not self:IsHomeCampaign(campaignEntry) and self:CanSetHomeCampaign(campaignEntry) then self:AddExpandedCampaignEntryToList(entries, campaignEntry, GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_CHOOSE_HOME_CAMPAIGN), ICON_HOME, CONTENT_TYPES.CAMPAIGN, ENTRY_TYPES.SET_HOME) end -- BONUSES self:AddExpandedCampaignEntryToList(entries, campaignEntry, GetString(SI_CAMPAIGN_OVERVIEW_CATEGORY_BONUSES), ICON_BONUS, CONTENT_TYPES.BONUSES, ENTRY_TYPES.BONUSES) -- SCORING self:AddExpandedCampaignEntryToList(entries, campaignEntry, GetString(SI_CAMPAIGN_OVERVIEW_CATEGORY_SCORING), ICON_SCORING, CONTENT_TYPES.SCORING, ENTRY_TYPES.SCORING) -- EMPERORSHIP self:AddExpandedCampaignEntryToList(entries, campaignEntry, GetString(SI_CAMPAIGN_OVERVIEW_CATEGORY_EMPERORSHIP), ICON_EMPEROR, CONTENT_TYPES.EMPERORSHIP, ENTRY_TYPES.EMPERORSHIP) -- ABANDON if self:IsHomeAndNotLocalCampaign(campaignEntry) then self:AddExpandedCampaignEntryToList(entries, campaignEntry, GetString(SI_CAMPAIGN_BROWSER_ABANDON_CAMPAIGN), ICON_ABANDON, CONTENT_TYPES.CAMPAIGN, ENTRY_TYPES.ABANDON_CAMPAIGN) end return entries end function ZO_CampaignBrowser_Gamepad:BuildCampaignRulesetTypeList() self.campaignRulesetTypeList:Clear() self:CreateAndSortCampaignRulesetTypes() for _, campaignRulesetType in ipairs(self.campaignRulesetTypes) do self.campaignRulesetTypeList:AddEntry("ZO_GamepadNewMenuEntryTemplate", self:CreateCampaignRulesetTypeEntry(campaignRulesetType)) end local DEFAULT_RESELECT = nil local BLOCK_SELECTION_CHANGED_CALLBACK = true self.campaignRulesetTypeList:Commit(DEFAULT_RESELECT, BLOCK_SELECTION_CHANGED_CALLBACK) end function ZO_CampaignBrowser_Gamepad:BuildCampaignList() self.campaignList:Clear() self:CreateAndSortCampaignEntries() local lastCampaignListHeaderText = nil for _, campaignEntry in ipairs(self.campaignEntries) do if campaignEntry.rulesetType == self.campaignRulesetTypeFilter then local entries if self:DoesCampaignHaveScoreInfo(campaignEntry) then entries = self:CreateExpandedCampaignEntries(campaignEntry) else entries = {campaignEntry} end for _, entry in ipairs(entries) do if lastCampaignListHeaderText ~= entry.headerText then entry:SetHeader(entry.headerText) self.campaignList:AddEntryWithHeader("ZO_GamepadNewMenuEntryTemplate", entry) lastCampaignListHeaderText = entry.headerText else self.campaignList:AddEntry("ZO_GamepadNewMenuEntryTemplate", entry) end end end end local DEFAULT_RESELECT = nil local BLOCK_SELECTION_CHANGED_CALLBACK = true self.campaignList:Commit(DEFAULT_RESELECT, BLOCK_SELECTION_CHANGED_CALLBACK) end function ZO_CampaignBrowser_Gamepad:GetPriceMessage(cost, hasEnough, useGold) if useGold then local goldIconMarkup = ZO_Currency_GetGamepadFormattedCurrencyIcon(CURT_MONEY) if hasEnough then return zo_strformat(ZO_SELECTED_TEXT:Colorize(GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_PRICE)), cost, goldIconMarkup) else return zo_strformat(ZO_ERROR_COLOR:Colorize(GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_PRICE)), cost, goldIconMarkup) end else local alliancePointIconMarkup = ZO_Currency_GetGamepadFormattedCurrencyIcon(CURT_ALLIANCE_POINTS) if hasEnough then return zo_strformat(ZO_SELECTED_TEXT:Colorize(GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_PRICE)), cost, alliancePointIconMarkup) else return zo_strformat(ZO_ERROR_COLOR:Colorize(GetString(SI_GAMEPAD_CAMPAIGN_BROWSER_PRICE)), cost, alliancePointIconMarkup) end end end function ZO_CampaignBrowser_Gamepad:GetTextParamsForAbandonHomeDialog() local homeCampaignId = GetAssignedCampaignId() local warning = zo_strformat(GetString(SI_ABANDON_HOME_CAMPAIGN_QUERY), GetCampaignName(homeCampaignId)) local alliancePointCost = ZO_AbandonHomeCampaign_GetCost() local isFree = alliancePointCost == 0 local costMessage if isFree then costMessage = GetString(SI_ABANDON_HOME_CAMPAIGN_FREE) else costMessage = "" end return {warning, costMessage} end function ZO_CampaignBrowser_Gamepad:OnCampaignQueuePositionChanged() KEYBIND_STRIP:UpdateCurrentKeybindButtonGroups() end function ZO_CampaignAvARank_Gamepad_OnInitialized(control) CAMPAIGN_AVA_RANK_GAMEPAD = CampaignAvARank:New(control) end function ZO_CampaignBrowser_Gamepad_Initialize(control) GAMEPAD_AVA_BROWSER = ZO_CampaignBrowser_Gamepad:New(control) end function ZO_AvAFactionPopulation_Gamepad_OnInitialize(control, alliance) local allianceTexture = nil if alliance == ALLIANCE_EBONHEART_PACT then allianceTexture = "EsoUI/Art/Campaign/Gamepad/gp_overview_allianceIcon_ebonheart.dds" elseif alliance == ALLIANCE_ALDMERI_DOMINION then allianceTexture = "EsoUI/Art/Campaign/Gamepad/gp_overview_allianceIcon_aldmeri.dds" elseif alliance == ALLIANCE_DAGGERFALL_COVENANT then allianceTexture = "EsoUI/Art/Campaign/Gamepad/gp_overview_allianceIcon_daggerfall.dds" end control.populationControl = control:GetNamedChild("Population") control.factionControl = control:GetNamedChild("Faction") control.allianceNameControl = control:GetNamedChild("AllianceName") control.lockedIconControl = control:GetNamedChild("LockedIcon") control.fullTextControl = control:GetNamedChild("FullText") control.estimatedWaitControl = control:GetNamedChild("EstimatedWait") control.estimatedWaitValueControl = control.estimatedWaitControl:GetNamedChild("Value") local r,g,b,a = GetInterfaceColor(INTERFACE_COLOR_TYPE_ALLIANCE, alliance) control.populationControl:SetColor(r,g,b,a) control.factionControl:SetTexture(allianceTexture) local allianceName = GetAllianceName(alliance) control.allianceNameControl:SetText(zo_strformat(GetString(SI_ALLIANCE_NAME), allianceName)) end
snippet #! "#! sh" #! /bin/sh endsnippet snippet #! "#! bash" #! /bin/bash endsnippet
local vector = require "vector" local platform = {} platform.position = vector( 300, 500 ) platform.speed = vector( 800, 0 ) platform.image = love.graphics.newImage( "img/800x600/platform.png" ) platform.small_tile_width = 75 platform.small_tile_height = 16 platform.small_tile_x_pos = 0 platform.small_tile_y_pos = 0 platform.norm_tile_width = 108 platform.norm_tile_height = 16 platform.norm_tile_x_pos = 0 platform.norm_tile_y_pos = 32 platform.large_tile_width = 141 platform.large_tile_height = 16 platform.large_tile_x_pos = 0 platform.large_tile_y_pos = 64 platform.glued_x_pos_shift = 192 platform.tileset_width = 333 platform.tileset_height = 80 platform.quad = love.graphics.newQuad( platform.norm_tile_x_pos, platform.norm_tile_y_pos, platform.norm_tile_width, platform.norm_tile_height, platform.tileset_width, platform.tileset_height ) platform.width = platform.norm_tile_width platform.height = platform.norm_tile_height function platform.update( dt ) platform.follow_mouse( dt ) end function platform.draw() love.graphics.draw( platform.image, platform.quad, platform.position.x, platform.position.y ) end function platform.follow_mouse( dt ) local x, y = love.mouse.getPosition() local left_wall_plus_half_platform = 34 + platform.width / 2 local right_wall_minus_half_platform = 576 - platform.width / 2 if ( x > left_wall_plus_half_platform and x < right_wall_minus_half_platform ) then platform.position.x = x - platform.width / 2 elseif x < left_wall_plus_half_platform then platform.position.x = left_wall_plus_half_platform - platform.width / 2 elseif x > right_wall_minus_half_platform then platform.position.x = right_wall_minus_half_platform - platform.width / 2 end end function platform.bounce_from_wall( shift_platform ) platform.position.x = platform.position.x + shift_platform.x end return platform
animation { width = 1920, height = 1080, length = 4.5 } -- la libs local la = {} la.trim = pan.require "la/trim" la.palette, la.paints = unpack(pan.require "la/palette") la.fonts = pan.require "la/fonts" la.text = pan.require "la/text" -- logo data local LogoSize = 400 local LOffset = -LogoSize / 2 + 48 local LogoHalf = { { x = LOffset + 32, y = -LogoSize / 2 }, { x = LOffset + 32, y = 64 }, { x = LOffset + math.floor(LogoSize / 3), y = 32 }, { x = LOffset + math.floor(LogoSize / 3), y = -48 }, } local LogoFont = la.fonts.bold local LogoName = "lqdev" local LogoTextSize = 72 la.trim.prepare(LogoHalf) -- box with logo inside of it function addLogo() rect(-LogoSize / 2, -LogoSize / 2, LogoSize, LogoSize) for _, scale in ipairs({-1, 1}) do push() pan.scale(scale, scale) la.trim.add(LogoHalf, 0.0, easel(0.0, 1.0, 0.0, 2.5, quinticInOut)) pop() end end function drawLogo(dx, dy, scale, paint) if scale ~= 0 then begin() push() translate(width / 2, height / 2) translate(dx, dy) pan.scale(scale, scale) addLogo() pop() stroke(paint) end end function drawName(dx, dy, paint) local tw, th = pan.textSize(LogoFont, LogoName, LogoTextSize) push() translate(width / 2, height / 2) translate(0, LogoSize / 2 + 48) translate(dx, dy) begin() if time < 3 then cliprect(-tw / 2, 0, tw, th + 12, la.paints.text) end la.text.perchar( LogoFont, 0, 0, LogoName, LogoTextSize, function (add, index) local t = 1 + (index - 1) * 0.1 add(0, keyframes { { time = t, val = 72 }, { time = t + 1.0, val = 0, easing = quarticOut }, { time = t + 1.75, val = 0 }, { time = t + 2.75, val = height / 2, easing = quinticIn }, }) end, 0, 0, taCenter, taTop ) fill(paint) pop() end function render() clear(la.paints.background) local logoScale = keyframes { { time = 0.0, val = 0.0 }, { time = 1.5, val = 1.0, easing = quarticOut }, { time = 2.5, val = 1.0 }, { time = 4.0, val = 0.0, easing = quarticIn }, } drawLogo(32, 32, logoScale, la.paints.lightBackground) drawLogo(16, 16, logoScale, la.paints.neonPink) drawLogo(0, 0, logoScale, la.paints.text) drawName(12, 12, la.paints.neonPink) drawName(0, 0, la.paints.text) end
EXPORTS["tripmine"] = { }; EXPORTS["tripmine"].Name = "Tripmine"; EXPORTS["tripmine"].Desc = "Detonates if it detects movement in its line-of-sight.\n\nOnce used, you can get more at your truck."; EXPORTS["tripmine"].Secondary = true; EXPORTS["tripmine"].Price = 4600; EXPORTS["tripmine"].Model = "models/weapons/w_slam.mdl"; EXPORTS["tripmine"].W = 2; EXPORTS["tripmine"].H = 2; EXPORTS["tripmine"].SWEP = "weapon_coi_tripmine";
local _super _super = function(cls, self, method, ...) local fn if method == "new" then fn = cls.__parent.__init else fn = cls.__parent.__base[method] end return fn(self, ...) end local _class _class = function(name, tbl, extend, setup_fn) local cls if extend then do local _class_0 local _parent_0 = extend local _base_0 = { } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) _class_0 = setmetatable({ __init = tbl and tbl.new, __base = _base_0, __name = "cls", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then local parent = rawget(cls, "__parent") if parent then return parent[name] end else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 local self = _class_0 self.super = _super self.__name = name if tbl then tbl.new = nil for k, v in pairs(tbl) do self.__base[k] = v end end local _ = setup_fn and setup_fn(self) if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end cls = _class_0 end else do local _class_0 local _base_0 = { } _base_0.__index = _base_0 _class_0 = setmetatable({ __init = tbl and tbl.new, __base = _base_0, __name = "cls" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 local self = _class_0 self.super = _super self.__name = name if tbl then tbl.new = nil for k, v in pairs(tbl) do self.__base[k] = v end end local _ = setup_fn and setup_fn(self) cls = _class_0 end end return cls end return { class = _class }
--[[ file meta info @file WhatsTrainingUI.lua @brief Functions to build the ingame UI window --]] --[[ @brief Accessing the addons private table @var _ addonName, thrown away @var wt Global addonTable --]] local _, wt = ... -- @brief "Constant" variables local BOOKTYPE_SPELL = BOOKTYPE_SPELL -- Used to specify the players spellbook from in-game constant local MAX_ROWS = 22 -- Max rows for the data shown in the spellbook local ROW_HEIGHT = 14 -- Height of each row in the spellbook local SKILL_LINE_TAB = MAX_SKILLLINE_TABS - 1 -- Position for the addons tab in the spellbook local HIGHLIGHT_TEXTURE_PATH = "Interface\\AddOns\\WhatsTraining_WotLK\\res\\highlight" local LEFT_BG_TEXTURE_PATH = "Interface\\AddOns\\WhatsTraining_WotLK\\res\\left" local RIGHT_BG_TEXTURE_PATH = "Interface\\AddOns\\WhatsTraining_WotLK\\res\\right" local TAB_TEXTURE_PATH = "Interface\\Icons\\INV_Misc_QuestionMark" -- @brief Creating the tooltip frame local tooltip = CreateFrame("GameTooltip", -- Type of frame "WhatsTrainingTooltip", -- Name of frame, globally accessable UIParent, -- Parent frame "GameTooltipTemplate") -- Template to use building the frame --[[ @brief @param spellInfo --]] local function setTooltip(spellInfo) tooltip:ClearLines() if (spellInfo.id) then tooltip:SetSpellByID(spellInfo.id) else tooltip:ClearLines() end if (spellInfo.cost > 0) then local coloredCoinString = spellInfo.formattedCost or GetCoinTextureString(spellInfo.cost) if (GetMoney() < spellInfo.cost) then coloredCoinString = RED_FONT_COLOR_CODE .. coloredCoinString .. FONT_COLOR_CODE_CLOSE end local formatString = spellInfo.isHeader and (spellInfo.costFormat or wt.L.TOTALCOST_FORMAT) or wt.L.COST_FORMAT tooltip:AddLine(HIGHLIGHT_FONT_COLOR_CODE .. format(formatString, coloredCoinString) .. FONT_COLOR_CODE_CLOSE) end if (spellInfo.tooltip) then tooltip:AddLine(spellInfo.tooltip) end tooltip:Show() end local function setRowSpell(row, spell) if (spell == nil) then row.currentSpell = nil row:Hide() return elseif (spell.isHeader) then row.spell:Hide() row.header:Show() row.header:SetText(spell.formattedName) row:SetID(0) row.highlight:SetTexture(nil) else local rowSpell = row.spell row.header:Hide() row.isHeader = false row.highlight:SetTexture(HIGHLIGHT_TEXTURE_PATH) rowSpell:Show() rowSpell.label:SetText(spell.name) rowSpell.subLabel:SetText(spell.formattedSubText) if (not spell.hideLevel) then rowSpell.level:Show() rowSpell.level:SetText(spell.formattedLevel) local color = spell.levelColor rowSpell.level:SetTextColor(color.r, color.g, color.b) else rowSpell.level:Hide() end row:SetID(spell.id) rowSpell.icon:SetTexture(spell.icon) end if (spell.click) then row:SetScript("OnClick", spell.click) elseif (not spell.isHeader) then row:SetScript("OnClick", function(_, button) if (not wt.ClickHook) then return end if (button == "RightButton") then wt.ClickHook(spell.id, function() wt:RebuildData() end) end end) else row:SetScript("OnClick", nil) end row.currentSpell = spell if (tooltip:IsOwned(row)) then setTooltip(spell) end row:Show() end -- When holding down left mouse on the slider knob, it will keep firing update even though -- the offset hasn't changed so this will help throttle that local lastOffset = -1 function wt.Update(frame, forceUpdate) local scrollBar = frame.scrollBar local offset = FauxScrollFrame_GetOffset(scrollBar) if (offset == lastOffset and not forceUpdate) then return end for i, row in ipairs(frame.rows) do local spellIndex = i + offset local spell = wt.data[spellIndex] setRowSpell(row, spell) end FauxScrollFrame_Update(wt.MainFrame.scrollBar, #wt.data, MAX_ROWS, ROW_HEIGHT, nil, nil, nil, nil, nil, nil, true) lastOffset = offset end local hasFrameShown = false function wt.CreateFrame() local mainFrame = CreateFrame("Frame", "WhatsTrainingFrame", SpellBookFrame) mainFrame:SetPoint("TOPLEFT", SpellBookFrame, "TOPLEFT", 0, 0) mainFrame:SetPoint("BOTTOMRIGHT", SpellBookFrame, "BOTTOMRIGHT", 0, 0) mainFrame:SetFrameStrata("HIGH") local left = mainFrame:CreateTexture(nil, "ARTWORK") left:SetTexture(LEFT_BG_TEXTURE_PATH) left:SetWidth(256) left:SetHeight(512) left:SetPoint("TOPLEFT", mainFrame) local right = mainFrame:CreateTexture(nil, "ARTWORK") right:SetTexture(RIGHT_BG_TEXTURE_PATH) right:SetWidth(128) right:SetHeight(512) right:SetPoint("TOPRIGHT", mainFrame) mainFrame:Hide() local skillLineTab = _G["SpellBookSkillLineTab" .. SKILL_LINE_TAB] -- hooksecurefunc("SpellBookFrame_UpdateSkillLineTabs", function() hooksecurefunc("SpellBookFrame_Update", function() skillLineTab:SetNormalTexture(TAB_TEXTURE_PATH) skillLineTab.tooltip = wt.L.TAB_TEXT skillLineTab:Show() if (SpellBookFrame.selectedSkillLine == SKILL_LINE_TAB) then skillLineTab:SetChecked(true) mainFrame:Show() else skillLineTab:SetChecked(false) mainFrame:Hide() end end) hooksecurefunc("SpellBookFrame_Update", function() if (SpellBookFrame.bookType ~= BOOKTYPE_SPELL) then mainFrame:Hide() elseif (SpellBookFrame.selectedSkillLine == SKILL_LINE_TAB) then mainFrame:Show() end end) local scrollBar = CreateFrame("ScrollFrame", "$parentScrollBar", mainFrame, "FauxScrollFrameTemplate") scrollBar:SetPoint("TOPLEFT", 0, -75) scrollBar:SetPoint("BOTTOMRIGHT", -65, 81) scrollBar:SetScript("OnVerticalScroll", function(self, offset) FauxScrollFrame_OnVerticalScroll(self, offset, ROW_HEIGHT, function() wt.Update(mainFrame) end) end) scrollBar:SetScript("OnShow", function() if (not hasFrameShown) then wt:RebuildData() hasFrameShown = true end wt.Update(mainFrame, true) end) mainFrame.scrollBar = scrollBar local rows = {} for i = 1, MAX_ROWS do local row = CreateFrame("Button", "$parentRow" .. i, mainFrame) row:SetHeight(ROW_HEIGHT) row:EnableMouse(true) row:RegisterForClicks("LeftButtonUp", "RightButtonUp") row:SetScript("OnEnter", function(self) tooltip:SetOwner(self, "ANCHOR_RIGHT") setTooltip(self.currentSpell) end) row:SetScript("OnLeave", function() tooltip:Hide() end) local highlight = row:CreateTexture("$parentHighlight", "HIGHLIGHT") highlight:SetAllPoints() local spell = CreateFrame("Frame", "$parentSpell", row) spell:SetPoint("LEFT", row, "LEFT") spell:SetPoint("TOP", row, "TOP") spell:SetPoint("BOTTOM", row, "BOTTOM") local spellIcon = spell:CreateTexture(nil, "OVERLAY") spellIcon:SetPoint("TOPLEFT", spell) spellIcon:SetPoint("BOTTOMLEFT", spell) local iconWidth = ROW_HEIGHT spellIcon:SetWidth(iconWidth) local spellLabel = spell:CreateFontString("$parentLabel", "OVERLAY", "GameFontNormal") spellLabel:SetPoint("TOPLEFT", spell, "TOPLEFT", iconWidth + 4, 0) spellLabel:SetPoint("BOTTOM", spell) spellLabel:SetJustifyV("MIDDLE") spellLabel:SetJustifyH("LEFT") local spellSublabel = spell:CreateFontString("$parentSubLabel", "OVERLAY", --"NewSubSpellFont") "SpellFont_Small") -- test spellSublabel:SetTextColor(255/255, 255/255, 153/255) -- Works! --test end spellSublabel:SetJustifyH("LEFT") spellSublabel:SetPoint("TOPLEFT", spellLabel, "TOPRIGHT", 2, 0) spellSublabel:SetPoint("BOTTOM", spellLabel) local spellLevelLabel = spell:CreateFontString("$parentLevelLabel", "OVERLAY", "GameFontWhite") spellLevelLabel:SetPoint("TOPRIGHT", spell, -4, 0) spellLevelLabel:SetPoint("BOTTOM", spell) spellLevelLabel:SetJustifyH("RIGHT") spellLevelLabel:SetJustifyV("MIDDLE") spellSublabel:SetPoint("RIGHT", spellLevelLabel, "LEFT") spellSublabel:SetJustifyV("MIDDLE") local headerLabel = row:CreateFontString("$parentHeaderLabel", "OVERLAY", "GameFontWhite") headerLabel:SetAllPoints() headerLabel:SetJustifyV("MIDDLE") headerLabel:SetJustifyH("CENTER") spell.label = spellLabel spell.subLabel = spellSublabel spell.icon = spellIcon spell.level = spellLevelLabel row.highlight = highlight row.header = headerLabel row.spell = spell if (rows[i - 1] == nil) then row:SetPoint("TOPLEFT", mainFrame, 26, -78) else row:SetPoint("TOPLEFT", rows[i - 1], "BOTTOMLEFT", 0, -2) end row:SetPoint("RIGHT", scrollBar) rawset(rows, i, row) end mainFrame.rows = rows wt.MainFrame = mainFrame end
function p_print(...) local info = debug.getinfo(2, "Sl") local source = info.source local msg = ("%s:%i ->"):format(source, info.currentline) print(msg, ...) end function resize( s ) love.window.setMode(s*gw,s*gh) sx,sy = s,s end function UUID() local fn = function ( x ) local r = love.math.random(16) - 1 r = (x == 'x') and (r + 1) or (r % 4) + 9 return ("0123456789abcdef"):sub(r,r) end return (("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"):gsub("[xy]",fn)) end function addRoom( room_type, room_name, ... ) local room = _G[room_type](room_name, ...) rooms[room_name] = room return room end function gotoRoom( room_type, room_name, ... ) if current_room and current_room.destroy then current_room:destroy() end if current_room and rooms[room_name] then if current_room.deactivate then current_room:activate() end current_room = rooms[room_name] if current_room.activate then current_room:activate() end else current_room = addRoom(room_type, room_name, ...) end end function recursiveEnumerate( folder,file_list ) local items = love.filesystem.getDirectoryItems(folder) for _,item in ipairs(items) do local file = folder .. '/' .. item if love.filesystem.isFile(file) then table.insert(file_list,file) elseif love.filesystem.isDirectory(file) then recursiveEnumerate(file,file_list) end end end function requireFiles(files) for _, file in ipairs(files) do local file = file:sub(1,-5) require(file) end end function random(min,max) local min,max = min or 0, max or 1 return (min > max and (love.math.random()*(min - max) + max)) or (love.math.random()*(max - min) + min) end function count_all(f) local seen = {} local count_table count_table = function(t) if seen[t] then return end f(t) seen[t] = true for k,v in pairs(t) do if type(v) == "table" then count_table(v) elseif type(v) == "userdata" then f(v) end end end count_table(_G) end function type_count() local counts = {} local enumerate = function (o) local t = type_name(o) counts[t] = (counts[t] or 0) + 1 end count_all(enumerate) return counts end global_type_table = nil function type_name(o) if global_type_table == nil then global_type_table = {} for k,v in pairs(_G) do global_type_table[v] = k end global_type_table[0] = "table" end return global_type_table[getmetatable(o) or 0] or "Unknown" end GUI = {} function GUI.box(x,y,w,h,fill_color,line_color) local x,y = x,y or 0,0 local w,h = w,h or 200,200 local fill_color = fill_color or {1,1,1,0.3} local line_color = line_color or {1,1,1,1} love.graphics.setColor(fill_color) love.graphics.rectangle("fill",x,y,w,h,8) love.graphics.setColor(line_color) love.graphics.rectangle("line",x,y,w,h,8) end
--* This Document is AutoGenerate by OrangeFilter, Don't Change it! * ---@meta --- ---[3.3]trail renderer[parent:] --- ---@class TrailRenderer TrailRenderer = {} --- ---[3.3]constructor, 1 param --- --- @param arg0 Context#context --- @nodiscard function TrailRenderer:new(arg0) end --- ---[3.3]add new point, and update buffer --- --- @param arg0 Vec3f#vec3f --- @param arg1 float --- @param arg2 bool --- @nodiscard function TrailRenderer:update(arg0, arg1, arg2) end --- ---[3.3]add new point --- --- @param arg0 Vec3f#vec3f --- @param arg1 float --- @param arg2 bool --- @nodiscard function TrailRenderer:addPoint(arg0, arg1, arg2) end --- ---[3.3]update buffer --- --- @param arg0 float --- @nodiscard function TrailRenderer:updateBuffer(arg0) end --- ---[3.3]render --- --- @nodiscard function TrailRenderer:render() end --- ---[3.3]set shader --- --- @param arg0 string --- @nodiscard function TrailRenderer:setShader(arg0) end --- ---[3.3]set texture --- --- @param arg0 Texture#texture --- @param arg1 Vec4f#vec4f --- @nodiscard function TrailRenderer:setTexture(arg0, arg1) end --- ---[3.3]set texture mode --- --- @param arg0 OF_LineTextureMode#of_linetexturemode --- @nodiscard function TrailRenderer:setTextureMode(arg0) end --- ---[3.3]set texture tiling rate --- --- @param arg0 float --- @nodiscard function TrailRenderer:setTextureTilingRate(arg0) end --- ---[3.3]get material --- --- @return MaterialLegacy#materiallegacy --- @nodiscard function TrailRenderer:getMaterial() end --- ---[3.3]set min vertex distance --- --- @param arg0 float --- @nodiscard function TrailRenderer:setMinVertexDistance(arg0) end --- ---[3.3]set width curve --- --- @param arg0 AnimationCurve#animationcurve --- @nodiscard function TrailRenderer:setWidthCurve(arg0) end --- ---[3.3]set width multiplier --- --- @param arg0 float --- @nodiscard function TrailRenderer:setWidthMultiplier(arg0) end --- ---[3.3]set color gradient --- --- @param arg0 Gradient#gradient --- @nodiscard function TrailRenderer:setColorGradient(arg0) end --- ---[3.3]set trail time --- --- @param arg0 float --- @nodiscard function TrailRenderer:setTime(arg0) end --- ---[3.3]set curvelize --- --- @param arg0 bool --- @nodiscard function TrailRenderer:setCurvelize(arg0) end --- ---[3.3]set curve insert point count --- --- @param arg0 int --- @nodiscard function TrailRenderer:setCurveInsertPointCount(arg0) end --- ---[3.3]clear all points --- --- @nodiscard function TrailRenderer:clear() end --- ---[3.3]get point count --- --- @return int --- @nodiscard function TrailRenderer:getPositionCount() end --- ---[3.3]get point position --- --- @param arg0 int --- @return Vec3f#vec3f --- @nodiscard function TrailRenderer:getPosition(arg0) end return TrailRenderer
local PANEL = {} local nextSG = 0 local quickTools = { { name = "Goto", icon = "icon16/arrow_right.png", onRun = function(ply, sid) LocalPlayer():ConCommand("say /goto "..sid) end }, { name = "Bring", icon = "icon16/arrow_inout.png", onRun = function(ply, sid) LocalPlayer():ConCommand("say /bring "..sid) end }, { name = "Respawn", icon = "icon16/arrow_refresh.png", onRun = function(ply, sid) LocalPlayer():ConCommand("say /respawn "..sid) end }, { name = "Unarrest", icon = "icon16/lock_open.png", onRun = function(ply, sid) LocalPlayer():ConCommand("say /unarrest "..sid) end }, { name = "Name change", icon = "icon16/textfield_rename.png", onRun = function(ply, sid) LocalPlayer():ConCommand("say /forcenamechange "..sid) end }, { name = "Set team", icon = "icon16/group_edit.png", onRun = function(ply, sid) local teams = DermaMenu() for v,k in pairs(impulse.Teams.Data) do teams:AddOption(k.name, function() LocalPlayer():ConCommand("say /setteam "..sid.." "..v) end) end teams:Open() end }, { name = "View inventory", icon = "icon16/magnifier.png", onRun = function(ply, sid) LocalPlayer():ConCommand("say /viewinv "..sid) end }, { name = "Combine Ban", icon = "icon16/group_delete.png", onRun = function(ply, sid) Derma_StringRequest("impulse", "Enter the length (in minutes) (1 WEEK MAX):", "", function(length) LocalPlayer():ConCommand("say /combineban "..sid.." "..length) end) end }, { name = "OOC timeout", icon = "icon16/sound_add.png", onRun = function(ply, sid) Derma_StringRequest("impulse", "Enter the timeout length (in minutes):", "10", function(length) LocalPlayer():ConCommand("say /ooctimeout "..sid.." "..length) end) end }, { name = "Un-OOC timeout", icon = "icon16/sound_delete.png", onRun = function(ply, sid) LocalPlayer():ConCommand("say /unooctimeout "..sid) end }, { name = "Cleanup Props", icon = "icon16/building_delete.png", onRun = function(ply, sid) Derma_Query("Are you sure you want to cleanup the props of:\n"..ply:Nick().."("..ply:SteamName()..")?", "ops", "Yes", function() LocalPlayer():ConCommand("say /cleanup "..sid) end, "No, take me back!") end }, { name = "Warn", icon = "icon16/error_add.png", onRun = function(ply, sid) Derma_StringRequest("impulse", "Enter the reason:", "", function(reason) LocalPlayer():ConCommand("say /warn "..sid.." "..reason) end) end }, { name = "Kick", icon = "icon16/user_go.png", onRun = function(ply, sid) Derma_StringRequest("impulse", "Enter the reason:", "Violation of community guidelines", function(reason) LocalPlayer():ConCommand("say /kick "..sid.." "..reason) end) end }, { name = "Ban", icon = "icon16/user_delete.png", onRun = function(ply, sid) local i = Derma_StringRequest("impulse", "Enter the length (in minutes):", "", function(length) Derma_StringRequest("impulse", "Enter the reason:", "", function(reason) local userInfo = sid local targ = player.GetBySteamID(sid) if IsValid(targ) then userInfo = targ:Nick().." ("..targ:SteamName()..")" end Derma_Query("Please confirm the ban:\nUser: "..userInfo.."\nLength: "..string.NiceTime(tonumber(length) * 60).." ("..length.." minutes)\nReason: "..reason.."\n\nAll issued bans are logged forever, even if deleted.", "impulse", "Confirm", function() LocalPlayer():ConCommand("say /ban "..sid.." "..length.." "..reason) end, "Abort") end) end) local textEntry = i:GetChild(4):GetChildren()[2] local function addTime(time) local v = textEntry:GetValue() local new = (tonumber(v) or 0) + time textEntry:SetValue(new) LocalPlayer():Notify("Added "..time.." minutes.") end local addDay = vgui.Create("DButton", i) addDay:SetPos(10, 90) addDay:SetSize(25, 20) addDay:SetText("+1D") addDay.DoClick = function() addTime(1440) end local addDay = vgui.Create("DButton", i) addDay:SetPos(40, 90) addDay:SetSize(25, 20) addDay:SetText("+1W") addDay.DoClick = function() addTime(10080) end local addDay = vgui.Create("DButton", i) addDay:SetPos(70, 90) addDay:SetSize(25, 20) addDay:SetText("+1M") addDay.DoClick = function() addTime(43200) end local addDay = vgui.Create("DButton", i) addDay:SetPos(100, 90) addDay:SetSize(25, 20) addDay:SetText("+6M") addDay.DoClick = function() addTime(259200) end end }, { name = "IAC Flag", icon = "icon16/flag_red.png", onRun = function(ply, sid) Derma_Query("BEFORE FLAGGING READ THE GUIDE AT: https://impulse-community.com/threads/how-to-iac-flag-a-user.3044/\nAre you sure you want to flag:\n"..ply:Nick().."("..ply:SteamName()..")?", "ops", "Yes", function() LocalPlayer():ConCommand("say /iacflag "..sid) end, "No, take me back!") end } } function PANEL:Init() self:Hide() timer.Simple(0, function() -- Time to allow SetPlayer to catch up if not IsValid(self) then return end self:Show() self:SetSize(600, 400) self:Center() self:SetTitle("Player Information") self:MakePopup() -- 3d model self.characterPreview = vgui.Create("impulseModelPanel", self) self.characterPreview:SetSize(600,400) self.characterPreview:SetPos(200,30) self.characterPreview:SetFOV(80) self.characterPreview:SetModel(self.Player:GetModel(), self.Player:GetSkin()) self.characterPreview:MoveToBack() self.characterPreview:SetCursor("arrow") --local charPreview = self.characterPreview function self.characterPreview:LayoutEntity(ent) --ent:SetSequence(ent:LookupSequence("idle")) ent:SetAngles(Angle(0,40,0)) --charPreview:RunAnimation() end timer.Simple(0, function() if not IsValid(self.characterPreview) then return end local ent = self.characterPreview.Entity if IsValid(ent) and IsValid(self.Player) then for v,k in pairs(self.Player:GetBodyGroups()) do ent:SetBodygroup(k.id, self.Player:GetBodygroup(k.id)) end end end) self.profileImage = vgui.Create("AvatarImage", self) self.profileImage:SetSize(70, 70) self.profileImage:SetPos(10, 30) self.profileImage:SetPlayer(self.Player, 64) -- Steam name self.oocName = vgui.Create("DLabel", self) self.oocName:SetFont("Impulse-CharacterInfo-NO") self.oocName:SetText(self.Player:SteamName()) self.oocName:SizeToContents() self.oocName:SetPos(86,30) self.rpName = vgui.Create("DLabel", self) self.rpName:SetFont("Impulse-Elements18") self.rpName:SetText(self.Player:Name()) self.rpName:SizeToContents() self.rpName:SetPos(self.oocName:GetWide() + 88, 42) -- team name self.teamName = vgui.Create("DLabel", self) self.teamName:SetFont("Impulse-Elements23") self.teamName:SetText(team.GetName(self.Player:Team())) self.teamName:SetTextColor(team.GetColor(self.Player:Team())) self.teamName:SizeToContents() self.teamName:SetPos(86,60) -- buttons self.profileButton = vgui.Create("DButton", self) self.profileButton:SetText("Steam Profile") self.profileButton:SetPos(10,105) self.profileButton:SetSize(90,20) self.profileButton.DoClick = function() gui.OpenURL("http://steamcommunity.com/profiles/"..self.Player:SteamID64()) end self.sidButton = vgui.Create("DButton", self) self.sidButton:SetText("Copy Steam ID") self.sidButton:SetPos(105,105) self.sidButton:SetSize(90,20) self.sidButton.DoClick = function() SetClipboardText(self.Player:SteamID()) LocalPlayer():Notify("Copied SteamID.") end self.forumButton = vgui.Create("DButton", self) self.forumButton:SetText("Panel Profile") self.forumButton:SetPos(200,105) self.forumButton:SetSize(90,20) self.forumButton.DoClick = function() gui.OpenURL(impulse.Config.PanelURL.."/index.php?t=user&id="..self.Player:SteamID64()) end self.whitelistButton = vgui.Create("DButton", self) self.whitelistButton:SetText("Forum Profile") self.whitelistButton:SetPos(295, 105) self.whitelistButton:SetSize(90, 20) self.whitelistButton.DoClick = function() if not IsValid(self.Player) then return end gui.OpenURL("https://impulse-community.com/api/getforumprofile.php?id="..self.Player:SteamID64()) end -- badges local xShift = 0 for badgeName, badgeData in pairs(impulse.Badges) do if badgeData[3](self.Player) then local badge = vgui.Create("DImageButton", self) badge:SetPos(86 + xShift, 84) badge:SetSize(16, 16) badge:SetMaterial(badgeData[1]) badge.info = badgeData[2] function badge:DoClick() Derma_Message(badge.info, "impulse", "Close") end xShift = xShift + 20 end end -- xp/playtime self.playtime = vgui.Create("DLabel", self) self.playtime:SetFont("Impulse-Elements18-Shadow") self.playtime:SetText("XP: "..self.Player:GetXP()) self.playtime:SizeToContents() self.playtime:SetPos(10,130) -- tp self.tp = vgui.Create("DLabel", self) self.tp:SetFont("Impulse-Elements18-Shadow") self.tp:SetText("Achievement Points: "..self.Player:GetSyncVar(SYNC_TROPHYPOINTS, 0)) self.tp:SizeToContents() self.tp:SetPos(10,150) -- admin stuff if LocalPlayer():IsAdmin() then self.adminTools = vgui.Create("DCollapsibleCategory", self) self.adminTools:SetPos(10,180) self.adminTools:SetSize(400, 250) self.adminTools:SetExpanded(0) self.adminTools:SetLabel("Admin tools (click to expand)") local colInv = Color(0, 0, 0, 0) function self.adminTools:Paint() self:SetBGColor(colInv) end self.adminList = vgui.Create("DIconLayout", self.adminTools) self.adminList:Dock(FILL) self.adminList:SetSpaceY(5) self.adminList:SetSpaceX(5) for v,k in pairs(quickTools) do local action = self.adminList:Add("DButton") action:SetSize(125,30) action:SetText(k.name) action:SetIcon(k.icon) action.runFunc = k.onRun local target = self.Player function action:DoClick() if not IsValid(target) then return LocalPlayer():Notify("This player has disconnected.") end self.runFunc(target, target:SteamID()) end end end end) end function PANEL:SetPlayer(player, badges) self.Player = player self.Badges = badges end vgui.Register("impulsePlayerInfoCard", PANEL, "DFrame")
--ZFUNC-joinpath-v1 local function joinpath( tab ) --> path --ZFUNC-firstchar-v1 local function firstchar( str ) return string.sub( str, 1, 1 ) end --ZFUNC-lastchar-v1 local function lastchar( str ) return string.sub( str, #str ) end local rooted = false local tmptab = {} for k, s in ipairs( tab ) do if k == 1 and firstchar( s ) == "/" then rooted = true end if firstchar( s ) == "/" then s = s:sub( 2 ) end if lastchar( s ) == "/" then s = s:sub( 1, #s - 1 ) end if #s > 0 then table.insert( tmptab, s ) end end if rooted then return "/"..table.concat( tmptab, "/" ) end return table.concat( tmptab, "/" ) end return joinpath
local MetaPlayer = FindMetaTable("Player") function MetaPlayer:CycleSpectator(a) if self:Alive() then Error("Can't spectate while alive!") return false end if not self.SpecIDX then self.SpecIDX = 0 end self.SpecIDX = self.SpecIDX + a local Players = {} for _, ply in pairs(GAMEMODE:GetActivePlayers()) do Players[#Players + 1] = ply end if self.SpecIDX < 1 then self.SpecIDX = #Players end if self.SpecIDX > #Players then self.SpecIDX = 0 end local ply ply = Players[self.SpecIDX] self:Spectate(OBS_MODE_CHASE) self:SpectateEntity(ply) end
local PANEL = {} function PANEL:Init() self:SetSkin( GAMEMODE.HudSkin ) self:ParentToHUD() self.ControlCanvas = vgui.Create( "Panel", self ) self.ControlCanvas:MakePopup() self.ControlCanvas:SetKeyboardInputEnabled( false ) self.lblCountDown = vgui.Create( "DLabel", self.ControlCanvas ) self.lblCountDown:SetText( "60" ) self.lblActionName = vgui.Create( "DLabel", self.ControlCanvas ) self.ctrlList = vgui.Create( "DPanelList", self.ControlCanvas ) self.ctrlList:SetDrawBackground( false ) self.ctrlList:SetSpacing( 2 ) self.ctrlList:SetPadding( 2 ) self.ctrlList:EnableHorizontal( true ) self.ctrlList:EnableVerticalScrollbar() self.Peeps = {} for i =1, game.MaxPlayers() do self.Peeps[i] = vgui.Create( "DImage", self.ctrlList:GetCanvas() ) self.Peeps[i]:SetSize( 16, 16 ) self.Peeps[i]:SetZPos( 1000 ) self.Peeps[i]:SetVisible( false ) self.Peeps[i]:SetImage( "icon16/emoticon_smile.png" ) end end function PANEL:PerformLayout() local cx, cy = chat.GetChatBoxPos() local cw, ch = chat.GetChatBoxSize() self:SetPos( 0, 0 ) self:SetSize( ScrW(), ScrH() ) self.ControlCanvas:StretchToParent( 0, 0, 0, 0 ) self.ControlCanvas:SetWide( ( math.Round((ScrW() / 256) - 0.5) * 256 ) + 17 ) self.ControlCanvas:SetTall( cy - 30 + (ch * 0.5) ) self.ControlCanvas:SetPos( 0, 30 ) self.ControlCanvas:CenterHorizontal() self.ControlCanvas:SetZPos( 0 ) self.lblCountDown:SetFont( "FRETTA_MEDIUM_SHADOW" ) self.lblCountDown:AlignRight() self.lblCountDown:SetTextColor( color_white ) self.lblCountDown:SetContentAlignment( 6 ) self.lblCountDown:SetWidth( 500 ) self.lblActionName:SetFont( "FRETTA_LARGE_SHADOW" ) self.lblActionName:AlignLeft() self.lblActionName:SetTextColor( color_white ) self.lblActionName:SizeToContents() self.lblActionName:SetWidth( 500 ) self.ctrlList:StretchToParent( 0, 60, 0, 0 ) end function PANEL:ChooseGamemode() self.lblActionName:SetText( "Which Gamemode Next?" ) self.ctrlList:Clear() for name, gamemode in RandomPairs( g_PlayableGamemodes ) do local lbl = vgui.Create( "DButton", self.ctrlList ) lbl:SetText( gamemode.label or name ) Derma_Hook( lbl, "Paint", "Paint", "GamemodeButton" ) Derma_Hook( lbl, "ApplySchemeSettings", "Scheme", "GamemodeButton" ) Derma_Hook( lbl, "PerformLayout", "Layout", "GamemodeButton" ) lbl:SetTall( 24 ) lbl:SetWide( 240 ) local desc = tostring( gamemode.description ) if ( gamemode.author ) then desc = desc .. "\nBy: " .. tostring( gamemode.author ) end if ( gamemode.authorurl ) then desc = desc .. "\n" .. tostring( gamemode.authorurl ) end lbl:SetTooltip( desc ) lbl.WantName = name lbl.NumVotes = 0 lbl.DoClick = function() if GetGlobalFloat( "VoteEndTime", 0 ) - CurTime() <= 0 then return end RunConsoleCommand( "votegamemode", name ) end self.ctrlList:AddItem( lbl ) end end function PANEL:ChooseMap( gamemode ) self.lblActionName:SetText( "Which Map?" ) self:ResetPeeps() self.ctrlList:Clear() local gm = g_PlayableGamemodes[ gamemode ] if ( !gm ) then MsgN( "GAMEMODE MISSING, COULDN'T VOTE FOR MAP ", gamemode ) return end for id, mapname in RandomPairs( gm.maps ) do local lbl = vgui.Create( "DButton", self.ctrlList ) lbl:SetText( mapname ) Derma_Hook( lbl, "Paint", "Paint", "MapButton" ) Derma_Hook( lbl, "ApplySchemeSettings", "Scheme", "MapButton" ) Derma_Hook( lbl, "PerformLayout", "Layout", "MapButton" ) lbl:SetTall( 154 ) lbl:SetWide( 256 ) lbl.WantName = mapname lbl.NumVotes = 0 lbl.DoClick = function() if GetGlobalFloat( "VoteEndTime", 0 ) - CurTime() <= 0 then return end RunConsoleCommand( "votemap", mapname ) end -- IMAGES! yay local Image = vgui.Create("DImage", lbl) if file.Exists("maps/thumb/"..mapname..".png", "GAME") then -- Setting the image does not require a parent directory thing Image:SetImage("maps/thumb/"..mapname..".png") else Image:SetImage("maps/thumb/noicon.png") end Image:SizeToContents() Image:SetSize(math.min(Image:GetWide(), 128), math.min(Image:GetTall(), 128)) Image:SetPos( (lbl:GetWide() * 0.5) - 64, 4 ) self.ctrlList:AddItem( lbl ) end end function PANEL:ResetPeeps() for i=1, game.MaxPlayers() do self.Peeps[i]:SetPos( math.random( 0, 600 ), -16 ) self.Peeps[i]:SetVisible( false ) self.Peeps[i].strVote = nil end end function PANEL:FindWantBar( name ) for k, v in pairs( self.ctrlList:GetItems() ) do if ( v.WantName == name ) then return v end end end function PANEL:PeepThink( peep, ent ) if ( !IsValid( ent ) ) then peep:SetVisible( false ) return end peep:SetTooltip( ent:Nick() ) peep:SetMouseInputEnabled( true ) if ( !peep.strVote ) then peep:SetVisible( true ) peep:SetPos( math.random( 0, 600 ), -16 ) if ( ent == LocalPlayer() ) then peep:SetImage( "icon16/star.png" ) end end peep.strVote = ent:GetNWString( "Wants", "" ) local bar = self:FindWantBar( peep.strVote ) if ( IsValid( bar ) ) then bar.NumVotes = bar.NumVotes + 1 local vCurrentPos = Vector( peep.x, peep.y, 0 ) local vNewPos = Vector( (bar.x + bar:GetWide()) - 15 * bar.NumVotes - 4, bar.y + ( bar:GetTall() * 0.5 - 8 ), 0 ) if ( !peep.CurPos || peep.CurPos != vNewPos ) then peep:MoveTo( vNewPos.x, vNewPos.y, 0.2 ) peep.CurPos = vNewPos end end end function PANEL:Think() local Seconds = GetGlobalFloat( "VoteEndTime", 0 ) - CurTime() if ( Seconds < 0 ) then Seconds = 0 end self.lblCountDown:SetText( Format( "%i", Seconds ) ) for k, v in pairs( self.ctrlList:GetItems() ) do v.NumVotes = 0 end for i=1, game.MaxPlayers() do self:PeepThink( self.Peeps[i], Entity(i) ) end end function PANEL:Paint() Derma_DrawBackgroundBlur( self ) local CenterY = ScrH() / 2.0 local CenterX = ScrW() / 2.0 surface.SetDrawColor( 0, 0, 0, 200 ) surface.DrawRect( 0, 0, ScrW(), ScrH() ) end function PANEL:FlashItem( itemname ) local bar = self:FindWantBar( itemname ) if ( !IsValid( bar ) ) then return end timer.Simple( 0.0, function() bar.bgColor = Color( 0, 255, 255 ) surface.PlaySound( "hl1/fvox/blip.wav" ) end ) timer.Simple( 0.2, function() bar.bgColor = nil end ) timer.Simple( 0.4, function() bar.bgColor = Color( 0, 255, 255 ) surface.PlaySound( "hl1/fvox/blip.wav" ) end ) timer.Simple( 0.6, function() bar.bgColor = nil end ) timer.Simple( 0.8, function() bar.bgColor = Color( 0, 255, 255 ) surface.PlaySound( "hl1/fvox/blip.wav" ) end ) timer.Simple( 1.0, function() bar.bgColor = Color( 100, 100, 100 ) end ) end derma.DefineControl( "VoteScreen", "", PANEL, "DPanel" )
VERSION = "2.0.2" local micro = import("micro") local config = import("micro/config") local shell = import("micro/shell") local buffer = import("micro/buffer") -- outside init because we want these options to take effect before -- buffers are initialized config.RegisterCommonOption("rust", "rustfmt", true) function init() config.MakeCommand("rustfmt", rustfmt, config.NoComplete) config.AddRuntimeFile("rs", config.RTHelp, "help/rust-plugin.md") end function onSave(bp) if bp.Buf:FileType() == "rs" then rustfmt(bp) end return true end function rustfmt(bp) bp:Save() local _, err = shell.RunCommand("rustfmt " .. bp.Buf.Path) if err ~= nil then micro.InfoBar():Error(err) return end bp.Buf:ReOpen() end
-- This performance benchmark was initially exposed in LuaJIT mailing list -- by Laurent Deniau (Laurent.Deniau@cern.ch): -- -- This particualar version is slightly modified in order to make -- callgrind profiling possible. -- Copyright (C) 2015-2019 IPONWEB Ltd. See Copyright Notice in COPYRIGHT local function find_duplicates(inp) local out = {} for _,v in ipairs(inp) do out[v] = out[v] and out[v]+1 or 1 end for _,v in ipairs(inp) do if out[v] > 1 then out[#out+1], out[v] = v, 0 end end return out end local inp, out inp = {"b","a","c","c","e","a","c","d","c","d"} -- Different iteration counts are possible for different situations. -- In case you need an integral performance test (i.e. to run with `time`), -- you can use original 10'000'000 iteration count. -- In case you need a speedrun, callgrind profile or readable JIT dump, you -- can use smaller numbers, i.e. 100'000. Note that big iteration counts will -- result in callgrind OOMs. --for i=1,100000 do for _=1,10000000 do out = find_duplicates(inp) end io.write('{ "', table.concat(out, '", "'), '" }\n')
#!/usr/bin/env luajit --------- -- This script connects to fedmsg/zeromq interface of Anitya -- <https://release-monitoring.org> and flags packages in the edge branch -- for which a new version is released. It should be run as a daemon. Before -- first run or after an outage run anitya-check-all to check all packages. -- -- ## How does it work -- -- Anitya watches registered projects and when a new release is found, then it -- sends a message via fedmsg. This scripts consumes these messages. If the -- updated project contains mapping for the configured distro, then it takes -- distro's package name and new version from the message. Then looks into the -- aports database; if there's an older version that is not flagged yet, or the -- flag contains older new version, then it flags the package and sends email -- to its maintainer. -- local log = require 'turbo.log' local escape = require 'turbo.escape' local zmq = require 'lzmq' local zpoller = require 'lzmq.poller' local aports = require 'anitya_aports' local conf = require 'config' local utils = require 'utils' local get = utils.get local distro = conf.anitya.distro local json_decode = escape.json_decode --- Receives multipart message and returns decoded JSON payload. local function receive_json_msg(sock) local resp, err = sock:recv_multipart() if err then return nil, err end log.debug('Received message from topic '..resp[1]) local ok, res = pcall(json_decode, resp[2]) if not ok then return nil, 'Failed to parse message as JSON: '..res end return res end --- Handles message from topic `anitya.project.map.new`; if it's mapping for -- our distro, then flags the package if it's outdated. local function handle_map_new(msg) if get(msg, 'distro.name') ~= distro then return nil end local pkgname = get(msg, 'message.new') local version = get(msg, 'project.version') if pkgname and version then log.notice(("Received version update: %s %s"):format(pkgname, version)) aports.flag_outdated_pkgs(pkgname, version) end end --- Handles message from topic `anitya.project.version.update`; if the project -- contains mapping for our distro, then flags the package if it's outdated. local function handle_version_update(msg) local pkgname = nil for _, pkg in ipairs(get(msg, 'message.packages') or {}) do if pkg.distro == distro then pkgname = pkg.package_name break end end local version = get(msg, 'message.upstream_version') if pkgname and version then log.notice(("Received version update: %s %s"):format(pkgname, version)) aports.flag_outdated_pkgs(pkgname, version) end end -------- M a i n -------- local sock, err = zmq.context():socket(zmq.SUB, { connect = conf.anitya.fedmsg_uri }) zmq.assert(sock, err) local handlers = { ['org.release-monitoring.prod.anitya.project.version.update'] = handle_version_update, ['org.release-monitoring.prod.anitya.project.map.new'] = handle_map_new, } for topic, _ in pairs(handlers) do sock:subscribe(topic) end local poller = zpoller.new(1) poller:add(sock, zmq.POLLIN, function() local payload, err2 = receive_json_msg(sock) if err2 then log.error('Failed to receive message from fedmsg: '..err) end local ok, err3 = pcall(handlers[payload.topic], payload.msg) if not ok then log.error(err3) end end) log.notice('Connecting to '..conf.anitya.fedmsg_uri) poller:start()