content
stringlengths
5
1.05M
HedgewarsScriptLoad("/Scripts/Locale.lua") HedgewarsScriptLoad("/Scripts/Achievements.lua") local playerTeamName local player = nil local enemy = nil local firedShell = false local turnNumber = 0 local hhs = {} local numhhs = 0 function onGameInit() Seed = 0 TurnTime = 20000 CaseFreq = 0 MinesNum = 0 Explosives = 0 Map = "Bamboo" Theme = "Bamboo" -- Disable Sudden Death HealthDecrease = 0 WaterRise = 0 GameFlags = gfDisableWind playerTeamName = AddMissionTeam(-1) player = AddMissionHog(10) AddTeam(loc("Cybernetic Empire"), -6, "ring", "Island", "Robot_qau", "cm_cyborg") enemy = AddHog(loc("Unit 835"), 1, 10, "cyborg1") SetGearPosition(player,142,656) SetGearPosition(enemy,1824,419) end function onGameStart() ShowMission(loc("Bamboo Thicket"), loc("Scenario"), loc("Eliminate the enemy."), -amBazooka, 0) -- CRATE LIST. SpawnSupplyCrate(891,852,amBazooka) SpawnSupplyCrate(962,117,amBlowTorch) SpawnSupplyCrate(403,503,amParachute) AddAmmo(enemy, amGrenade, 100) SetWind(100) end function onNewTurn() turnNumber = turnNumber + 1 end function onAmmoStoreInit() SetAmmo(amSkip, 9, 0, 0, 0) SetAmmo(amGirder, 4, 0, 0, 0) SetAmmo(amBlowTorch, 0, 0, 0, 1) SetAmmo(amParachute, 0, 0, 0, 2) SetAmmo(amBazooka, 0, 0, 0, 2) end function onGearAdd(gear) if GetGearType(gear) == gtHedgehog then hhs[numhhs] = gear numhhs = numhhs + 1 elseif GetGearType(gear) == gtShell then firedShell = true end end function onGameResult(winner) if (winner == GetTeamClan(playerTeamName)) then SaveMissionVar("Won", "true") SendStat(siGameResult, loc("Mission succeeded!")) if (turnNumber < 6) and (firedShell == false) then awardAchievement(loc("Energetic Engineer")) end else SendStat(siGameResult, loc("Mission failed!")) end end
local image = require 'image' local paths = require 'paths' local t = require 'datasets/transforms' local ffi = require 'ffi' local M = {} local LaneDataset = torch.class('resnet.LaneDataset', M) function LaneDataset:__init(imageInfo, opt, split) self.imageInfo = imageInfo[split] self.opt = opt self.split = split self.dir = opt.data assert(paths.dirp(self.dir), 'directory does not exist: ' .. self.dir) end function LaneDataset:get(i) local imgpath = ffi.string(self.imageInfo.imagePath[i]:data()) local lbpath = ffi.string(self.imageInfo.labelPath[i]:data()) local image = self:_loadImage(self.dir .. imgpath, 3, 'float') local label = self:_loadImage(self.dir .. lbpath, 1, 'byte') assert(torch.max(label)<=6, 'label larger than 6!') assert(torch.min(label)>=0, 'label smaller than 0!') label:add(1) return { input = image, segLabel = label, exist = self.imageInfo.Exist[i], imgpath = self.imageInfo.imagePath[i], } end --[[function LaneDataset:get_seq(i, frame) local imgpath = ffi.string(self.imageInfo.imagePath[i+frame-1]:data()) local lbpath = ffi.string(self.imageInfo.labelPath[i+frame-1]:data()) local image = self:_loadImage(self.dir .. imgpath, 3, 'float') local label = self:_loadImage(self.dir .. lbpath, 1, 'byte') label:add(1) return { input = image, target = label, imgpath = self.imageInfo.imagePath[i+frame-1], } end]] function LaneDataset:_loadImage(path, channel, ttype) local ok, input = pcall(function() return image.load(path, channel, ttype) end) if not ok then print(path) print("load image failed!") return -1 end return input end function LaneDataset:size() return self.imageInfo.imagePath:size(1) end local meanstd = { mean = { 0.3598, 0.3653, 0.3662 }, std = { 0.2573, 0.2663, 0.2756 }, } function LaneDataset:preprocess() -- Don't use data augmentation for training RNN if self.split == 'train' then return t.Compose{ --t.ScaleWH(768, 432), --t.ScaleWH(850, 368), t.ScaleWH(640, 368), --t.RandomCrop(640, 368), t.ColorNormalize(meanstd), } elseif self.split == 'val' then return t.Compose{ t.ScaleWH(640, 368), --t.ScaleWH(768, 432), --t.ScaleWH(850, 368), --t.RandomCrop(640, 368), t.ColorNormalize(meanstd), } else error('invalid split: ' .. self.split) end end function LaneDataset:preprocess_aug() if self.split == 'train' then return t.Compose{ --t.RandomScaleRatio(780, 864, 274, 304), t.RandomScaleRatio(860, 900, 425, 445), --t.RandomScaleRatio(860, 940, 412, 452), --for r50 large --t.RandomScaleRatio(600, 680, 350, 390), t.ColorNormalize(meanstd), t.Rotation(1, -1.7), --t.RandomCrop(728, 264), t.RandomCropLane(640, 368), --t.RandomCropLane(768, 432), --t.RandomCrop(816, 288), } elseif self.split == 'val' then return t.Compose{ t.ScaleWH(640, 368), --t.ScaleWH(880, 435), --t.ScaleWH(900, 432), --t.RandomCropLane(640, 368), --t.RandomCropLane(768, 432), t.ColorNormalize(meanstd), } else error('invalid split: ' .. self.split) end end return M.LaneDataset
-- -*- lua -*- help( [[ This module loads the gpaw environment version 0.10.0 Note that this module removes all other modules during load ]]) purgeAndLoad('gcc/4.7.2', 'intelmpi/4.1.0', 'ase/3.9.1', 'openblas/0.2.6', 'python/2.7.3', 'mkl/11.0.2', 'hdf5-par/1.8.10', 'gpaw/0.11.0', 'gpaw-setups/0.9.11271')
-- Beatmap Select Button -- Part of Live Simulator: 2 -- See copyright notice in main.lua local love = require("love") local Luaoop = require("libs.Luaoop") local MainFont = require("main_font") local color = require("color") local ImageButton = require("game.ui.image_button") local beatmapSelButton = Luaoop.class("Livesim2.BeatmapSelectButtonUI", ImageButton) function beatmapSelButton:new(name, format, difficulty) ImageButton.new(self, "assets/image/ui/s_button_03", 0.75) local fmtfont, difffont, namefont = MainFont.get(11, 14, 20) self.formatText = love.graphics.newText(fmtfont) self.formatText:add({color.black, format}, 6, 41) self.nameText = love.graphics.newText(namefont) self.nameText:add({color.white, name}, 8, 12) if difficulty and #difficulty > 0 then self.difficultyText = love.graphics.newText(difffont) self.difficultyText:add({color.white, difficulty}, 314 - difffont:getWidth(difficulty), 5) end end function beatmapSelButton:render(x, y) ImageButton.render(self, x, y) love.graphics.draw(self.nameText, x, y) love.graphics.draw(self.formatText, x, y) if self.difficultyText then love.graphics.draw(self.difficultyText, x, y) end end return beatmapSelButton
local Modules = game:GetService("Players").LocalPlayer.PlayerGui.AvatarEditorInGame.Modules local Action = require(Modules.Common.Action) return Action(script.Name, function(left, top, right, bottom) return { left = left, top = top, right = right, bottom = bottom, } end)
return { name = "Česky [Built-in]", description = "Překlad do češtiny.", api_version = 4, -- incomplete skip = true, -- please use ISO 639-1 plus country code if required language_code = "cs" }
--[[ desc: Pathgate, a article of path gate. author: Musoucrow since: 2018-6-5 alter: 2019-5-7 ]]-- local _Point = require("graphics.drawunit.point") ---@class Actor.Component.Article.Pathgate ---@field public lightTweener Util.Gear.Tweener ---@field public doorTweener Util.Gear.Tweener ---@field public isOpened boolean ---@field public isLock boolean ---@field public doorTime milli ---@field public lightTime milli ---@field public enable boolean ---@field public isBoss boolean ---@field public crossActorDatas table<int, Actor.RESMGR.InstanceData> ---@field public portPosition Graphics.Drawunit.Point ---@field public isEntrance boolean local _Pathgate = require("core.class")() function _Pathgate:Ctor(data, param) self.isOpened = false self.isLock = false self.enable = param.pathgateEnable self.doorTime = data.doorTime or 500 self.lightTime = data.lightTime or 1000 self.isBoss = data.isBoss self.crossActorDatas = {} self.portPosition = _Point.New(true, param.portPosition.x, param.portPosition.y) self.isEntrance = param.isEntrance end return _Pathgate
local folderOfThisFile = (...):match("(.-)[^%/%.]+$") local class = require(folderOfThisFile.."/middleclass") local LineSegment = class("LineSegment") function LineSegment:init(p0, p1) -- p0, p1: type(Point) self.p0 = p0 self.p1 = p1 end function LineSegment.compareLengths_MAX(segment0, segment1) -- segment0, segment1: type(LineSegment) local len0 = Point.distance(segment0.p0, segment0.p1) local len1 = Point.distance(segment1.p0, segment1.p1) if len0 < len1 then return 1 end if len0 > len1 then return -1 end return 0 end function LineSegment.compareLengths(edge0, edge1) -- edge0, edge1: type(LineSegment) return -LineSegment.compareLengths_MAX(edge0, edge1) end return LineSegment
local webhook = {} function webhook:modify(callback, payload) self.client:modifyWebhook(callback, self.id, payload) end function webhook:modifyWithToken(callback, payload) self.client:modifyWebhookWithToken(callback, self.id, self.token, payload) end function webhook:delete(callback) self.client:deleteWebhook(callback, self.id) end function webhook:deleteWithToken(callback) self.client:deleteWebhookWithToken(callback, self.id, self.token) end function webhook:executeSlack(callback, payload) self.client:executeSlackCompatibleWebhook(callback, self.id, self.token, payload) end function webhook:executeGitHub(callback, payload) self.client:executeGitHubCompatibleWebhook(callback, self.id, self.token, payload) end return webhook
-- ShowUserGuide -- created on 2021/9/4 -- author @zoloypzuo function ImGui.ShowUserGuide() -- ImGuiIO& io = ImGui.GetIO(); ImGui.BulletText("Double-click on title bar to collapse window."); ImGui.BulletText("Click and drag on lower corner to resize window\n" .. "(double-click to auto fit window to its contents)."); ImGui.BulletText("CTRL+Click on a slider or drag box to input value as text."); ImGui.BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); -- if (io.FontAllowUserScaling) -- ImGui.BulletText("CTRL+Mouse Wheel to zoom window contents."); ImGui.BulletText("While inputing text:\n"); ImGui.Indent(); ImGui.BulletText("CTRL+Left/Right to word jump."); ImGui.BulletText("CTRL+A or double-click to select all."); ImGui.BulletText("CTRL+X/C/V to use clipboard cut/copy/paste."); ImGui.BulletText("CTRL+Z,CTRL+Y to undo/redo."); ImGui.BulletText("ESCAPE to revert."); ImGui.BulletText("You can apply arithmetic operators +,*,/ on numerical values.\nUse +- to subtract."); ImGui.Unindent(); ImGui.BulletText("With keyboard navigation enabled:"); ImGui.Indent(); ImGui.BulletText("Arrow keys to navigate."); ImGui.BulletText("Space to activate a widget."); ImGui.BulletText("Return to input text into a widget."); ImGui.BulletText("Escape to deactivate a widget, close popup, exit child window."); ImGui.BulletText("Alt to jump to the menu layer of a window."); ImGui.BulletText("CTRL+Tab to select a window."); ImGui.Unindent(); end
Locales['de'] = { -- Cloakroom ['cloakroom'] = 'Umkleide', ['ems_clothes_civil'] = 'Zivil', ['ems_clothes_ems'] = 'Uniform', -- Vehicles ['ambulance'] = 'Rettungsdienst', ['helicopter_prompt'] = 'Drücke ~INPUT_CONTEXT~ um auf das ~y~Helikopter-Menü~s~ zuzugreifen.', ['garage_prompt'] = 'Drücke ~INPUT_CONTEXT~ um auf das ~y~Fahrzeug-Menü~s~ zuzugreifen.', ['garage_title'] = 'Fahrzeugmenü', ['garage_stored'] = 'gelagert', ['garage_notstored'] = 'nicht in der Garage', ['garage_storing'] = 'Wir versuchen das Fahrzeug einzulagern. Bitte stelle sicher, dass sich kein Spieler in der Nähe des Fahrzeugs befindet.', ['garage_has_stored'] = 'Das Fahrzeug wurde in deiner Garage eingelagert.', ['garage_has_notstored'] = 'Es wurde kein Fahrzeug in der Nähe gefunden, dass dir gehört.', ['garage_notavailable'] = 'Dein Fahrzeug ist nicht in der Garage.', ['garage_blocked'] = 'Es existieren keine verfügbaren Spawnpoints!', ['garage_empty'] = 'Du hast keine Fahrzeuge in deiner Garage.', ['garage_released'] = 'Dein Fahrzeug wurde aus der Garage gefahren.', ['garage_store_nearby'] = 'Es sind keine Fahrzeuge in der Nähe.', ['garage_storeditem'] = 'Öffne Garage', ['garage_storeitem'] = 'Fahrzeug in der Garage einlagern', ['garage_buyitem'] = 'Fahrzeug-Shop', ['shop_item'] = '$%s', ['vehicleshop_title'] = 'Fahrzeug-Shop', ['vehicleshop_confirm'] = 'Du möchstest dieses Fahrzeug kaufen?', ['vehicleshop_bought'] = 'Du hast dir einen ~y~%s~s~ für ~g~$%s~s~ gekauft!', ['vehicleshop_money'] = 'Du kannst dir dieses Fahrzeug nicht leisten!', ['vehicleshop_awaiting_model'] = 'Dieses Fahrzeug ~g~LÄDT~s~ bitte warte', ['confirm_no'] = 'Nein', ['confirm_yes'] = 'Ja', -- Action Menu ['revive_inprogress'] = 'Eine Wiederbelebung findet statt!', ['revive_complete'] = 'Du hast ~y~%s~s~ wiederbelebt', ['revive_complete_award'] = 'Du hast ~y~%s~s~ wiederbelebt und dabei ~g~$%s~s~ erhalten!', ['revive_fail_offline'] = 'Dieser Spieler ist nicht länger online', ['heal_inprogress'] = 'Du heilst!', ['heal_complete'] = 'yDu hast ~y~%s~s~ geheilt!', ['no_players'] = 'Keine Spieler in der Nähe', ['player_not_unconscious'] = 'Diese Spieler ist nicht bewusstlos!', ['player_not_conscious'] = 'Dieser Spieler ist nicht bei Bewusstsein!', -- Boss Menu ['boss_actions'] = 'Chef-Aktionen', -- Misc ['invalid_amount'] = '~r~Ungültige Menge', ['actions_prompt'] = 'Drücke ~INPUT_CONTEXT~ um das ~y~Rettungsdienst-Menü~s~ zu öffnen.', ['deposit_amount'] = 'Menge deponieren', ['money_withdraw'] = 'Menge abheben', ['fast_travel'] = 'Drücke ~INPUT_CONTEXT~ zu schnellreisen.', ['open_pharmacy'] = 'Drücke ~INPUT_CONTEXT~ um die Apotheke zu öffnen.', ['pharmacy_menu_title'] = 'Apotheke', ['pharmacy_take'] = 'Nimm <span style="color:blue;">%s</span>', ['medikit'] = 'Medikit', ['bandage'] = 'Verbände', ['max_item'] = 'Du trägst bereits genug.', -- F6 Menu ['ems_menu'] = 'Rettungsdienst-Menü', ['ems_menu_title'] = 'Rettungsdienst-Menü', ['ems_menu_revive'] = 'Spieler wiederbeleben', ['ems_menu_putincar'] = 'In Fahrzeug stecken', ['ems_menu_small'] = 'Kleine Wunden behandeln', ['ems_menu_big'] = 'Ernsthafte Verletzungen behandeln', -- Phone ['alert_ambulance'] = 'Rettungsdienst alarmieren', -- Death ['respawn_available_in'] = 'Respawn in ~b~%s Minuten %s Sekunden~s~ verfügbar', ['respawn_bleedout_in'] = 'Du wirst in ~b~%s Minuten %s Sekunden~s~ ausbluten\n', ['respawn_bleedout_prompt'] = 'Drücke [~b~E~s~] um zu respawnen', ['respawn_bleedout_fine'] = 'Drücke [~b~E~s~] um für ~g~$%s~s~ zu respawnen', ['respawn_bleedout_fine_msg'] = 'Du hast ~r~$%s~s~ bezahlt, um zu respawnen.', ['distress_send'] = 'Drücke [~b~G~s~] um ein Notsignal zu senden', ['distress_sent'] = 'Notsignal wurde an den Rettungsdienst übermittelt!', ['combatlog_message'] = 'Du wurdest respawnt, da du den Server verlassen hast, als du gestorben bist.', -- Revive ['revive_help'] = 'Belebe einen Spieler wieder', -- Item ['used_medikit'] = 'Du hast ~y~ein~s~ Medikit verwendet', ['used_bandage'] = 'Du hast ~y~einen~s~ Verband verwendet', ['not_enough_medikit'] = 'Du hast keine ~b~Medikits~s~.', ['not_enough_bandage'] = 'Du hast keine ~b~Verbände~s~.', ['healed'] = 'Du wurdest behandelt.', -- Blips ['blip_hospital'] = 'Krankenhaus', ['blip_dead'] = 'Bewusstloser Spieler', }
local _, ns = ... local oUF = ns.oUF or oUF assert(oUF, 'oUF not loaded') local Update = function(self, event, ...) local _, instanceType = IsInInstance() if instanceType ~= 'arena' then self.Trinket.Icon:SetTexture("Interface\\Icons\\Ability_pvp_gladiatormedallion") self.Trinket:Hide() return else self.Trinket:Show() end if(self.Trinket.PreUpdate) then self.Trinket:PreUpdate(event, ...) end if event == "ARENA_COOLDOWNS_UPDATE" then local unit = ... local tunit = self.unit if self.unit == unit then C_PvP.RequestCrowdControlSpell(unit) local spellID, startTime, duration = C_PvP.GetArenaCrowdControlInfo(unit) if spellID and startTime ~= 0 and duration ~= 0 then CooldownFrame_Set(self.Trinket.cooldownFrame, startTime / 1000, duration / 1000, 1) end end elseif event == "ARENA_CROWD_CONTROL_SPELL_UPDATE" then local unit, spellID = ... if self.unit == unit then local _, _, spellTexture = GetSpellInfo(spellID) self.Trinket.Icon:SetTexture(spellTexture) end elseif event == 'PLAYER_ENTERING_WORLD' then CooldownFrame_Set(self.Trinket.cooldownFrame, 1, 1, 1) end if(self.Trinket.PostUpdate) then self.Trinket:PostUpdate(event, ...) end end local Enable = function(self) if self.Trinket then self:RegisterEvent("ARENA_COOLDOWNS_UPDATE", Update, true) self:RegisterEvent("PLAYER_ENTERING_WORLD", Update, true) self:RegisterEvent("ARENA_CROWD_CONTROL_SPELL_UPDATE", Update, true) if not self.Trinket.cooldownFrame then self.Trinket.cooldownFrame = CreateFrame("Cooldown", nil, self.Trinket) self.Trinket.cooldownFrame:SetAllPoints(self.Trinket) end if not self.Trinket.Icon then self.Trinket.Icon = self.Trinket:CreateTexture(nil, "BORDER") self.Trinket.Icon:SetAllPoints(self.Trinket) self.Trinket.Icon:SetTexCoord(0.07, 0.93, 0.07, 0.93) self.Trinket.Icon:SetTexture("Interface\\Icons\\Ability_pvp_gladiatormedallion") end return true end end local Disable = function(self) if self.Trinket then self:UnregisterEvent("ARENA_COOLDOWNS_UPDATE", Update) self:UnregisterEvent("PLAYER_ENTERING_WORLD", Update) self:UnregisterEvent("ARENA_CROWD_CONTROL_SPELL_UPDATE", Update) self.Trinket:Hide() end end oUF:AddElement('Trinket', Update, Enable, Disable)
-- config: (lint (only syntax:misplaced-dots)) local function f(..., x) end local function f(x, ...) end -- ok
--====================================================================-- -- dmc_corona/dmc_websockets/frame.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (C) 2014-2015 David McCuskey. All Rights Reserved. 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. --]] --====================================================================-- --== DMC Corona Library : DMC WebSockets Frame --====================================================================-- --[[ WebSocket support adapted from: * Lumen (http://github.com/xopxe/Lumen) * lua-websocket (http://lipp.github.io/lua-websockets/) * lua-resty-websocket (https://github.com/openresty/lua-resty-websocket) --]] -- Semantic Versioning Specification: http://semver.org/ local VERSION = "1.2.0" --====================================================================-- --== Imports local bit = require 'lib.dmc_lua.bit' local ByteArray = require 'lib.dmc_lua.lua_bytearray' local Error = require 'dmc_websockets.exception' local Utils = require 'lib.dmc_lua.lua_utils' --====================================================================-- --== Setup, Constants local ProtocolError = Error.ProtocolError local band = bit.band local bor = bit.bor local bxor = bit.bxor local lshift = bit.lshift local rshift = bit.rshift local tohex = bit.tohex local mmin = math.min local mfloor = math.floor local mrandom = math.random local schar = string.char local sbyte = string.byte local ssub = string.sub local tinsert = table.insert local tconcat = table.concat -- Forward declare local bit_4, bit_7, bit_3_0, bit_6_0, bit_6_4 local decodeCloseFrameData, encodeCloseFrameData --== WebSockets Constants local SML_FRAME_SIZE = 125 -- 125 bytes local MED_FRAME_SIZE = 0xffff -- 65535 bytes local LRG_FRAME_SIZE = 0xffffffffffffffff -- a lot local MED_FRAME_TOKEN = 126 local LRG_FRAME_TOKEN = 127 local FRAME_TYPE = { [0x0] = "continuation", continuation = 0x0, [0x1] = "text", text = 0x1, [0x2] = "binary", binary = 0x2, [0x8] = "close", close = 0x8, [0x9] = "ping", ping = 0x9, [0xa] = "pong", pong = 0xa, } local CLOSE_CODES = { OK = { code=1000, reason="Purpose for connection has been fulfilled" }, GOING_AWAY = { code=1001, reason="Going Away" }, PROTO_ERR = { code=1002, reason="Termination due to protocol error" }, UNHANDLED_DATA = { code=1003, reason="Cannot accept data type" }, -- 1004, reserved for future use, DO NOT USE RESERVED_1004 = { code=1004, reason="reserved, DO NOT USE" }, -- 1005, internal use only, No status code received NO_STATUS_CODE = { code=1005, reason="No status code received" }, -- 1006, internal use only, Abnormal Close, eg without Close frame CONNECTION_CLOSE_ERR = { code=1006, reason="Connection closed abnormally" }, INVALID_DATA = { code=1007, reason="invalid data received" }, POLICY_VIOLATION = { code=1008, reason="internal policy violation" }, MSG_SIZE_ERR = { code=1009, reason="message is too big for processing" }, EXTENSION_ERR = { code=1010, reason="expected extension negotiation (client)" }, UNEXPECTED_ERR = { code=1011, reason="unexpected internal error" }, -- 1015, internal use only, TLS handshake error TLS_HANDSHAKE_ERR = { code=1015, reason="TLS handshake failure" }, } local VALID_CLOSE_CODES = { CLOSE_CODES.OK.code, CLOSE_CODES.GOING_AWAY.code, CLOSE_CODES.PROTO_ERR.code, CLOSE_CODES.UNHANDLED_DATA.code, CLOSE_CODES.INVALID_DATA.code, CLOSE_CODES.POLICY_VIOLATION.code, CLOSE_CODES.MSG_SIZE_ERR.code, CLOSE_CODES.EXTENSION_ERR.code, CLOSE_CODES.UNEXPECTED_ERR.code } --====================================================================-- --== Support Functions local bits = function(...) local n = 0 for _,bitn in pairs{...} do n = n + 2^bitn end return n end bit_4 = bits(3) bit_7 = bits(7) bit_3_0 = bits(3,2,1,0) bit_6_0 = bits(6,5,4,3,2,1,0) bit_6_4 = bits(6,5,4) local function getunsigned_2bytes_bigendian(s) return 256*s:byte(1) + s:byte(2) end --from http://stackoverflow.com/questions/5241799/lua-dealing-with-non-ascii-byte-streams-byteorder-change --adapted for fixed 4 byte bigendian unsigned ints. local function int_to_bytes( num, endian ) local res={} endian = 'big' local n = 4 --math.ceil(select(2,math.frexp(num))/8) -- number of bytes to be used. for k=n,1,-1 do -- 256 = 2^8 bits per char. local mul=2^(8*(k-1)) res[k]=mfloor(num/mul) num=num-res[k]*mul end assert(num==0) if endian == "big" then local t={} for k=1,n do t[k]=res[n-k+1] end res=t end return schar(unpack(res)) end -- endian big, 4 bytes local function bytes_to_int( str ) local t={str:byte(1,4)} local n=0 for k=1,#t do n=n+t[#t-k+1]*2^((k-1)*8) end return n end local xor_mask = function( encoded, mask, payload ) local transformed_arr = {} -- xor chunk-wise to prevent stack overflow. -- sbyte and schar multiple in/out values -- which require stack for p=1,payload,2000 do local transformed = {} local last = mmin(p+1999,payload) local original = {sbyte(encoded,p,last)} for i=1,#original do local j = (i-1) % 4 + 1 transformed[i] = bxor(original[i],mask[j]) -- transformed[i] = band(bxor(original[i],mask[j]), 0xFF) end local xored = schar(unpack(transformed)) tinsert(transformed_arr,xored) end return tconcat(transformed_arr) end --====================================================================-- --== Main Functions --====================================================================-- -- forward declarations local readFrameHeader -- step 1 local processFrameType -- step 2 local processFramePayload -- step 3 local verifyFramePayload -- step 4 local readMaskData -- step 5a local readPayloadData -- step 5b -- read header and payload info readFrameHeader = function( frame, bytearray ) -- print( "readFrameHeader", bytearray.pos ) local data = bytearray:readBuf( 2 ) frame.type, frame.payload = data:byte( 1, 2 ) end -- process frame type info processFrameType = function( frame ) -- print( "processFrameType" ) frame.fin = band( frame.type, bit_7 ) ~= 0 frame.opcode = band( frame.type, bit_3_0 ) -- print( '>>>>', frame.opcode, frame.fin ) if band( frame.type, bit_6_4 ) ~= 0 then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Data packet too large for control frame" }) return end if frame.opcode >= 0x3 and frame.opcode <= 0x7 then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Received reserved non-control frame" } ) return end if frame.opcode >= 0xb and frame.opcode <= 0xf then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Received reserved control frame" } ) return end end -- process frame payload info processFramePayload = function( frame, bytearray ) -- print( "processFramePayload", bytearray.pos ) frame.masked = band( frame.payload, bit_7 ) ~= 0 frame.payload_len = band( frame.payload, bit_6_0 ) local payload_len = frame.payload_len local data if payload_len <= SML_FRAME_SIZE then -- pass elseif payload_len == MED_FRAME_TOKEN then data = bytearray:readBuf( 2 ) frame.payload_len = bor( lshift( data:byte(1), 8), data:byte(2) ) elseif payload_len == LRG_FRAME_TOKEN then data = bytearray:readBuf( 8 ) if data:byte(1) ~= 0 or data:byte(2) ~= 0 or data:byte(3) ~= 0 or data:byte(4) ~= 0 then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Payload length too large" } ) return end local byte_5 = data:byte(5) if band( byte_5, bit_7 ) ~= 0 then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Payload length too large" } ) return end frame.payload_len = bor( lshift(byte_5, 24), lshift( data:byte(6), 16), lshift( data:byte(7), 8), data:byte(8) ) else error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Invalid payload size" } ) end end -- verify frame payload verifyFramePayload = function( frame, bytearray ) -- print( "verifyFramePayload", bytearray.pos ) -- control frame check if band( frame.opcode, bit_4 ) ~= 0 then if frame.payload_len > SML_FRAME_SIZE then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Data packet too large for control frame<<<" } ) return end if not frame.fin then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Fragmented control frame" } ) return end end if frame.masked then readMaskData( frame, bytearray ) else readPayloadData( frame, bytearray ) end end -- process frame mask readMaskData = function( frame, bytearray ) -- print( "readMaskData", bytearray.pos ) local data = bytearray:readBuf( 4 ) local m1,m2,m3,m4 = data:byte( 1, 4 ) frame.mask = { m1,m2,m3,m4 } readPayloadData( frame, bytearray ) end -- read actual payload data readPayloadData = function( frame, bytearray ) -- print( "readPayloadData", bytearray.pos ) local bytes = frame.payload_len local data -- Verify Close frame size if frame.opcode == FRAME_TYPE.close and not ( bytes == 0 or bytes >= 2 ) then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Data packet wrong size for Close frame" } ) return end --== read rest of data if bytes == 0 then data = "" else data = bytearray:readBuf( bytes ) end if frame.mask then data = xor_mask( data, frame.mask, bytes ) end frame.data = data -- Verify Close frame code if frame.opcode == FRAME_TYPE.close and bytes >= 2 then local code, reason = decodeCloseFrameData( data ) if code >=0 and code <= 999 then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Invalid close code: %s" % code } ) return elseif code >= 1000 and code <= 2999 then if not Utils.propertyIn( VALID_CLOSE_CODES, code ) then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Invalid close code: %s" % code } ) return end end end end -- @params params -- bytearray ByteArray instance -- local function receiveWSFrame( bytearray ) -- print( "receiveWSFrame" ) assert( bytearray and bytearray:isa( ByteArray ), "ReceiveFrame() requires byte array for data container" ) --==-- -- Frame info structure local frame = { -- header="", basic framing info (string) -- payload="", basic framing info (string) -- payload_len=0, (number) -- fin=true, (boolean) -- opcode=0x1, (number) -- masked=true, (boolean) -- mask={ b1, b2, b3, b4 }, (table) -- data="", actual frame data/payload } readFrameHeader( frame, bytearray ) processFrameType( frame, bytearray ) processFramePayload( frame, bytearray ) verifyFramePayload( frame, bytearray ) return { opcode=frame.opcode, type=FRAME_TYPE[ frame.opcode ], data=frame.data, fin=frame.fin } end -- @params params table structure -- data: data to send -- fin: boolean, end of data packet -- opcode: type of message to send -- masked: boolean, masked packet -- local function buildFrame( params ) -- print( "buildFrame" ) local msg = params.msg local data = params.data local fin = params.fin local opcode = params.opcode local masked = params.masked local payload_len = #data local frame = {} -- frame info -- frame header vars local h_type, h_payload = opcode, 0 --== process header if fin == nil or fin == true then h_type = bor( h_type, bit_7 ) end if masked then h_payload = bor( h_payload, bit_7 ) end if payload_len <= SML_FRAME_SIZE then h_payload = bor( h_payload, payload_len ) tinsert( frame, schar( h_type, h_payload ) ) elseif payload_len <= MED_FRAME_SIZE then h_payload = bor( h_payload, MED_FRAME_TOKEN ) tinsert( frame, schar( h_type, h_payload, mfloor(payload_len/256), payload_len%256 ) ) elseif payload_len < 2^53 then h_payload = bor( h_payload, LRG_FRAME_TOKEN ) local high = mfloor( payload_len / 2^32 ) local low = payload_len - high*2^32 tinsert( frame, schar( h_type, h_payload ) ) tinsert( frame, int_to_bytes( high ) ) tinsert( frame, int_to_bytes( low ) ) else error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Data packet too big for protocol" } ) end --== process mask if not masked then tinsert( frame, data ) else local m1 = mrandom( 0, 0xff ) local m2 = mrandom( 0, 0xff ) local m3 = mrandom( 0, 0xff ) local m4 = mrandom( 0, 0xff ) local mask = { m1,m2,m3,m4 } tinsert( frame, schar( m1, m2, m3, m4 ) ) tinsert( frame, xor_mask( data, mask, #data ) ) end return tconcat( frame ) end -- @param data -- @param opcode -- @param masked -- @param onFrame -- @param max_frame_size local function buildWSFrames( params ) -- print( "buildWSFrames" ) local msg = params.message local data_len = msg:getAvailable() local opcode if msg.start == 1 then opcode = msg.opcode else opcode = FRAME_TYPE.continuation end local max_frame_size = params.max_frame_size if max_frame_size and max_frame_size > LRG_FRAME_SIZE then max_frame_size = LRG_FRAME_SIZE end -- control frame check if band( opcode, bit_4 ) ~= 0 then if data_len > SML_FRAME_SIZE then error( ProtocolError{ code=CLOSE_CODES.PROTO_ERR.code, reason=CLOSE_CODES.PROTO_ERR.code, message="Data packet too large for control frame" } ) return end end local divisor, chunk, fin local frame if max_frame_size then divisor = max_frame_size elseif data_len <= SML_FRAME_SIZE then divisor = SML_FRAME_SIZE elseif data_len <= MED_FRAME_SIZE then divisor = MED_FRAME_SIZE else divisor = LRG_FRAME_SIZE end chunk = msg:read( divisor ) fin = ( msg:getAvailable() == 0 ) frame = buildFrame{ data=chunk, fin=fin, masked=msg.masked, opcode=opcode } return { frame=frame } end encodeCloseFrameData = function(code,reason) local data if code and type(code) == 'number' then --data = spack('>H',code) data = schar(mfloor(code/256),code%256) if reason then data = data..tostring(reason) end end return data or '' end decodeCloseFrameData = function( data ) local _,code,reason if data then if #data > 1 then code = getunsigned_2bytes_bigendian(data) end if #data > 2 then reason = data:sub(3) end end return code, reason end --====================================================================-- --== Module Facade --====================================================================-- return { type = FRAME_TYPE, close = CLOSE_CODES, size = { SMALL = SML_FRAME_SIZE, MEDIUM = MED_FRAME_SIZE, LARGE = LRG_FRAME_SIZE }, receiveFrame = receiveWSFrame, buildFrames = buildWSFrames, encodeCloseFrameData = encodeCloseFrameData, decodeCloseFrameData = decodeCloseFrameData }
#!/usr/bin/env tarantool -- Instance file for one of the 10 swarm nodes. They bootstrap the cluster, each -- bump their vclock component and then do nothing and serve as replication -- masters for the eleventh node. local id = tonumber(arg[1]) assert(id ~= nil, 'Please pass a numeric instance id') assert(id >= 2 and id <= 11, 'The id should be in ramge [2, 11]') box.cfg{ listen = 3300 + id, replication = { 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, }, background = true, work_dir = tostring(id), pid_file = id..'.pid', log = id..'.log', } box.once('bootstrap', function() box.schema.user.grant('guest', 'replication') end) -- This is executed on every instance so that vclock is non-empty in each -- component. This will make the testing instance copy a larger portion of data -- on each write and make the performance degradation, if any, more obvious. box.space._schema:replace{'Something to bump vclock '..id}
local Game = {} function Game.getDistance(xa, ya, xb, yb) local xDist = xb - xa local yDist = yb - ya return math.sqrt((xDist ^ 2) + (yDist ^ 2)) end function Game.getPokemonNumberWithMove(move, joy) -- optional parameter happiness joy = joy or 0 for i = 1, getTeamSize() do if hasMove(i, move) and getPokemonHappiness(i) >= joy then return i end end return nil end return Game
MAX_SKILLS = 8 -- Skill type tree SkillTypeSkill = 0 -- Everything is a skill SkillTypeAttack = 1 SkillTypeRangedAttack = SkillTypeAttack | 1 << 16 SkillTypeBowAttack = SkillTypeRangedAttack | 1 << 32 SkillTypeSpearAttack = SkillTypeRangedAttack | 2 << 32 SkillTypeMeleeAttack = SkillTypeAttack | 2 << 16 SkillTypeAxeAttack = SkillTypeMeleeAttack | 1 << 32 SkillTypeDaggerAttack = SkillTypeMeleeAttack | 2 << 32 SkillTypeLeadAttack = SkillTypeDaggerAttack | 1 << 48 SkillTypeOffHandAttack = SkillTypeDaggerAttack | 2 << 48 SkillTypeDualAttack = SkillTypeDaggerAttack | 4 << 48 SkillTypeHammerAttack = SkillTypeMeleeAttack | 4 << 32 SkillTypeScyteAttack = SkillTypeMeleeAttack | 8 << 32 SkillTypeSwordAttack = SkillTypeMeleeAttack | 16 << 32 SkillTypePetAttack = SkillTypeAttack | 4 << 16 SkillTypeShout = 2 SkillTypeChant = 4 SkillTypeEcho = 8 SkillTypeForm = 16 SkillTypeGlypthe = 32 SkillTypePreparation = 64 SkillTypeRitual = 128 SkillTypeBindingRitual = SkillTypeRitual | 1 << 16 SkillTypeNatureRitual = SkillTypeRitual | 2 << 16 SkillTypeSignet = 256 SkillTypeSpell = 512 SkillTypeEnchantment = SkillTypeSpell | 1 << 16 SkillTypeFlashEnchantment = SkillTypeEnchantment | 1 << 32 SkillTypeHex = SkillTypeSpell | 2 << 16 SkillTypeItemSpell = SkillTypeSpell | 4 << 16 SkillTypeWardSpell = SkillTypeSpell | 8 << 16 SkillTypeWeaponSpell = SkillTypeSpell | 16 << 16 SkillTypeWellSpell = SkillTypeSpell | 32 << 16 SkillTypeStance = 1024 SkillTypeTrap = 2048 SkillTypeAll = 0xFFFFFFFFFFFFFFFF -- Effects skills can have SkillEffectNone = 0 SkillEffectResurrect = 1 << 1 SkillEffectHeal = 1 << 2 SkillEffectProtect = 1 << 3 SkillEffectDamage = 1 << 4 SkillEffecSpeed = 1 << 5 SkillEffectInterrupt = 1 << 6 SkillEffectGainEnergy = 1 << 7 SkillEffectRemoveEnchantment = 1 << 8 SkillEffectRemoveHex = 1 << 9 SkillEffectRemoveStance = 1 << 10 -- What the skill targets SkillTargetNone = 0 SkillTargetSelf = 1 << 1 SkillTargetTarget = 1 << 2 SkillTargetAoe = 1 << 3 SkillTargetParty = 1 << 4 -- Needed target for the skill SkillTargetTypeNone = 0 SkillTargetTypeSelf = 1 SkillTargetTypeAllyAndSelf = 2 SkillTargetTypeAllyWithoutSelf = 3 SkillTargetTypeFoe = 4 -- Error codes SkillErrorNone = 0 SkillErrorInvalidSkill = 1 SkillErrorInvalidTarget = 2 SkillErrorOutOfRange = 3 SkillErrorNoEnergy = 4 SkillErrorNoAdrenaline = 5 SkillErrorRecharging = 6 SkillErrorTargetUndestroyable = 7 SkillErrorCannotUseSkill = 8 SkillErrorNotAppropriate = 255 -- Effect categories EffectCategoryNone = 0 EffectCategoryCondition = 1 EffectCategoryEnchantment = 2 EffectCategoryHex = 3 EffectCategoryPreparation = 4 EffectCategoryShout = 5 EffectCategorySpirit = 6 EffectCategoryStance = 7 EffectCategoryWard = 8 EffectCategortyWell = 9 EffectCategoryGeneral = 20 EffectCategoryEnvironment = 254
local LoveUI=LoveUI LoveUI.require("LoveUIRect.lua") LoveUI.require("LoveUIResponder.lua") LoveUI.View=LoveUI.Responder:new(); function LoveUI.View:init(frame, ...) -- e.g local o=LoveUI.Object:alloc():init(); LoveUI.Responder.init(self, frame, ...); self.frame=frame or LoveUI.Rect:new(-1,-1,-1,-1); self.scissorFrame=self.frame; self.subviews={}; self.superview=nil; self.context=nil; self.opaque=false; self.escapeScissor=false; self.hidden=false; self.backgroundColor=LoveUI.defaultBackgroundColor self.textColor=LoveUI.defaultTextColor; self.selectColor=LoveUI.defaultSelectColor return self; end function LoveUI.View:acceptsFirstResponder() return true; end function LoveUI.View:setFrame(aFrame) self.frame=aFrame; self:calculateScissor(); end function LoveUI.View:setOrigin(aPoint) self.frame.origin=aPoint:copy(); self:calculateScissor(); end function LoveUI.View:setSize(aSize) self.frame.size=aSize:copy(); self:calculateScissor(); end function LoveUI.View:display() --error(tostring(self.class.className())) --if self.class.className()=="Button" then error("b") end if self.opaque then local size=self.frame.size; LoveUI.graphics.setColor(unpack(self.backgroundColor)) LoveUI.graphics.rectangle('fill', 0, 0, size.width, size.height) end end function LoveUI.View:toSubviews(fn) fn(self); for k, v in pairs(self.subviews) do if fn(v) == false then return false; end v:toSubviews(fn); end end function LoveUI.View:update(dt) if not self.hidden then end end function LoveUI.View:convertOriginToBase() local p=self.superview:convertPointToBase(self.frame.origin) return p.x, p.y; end function LoveUI.View:updateSubviews(dt) if not self.hidden then for k, v in pairs(self.subviews) do if not v.hidden then LoveUI.pushMatrix() LoveUI.translate(v.frame.origin:get()) v:update(dt); v:updateSubviews(dt); LoveUI.popMatrix() end end end end function LoveUI.View:calculateScissor() if self.superview then local super_frame=self:convertRectFromView(self.superview.scissorFrame, self.superview) local child_frame=self:convertRectFromView(self.frame, self); local x1, y1, x2, y2 = math.max(super_frame.origin.x, 0), math.max(super_frame.origin.y, 0), math.min(super_frame.size.width+super_frame.origin.x, child_frame.size.width), math.min(super_frame.size.height+super_frame.origin.y, child_frame.size.height); self.scissorFrame=LoveUI.Rect:new(x1, y1, x2-x1, y2-y1); for i, v in ipairs(self.subviews) do v:calculateScissor() end end end function LoveUI.View:getScissor() if not self.scissorFrame then self:calculateScissor(); end return self.scissorFrame:get(); end function LoveUI.View:displaySubviews() --a View is responsible for drawing itself and subviews if not self.hidden then for k, v in pairs(self.subviews) do if not v.hidden then self.context:store() LoveUI.pushMatrix() LoveUI.translate(v.frame.origin:get()) v:preDisplay() if not v.escapeScissor then LoveUI.graphics.setScissor(v:getScissor()) else LoveUI.graphics.setScissor(); end v:display(); v:displaySubviews(); LoveUI.popMatrix() v:postDisplay() self.context:restore() end end end end function LoveUI.View:preDisplay() end function LoveUI.View:postDisplay() local size=self.frame.size; if self.tabAccessible and self.context.firstResponder == self then LoveUI.graphics.setColor(unpack(LoveUI.defaultSelectBgColor)) LoveUI.graphics.rectangle('fill', self.frame.origin.x+1, self.frame.origin.y+1 , size.width-2, size.height-2) end end function LoveUI.View:getIndex() if self.superview then for k, v in pairs(self.superview.subviews) do if v==self then return k end end end end function LoveUI.View:getPreviousView() if not self.superview then return nil end; local k=self:getIndex(); if k-1>=1 then return self.superview.subviews[k-1] end return nil; end function LoveUI.View:getPreviousViewInHierarchy() if #self.subviews>=1 then return self.subviews[#self.subviews] end local previousView; previousView=self:getPreviousView(); if previousView then return previousView; end local pSuper=self.superview nextView=pSuper:getPreviousView() while not previousView do pSuper=pSuper.superview if not pSuper then break; end previousView=pSuper:getPreviousView() if previousView then break; end end if previousView then return previousView; else return self.context.contentView end end function LoveUI.View:getNextView() if not self.superview then return nil end; local k=self:getIndex(); return self.superview.subviews[k+1] end function LoveUI.View:getNextViewInHierarchy() if #self.subviews>=1 then return self.subviews[1] end local nextView; nextView=self:getNextView(); if nextView then return nextView; end local pSuper=self.superview nextView=pSuper:getNextView() while not nextView do pSuper=pSuper.superview if not pSuper then break; end nextView=pSuper:getNextView() if nextView then break; end end if nextView then return nextView; else return self.context.contentView end end function LoveUI.View:getNextTabAccessControl() local nextView=self;--=self:getNextView(); while true do nextView=nextView:getNextViewInHierarchy(); if nextView.tabAccessible and not nextView.hidden and nextView.enabled and nextView.context and nextView:acceptsFirstResponder() then self.context:setFirstResponder(nextView); break; end if nextView==self then return false; end end return true end function LoveUI.View:getPreviousTabAccessControl() local previousView=self;--=self:getNextView(); while true do previousView=previousView:getPreviousViewInHierarchy(); if previousView.tabAccessible and not previousView.hidden and previousView.enabled and previousView.context and previousView:acceptsFirstResponder() then self.context:setFirstResponder(previousView); break; end if previousView==self then return false; end end return true end function LoveUI.View:keyDown(theEvent) if theEvent.keyCode==love.key_tab and (self.tabAccessible or self==self.context.contentView) then if theEvent.keysDown[love.key_lshift] or theEvent.keysDown[love.key_rshift] then self:getPreviousTabAccessControl(); else self:getNextTabAccessControl(); end else LoveUI.Responder.keyDown(self, theEvent); end end function LoveUI.View:removeSubview(...) local views={...}; for k, aView in pairs(views) do for l, v in pairs(self.subviews) do if v==aView then table.remove(self.subviews, l); aView.superview=nil; aView.context=nil; aView.nextResponder=nil; break; end end end end function LoveUI.View:apply(t) for k, v in pairs(t) do self[k]=v; end end function LoveUI.View:addSubview(...) local views={...}; for k, aView in pairs(views) do if aView.superview==nil then self.subviews[#self.subviews+1]=aView aView.superview=self; aView.context=self.context; aView.nextResponder=self; aView:toSubviews(function (v) v.context=self.context end) aView:calculateScissor(); else LoveUI.error("View to be added already has a super view! It must be removed from its super view's subviews before being added to a view as a subview again! You can copy views by going aView:copy(), which returns a copy") end end end function LoveUI.View:lastSubview() local lastIndex=#self.subviews; while self.subviews[lastIndex].hidden do if lastIndex==0 then return nil end lastIndex=lastIndex-1; end return self.subviews[lastIndex]; end function LoveUI.View:mouseInRect(aPoint, aRect) return LoveUI.mouseInRect(aPoint, aRect) and not self.hidden end function LoveUI.View:convertPointToBase(aPoint) --each view's origin is in its superview's coord system local view=self; local x=aPoint.x local y=aPoint.y while view~=nil do x=x+view.frame.origin.x; y=y+view.frame.origin.y; view=view.superview; end return LoveUI.Point:new(x, y) end function LoveUI.View:convertPointFromBase(aPoint) local view=self; local x=aPoint.x local y=aPoint.y while view~=nil do x=x-view.frame.origin.x; y=y-view.frame.origin.y; view=view.superview; end return LoveUI.Point:new(x, y) end function LoveUI.View:convertRectToView(aRect, aView) local originThatView=0; if aView~=nil then originThatView=aView:convertPointFromBase(self:convertPointToBase(aRect.origin)); else originThatView=self:convertPointToBase(aRect.origin); end return LoveUI.Rect:new(originThatView.x, originThatView.y, aRect.size.width, aRect.size.height); end function LoveUI.View:convertRectFromView(aRect, aView) local originThisView=0; if aView~=nil then originThisView=self:convertPointFromBase(aView:convertPointToBase(aRect.origin)); else originThisView=self:convertPointFromBase(aRect.origin); end return LoveUI.Rect:new(originThisView.x, originThisView.y, aRect.size.width, aRect.size.height); end function LoveUI.View:bringToFront() end
---@class CS.FairyEditor.Framework.Gears.FGearDisplay2 : CS.FairyEditor.Framework.Gears.FGearBase_CS.System.String ---@field public pages String[] ---@type CS.FairyEditor.Framework.Gears.FGearDisplay2 CS.FairyEditor.Framework.Gears.FGearDisplay2 = { } ---@return CS.FairyEditor.Framework.Gears.FGearDisplay2 ---@param owner CS.FairyEditor.FObject function CS.FairyEditor.Framework.Gears.FGearDisplay2.New(owner) end ---@return boolean ---@param connected boolean function CS.FairyEditor.Framework.Gears.FGearDisplay2:Evaluate(connected) end function CS.FairyEditor.Framework.Gears.FGearDisplay2:Apply() end return CS.FairyEditor.Framework.Gears.FGearDisplay2
object_tangible_item_crusader_armor_dye_kit = object_tangible_item_shared_crusader_armor_dye_kit:new { } ObjectTemplates:addTemplate(object_tangible_item_crusader_armor_dye_kit, "object/tangible/item/crusader_armor_dye_kit.iff")
local ngx_abort = require('acid.ngx_abort') local function callback_func() end function test.basic(t) ngx.ctx.callbacks = nil local cb_1, err, errmsg = ngx_abort.add_callback(callback_func) t:eq(nil, err) t:eq(nil, errmsg) t:eq(cb_1, ngx.ctx.callbacks[1][1]) local cb_2, err, errmsg = ngx_abort.add_callback(callback_func) t:eq(nil, err) t:eq(nil, errmsg) t:eq(cb_1, ngx.ctx.callbacks[1][1]) t:eq(cb_2, ngx.ctx.callbacks[1][2]) local _, err, errmsg = ngx_abort.remove_callback(cb_1) t:eq(nil, err) t:eq(nil, errmsg) t:eq(cb_2, ngx.ctx.callbacks[1][1]) t:eq(nil, ngx.ctx.callbacks[1][2]) local _, err, errmsg = ngx_abort.remove_callback(cb_1) t:eq(nil, err) t:eq(nil, errmsg) t:eq(cb_2, ngx.ctx.callbacks[1][1]) t:eq(nil, ngx.ctx.callbacks[1][2]) local _, err, errmsg = ngx_abort.remove_callback(cb_2) t:eq(nil, err) t:eq(nil, errmsg) t:eq(nil, ngx.ctx.callbacks[1][1]) t:eq(nil, ngx.ctx.callbacks[1][2]) end function test.last(t) ngx.ctx.callbacks = nil local cb, err, errmsg = ngx_abort.add_callback_with_opts( callback_func, {position='last'}) t:eq(nil, err) t:eq(nil, errmsg) t:eq(cb, ngx.ctx.callbacks.last[1]) end function test.opts_position(t) ngx.ctx.callbacks = nil local cb_1, err, errmsg = ngx_abort.add_callback_with_opts( callback_func, {position=100}) t:eq(nil, err) t:eq(nil, errmsg) t:eq(cb_1, ngx.ctx.callbacks[100][1]) local cb_2, err, errmsg = ngx_abort.add_callback_with_opts( callback_func, {position=100}) t:eq(nil, err) t:eq(nil, errmsg) t:eq(cb_1, ngx.ctx.callbacks[100][1]) t:eq(cb_2, ngx.ctx.callbacks[100][2]) local cb_3, err, errmsg = ngx_abort.add_callback(callback_func) t:eq(nil, err) t:eq(nil, errmsg) t:eq(cb_1, ngx.ctx.callbacks[100][1]) t:eq(cb_2, ngx.ctx.callbacks[100][2]) t:eq(cb_3, ngx.ctx.callbacks[1][1]) local cb_4, err, errmsg = ngx_abort.add_callback_with_opts( callback_func, {position=101}) t:eq(nil, err) t:eq(nil, errmsg) t:eq(cb_1, ngx.ctx.callbacks[100][1]) t:eq(cb_2, ngx.ctx.callbacks[100][2]) t:eq(cb_3, ngx.ctx.callbacks[1][1]) t:eq(cb_4, ngx.ctx.callbacks[101][1]) end function test.args(t) ngx.ctx.callbacks = nil local cb, err, errmsg = ngx_abort.add_callback(callback_func, 1, 2, 3) t:eq(nil, err) t:eq(nil, errmsg) t:eq(1, cb.args[1]) t:eq(2, cb.args[2]) t:eq(3, cb.args[3]) t:eq(nil, cb.args[4]) local cb, err, errmsg = ngx_abort.add_callback(callback_func) t:eq(nil, err) t:eq(nil, errmsg) t:eq(nil, next(cb.args)) local cb, err, errmsg = ngx_abort.add_callback_with_opts( callback_func, nil, 1, 2, 3) t:eq(nil, err) t:eq(nil, errmsg) t:eq(1, cb.args[1]) t:eq(2, cb.args[2]) t:eq(3, cb.args[3]) t:eq(nil, cb.args[4]) end function test.invalid_funv(t) local _, err, errmsg = ngx_abort.add_callback('foo') t:neq(nil, err) t:neq(nil, errmsg) local _, err, errmsg = ngx_abort.add_callback_with_opts('foo') t:neq(nil, err) t:neq(nil, errmsg) end function test.remove(t) ngx.ctx.callbacks = nil local cb_1, err, errmsg = ngx_abort.add_callback_with_opts( callback_func, {position='last'}) t:eq(nil, err) t:eq(nil, errmsg) t:eq(cb_1, ngx.ctx.callbacks.last[1]) local _, err, errmsg = ngx_abort.remove_callback(cb_1) t:eq(nil, err) t:eq(nil, errmsg) t:eq(0, #ngx.ctx.callbacks.last) end
local isInRagdoll = false Citizen.CreateThread(function() while true do Citizen.Wait(10) if isInRagdoll then SetPedToRagdoll(PlayerPedId(), 1000, 1000, 0, 0, 0, 0) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(0) if IsControlJustPressed(2, Config.RagdollKeybind) and Config.RagdollEnabled and IsPedOnFoot(PlayerPedId()) then if isInRagdoll then isInRagdoll = false else isInRagdoll = true Wait(500) end end end end)
return {'ace','acetaat','aceton','acetylcholine','acetyleen','acetyleenbrander','acetyleengas','acetylsalicylzuur','aceh','acetyleenbranders','aces','acetaten'}
local InCombat = { } local OutCombat = { } XB.CR:Add(269, '[XB] Monk - Windwalker', inCombat, outCombat)
if kunkka_tidebringer_ff == nil then kunkka_tidebringer_ff = class({}) end LinkLuaModifier("modifier_tidebringer_ff", "heroes/kunkka/modifier_tidebringer_ff.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_tidebringer_ff_weapon_effect", "heroes/kunkka/modifier_tidebringer_ff_weapon_effect.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_tidebringer_cd_reduction_talent", "heroes/kunkka/modifier_tidebringer_cd_reduction_talent.lua", LUA_MODIFIER_MOTION_NONE) function kunkka_tidebringer_ff:GetCooldown(level) local caster = self:GetCaster() local cooldown = self.BaseClass.GetCooldown(self, level) if IsServer() then -- Server side -- Talent that reduces cooldown local talent = caster:FindAbilityByName("special_bonus_unique_kunkka_5") if talent then if talent:GetLevel() ~= 0 then local reduction = talent:GetSpecialValueFor("value") cooldown = cooldown - reduction end end else -- Client side if caster:HasModifier("modifier_tidebringer_cd_reduction_talent") then cooldown = cooldown - caster.tidebringer_cd_reduction_talent_value end end return cooldown end function kunkka_tidebringer_ff:IsStealable() return false end function kunkka_tidebringer_ff:GetIntrinsicModifierName() return "modifier_tidebringer_ff" end function kunkka_tidebringer_ff:CastFilterResultTarget(target) local caster = self:GetCaster() local default_result = self.BaseClass.CastFilterResultTarget(self, target) if target == caster then return UF_FAIL_CUSTOM end return default_result end function kunkka_tidebringer_ff:GetCustomCastErrorTarget(target) local caster = self:GetCaster() if target == caster then return "#dota_hud_error_cant_cast_on_self" end end function kunkka_tidebringer_ff:GetCastRange(location, target) return self:GetCaster():GetAttackRange() end function kunkka_tidebringer_ff:ShouldUseResources() return true end function kunkka_tidebringer_ff:OnUpgrade() -- First point to the ability if self:GetLevel() == 1 then -- Turn on autocast when the ability is leveled-up for the first time if not self:GetAutoCastState() then self:ToggleAutoCast() end end end
-- 自定义函数指针 local type = type local u_each = require("app.utils.each") local s_cache = require("app.store.cache.base_cache") ----------------------------------------------------------------------------------------------------------------- local _obj = s_cache:extend() ------------------------------------------ 通用配置信息,使它分离出多个区域 ------------------------------------- --[[ ---> RDS 选区 --]] function _obj:new(conf) self._VERSION = '0.02' self._name = "cache-nginx-store" self.store = ngx.shared[conf.name] _obj.super.new(self, conf, self._name) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------- NGX 缓存设置 ---------------------------------------------------- -- 设置 NGX 缓存值 function _obj:set_by_json(list, timeout) local ok,err,effect_len,forcible = "","",0,"" timeout = _obj.filter_timeout(timeout, 0) local json_obj = self.utils.json.decode(list) u_each.json_action(json_obj, function(k,v) ok,err,forcible = self.store:set(k, v, timeout) if not err then effect_len = effect_len + 1 end end) return ok,err,effect_len,forcible end -- 设置 NGX 缓存值 function _obj:set(key, value, timeout) timeout = _obj.filter_timeout(timeout, 0) return self.store:set(key, value, timeout) end -- 设置 NGX 缓存值 依据 function function _obj:set_by_func(key, func, timeout) timeout = _obj.filter_timeout(timeout, 0) return self.store:set(key, func(), timeout) end -- 获取 NGX 缓存值 function _obj:get(key) local status,value,effect_len = "OK",nil,0 local value,err = self.store:get(key) if not value then status = "FAILURE" else effect_len = 1 end return value,err,effect_len,status end ----------------------------------------------------------------------------------------------------------------- function _obj:delete(key) self.store:delete(key) end function _obj:delete_all() self.store:flush_all() self.store:flush_expired() end function _obj:incr(key, step, timeout) timeout = _obj.filter_timeout(timeout, 0) return self.store:incr(key, step, timeout) end function _obj:keys(pattern) if not pattern then pattern = 0 end return self.store:get_keys(pattern) end ----------------------------------------------------------------------------------------------------------------- -- 获取推送 REDIS 队列长度 function _obj:llen(key) return self.store:llen(key) end -- 推送 REDIS 缓存值 function _obj:lpush(key, value) return self.store:lpush(key, value) end -- 推送 REDIS 缓存值 function _obj:rpush(key, value) return self.store:rpush(key, value) end -- 推出 REDIS 缓存值 function _obj:lpop(key) return self.store:lpop(key) end -- 推出 REDIS 缓存值 function _obj:rpop(key) return self.store:rpop(key) end ----------------------------------------------------------------------------------------------------------------- return _obj
function getNearbyElementsByType( x, y, z, type, distance ) local elements = { } for _, element in ipairs( getElementsByType( type ) ) do if ( getDistanceBetweenPoints3D( x, y, z, getElementPosition( element ) ) < distance ) then table.insert( elements, element ) end end return elements end
--- -- Placeholder for false --- do local function __eq(a, b) return (lemma.type(a) == lemma.type(b)) and (tostring(a) == tostring(b)) end local function __tostring(e) return 'False' end local t = {} local mt = { class = 'False', implements = nil, __index = t, __tostring = __tostring, __eq = __eq } False = {} function False:string() return 'False' end setmetatable(False, mt) end
--[[ Day 16: Chronal Classification ]]-- local fname = arg[1] local verbose = (fname == '-v') local printf = function(s,...) return io.write(s:format(...)) end local regs = {[0] = 0, 0, 0, 0} local qregs = 4 local regok = function (n) return n >= 0 and n < qregs end local _I = {} -- instruction table --[[ addr (add register) stores into register C the result of adding register A and register B. ]]-- _I.addr = function (A, B, C) if regok(A) and regok(B) and regok(C) then regs[C] = regs[A] + regs[B] return true else return false end end --[[ addi (add immediate) stores into register C the result of adding register A and value B. ]]-- _I.addi = function (A, B, C) if regok(A) and regok(C) then regs[C] = regs[A] + B return true else return false end end --[[ mulr (multiply register) stores into register C the result of multiplying register A and register B. ]]-- _I.mulr = function (A, B, C) if regok(A) and regok(B) and regok(C) then regs[C] = regs[A] * regs[B] return true else return false end end --[[ muli (multiply immediate) stores into register C the result of multiplying register A and value B. ]]-- _I.muli = function (A, B, C) if regok(A) and regok(C) then regs[C] = regs[A] * B return true else return false end end --[[ banr (bitwise AND register) stores into register C the result of the bitwise AND of register A and register B. ]]-- _I.banr = function (A, B, C) if regok(A) and regok(B) and regok(C) then regs[C] = regs[A] & regs[B] return true else return false end end --[[ bani (bitwise AND immediate) stores into register C the result of the bitwise AND of register A and value B. ]]-- _I.bani = function (A, B, C) if regok(A) and regok(C) then regs[C] = regs[A] & B return true else return false end end --[[ borr (bitwise OR register) stores into register C the result of the bitwise OR of register A and register B. ]]-- _I.borr = function (A, B, C) if regok(A) and regok(B) and regok(C) then regs[C] = regs[A] | regs[B] return true else return false end end --[[ bori (bitwise OR immediate) stores into register C the result of the bitwise OR of register A and value B. ]]-- _I.bori = function (A, B, C) if regok(A) and regok(C) then regs[C] = regs[A] | B return true else return false end end --[[ setr (set register) copies the contents of register A into register C. (Input B is ignored.) ]]-- _I.setr = function (A, B, C) if regok(A) and regok(C) then regs[C] = regs[A] return true else return false end end --[[ seti (set immediate) stores value A into register C. (Input B is ignored.) ]]-- _I.seti = function (A, B, C) if regok(C) then regs[C] = A return true else return false end end --[[ gtir (greater-than immediate/register) sets register C to 1 if value A is greater than register B. Otherwise, register C is set to 0. ]]-- _I.gtir = function (A, B, C) if regok(B) and regok(C) then if A > regs[B] then regs[C] = 1 else regs[C] = 0 end return true else return false end end --[[ gtri (greater-than register/immediate) sets register C to 1 if register A is greater than value B. Otherwise, register C is set to 0. ]]-- _I.gtri = function (A, B, C) if regok(A) and regok(C) then if regs[A] > B then regs[C] = 1 else regs[C] = 0 end return true else return false end end --[[ gtrr (greater-than register/register) sets register C to 1 if register A is greater than register B. Otherwise, register C is set to 0. ]]-- _I.gtrr = function (A, B, C) if regok(A) and regok(B) and regok(C) then if regs[A] > regs[B] then regs[C] = 1 else regs[C] = 0 end return true else return false end end --[[ eqir (equal immediate/register) sets register C to 1 if value A is equal to register B. Otherwise, register C is set to 0. ]]-- _I.eqir = function (A, B, C) if regok(B) and regok(C) then if A == regs[B] then regs[C] = 1 else regs[C] = 0 end return true else return false end end --[[ eqri (equal register/immediate) sets register C to 1 if register A is equal to value B. Otherwise, register C is set to 0. ]]-- _I.eqri = function (A, B, C) if regok(A) and regok(C) then if regs[A] == B then regs[C] = 1 else regs[C] = 0 end return true else return false end end --[[ eqrr (equal register/register) sets register C to 1 if register A is equal to register B. Otherwise, register C is set to 0. ]]-- _I.eqrr = function (A, B, C) if regok(A) and regok(B) and regok(C) then if regs[A] == regs[B] then regs[C] = 1 else regs[C] = 0 end return true else return false end end -- destructive sets local dunion = function (T, S) for k,_ in pairs(S) do T[k] = true end return T end local dremove = function (T, v) T[v] = nil return T end local setsize = function (S) local n = 0 for _,_ in pairs(S) do n = n + 1 end return n end -- setup sets local opcode2instr = {} local printo2i = function () for i = 0, 15 do printf("%2d (%2d)", i, setsize(opcode2instr[i])) for k,_ in pairs(opcode2instr[i]) do printf(" %s", k) end printf("\n") end end local setupsets = function () for i = 0, 15 do opcode2instr[i] = dunion({},_I) end if verbose then printo2i() if opcode2instr[1] == opcode2instr[2] then print "Error" end end end -- local rejects = 0 local tryins = function (rin, ins, rou) local bad = {} local ops = opcode2instr[ins[0]] for k,_ in pairs(ops) do for i = 0, 3 do regs[i] = rin[i] end --if verbose then printf("Registers %d %d %d %d\n", regs[0], regs[1], regs[2], regs[3]) end --if verbose then printf("Trying %s %d %d %d\n", k, ins[1], ins[2], ins[3]) end local ok = _I[k](ins[1], ins[2], ins[3]) if ok then for i = 0, 3 do if regs[i] ~= rou[i] then ok = false break end end end if not ok then bad[#bad+1] = k rejects = rejects + 1 end end for i = 1, #bad do dremove(ops, bad[i]) end end local runins = function (ins) local ops = opcode2instr[ins[0]] for k,_ in pairs(ops) do --if verbose then printf("Registers %d %d %d %d\n", regs[0], regs[1], regs[2], regs[3]) end --if verbose then printf("Running %s %d %d %d\n", k, ins[1], ins[2], ins[3]) end local ok = _I[k](ins[1], ins[2], ins[3]) if not ok then printf("Bad instruction: %s %d %d %d\n", k, ins[1], ins[2], ins[3]) end end end local trysam = function (rin, ins, rou) local qbad = 0 local ops = opcode2instr[ins[0]] for k,_ in pairs(ops) do for i = 0, 3 do regs[i] = rin[i] end --if verbose then printf("Registers %d %d %d %d\n", regs[0], regs[1], regs[2], regs[3]) end --if verbose then printf("Trying %s %d %d %d\n", k, ins[1], ins[2], ins[3]) end local ok = _I[k](ins[1], ins[2], ins[3]) if ok then for i = 0, 3 do if regs[i] ~= rou[i] then ok = false break end end end if not ok then qbad = qbad + 1 rejects = rejects + 1 end end return 16 - qbad end local finduniop = function (unfoundops) local op for i = 0, 15 do local count = 0 for k,_ in pairs(opcode2instr[i]) do if unfoundops[k] then op = k count = count + 1 end end if count == 1 then return op, i end end return nil end local removedupop = function (op, i) for j = 0, 15 do if i ~= j then dremove(opcode2instr[j], op) end end end -- the 1st question is "how many samples in your puzzle input behave like three or more opcodes?" local function part1 () -- this does: what opcodes work for all samples local infile = io.open("2018_advent_16a.txt") local line = infile:read("l") setupsets() local rin = {} local ins = {} local rou = {} local result = 0 local tried = {} rejects = 0 while line do if line:len() == 0 then -- punt line = infile:read("l") else local i0,i1,i2,i3 = line:match("Before: %[(%d+), (%d+), (%d+), (%d+)%]") -- Before: [3, 2, 3, 3] rin[0] = tonumber(i0) rin[1] = tonumber(i1) rin[2] = tonumber(i2) rin[3] = tonumber(i3) line = infile:read("l") local i0,i1,i2,i3 = line:match("(%d+) (%d+) (%d+) (%d+)") -- 14 0 2 3 ins[0] = tonumber(i0) ins[1] = tonumber(i1) ins[2] = tonumber(i2) ins[3] = tonumber(i3) line = infile:read("l") local i0,i1,i2,i3 = line:match("After: %[(%d+), (%d+), (%d+), (%d+)%]") -- After: [3, 2, 3, 3] rou[0] = tonumber(i0) rou[1] = tonumber(i1) rou[2] = tonumber(i2) rou[3] = tonumber(i3) line = infile:read("l") local candidates = trysam(rin, ins, rou) if candidates >= 3 then result = result + 1 end tried[ins[0]] = (tried[ins[0]] or 0) + 1 end end infile:close() printf("Part1: %d samples have more than 3 possibilites\n", result) end --part1() local function part2 () local infile = io.open("2018_advent_16a.txt") local line = infile:read("l") setupsets() local rin = {} local ins = {} local rou = {} local tried = {} rejects = 0 while line do if line:len() == 0 then -- punt line = infile:read("l") else local i0,i1,i2,i3 = line:match("Before: %[(%d+), (%d+), (%d+), (%d+)%]") -- Before: [3, 2, 3, 3] rin[0] = tonumber(i0) rin[1] = tonumber(i1) rin[2] = tonumber(i2) rin[3] = tonumber(i3) line = infile:read("l") local i0,i1,i2,i3 = line:match("(%d+) (%d+) (%d+) (%d+)") -- 14 0 2 3 ins[0] = tonumber(i0) ins[1] = tonumber(i1) ins[2] = tonumber(i2) ins[3] = tonumber(i3) line = infile:read("l") local i0,i1,i2,i3 = line:match("After: %[(%d+), (%d+), (%d+), (%d+)%]") -- After: [3, 2, 3, 3] rou[0] = tonumber(i0) rou[1] = tonumber(i1) rou[2] = tonumber(i2) rou[3] = tonumber(i3) line = infile:read("l") tryins(rin, ins, rou) tried[ins[0]] = (tried[ins[0]] or 0) + 1 end end infile:close() printo2i() local totaltries = 0 if verbose then printf("Tries:") for i = 0, 15 do printf(" %d", tried[i]) totaltries = totaltries + tried[i] end printf(" (%d), %d rejects\n", totaltries, rejects) end local unfoundops = dunion({},_I) while true do local op, i = finduniop(unfoundops) if op then dremove(unfoundops, op) removedupop(op, i) else break end end printo2i() local result = 0 for i = 0, 15 do local count = 0 for k,_ in pairs(opcode2instr[i]) do count = count + 1 end if count ~= 1 then result = result + 1 end end printf("Part2a: %d ops are undetermined\n", result) if result ~= 0 then return end infile = io.open("2018_advent_16b.txt") line = infile:read("l") tried = {} for i = 0, 3 do regs[i] = 0 end while line do if line:len() == 0 then -- punt line = infile:read("l") else local i0,i1,i2,i3 = line:match("(%d+) (%d+) (%d+) (%d+)") -- 14 0 2 3 ins[0] = tonumber(i0) ins[1] = tonumber(i1) ins[2] = tonumber(i2) ins[3] = tonumber(i3) line = infile:read("l") runins(ins) tried[ins[0]] = (tried[ins[0]] or 0) + 1 end end infile:close() totaltries = 0 if verbose then printf("Tries:") for i = 0, 15 do printf(" %d", tried[i]) totaltries = totaltries + tried[i] end printf(" (%d)\n", totaltries) end printf("Part2b: regs[0] is %d\n", regs[0]) end part2()
local format = { } for _, module in ipairs(script:GetChildren()) do format[module.Name] = require(module) end return format
-- Thu Aug 30 13:59:57 2018 -- (c) Alexander Veledzimovich -- scr SWARM local Tmr = require('lib/tmr') local cls = require('lib/cls') local ctrl = require('lib/lovctrl') local ui = require('lib/lovui') local cmp = require('lib/lovcmp') local b2d = require('lib/lovb2d') local fl = require('lib/lovfl') local obj = require('game/obj') local set = require('game/set') local Proto=cls.Class({tag='proto',objects={},garbage={},particles={}, avatar=nil,fade=0,pause=false}) -- static cmp Proto.getRandOffsetXY = cmp.getRandOffsetXY -- particle Proto.objectParticle = cmp.objectParticle function Proto:__tostring() return self.tag end function Proto:spawn(object) self.objects[object] = object end function Proto:trash(object) self.garbage[object]=object end function Proto:destroy(object) self.objects[object] = nil end function Proto:get_objects() return self.objects end function Proto:get_particles() return self.particles end function Proto:get_avatar() return self.avatar end function Proto:get_fade() return self.fade end function Proto:update(dt) ui.Manager.update(dt) end function Proto:draw() love.graphics.draw(self.bg) ui.Manager.draw() end function Proto:set_pause(pause) self.pause = pause or not self.pause self:set_label('PAUSE',self.pause) end function Proto:set_label(text,bool) if self.label then self.label:remove() end if bool then self.label = ui.Label{x=set.MIDWID,y=set.MIDHEI, text=text, fnt=set.MENUFNT, fntclr=set.DARKRED, anchor='s'} end end function Proto:set_cursor() love.mouse.setVisible(false) self.cursor = self:objectParticle(4, {set.GRAY,set.WHITEHHHF, set.WHITEF},'circle',{0.1,4},{1,0.1}) end function Proto:cursor_upd() local x,y=ctrl:position() self.cursor.particle:setPosition(x,y) self.cursor.particle:emit(30) end function Proto:clear() self.avatar=nil -- clean corpses -- for object in pairs(self.garbage) do self.garbage[object]=nil end -- self.garbage={} for object in pairs(self.objects) do self:destroy(object) end self.objects={} for particle in pairs(self.particles) do particle:reset() end self.particles={} if self.world then self.world:destroy() end end local SCR = {} SCR.Menu=cls.Class(Proto,{tag='menu',fade=1}) SCR.Menu.bg=love.graphics.newImage(set.IMG['uibg']) function SCR.Menu:new(o) ui.Manager.clear() self.tmr = Tmr:new() cmp.GRAVITY = {x=0,y=10} b2d.setWorld(self,10,cmp.GRAVITY.x,cmp.GRAVITY.y) local deadhand=obj.DeadHand{screen=self,x=390,y=460, scale=0.4,angle=math.rad(70),active=true} deadhand:turn() local x,y=ctrl:position() self.avatar=self.avatar or obj.Avatar{screen=self,x=x,y=y} ui.Label{x=set.MIDWID,y=set.MIDHEI-20,text=set.GAMENAME:upper(), fntclr=set.GRAY, fnt=set.TITLEFNT} local oldscore = fl.loadLove(set.SAVE) or {42} ui.Label{text=oldscore[1],x=556,y=427, fntclr=set.GRAY,fnt=set.GAMEFNT,angle=10} self:set_cursor() set.AUD['swamp']:setVolume(0.3) set.AUD['swamp']:setLooping(true) set.AUD['swamp']:play() self.set_pause = function() end end function SCR.Menu.beginContact(obj1, obj2, coll) local ud1=obj1:getUserData() local ud2=obj2:getUserData() if ud1.tag=='swarm' and ud2.tag=='deadhand' then ud1,ud2 = ud2,ud1 end if ud1.tag=='deadhand' and ud2.tag=='swarm' then ud2:catch() SCR.Menu.fade = SCR.Menu.fade-0.01 end end function SCR.Menu:update(dt) -- ui ui.Manager.update(dt) self:cursor_upd() for particle in pairs(self.particles) do particle:update(dt) if particle:getCount()==0 then particle:reset() self.particles[particle]=nil end end -- objects for object in pairs(self.objects) do if object.update then object:update(dt) end end -- box2d to avoid problem with destroy if not self.world:isDestroyed() then self.world:update(dt) end if self.fade<=0.1 then SCR.Menu.fade=1 love.audio.stop() love:game() end end function SCR.Menu:draw() love.graphics.setColor({self.fade,self.fade,self.fade,1}) love.graphics.draw(self.bg) -- items for item in pairs(self.objects) do if item.draw then item:draw() end end -- particle for particle in pairs(self.particles) do love.graphics.draw(particle) end ui.Manager.draw() end SCR.Game=cls.Class(Proto,{tag='game'}) SCR.Game.bg=love.graphics.newImage(set.IMG['bg']) SCR.Game.fg=love.graphics.newImage(set.IMG['fg']) function SCR.Game:new(o) ui.Manager.clear() self.tmr = Tmr:new() cmp.GRAVITY = {x=0,y=10} b2d.setWorld(self,10,cmp.GRAVITY.x,cmp.GRAVITY.y) self:set_objects() self:set_cursor() self.fog=self:objectParticle(10, {set.WHITEF,set.WHITEHF,set.GRAYF}, set.IMG['fog'], {6,12}, {0.1,10}, 1) self.fog.particle:setRotation(0.3, 1) self.fog.particle:setEmitterLifetime(-1) self.fog.particle:emit(1) self.cloud = self:objectParticle(1, {set.GRAYHF,set.WHITEHHHF,set.GRAYF}, set.IMG['cloud'], {30,40}, {0.8,1.5}, 0.01) self.cloud.particle:setSpeed(10,40) self.cloud.particle:setPosition(set.MIDWID,0) self.cloud.particle:setEmissionArea('uniform', 200, 100, 0.3) self.cloud.particle:setRotation(0, 0) self.cloud.particle:setSpin(0, 0) self.cloud.particle:emit(40) self.cloud.particle:setPosition(-set.IMG['cloud']:getWidth(),0) self.fade=0 self.tmr:tween(4, self, {fade=1},'linear', function() self.deadhand:show_score(0) end) set.AUD['swamp']:stop() set.AUD['wood']:setVolume(0.4) set.AUD['wood']:setLooping(true) set.AUD['wood']:play() end function SCR.Game:set_objects() local x,y=ctrl:position() obj.Ground{screen=self,x=set.MIDWID,y=set.HEI} obj.Spider{screen=self,x=740,y=365} obj.Owl{screen=self,x=190,y=226} self.deadhand=obj.DeadHand{screen=self,x=405,y=460} self.zombie = 12 for _=1,self.zombie do local zx = love.math.random(set.WID) local zy = love.math.random(set.HEI-40,set.HEI-20) obj.Zombie{screen=self,x=zx,y=zy} end self.avatar=self.avatar or obj.Avatar{screen=self,x=x,y=y} self.score = {val=nil} ui.Label{x=392,y=428,var=self.score, fntclr=set.GRAY,fnt=set.GAMEFNT,angle=10} end function SCR.Game:get_score() return self.score.val end function SCR.Game:set_score(score) self.score.val = score end function SCR.Game:destroy(...) self.Super.destroy(self,...) self.zombie=self.zombie-1 if self.zombie==0 then local scrscore=(fl.loadLove(set.SAVE) or {0})[1] self.tmr:after(3,function() if self.score.val > scrscore then scrscore = self.score.val end fl.saveLove(set.SAVE,'return {'..scrscore..'}') love:startgame() end) end end function SCR.Game.beginContact(obj1, obj2, coll) local ud1=obj1:getUserData() local ud2=obj2:getUserData() if ud1.tag=='swarm' and ud2.tag=='ground' then ud1,ud2 = ud2,ud1 end if ud1.tag=='ground' and ud2.tag=='swarm' then obj.Swarm.set_done(true) ud2:splash(ud2.wid,set.BLACK) ud2.groundaud:play() end if ud1.tag=='zombie' and ud2.tag=='swarm' then ud1,ud2 = ud2,ud1 end if ud1.tag=='swarm' and ud2.tag=='zombie' then ud1:catch(ud2) end if ud1.tag=='zombie' and ud2.tag=='zombie' then ud2:set_dead(false) ud1:turn() ud2:turn() end if ud1.tag=='zombie' and ud2.tag=='ground' then ud1,ud2 = ud2,ud1 end if ud1.tag=='ground' and ud2.tag=='zombie' then if ud2:get_dead() then ud2:destroy() end if (math.abs(ud2.xvel)>50 or math.abs(ud2.yvel)>100) then ud2.dust.particle:emit(25) end end end function SCR.Game:update(dt) -- ui ui.Manager.update(dt) self:cursor_upd() if self.pause then return end -- garbage for object in pairs(self.garbage) do if object.update then object:update(dt) end end -- objects for object in pairs(self.objects) do if object.update then object:update(dt) end end for particle in pairs(self.particles) do particle:update(dt) if particle:getCount()==0 then particle:reset() self.particles[particle]=nil end end local randx,randy=self.getRandOffsetXY(nil, nil, set.WID, set.HEI, 'rand') self.fog.particle:setEmissionRate(love.math.random(1,3)) self.fog.particle:setPosition(randx,randy) local cloud_emit=love.math.random(9) if cloud_emit==1 then self.cloud.particle:emit(cloud_emit) end -- box2d to avoid problem with destroy if not self.world:isDestroyed() then self.world:update(dt) end end function SCR.Game:draw() love.graphics.setColor({self.fade,self.fade,self.fade,1}) love.graphics.draw(self.bg) -- garbage for object in pairs(self.garbage) do if object.draw then object:draw() end end -- objects for object in pairs(self.objects) do if object.draw then object:draw() end end -- grass love.graphics.draw(self.fg,-14,set.HEI-85) -- particle for particle in pairs(self.particles) do love.graphics.draw(particle) end -- ui ui.Manager.draw() end return SCR
#!./hive require("common/log"); require("common/tree"); require("common/alt_getopt"); require("common/signal"); lbus = require("lbus") lredis = require("lredis"); _G.s2s = s2s or {}; if not hive.init_flag then local long_opts = { routers=1, --router addr: 127.0.0.1:6000;127.0.0.1:6001 index=1, --instance index log=1, --log file: gamesvr.1 daemon=0, }; local args, optind = alt_getopt.get_opts(hive.args, "", long_opts); if args.daemon then hive.daemon(1, 1); end log_open(args.log or "dbagent", 60000); hive.print = log_info; _G.print = log_debug; _G.socket_mgr = lbus.create_socket_mgr(args.connections or 1024); _G.redis = lredis.create_agent(); redis.connect("127.0.0.1", 6379, 1000); hive.args = args; hive.optind = optind; hive.start_time = hive.start_time or hive.get_time_ms(); hive.frame = hive.frame or 0; router_mgr = import("common/router_mgr.lua"); router_mgr.setup("dbagent"); hive.init_flag = true; end collectgarbage("stop"); import("dbagent/lease_mgr.lua"); redis.on_connect = function(ok) log_info("connect redis server ... %s", ok and "ok" or "failed"); if ok then redis.command("set", "rolename:123", "tom"); redis.command("get", "rolename:123"); end end redis.on_disconnect = function() log_err("db connection lost !"); end redis.on_reply = function(reply) log_tree("reply", reply); end hive.run = function() hive.now = os.time(); local count = socket_mgr.wait(10) + redis.update(); local cost_time = hive.get_time_ms() - hive.start_time; if 100 * hive.frame < cost_time then hive.frame = hive.frame + 1; local ok, err = xpcall(on_tick, debug.traceback, hive.frame); if not ok then log_err("on_tick error: %s", err); end collectgarbage("collect"); end if check_quit_signal() then log_info("service quit for signal !"); hive.run = nil; end end function on_tick(frame) if frame % 10 == 0 then call_router_all("heartbeat", nil); end router_mgr.update(frame); end
return {'sweater','sweatshirt','sweelinck','sweder','swen','sweep','sweers','sweere','sweet','swertz','swets','sweegers','sweelssen','sweerts','sweens','swenne','swenker','sweaters','sweatshirts','sweders','swens'}
----------------------------------- -- Area: The Celestial Nexus -- Mob: Eald'narche (Phase 2) -- Zilart Mission 16 BCNM Fight ----------------------------------- require("scripts/globals/titles") require("scripts/globals/status") require("scripts/globals/magic") ----------------------------------- function onMobInitialize(mob) -- 60% fast cast, -75% physical damage taken, 10tp/tick regain, no standback mob:addMod(tpz.mod.UFASTCAST, 60) mob:addMod(tpz.mod.UDMGPHYS, -75) mob:addMod(tpz.mod.REGAIN, 100) mob:setMobMod(tpz.mobMod.HP_STANDBACK,-1) end function onMobSpawn(mob) mob:setMobMod(tpz.mobMod.GA_CHANCE,25) end function onMobDeath(mob, player, isKiller) mob:getBattlefield():setLocalVar("loot", 0) end
addEvent ( "doSendDriveBySettings", true ) addEvent ( "deletePedForDrivebyFix", true ) addEvent ( "savePedForDrivebyFix", true ) ---Left/right toggling local bikes = { [581]=true,[509]=true,[481]=true,[462]=true,[521]=true,[463]=true, [510]=true,[522]=true,[461]=true,[448]=true,[468]=true,[586]=true } local driver = false local shooting = false local exitingvehicle = false local helpText, helpAnimation, block local lastSlot = 0 local settings = {} local functions = {} -- using this table to easily localize functions local limiterTimer local peds = {} local pedowner = {} -- Use this to detect damage on the player using driveby on a bike -- local function pedGotHit ( attacker, weapon, bodypart, loss ) -- Let the attacker trigger it -- if attacker == localPlayer and pedowner[source] ~= attacker then triggerEvent ( "onClientPlayerDamage", pedowner[source], attacker, weapon, bodypart, loss ) end end -- function to change the alpha of the helptext -- local function helpTextChangeAlpha ( alpha ) helpText:color(255,255,255,alpha) end -- fade in help -- local function fadeInHelp () if helpAnimation then helpAnimation:remove() end local _,_,_,a = helpText:color() if a ~= 255 then helpAnimation = Animation.createAndPlay(helpText, Animation.presets.dxTextFadeIn(300)) setTimer ( helpTextChangeAlpha, 300, 1, 255 ) end end -- fade out help -- local function fadeOutHelp () if helpAnimation then helpAnimation:remove() end local _,_,_,a = helpText:color() if a ~= 0 then helpAnimation = Animation.createAndPlay(helpText, Animation.presets.dxTextFadeOut(300)) setTimer ( helpTextChangeAlpha, 300, 1, 0 ) end end -- remove keys for using driveby -- functions.removeKeyToggles = function ( vehicle ) toggleControl ( "vehicle_look_left",true ) toggleControl ( "vehicle_look_right",true ) toggleControl ( "vehicle_secondary_fire",true ) functions.toggleTurningKeys(getElementModel(vehicle),true) fadeOutHelp() removeEventHandler ( "onClientPlayerVehicleExit", localPlayer, functions.removeKeyToggles ) end --Get the settings details from the server, and act appropriately according to them addEventHandler("doSendDriveBySettings",localPlayer, function ( newSettings, thepeds ) settings = newSettings --We change the tables into an indexed table that's easier to check local newTable = {} if settings.blockedVehicles[1] then for i=1, #settings.blockedVehicles do newTable[settings.blockedVehicles[i]] = true end end settings.blockedVehicles = newTable newTable = {} if settings.driver[1] then for i=1, #settings.driver do newTable[settings.driver[i]] = true end end settings.driver = newTable -- get the peds of the guys using driveby -- newTable = {} if settings.passenger[1] then for i=1, #settings.passenger do newTable[settings.passenger[i]] = true end end settings.passenger = newTable peds = {} pedowner = {} for i, v in pairs ( thepeds ) do peds[i] = v pedowner[v] = i end end ) -- Use driveby -- functions.toggleDriveby = function() -- if you are in a vehicle -- if isPedInVehicle ( localPlayer ) then local veh = getPedOccupiedVehicle ( localPlayer ) local vehicleID = getElementModel ( veh ) -- if the vehicle isn't blocked for using driveby -- if not settings.blockedVehicles[vehicleID] then local equipedWeapon = getPedWeaponSlot ( localPlayer ) -- if you dont have any equiped weapons (not doing driveby) -- if equipedWeapon == 0 then -- if the player isn't exiting the vehicle -- if not exitingvehicle then local weaponsTable = driver and settings.driver or settings.passenger local switchTo local switchToWeapon local lastSlotAmmo = getPedTotalAmmo ( localPlayer, lastSlot ) local lastSlotWeapon = getPedWeapon ( localPlayer, lastSlot ) -- if you didn't used a weapon last time or don't have ammo for it, get a new weapon -- if ( not lastSlotAmmo or lastSlotAmmo == 0 or lastSlot == 0 ) and not weaponsTable[lastSlotWeapon] then for i=1, 12 do local weapon = getPedWeapon ( localPlayer, i ) if weaponsTable[( weapon == 1 and 0 or weapon )] then if getPedTotalAmmo ( localPlayer, i ) ~= 0 then if not switchTo or i == 4 then switchTo = i switchToWeapon = weapon break end end end end else switchTo = lastSlot switchToWeapon = lastSlotWeapon end -- if you got a weapon to switch to -- if switchTo then setPedDoingGangDriveby ( localPlayer, true ) setPedWeaponSlot( localPlayer, switchTo ) functions.limitDrivebySpeed ( switchToWeapon ) toggleControl ( "vehicle_look_left",false ) toggleControl ( "vehicle_look_right",false ) toggleControl ( "vehicle_secondary_fire",false ) functions.toggleTurningKeys(vehicleID,false) if settings.bikeHitboxFix and getVehicleType ( veh ) == "Bike" then triggerServerEvent ( "createPedForDrivebyFix", localPlayer ) end addEventHandler ( "onClientPlayerVehicleExit",localPlayer,functions.removeKeyToggles ) local prevw,nextw = next(getBoundKeys ( "Previous driveby weapon" )),next(getBoundKeys ( "Next driveby weapon" )) if prevw and nextw then if animation then Animation:remove() end helpText:text( "Press '"..prevw.."' or '"..nextw.."' to change weapon" ) fadeInHelp() setTimer ( fadeOutHelp, 10000, 1 ) end end end else -- if you are already in driveby setPedDoingGangDriveby ( localPlayer, false ) setPedWeaponSlot( localPlayer, 0 ) functions.limitDrivebySpeed ( switchToWeapon ) toggleControl ( "vehicle_look_left",true ) toggleControl ( "vehicle_look_right",true ) toggleControl ( "vehicle_secondary_fire",true ) functions.toggleTurningKeys(vehicleID,true) fadeOutHelp() triggerServerEvent ( "destroyPedForDrivebyFix", localPlayer ) removeEventHandler ( "onClientPlayerVehicleExit",localPlayer,functions.removeKeyToggles ) end end end end addCommandHandler ( "Toggle Driveby", functions.toggleDriveby ) --This function handles the driveby switch weapon key functions.switchDrivebyWeapon = function(cmd,progress) if not block then -- progress = -1 (previous weapon) or 1 (next weapon) progress = tonumber(progress) if progress then if not shooting then if isPedInVehicle( localPlayer ) then local currentWeapon = getPedWeapon( localPlayer ) local currentSlot = getPedWeaponSlot(localPlayer) if currentSlot ~= 0 then local weaponsTable = driver and settings.driver or settings.passenger local switchTo, switchToWeapon if not weaponsTable[currentWeapon] then switchToWeapon = 0 switchTo = 0 end local j = currentSlot + progress while j ~= currentSlot do local nextWeapon = getPedWeapon ( localPlayer, j ) if nextWeapon and weaponsTable[nextWeapon] then switchToWeapon = nextWeapon switchTo = j break end if j + progress < 0 or j + progress > 12 then j = progress < 0 and 12 or 1 else j = j + progress end end --If a valid weapon was not found, dont set anything. if switchTo then lastSlot = switchTo setPedWeaponSlot( localPlayer, switchTo ) functions.limitDrivebySpeed ( switchToWeapon ) end end end end end end end addCommandHandler ( "Next driveby weapon", functions.switchDrivebyWeapon ) addCommandHandler ( "Previous driveby weapon", functions.switchDrivebyWeapon ) --Here lies the stuff that limits shooting speed (so slow weapons dont shoot ridiculously fast) functions.limitDrivebySpeed = function( weaponID ) local speed = settings.shotdelay[tostring(weaponID)] if not speed then if not isControlEnabled ( "vehicle_fire" ) then toggleControl ( "vehicle_fire", true ) end removeEventHandler("onClientPlayerVehicleExit",localPlayer,functions.unbindFire) removeEventHandler("onClientPlayerWasted",localPlayer,functions.unbindFire) unbindKey ( "vehicle_fire", "both", functions.limitedKeyPress ) elseif isControlEnabled ( "vehicle_fire" ) then toggleControl ( "vehicle_fire", false ) addEventHandler("onClientPlayerVehicleExit",localPlayer,functions.unbindFire) addEventHandler("onClientPlayerWasted",localPlayer,functions.unbindFire) bindKey ( "vehicle_fire","both",functions.limitedKeyPress,speed) end end functions.unbindFire = function() unbindKey ( "vehicle_fire", "both", functions.limitedKeyPress ) if not isControlEnabled ( "vehicle_fire" ) then toggleControl ( "vehicle_fire", true ) end removeEventHandler("onClientPlayerVehicleExit",localPlayer,functions.unbindFire) removeEventHandler("onClientPlayerWasted",localPlayer,functions.unbindFire) end functions.pressKey = function ( controlName ) setControlState ( controlName, true ) setTimer ( setControlState, 150, 1, controlName, false ) end functions.blockfalse = function() block = false end functions.limitedKeyPress = function(key,keyState,speed) if keyState == "down" then if not block then shooting = true functions.pressKey ( "vehicle_fire" ) block = true setTimer ( functions.blockfalse, speed, 1 ) limiterTimer = setTimer ( functions.pressKey, speed, 0, "vehicle_fire" ) end else shooting = false if isTimer ( limiterTimer ) then killTimer ( limiterTimer ) end end end functions.toggleTurningKeys = function(vehicleID, state) if bikes[vehicleID] then if not settings.steerBikes then toggleControl ( "vehicle_left", state ) toggleControl ( "vehicle_right", state ) end elseif not settings.steerCars then toggleControl ( "vehicle_left", state ) toggleControl ( "vehicle_right", state ) end end --[[ Block driveby when exiting vehicle: setPedDoingGangDriveby ejects the player if he is trying to get out of the vehicle (without animations ) ]] addEventHandler ( "onClientVehicleStartExit", root, function ( player ) if player == localPlayer then exitingvehicle = true end end ) --This function simply sets up the driveby upon vehicle entry addEventHandler( "onClientPlayerVehicleEnter", localPlayer, function ( _, seat ) --If his seat is 0, store the fact that he's a driver exitingvehicle = false driver = seat == 0 lastSlot = 0 --By default, we set the player's equiped weapon to nothing. setPedWeaponSlot( localPlayer, 0 ) if settings.autoEquip then functions.toggleDriveby() end end ) addEventHandler ("onClientPlayerWeaponSwitch", localPlayer, function ( _, curSlot ) if isPedDoingGangDriveby(source) then functions.limitDrivebySpeed(getPedWeapon(source, curSlot)) end end ) --Tell the server the clientside script was downloaded and started addEventHandler ( "onClientResourceStart", resourceRoot, function() bindKey ( "mouse2", "down", "Toggle Driveby", "" ) bindKey ( "e", "down", "Next driveby weapon", "1" ) bindKey ( "q", "down", "Previous driveby weapon", "-1" ) toggleControl ( "vehicle_next_weapon",false ) toggleControl ( "vehicle_previous_weapon",false ) triggerServerEvent ( "driveby_clientScriptLoaded", localPlayer ) helpText = dxText:create("",0.5,0.85) helpText:scale(1) helpText:type("stroke",1) end ) addEventHandler ( "onClientResourceStop", resourceRoot, function() toggleControl ( "vehicle_next_weapon",true ) toggleControl ( "vehicle_previous_weapon",true ) end ) addEventHandler ( "deletePedForDrivebyFix", root, function ( ) if peds[source] then pedowner[peds[source]] = nil end peds[source] = nil end ) addEventHandler ( "savePedForDrivebyFix", root, function ( ped ) local veh = getPedOccupiedVehicle ( source ) if isElement ( veh ) then --setElementAlpha ( ped, 0 ) peds[source] = ped pedowner[ped] = source addEventHandler ( "onClientPedDamage", ped, pedGotHit ) --setElementCollidableWith ( ped, veh, false ) if source == localPlayer then setElementCollisionsEnabled ( ped, false ) else setElementCollisionsEnabled ( ped, true ) end end end )
includeFile("custom_content/intangible/vendor/generic_vendor_control_device.lua")
object_mobile_dressed_corellia_ragtag_anita_bath = object_mobile_shared_dressed_corellia_ragtag_anita_bath:new { } ObjectTemplates:addTemplate(object_mobile_dressed_corellia_ragtag_anita_bath, "object/mobile/dressed_corellia_ragtag_anita_bath.iff")
-- vim.cmd [[packadd nvim-compe]] -- vim.cmd [[packadd vim-vsnip]] -- vim.cmd [[packadd vim-vsnip-integ]] local map = vim.api.nvim_set_keymap local protocol = require "vim.lsp.protocol" -- vim.cmd "au BufEnter *.jsx set filetype=javascript" vim.o.completeopt = "menuone,noselect" require "compe".setup { enabled = true, debug = false, min_length = 1, preselect = "always", source_timeout = 200, -- incomplete_delay = 400, allow_prefix_unmatch = false, documentation = true, source = { path = {menu = " "}, buffer = {menu = " "}, vsnip = {menu = " "}, nvim_lsp = {menu = "  "}, nvim_lua = {menu = " "}, treesitter = {menu = " "}, spell = true, calc = true, tags = true, orgmode = true, -- omni = true } } local t = function(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end local check_back_space = function() local col = vim.fn.col(".") - 1 if col == 0 or vim.fn.getline("."):sub(col, col):match("%s") then return true else return false end end -- Use (s-)tab to: --- move to prev/next item in completion menuone --- jump to prev/next snippet's placeholder _G.tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-n>" elseif vim.fn.call("vsnip#available", {1}) == 1 then return t "<Plug>(vsnip-expand-or-jump)" elseif check_back_space() then return t "<Tab>" else return vim.fn["compe#complete"]() end end _G.s_tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-p>" elseif vim.fn.call("vsnip#jumpable", {-1}) == 1 then return t "<Plug>(vsnip-jump-prev)" else return t "<S-Tab>" end end map("i", "<CR>", "compe#confirm('<CR>')", {expr = true}) map("i", "<C-Space>", "compe#complete()", {expr = true}) map("i", "<Tab>", "v:lua.tab_complete()", {noremap = false, expr = true}) map("s", "<Tab>", "v:lua.tab_complete()", {noremap = false, expr = true}) map("i", "<S-Tab>", "v:lua.tab_complete()", {noremap = false, expr = true}) map("s", "<S-Tab>", "v:lua.tab_complete()", {noremap = false, expr = true}) map("i", "C-u", "compe#scroll({ 'delta': +4 })", {noremap = false, expr = true}) map("i", "<C-d>", "compe#scroll({ 'delta': -4 })", {noremap = false, expr = true}) protocol.CompletionItemKind = { "ﮜ [text]", " [method]", " [function]", " [constructor]", "ﰠ [field]", " [variable]", " [class]", " [interface]", " [module]", " [property]", " [unit]", " [value]", " [enum]", " [key]", " [snippet]", " [color]", " [file]", " [reference]", " [folder]", " [enum member]", " [constant]", " [struct]", "⌘ [event]", " [operator]", "⌂ [type]" }
if minetest.get_modpath("basic_materials") == nil then -------------- -- PLASTICS -- -------------- minetest.register_craftitem(":basic_materials:oil_extract", { description = "Oil Extract", inventory_image = "elepower_oil_extract.png", }) minetest.register_craftitem(":basic_materials:paraffin", { description = "Unprocessed Paraffin", inventory_image = "elepower_paraffin.png", }) minetest.register_alias("basic_materials:plastic_base", "basic_materials:paraffin") minetest.register_alias("homedecor:plastic_base", "basic_materials:paraffin") minetest.register_alias("homedecor:paraffin", "basic_materials:paraffin") minetest.register_alias("homedecor:plastic_sheeting", "basic_materials:plastic_sheet") minetest.register_alias("homedecor:oil_extract", "basic_materials:oil_extract") minetest.register_craftitem(":basic_materials:plastic_sheet", { description = "Plastic Sheet", inventory_image = "elepower_plastic_sheet.png", }) minetest.register_craft({ type = "shapeless", output = "basic_materials:oil_extract 4", recipe = { "group:leaves", "group:leaves", "group:leaves", "group:leaves", "group:leaves", "group:leaves" } }) minetest.register_craft({ type = "cooking", output = "basic_materials:paraffin", recipe = "basic_materials:oil_extract", }) minetest.register_craft({ type = "cooking", output = "basic_materials:plastic_sheet", recipe = "basic_materials:paraffin", }) minetest.register_craft({ type = "fuel", recipe = "basic_materials:oil_extract", burntime = 30, }) minetest.register_craft({ type = "fuel", recipe = "basic_materials:paraffin", burntime = 30, }) minetest.register_craft({ type = "fuel", recipe = "basic_materials:plastic_sheet", burntime = 30, }) ----------------- -- COPPER WIRE -- ----------------- minetest.register_craftitem(":basic_materials:copper_wire", { description = "Copper Wire", inventory_image = "elepower_copper_wire.png", groups = {copper = 1, wire = 1, component = 1} }) minetest.register_craft({ output = "basic_materials:copper_wire 8", recipe = { {"default:copper_ingot", "default:copper_ingot", "default:copper_ingot"}, {"default:copper_ingot", "", "default:copper_ingot"}, {"default:copper_ingot", "default:copper_ingot", "default:copper_ingot"} } }) ----------- -- MOTOR -- ----------- minetest.register_craftitem(":basic_materials:motor", { description = "Motor", inventory_image = "elepower_motor.png", groups = {motor = 1, component = 1} }) minetest.register_craft({ output = "basic_materials:motor 3", recipe = { {"default:steel_ingot", "elepower_dynamics:wound_copper_coil", "default:steel_ingot"}, {"basic_materials:copper_wire", "elepower_dynamics:wound_copper_coil", "basic_materials:copper_wire"}, {"default:steel_ingot", "elepower_dynamics:capacitor", "default:steel_ingot"}, } }) ------------- -- SILICON -- ------------- minetest.register_craftitem(":basic_materials:silicon", { description = "Silicon", inventory_image = "elepower_silicon.png", groups = {silicon = 1, lump = 1} }) ----------- -- BRASS -- ----------- minetest.register_craftitem(":basic_materials:brass_ingot", { description = "Brass Ingot", inventory_image = "elepower_brass_ingot.png", groups = {brass = 1, ingot = 1} }) else minetest.clear_craft({output = "basic_materials:brass_ingot"}) end
--[[ Akilzon- Gauntlet Event This script was written and is protected by the GPL v2. This script was released by Paroxysm 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 -- Paroxysm, October 23, 2008. ~~End of License Agreement]] local amani_warrior = 24225 local amani_eagle = 24159 local amani_windwalker = 24179 local amani_lookout = 24175 local amani_protector = 24180 local amani_tempest = 24549 local soaring_eagle = 24858 local allowtempest = false local amani_adds = {} amani_adds["warriors"] = {} amani_adds["eagles"] = {} function AmaniLookOut_OnCombat(Unit,event,pmisc) Unit:DestroyCustomWaypointMap() Unit:CreateCustomWaypointMap() Unit:CreateWaypoint(1, 229.025361, 1465.758911, 25.916751, Unit:GetO(), 0, 256, 0) Unit:CreateWaypoint(2, 228.005325, 1435.453491, 26.726126, Unit:GetO(), 0, 256, 0) Unit:CreateWaypoint(3, 228.352188, 1374.711426, 46.888203, Unit:GetO(), 0, 256, 0) Unit:SetCombatCapable(1) Unit:RegisterEvent("AmaniLookOut_Waypoints", 200, 1) end function AmaniLookOut_Waypoints(Unit) Unit:SetAllowedToEnterCombat(0) Unit:StopMovement(0) Unit:SetAIState(AI_State.STATE_SCRIPTMOVE) Unit:SetMovementType(MovementType.MOVEMENTTYPE_FORWARDTHANSTOP) allowtempest = true Unit:RegisterEvent("AmaniTempest_Initialize", 10000, 1) end function AmaniLookOut_OnWipe(Unit) Unit:DestroyCustomWaypointMap() allowtempest = false; end function AmaniLookOut_OnDeath(Unit) Unit:DestroyCustomWaypointMap() allowtempest = false; end function AmaniLookOut_OnReachWp(Unit,null,null,wp) print("Current waypoint is : "..tonumber(wp)) if(wp == 1) then Unit:MoveToWaypoint(2) Unit:SetMovementType(MovementType.MOVEMENTTYPE_WANTEDWP) elseif(wp == 2) then Unit:MoveToWaypoint(3) Unit:SetMovementType(MovementType.MOVEMENTTYPE_WANTEDWP) elseif(wp == 3) then Unit:RemoveFromWorld() end end function AmaniTempest_Initialize(Unit) local tempest = Unit:GetCreatureNearestCoords(301.122009,1385.599976, 57.853100,amani_tempest) if(type(tempest) == "userdata") then if((tempest:IsAlive() == true) and (tempest:IsInCombat() == false)) then tempest:RemoveFromWorld()-- Need to use onspawn hook and set the tempest as event controller Unit:SpawnCreature(amani_tempest, 301.122009, 1385.599976, 57.853100, 3.263770, 1890, 0) end else Unit:SpawnCreature(amani_tempest, 301.122009, 1385.599976, 57.853100, 3.263770, 1890, 0) end end RegisterUnitEvent(amani_lookout, 1, "AmaniLookOut_OnCombat") RegisterUnitEvent(amani_lookout, 19, "AmaniLookOut_OnReachWp") RegisterUnitEvent(amani_lookout, 2, "AmaniLookOut_OnWipe") RegisterUnitEvent(amani_lookout, 4,"AmaniLookOut_OnDeath") function AmaniTempest_OnSpawn(Unit) Unit:DestroyCustomWaypointMap() if(allowtempest == true) then Unit:RegisterEvent("AmaniTempest_AddSpawn", 100, 1) end Unit:RegisterAIUpdateEvent(2000) end function AmaniTempest_AIUpdate(Unit) local warcount,eaglecount = table.getn(amani_adds["warriors"]),table.getn(amani_adds["eagles"]) if((warcount > 6) or (eaglecount > 15)) then allowtempest = false elseif((warcount <= 6) and (eaglecount <= 15)) then allowtempest = true end end function AmaniTempest_AddSpawn(Unit) if(allowtempest == true) then for i = 1, math.random(5,6) do Unit:CastSpellAoF(296.047699, 1384.848022, 56.057110, 43487) end Unit:CastSpellAoF(228.884476, 1489.821777, 25.937740, 43486) Unit:CastSpellAoF(223.590759, 1490.079712, 25.916952, 43486) Unit:RegisterEvent("AmaniTempest_AddSpawndeux", 15000, 1) else Unit:RegisterEvent("AmaniTempest_AddSpawndeux", 3000, 1) end end function AmaniTempest_AddSpawndeux(Unit) if(allowtempest == true) then for i = 1, math.random(5,6) do Unit:CastSpellAoF(296.047699, 1384.848022, 56.057110, 43487) end Unit:RegisterEvent("AmaniTempest_AddSpawn", 30000, 1) else Unit:RegisterEvent("AmaniTempest_AddSpawn", 3000, 1) end end function AmaniTempest_OnCombat(Unit) Unit:RemoveEvents() Unit:RegisterEvent("AmaniTempest_AOE",10000,0) end function AmaniTempest_AOE(Unit) if Unit:GetRandomPlayer(0)~= nil then Unit:FullCastSpell(44033) -- the aoe nature attack. end end function AmaniTempest_OnLeaveCombat(Unit) Unit:RemoveAIUpdateEvent() Unit:RemoveEvents() end function AmaniTempest_OnDeath(Unit) Unit:RemoveAIUpdateEvent() Unit:RemoveEvents() Unit:DisableRespawn() end RegisterUnitEvent(amani_tempest, 18, "AmaniTempest_OnSpawn") RegisterUnitEvent(amani_tempest, 1, "AmaniTempest_OnCombat") RegisterUnitEvent(amani_tempest, 2, "AmaniTempest_OnLeaveCombat") RegisterUnitEvent(amani_tempest, 4, "AmaniTempest_OnDeath") RegisterUnitEvent(amani_tempest, 21, "AmaniTempest_AIUpdate") local kick_timer = nil local charge_timer = nil function AmaniWarrior_OnSpawn(Unit) local args = getvars(Unit) if((args == nil) or (args.NALORAKK == nil)) then table.insert(amani_adds["warriors"],Unit) Unit:ModifySpeed(12) if(allowtempest == true) then Unit:DestroyCustomWaypointMap() Unit:CreateWaypoint(1, 229.025361+(math.random(3)*math.cos(math.random(20, 60))), 1465.758911+(math.random(3)*math.sin(math.random(20, 60))), 25.916751, Unit:GetO(), 500, 256, 0) Unit:CreateWaypoint(2, 228.005325+(math.random(3)*math.cos(math.random(20, 60))), 1435.453491+(math.random(3)*math.sin(math.random(20, 60))), 26.726126, Unit:GetO(), 500, 256, 0) Unit:CreateWaypoint(3, 228.352188+(math.random(3)*math.cos(math.random(20, 60))), 1374.711426+(math.random(3)*math.sin(math.random(20, 60))), 46.888203, Unit:GetO(), 500, 256, 0) Unit:CreateWaypoint(4, 284.307404+(math.random(3)*math.cos(math.random(20, 60))), 1379.991211+(math.random(3)*math.sin(math.random(20, 60))), 49.321771, Unit:GetO(), 500, 256, 0) Unit:SetMovementType(MovementType.MOVEMENTTYPE_FORWARDTHANSTOP) --Unit:MoveToWaypoint(1) Unit:DisableRespawn(1) end end end function AmaniWarrior_OnReachWp(Unit,null,null,wp) local args = getvars(Unit) if((args == nil) or (args.NALORAKK == nil)) then if(wp == 1) then --Unit:MoveToWaypoint(2) elseif(wp == 2) then --Unit:MoveToWaypoint(3) elseif(wp == 3) then --Unit:MoveToWaypoint(4) elseif(wp == 4) then Unit:RemoveFromWorld() end end end function AmaniWarrior_OnCombat(Unit,event,pMisc) kick_timer = 0 charge_timer = 0 Unit:DestroyCustomWaypointMap() Unit:StopMovement(100) Unit:RegisterAIUpdateEvent(2000) end function AmaniWarrior_Abilities(Unit) local args = getvars(Unit) if((args == nil) or (args.NALORAKK == nil) then return end if((type(args.NALORAKK) == "table") and (args.NALORAKK.gauntlet == true)) then return end if Unit:IsInCombat() == true then local tank = Unit:GetMainTank() kick_timer = kick_timer+2 charge_timer = charge_timer+2 if((kick_timer >= 10) and (type(tank) == "userdata") and (tank:IsAlive() == true)) then local casters = {} local tbl = Unit:GetInRangePlayers() for k,v in pairs(tbl) do if((type(v) == "userdata") and (Unit:GetDistance(v) <= 10) and (v:IsAlive() == true) and (v:GetCurrentSpellId() ~= nil)) then table.insert(casters,v) end end if table.getn(casters) ~= 0 then local randcaster = casters[math.random(1,table.getn(casters))] if((type(randcaster) == "userdata") and (randcaster:IsAlive() == true)) then Unit:FullCastSpellOnTarget(43518,randcaster) kick_timer = 0 end else Unit:FullCastSpellOnTarget(43518,tank) kick_timer = 0 end elseif((kick_timer >= 10) and (type(tank) ~= "userdata")) then kick_timer = kick_timer-2 end if((charge_timer >= 20) and (type(tank) == "userdata") and (tank:IsAlive() == true)) then local casters = {} local tbl = Unit:GetInRangePlayers() for k,v in pairs(tbl) do if((type(v) == "userdata") and (v:GetCurrentSpellId() ~= nil)) then table.insert(casters,v) end end if((table.getn(casters) ~= 0) then local randcaster = casters[math.random(1,table.getn(casters))] if((type(randcaster) == "userdata") and (randcaster:IsAlive() == true)) then Unit:FullCastSpellOnTarget(43519, randcaster) charge_timer = 0 end else Unit:FullCastSpellOnTarget(43519, tank) charge_timer = 0 end elseif((charge_timer >= 20) and (type(tank) ~= "userdata")) then charge_timer = charge_timer - 2 end end end function AmaniWarrior_OnWipe(Unit) Unit:DestroyCustomWaypointMap() Unit:RemoveAIUpdateEvent() end function AmaniWarrior_OnDeath(Unit) local args = getvars(Unit) if((type(args.NALORAKK) == "table") and (args.NALORAKK.gauntlet == true)) then for k,v in pairs(args.NALORAKK.guardssent) do if(v == Unit) then table.remove(args.NALORAKK.guardssent,k) end end elseif not ((type(args.NALORAKK) == "table") or (args.NALORAKK.gauntlet ~= true)) then Unit:DestroyCustomWaypointMap() Unit:RemoveAIUpdateEvent() for k,v in pairs(amani_adds["warriors"]) do if(v == Unit) then table.remove(amani_adds["warriors"],k) end end end end function AmaniEagle_OnSpawn(Unit) table.insert(amani_adds["eagles"],Unit) if(allowtempest == true) then Unit:ModifySpeed(20) Unit:CreateWaypoint(1, 284.307404+(math.random(3)*math.cos(math.random(20, 60))), 1379.991211+(math.random(3)*math.sin(math.random(20, 60))), 49.321771, Unit:GetO(), 500, 256, 0) Unit:CreateWaypoint(2, 228.352188+(math.random(3)*math.cos(math.random(20, 60))), 1374.711426+(math.random(3)*math.sin(math.random(20, 60))), 46.888203, Unit:GetO(), 500, 256, 0) Unit:CreateWaypoint(3, 228.005325+(math.random(3)*math.cos(math.random(20, 60))), 1435.453491+(math.random(3)*math.sin(math.random(20, 60))), 26.726126, Unit:GetO(), 500, 256, 0) Unit:CreateWaypoint(4, 229.025361+(math.random(3)*math.cos(math.random(20, 60))), 1465.758911+(math.random(3)*math.sin(math.random(20, 60))), 25.916751, Unit:GetO(), 500, 256, 0) Unit:MoveToWaypoint(1) Unit:DisableRespawn(1) end end function AmaniEagle_OnReachWp(Unit,null,null,wp) if(wp == 1) then Unit:MoveToWaypoint(2) elseif(wp == 2) then Unit:MoveToWaypoint(3) elseif(wp == 3) then Unit:MoveToWaypoint(4) elseif(wp == 4) then Unit:RemoveFromWorld() end end function AmaniEagle_OnCombat(Unit, event, pMisc) Unit:DestroyCustomWaypointMap() Unit:StopMovement(100) Unit:RegisterEvent("AmaniEagle_Abilities", 7000, 1) end function AmaniEagle_OnWipe(Unit) Unit:DestroyCustomWaypointMap() Unit:RemoveEvents() Unit:RemoveFromWorld() end function AmaniEagle_OnDeath(Unit) Unit:DestroyCustomWaypointMap() Unit:RemoveEvents() for k,v in pairs(amani_adds["eagles"]) do if(v == Unit) then table.remove(amani_adds["eagles"],k) end end end function AmaniEagle_Abilities(Unit) local tank = Unit:GetMainTank() if((Unit:IsAlive() == true) and (type(tank) == "userdata") and (tank:IsAlive()) and (Unit:GetDistance(tank) <= 10) then Unit:FullCastSpellOnTarget(43517,tank) -- talon Unit:RegisterEvent("AmaniEagle_Abilities", 7000, 1) elseif((Unit:IsAlive() == true) and (type(tank) ~= "userdata") then Unit:RegisterEvent("AmaniEagle_Abilities", 2000, 1) end end RegisterUnitEvent(amani_warrior, 18, "AmaniWarrior_OnSpawn") RegisterUnitEvent(amani_eagle, 18, "AmaniEagle_OnSpawn") RegisterUnitEvent(amani_warrior, 1,"AmaniWarrior_OnCombat") RegisterUnitEvent(amani_eagle, 1, "AmaniEagle_OnCombat") RegisterUnitEvent(amani_warrior, 2,"AmaniWarrior_OnWipe") RegisterUnitEvent(amani_warrior, 4, "AmaniWarrior_OnDeath") RegisterUnitEvent(amani_eagle, 2, "AmaniEagle_OnWipe") RegisterUnitEvent(amani_eagle, 4,"AmaniEagle_OnDeath") RegisterUnitEvent(amani_warrior, 19, "AmaniWarrior_OnReachWp") RegisterUnitEvent(amani_eagle, 19, "AmaniEagle_OnReachWp") RegisterUnitEvent(amani_warrior,21,"AmaniWarrior_Abilities") function AmaniProtector_OnCombat(Unit) Unit:RegisterEvent("AmaniProtector_Abilities", 10000, 0) end function AmaniProtector_OnWipe(Unit) Unit:RemoveEvents() end function AmaniProtector_OnDeath(Unit) Unit:RemoveEvents() end function AmaniProtector_Abilities(Unit) local tank = Unit:GetMainTank() if((math.random(3) == 1) and (type(tank) == "userdata") and (tank:IsAlive() == true)) then if(Unit:IsAlive() == true) then Unit:FullCastSpellOnTarget(15496, tank) end elseif((math.random(3) == 2) and (type(tank) == "userdata") and (tank:IsAlive() == true)) then if(Unit:IsAlive() == true) then Unit:FullCastSpellOnTarget(43529, tank) end elseif(math.random(3) == 3) then if((Unit:IsAlive() == true) and (tank:IsAlive() == true)) then local tbl = Unit:GetInRangePlayers() local movplayers = {} for k,v in pairs(tbl) do if((v:IsAlive()) and (v:IsMoving() == true) and (v:GetDistance(v) <= 10)) then table.insert(movplayers,v) end end if(table.getn(movplayers) ~= 0) then Unit:FullCastSpell(43530) else AmaniProtector_Abilities(Unit) end end end end RegisterUnitEvent(amani_protector, 1, "AmaniProtector_OnCombat") RegisterUnitEvent(amani_protector, 2, "AmaniProtector_OnWipe") RegisterUnitEvent(amani_protector, 4, "AmaniProtector_OnDeath") function AmaniWindWalker_OnCombat(Unit) Unit:RegisterEvent("AmaniWindWalker_Abilities", 5000, 1) Unit:RegisterAIUpdateEvent(2000) end function AmaniWindWalker_OnWipe(Unit) Unit:RemoveEvents() end function AmaniWindWalker_OnDeath(Unit) Unit:RemoveEvents() end function AmaniWindWalker_HealAI(Unit) local allies = Unit:GetInRangeFriends() local healtable = {} table.insert(allies,Unit) for k,v in pairs(allies) do if((type(v) == "userdata") and (v:GetHealthPct() <= 50)) then table.insert(healtable,v) if(Unit:GetHealthPct() <= 50) then table.insert(healtable,Unit) end end end if(table.getn(healtable) >= 1) then -- more than 1 target needs health! local healtar = healtable[math.random(1,table.getn(healtable))] if((type(healtar) == "userdata") and (healtar:IsAlive() == true)) then --Lets cast chain heal if(healtar == Unit) then Unit:FullCastSpell(43527) else Unit:FullCastSpellOnTarget(43527,healtar) end end end end function AmaniWindWalker_Abilities(Unit) local tank = Unit:GetMainTank() if((math.random(2) == 1) and (type(tank) == "userdata") and (tank:IsAlive())) then local plrs = Unit:GetInRangePlayers() local movplrs = {} for k,v in pairs(plrs) do if((type(v) == "userdata") and (v:IsAlive() == true) and (v:IsMoving() == true)) then table.insert(movplrs,v) end end if(table.getn(movplrs) ~= 0) then local freezetar = movplrs[math.random(1,table.getn(movplrs))] if((type(freezetar) == "userdata") and (freezetar:IsAlive() == true)) then Unit:FullCastSpellOnTarget(43524, freezetar)-- frost shock Unit:RegisterEvent("AmaniWindWalker_Abilities", 5000, 1) end else Unit:FullCastSpellOnTarget(43524,tank) Unit:RegisterEvent("AmaniWindWalker_Abilities", 2000, 1) end elseif((math.random(2) == 2) and (type(tank) == "userdata") and (tank:IsAlive() == true)) then local plrs = Unit:GetInRangePlayers() local besttar = {} for k,v in pairs(plrs) do if((type(v) == "userdata") and (v:IsAlive()) and (v:GetHealthPct() <= 50)) then -- store this target and try to spike him later table.insert(besttar,v) end end if table.getn(besttar) ~= 0 then local besttarget = besttar[math.random(1,table.getn(besttar))] if((type(besttarget) == "userdata") and (besttarget:IsAlive()) and (besttarget ~= tank)) then -- we attempt to finish off target Unit:FullCastSpellOnTarget(43526, besttarget) Unit:RegisterEvent("AmaniWindWalker_Abilities", 10000, 1) end else Unit:FullCastSpellOnTarget(43526, tank) Unit:RegisterEvent("AmaniWindWalker_Abilities", 10000, 1) end end end RegisterUnitEvent(amani_windwalker, 1, "AmaniWindWalker_OnCombat") RegisterUnitEvent(amani_windwalker, 2, "AmaniWindWalker_OnWipe") RegisterUnitEvent(amani_windwalker, 4, "AmaniWindWalker_OnDeath") RegisterUnitEvent(amani_windwalker, 21, "AmaniWindWalker_HealAI")
local scope={} ------------------------------------------------------------------------------- scope.address=function(address,next_scope) local block={ block_type = "scope_address", address = address or {}, next_scope = next_scope } return block end scope.index=function(index,next_scope) local block={ block_type = "scope_index", index = index, next_scope = next_scope } return block end ------------------------------------------------------------------------------- return scope
--[[ TheNexusAvenger Runs the TODO list plugin. --]] local NexusPluginComponents = require(script:WaitForChild("NexusPluginComponents")) local TodoListWindow = require(script:WaitForChild("TodoListWindow")) --Create the window. local Window = TodoListWindow.new(plugin) --Create the button. local NexusWidgetsToolbar = plugin:CreateToolbar("Nexus Widgets") local ToDoListButton = NexusWidgetsToolbar:CreateButton("TODO List", "Toggles the TODO list window.", "http://www.roblox.com/asset/?id=1690576230") local ToDoListToggleButton = NexusPluginComponents.new("PluginToggleButton", ToDoListButton, Window) ToDoListToggleButton.ClickableWhenViewportHidden = true
UnitPopupButtons["GM_MENU"] = { text = "GM Menu", dist = 0, nested = 1 }; UnitPopupMenus["GM_MENU"] = { "GM_PRINT_GUID" } tinsert(UnitPopupMenus["TARGET"], 1, "GM_MENU") tinsert(UnitPopupMenus["PLAYER"], 1, "GM_MENU") tinsert(UnitPopupMenus["RAID_PLAYER"], 1, "GM_MENU") tinsert(UnitPopupMenus["PARTY"], 1, "GM_MENU") UnitPopupButtons["SET_FOCUS"] = { text = "Set Focus", dist = 0, func = function() SetFocusByToken("target") end } UnitPopupButtons["GM_PRINT_GUID"] = { text = "Print Guid", dist = 0, checkable = 1, func = function() print(UnitName("target") .. "'s GUID: " .. UnitGUID("target")) end } hooksecurefunc("UnitPopup_ShowMenu", function() for i=1, UIDROPDOWNMENU_MAXBUTTONS do local button = _G["DropDownList"..UIDROPDOWNMENU_MENU_LEVEL.."Button"..i]; if button.value == "SET_FOCUS" then button.func = UnitPopupButtons["SET_FOCUS"].func elseif button.value == "GM_PRINT_GUID" then button.func = UnitPopupButtons["GM_PRINT_GUID"].func end end end)
AddCSLuaFile( 'cl_init.lua' ) AddCSLuaFile( 'shared.lua' ) include( 'shared.lua' ) timer.Destroy( 'HostnameThink' ) hook.Add( 'PreGamemodeLoaded', 'widgets_disabler_cpu', function() function widgets.PlayerTick() end hook.Remove( 'PlayerTick', 'TickWidgets' ) end )
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) local count = {} local transfer = {} function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local voices = { { text = 'Deposit your money here in the safety of the Tibian Bank!' }, { text = 'Any questions about the functions of your bank account? Feel free to ask me for help!' } } npcHandler:addModule(VoiceModule:new(voices)) local function greetCallback(cid) count[cid], transfer[cid] = nil, nil return true end local function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) ---------------------------- help ------------------------ if msgcontains(msg, 'bank account') then npcHandler:say({ 'Every Tibian has one. The big advantage is that you can access your money in every branch of the Tibian Bank! ...', 'Would you like to know more about the {basic} functions of your bank account, the {advanced} functions, or are you already bored, perhaps?' }, cid) npcHandler.topic[cid] = 0 return true ---------------------------- balance --------------------- elseif msgcontains(msg, 'balance') then npcHandler.topic[cid] = 0 if player:getBankBalance() >= 100000000 then npcHandler:say('I think you must be one of the richest inhabitants in the world! Your account balance is ' .. player:getBankBalance() .. ' gold.', cid) return true elseif player:getBankBalance() >= 10000000 then npcHandler:say('You have made ten millions and it still grows! Your account balance is ' .. player:getBankBalance() .. ' gold.', cid) return true elseif player:getBankBalance() >= 1000000 then npcHandler:say('Wow, you have reached the magic number of a million gp!!! Your account balance is ' .. player:getBankBalance() .. ' gold!', cid) return true elseif player:getBankBalance() >= 100000 then npcHandler:say('You certainly have made a pretty penny. Your account balance is ' .. player:getBankBalance() .. ' gold.', cid) return true else npcHandler:say('Your account balance is ' .. player:getBankBalance() .. ' gold.', cid) return true end ---------------------------- deposit --------------------- elseif msgcontains(msg, 'deposit') then count[cid] = player:getMoney() if count[cid] < 1 then npcHandler:say('You do not have enough gold.', cid) npcHandler.topic[cid] = 0 return false end if msgcontains(msg, 'all') then count[cid] = player:getMoney() npcHandler:say('Would you really like to deposit ' .. count[cid] .. ' gold?', cid) npcHandler.topic[cid] = 2 return true else if string.match(msg,'%d+') then count[cid] = getMoneyCount(msg) if count[cid] < 1 then npcHandler:say('You do not have enough gold.', cid) npcHandler.topic[cid] = 0 return false end npcHandler:say('Would you really like to deposit ' .. count[cid] .. ' gold?', cid) npcHandler.topic[cid] = 2 return true else npcHandler:say('Please tell me how much gold it is you would like to deposit.', cid) npcHandler.topic[cid] = 1 return true end end if not isValidMoney(count[cid]) then npcHandler:say('Sorry, but you can\'t deposit that much.', cid) npcHandler.topic[cid] = 0 return false end elseif npcHandler.topic[cid] == 1 then count[cid] = getMoneyCount(msg) if isValidMoney(count[cid]) then npcHandler:say('Would you really like to deposit ' .. count[cid] .. ' gold?', cid) npcHandler.topic[cid] = 2 return true else npcHandler:say('You do not have enough gold.', cid) npcHandler.topic[cid] = 0 return true end elseif npcHandler.topic[cid] == 2 then if msgcontains(msg, 'yes') then if player:getMoney() >= tonumber(count[cid]) then player:depositMoney(count[cid]) npcHandler:say('Alright, we have added the amount of ' .. count[cid] .. ' gold to your {balance}. You can {withdraw} your money anytime you want to.', cid) else npcHandler:say('You do not have enough gold.', cid) end elseif msgcontains(msg, 'no') then npcHandler:say('As you wish. Is there something else I can do for you?', cid) end npcHandler.topic[cid] = 0 return true ---------------------------- withdraw -------------------- elseif msgcontains(msg, 'withdraw') then if string.match(msg,'%d+') then count[cid] = getMoneyCount(msg) if isValidMoney(count[cid]) then npcHandler:say('Are you sure you wish to withdraw ' .. count[cid] .. ' gold from your bank account?', cid) npcHandler.topic[cid] = 7 else npcHandler:say('There is not enough gold on your account.', cid) npcHandler.topic[cid] = 0 end return true else npcHandler:say('Please tell me how much gold you would like to withdraw.', cid) npcHandler.topic[cid] = 6 return true end elseif npcHandler.topic[cid] == 6 then count[cid] = getMoneyCount(msg) if isValidMoney(count[cid]) then npcHandler:say('Are you sure you wish to withdraw ' .. count[cid] .. ' gold from your bank account?', cid) npcHandler.topic[cid] = 7 else npcHandler:say('There is not enough gold on your account.', cid) npcHandler.topic[cid] = 0 end return true elseif npcHandler.topic[cid] == 7 then if msgcontains(msg, 'yes') then if player:getFreeCapacity() >= getMoneyWeight(count[cid]) then if not player:withdrawMoney(count[cid]) then npcHandler:say('There is not enough gold on your account.', cid) else npcHandler:say('Here you are, ' .. count[cid] .. ' gold. Please let me know if there is something else I can do for you.', cid) end else npcHandler:say('Whoah, hold on, you have no room in your inventory to carry all those coins. I don\'t want you to drop it on the floor, maybe come back with a cart!', cid) end npcHandler.topic[cid] = 0 elseif msgcontains(msg, 'no') then npcHandler:say('The customer is king! Come back anytime you want to if you wish to {withdraw} your money.', cid) npcHandler.topic[cid] = 0 end return true ---------------------------- money exchange -------------- elseif msgcontains(msg, 'change gold') then npcHandler:say('How many platinum coins would you like to get?', cid) npcHandler.topic[cid] = 14 elseif npcHandler.topic[cid] == 14 then if getMoneyCount(msg) < 1 then npcHandler:say('Sorry, you do not have enough gold coins.', cid) npcHandler.topic[cid] = 0 else count[cid] = getMoneyCount(msg) npcHandler:say('So you would like me to change ' .. count[cid] * 100 .. ' of your gold coins into ' .. count[cid] .. ' platinum coins?', cid) npcHandler.topic[cid] = 15 end elseif npcHandler.topic[cid] == 15 then if msgcontains(msg, 'yes') then if player:removeItem(2148, count[cid] * 100) then player:addItem(2152, count[cid]) npcHandler:say('Here you are.', cid) else npcHandler:say('Sorry, you do not have enough gold coins.', cid) end else npcHandler:say('Well, can I help you with something else?', cid) end npcHandler.topic[cid] = 0 elseif msgcontains(msg, 'change platinum') then npcHandler:say('Would you like to change your platinum coins into gold or crystal?', cid) npcHandler.topic[cid] = 16 elseif npcHandler.topic[cid] == 16 then if msgcontains(msg, 'gold') then npcHandler:say('How many platinum coins would you like to change into gold?', cid) npcHandler.topic[cid] = 17 elseif msgcontains(msg, 'crystal') then npcHandler:say('How many crystal coins would you like to get?', cid) npcHandler.topic[cid] = 19 else npcHandler:say('Well, can I help you with something else?', cid) npcHandler.topic[cid] = 0 end elseif npcHandler.topic[cid] == 17 then if getMoneyCount(msg) < 1 then npcHandler:say('Sorry, you do not have enough platinum coins.', cid) npcHandler.topic[cid] = 0 else count[cid] = getMoneyCount(msg) npcHandler:say('So you would like me to change ' .. count[cid] .. ' of your platinum coins into ' .. count[cid] * 100 .. ' gold coins for you?', cid) npcHandler.topic[cid] = 18 end elseif npcHandler.topic[cid] == 18 then if msgcontains(msg, 'yes') then if player:removeItem(2152, count[cid]) then player:addItem(2148, count[cid] * 100) npcHandler:say('Here you are.', cid) else npcHandler:say('Sorry, you do not have enough platinum coins.', cid) end else npcHandler:say('Well, can I help you with something else?', cid) end npcHandler.topic[cid] = 0 elseif npcHandler.topic[cid] == 19 then if getMoneyCount(msg) < 1 then npcHandler:say('Sorry, you do not have enough platinum coins.', cid) npcHandler.topic[cid] = 0 else count[cid] = getMoneyCount(msg) npcHandler:say('So you would like me to change ' .. count[cid] * 100 .. ' of your platinum coins into ' .. count[cid] .. ' crystal coins for you?', cid) npcHandler.topic[cid] = 20 end elseif npcHandler.topic[cid] == 20 then if msgcontains(msg, 'yes') then if player:removeItem(2152, count[cid] * 100) then player:addItem(2160, count[cid]) npcHandler:say('Here you are.', cid) else npcHandler:say('Sorry, you do not have enough platinum coins.', cid) end else npcHandler:say('Well, can I help you with something else?', cid) end npcHandler.topic[cid] = 0 elseif msgcontains(msg, 'change crystal') then npcHandler:say('How many crystal coins would you like to change into platinum?', cid) npcHandler.topic[cid] = 21 elseif npcHandler.topic[cid] == 21 then if getMoneyCount(msg) < 1 then npcHandler:say('Sorry, you do not have enough crystal coins.', cid) npcHandler.topic[cid] = 0 else count[cid] = getMoneyCount(msg) npcHandler:say('So you would like me to change ' .. count[cid] .. ' of your crystal coins into ' .. count[cid] * 100 .. ' platinum coins for you?', cid) npcHandler.topic[cid] = 22 end elseif npcHandler.topic[cid] == 22 then if msgcontains(msg, 'yes') then if player:removeItem(2160, count[cid]) then player:addItem(2152, count[cid] * 100) npcHandler:say('Here you are.', cid) else npcHandler:say('Sorry, you do not have enough crystal coins.', cid) end else npcHandler:say('Well, can I help you with something else?', cid) end npcHandler.topic[cid] = 0 end return true end -- Basic keywords keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = 'I\'m Paulie.'}) keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = 'I\'m still a bank clerk-in-training. They say I can work on the mainland of Tibia once I have proven myself!'}) keywordHandler:addKeyword({'transfer'}, StdModule.say, {npcHandler = npcHandler, text = 'I\'m afraid this service is not available to you until you reach mainland.'}) keywordHandler:addKeyword({'change'}, StdModule.say, {npcHandler = npcHandler, text = 'There are three different coin types in Tibia: 100 gold coins equal 1 platinum coin, 100 platinum coins equal 1 crystal coin. For example, if you like to change 100 gold coins into 1 platinum coin, simply say \'{change gold}\' and then \'1 platinum\'.'}) keywordHandler:addKeyword({'advanced'}, StdModule.say, {npcHandler = npcHandler, text = 'Once you are on the Tibian mainland, you can access new functions of your bank account, such as transferring money to other players safely or taking part in house auctions.'}) keywordHandler:addKeyword({'king'}, StdModule.say, {npcHandler = npcHandler, text = 'HAIL TO THE KING!'}) keywordHandler:addKeyword({'academy'}, StdModule.say, {npcHandler = npcHandler, text = 'The academy is the big stone building in the town centre. When you are ready to leave Rookgaard, you should visit the {oracle} there.'}) keywordHandler:addKeyword({'time'}, StdModule.say, {npcHandler = npcHandler, text = 'It\'s exactly |TIME|.'}) keywordHandler:addKeyword({'temple'}, StdModule.say, {npcHandler = npcHandler, text = 'The temple is south of the city. Go there and talk to {Cipfried} if you are in dire need of healing.'}) keywordHandler:addKeyword({'mainland'}, StdModule.say, {npcHandler = npcHandler, text = 'I\'m looking forward to work on the mainland. The great Tibian cities are so much more interesting than this little village of {Rookgaard}.'}) keywordHandler:addKeyword({'rookgaard'}, StdModule.say, {npcHandler = npcHandler, text = 'What a godforsaken place! Well, at least there are no criminals robbing the bank which would be - me. <gulp>'}) keywordHandler:addKeyword({'premium'}, StdModule.say, {npcHandler = npcHandler, text = 'Another excellent way of investing your money.'}) keywordHandler:addKeyword({'trade'}, StdModule.say, {npcHandler = npcHandler, text = 'I don\'t trade. Ask the shop owners for a trade instead. I can only help you with your {bank account}.'}) keywordHandler:addAliasKeyword({'offer'}) keywordHandler:addAliasKeyword({'potion'}) keywordHandler:addAliasKeyword({'sell'}) keywordHandler:addAliasKeyword({'buy'}) keywordHandler:addAliasKeyword({'stuff'}) keywordHandler:addAliasKeyword({'wares'}) keywordHandler:addAliasKeyword({'weapon'}) keywordHandler:addAliasKeyword({'equip'}) keywordHandler:addAliasKeyword({'food'}) keywordHandler:addAliasKeyword({'armor'}) keywordHandler:addAliasKeyword({'shield'}) keywordHandler:addKeyword({'help'}, StdModule.say, {npcHandler = npcHandler, text = 'Every Tibian has a bank account. You can {deposit} your gold in one bank and {withdraw} it from the same or any other Tibian bank. Ask me for your {balance} to learn how much money you\'ve already saved. There are also {advanced} functions.'}) keywordHandler:addAliasKeyword({'function'}) keywordHandler:addAliasKeyword({'account'}) keywordHandler:addKeyword({'bank'}, StdModule.say, {npcHandler = npcHandler, text = 'You can {deposit} and {withdraw} money from your {bank account} here. I can also {change} money for you.'}) keywordHandler:addAliasKeyword({'money'}) -- Names keywordHandler:addKeyword({'zerbrus'}, StdModule.say, {npcHandler = npcHandler, text = 'Thank god that guy guards our bridge. Without him, I believe all sorts of critters would storm the bank!'}) keywordHandler:addAliasKeyword({'dallheim'}) keywordHandler:addKeyword({'al', 'dee'}, StdModule.say, {npcHandler = npcHandler, text = 'He sells general equipment such as ropes or torches.'}) keywordHandler:addKeyword({'amber'}, StdModule.say, {npcHandler = npcHandler, text = '<blushes> It\'s making me nervous to have her around my working place all the time. Actually it\'s distracting, but I can\'t say why.'}) keywordHandler:addKeyword({'billy'}, StdModule.say, {npcHandler = npcHandler, text = 'A fine cook and farmer.'}) keywordHandler:addKeyword({'willie'}, StdModule.say, {npcHandler = npcHandler, text = 'He\'s incredibly rude! I don\'t know what I\'ve done to him. Well, he buys and sells {food}.'}) keywordHandler:addKeyword({'tom'}, StdModule.say, {npcHandler = npcHandler, text = 'He\'s the local tanner. You could try selling fresh corpses or leather to him and then bring the earnt money to our {bank}.'}) keywordHandler:addKeyword({'seymour'}, StdModule.say, {npcHandler = npcHandler, text = 'A well-educated man.'}) keywordHandler:addKeyword({'zirella'}, StdModule.say, {npcHandler = npcHandler, text = 'She\'s a nice old lady, but I guess she prefers keeping her savings in one of her socks. She never comes to my bank.'}) keywordHandler:addKeyword({'santiago'}, StdModule.say, {npcHandler = npcHandler, text = 'Just a fisherman living outside the village.'}) keywordHandler:addKeyword({'paulie'}, StdModule.say, {npcHandler = npcHandler, text = 'That\'s me, in all my beauty! <coughs>'}) keywordHandler:addKeyword({'oracle'}, StdModule.say, {npcHandler = npcHandler, text = 'You can find the oracle on the top floor of the {academy}, just above {Seymour}. Go there when you are level 8.'}) keywordHandler:addKeyword({'obi'}, StdModule.say, {npcHandler = npcHandler, text = 'He sells {weapons}. His shop is south west of town, close to the {temple}.'}) keywordHandler:addKeyword({'norma'}, StdModule.say, {npcHandler = npcHandler, text = 'Going to her bar is not so much my cup of tea... I prefer reading a good book about economy.'}) keywordHandler:addKeyword({'loui'}, StdModule.say, {npcHandler = npcHandler, text = 'I don\'t know that guy.'}) keywordHandler:addKeyword({'lily'}, StdModule.say, {npcHandler = npcHandler, text = 'Lily sells {potions} in the South of town.'}) keywordHandler:addKeyword({'lee\'delle'}, StdModule.say, {npcHandler = npcHandler, text = 'Her shop is on the {premium} side of town. She has really good offers.'}) keywordHandler:addKeyword({'hyacinth'}, StdModule.say, {npcHandler = npcHandler, text = 'Hm, I\'ve never seen him. He\'s supposed to be a druid.'}) keywordHandler:addKeyword({'dixi'}, StdModule.say, {npcHandler = npcHandler, text = 'She\'s {Obi\'s} granddaughter and deals with {armors} and {shields}. Her shop is southwest of town, close to the {temple}.'}) keywordHandler:addKeyword({'cipfried'}, StdModule.say, {npcHandler = npcHandler, text = 'He guards the temple and can heal you if you are badly injured or poisoned.'}) npcHandler:setMessage(MESSAGE_GREET, 'Welcome |PLAYERNAME|! Here, you can {deposit} or {withdraw} your money from your bank account and {change} gold. I can also explain the {functions} of your bank account to you.') npcHandler:setMessage(MESSAGE_FAREWELL, 'Good bye, and remember: entrusting us with your gold is the safest way of storing it!') npcHandler:setMessage(MESSAGE_WALKAWAY, 'Good bye.') npcHandler:setCallback(CALLBACK_GREET, greetCallback) npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
local has_iter, iter = pcall(require, "kk.iter") if not has_iter then print "lua/kesav/tabline.lua: install kesav21/lua-stdlib" return end local function choose(first, second, condition) if condition then return first else return second end end local function is_equal(a) return function(b) return a == b end end local function buf_islisted(b) return vim.fn.buflisted(b) == 1 end local function buf_current_position(bufs) return iter.first( iter.filter_keys( is_equal(vim.api.nvim_get_current_buf()), iter.to_table(bufs) ) ) end local function buf_title() local bufs = vim.api.nvim_list_bufs() local listed_bufs = iter.filter(buf_islisted, iter.values(bufs)) return string.format( "[%s/%s]", buf_current_position(listed_bufs) or " ", iter.length(listed_bufs) ) end -- TODO: fix -- when a single regular window and two telescope windows are visible, -- the count shows five windows local function tab_title(current_tabnr, tabnr) local wins = vim.api.nvim_tabpage_list_wins(tabnr) local highlight = choose("%#TabSel#", "%#TabUnsel#", current_tabnr == tabnr) local current_winnr = vim.api.nvim_tabpage_get_win(tabnr) local current_win = iter.first( iter.filter_keys(is_equal(current_winnr), wins) ) return string.format("%s %s: [%s/%s]", highlight, tabnr, current_win, #wins) end local function get_tab_title() local current_tabnr = vim.api.nvim_get_current_tabpage() local tabs = vim.api.nvim_list_tabpages() local t = {} for _, tabnr in ipairs(tabs) do table.insert(t, tab_title(current_tabnr, tabnr)) end return table.concat(t, " ") end function _G.tabline() vim.cmd [[ hi TabSel guifg=#1d2021 guibg=#a89984 ]] vim.cmd [[ hi TabUnsel guifg=#a89984 guibg=#282828 ]] vim.cmd [[ hi TabClear guibg=#282828 ]] return string.format( "%%#TabUnsel# %s %s %%#TabClear#", buf_title(), get_tab_title() ) end vim.o.showtabline = 2 vim.o.tabline = "%!v:lua.tabline()"
local M = {} local hotfix_helper = require("hotfix_helper") local test = require("test") local function sleep(sec) local end_time = os.time() + sec while os.time() < end_time do end end -- sleep() function M.run() hotfix_helper.init() while true do test.func() sleep(2) hotfix_helper.check() end end -- run() return M
function genMiningDrills(inputs) -- Copy electric furnace local item = table.deepcopy(data.raw.item["electric-mining-drill"]) local recipe = table.deepcopy(data.raw.recipe["electric-mining-drill"]) local entity = table.deepcopy(data.raw["mining-drill"]["electric-mining-drill"]) local tech = table.deepcopy(data.raw.technology["advanced-material-processing"]) --Item if inputs.new then item.name = "5d-electric-mining-drill-" .. inputs.number end item.icon = "__5dim_mining__/graphics/icon/electric-mining-drill/electric-mining-drill-icon-" .. inputs.number .. ".png" item.subgroup = inputs.subgroup item.order = inputs.order item.place_result = item.name --Recipe recipe.name = item.name recipe.icon = item.icon recipe.icon_size = 64 if recipe.normal == nil then recipe.result = item.name if inputs.new then recipe.enabled = false end recipe.ingredients = inputs.ingredients else recipe.normal.result = item.name if inputs.new then recipe.normal.enabled = false end recipe.normal.ingredients = inputs.ingredients recipe.expensive.result = item.name if inputs.new then recipe.expensive.enabled = false end recipe.expensive.ingredients = inputs.ingredients end --Entity entity.name = item.name entity.next_upgrade = inputs.nextUpdate or nil entity.icon = item.icon entity.minable.result = item.name entity.mining_speed = inputs.craftingSpeed entity.module_specification.module_slots = inputs.moduleSlots entity.energy_usage = inputs.energyUsage .. "kW" entity.energy_source.emissions_per_minute = inputs.pollution --North entity.graphics_set.animation.north.layers[1].hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-N/electric-mining-drill-N-" .. inputs.number .. ".png" entity.wet_mining_graphics_set.animation.north.layers[1].hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-N/electric-mining-drill-N-wet-" .. inputs.number .. ".png" --East entity.graphics_set.animation.east.layers[1].hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-E/electric-mining-drill-E-" .. inputs.number .. ".png" entity.graphics_set.working_visualisations[7].east_animation.hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-E/electric-mining-drill-E-front-" .. inputs.number .. ".png" entity.wet_mining_graphics_set.animation.east.layers[1].hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-E/electric-mining-drill-E-wet-" .. inputs.number .. ".png" entity.wet_mining_graphics_set.working_visualisations[13].east_animation.layers[1].hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-E/electric-mining-drill-E-wet-front-" .. inputs.number .. ".png" --South entity.graphics_set.working_visualisations[7].south_animation.layers[2].hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-S/electric-mining-drill-S-front-" .. inputs.number .. ".png" entity.wet_mining_graphics_set.working_visualisations[13].south_animation.layers[2].hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-S/electric-mining-drill-S-wet-front-" .. inputs.number .. ".png" --West entity.graphics_set.animation.west.layers[1].hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-W/electric-mining-drill-W-" .. inputs.number .. ".png" entity.graphics_set.working_visualisations[7].west_animation.hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-W/electric-mining-drill-W-front-" .. inputs.number .. ".png" entity.wet_mining_graphics_set.animation.west.layers[1].hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-W/electric-mining-drill-W-wet-" .. inputs.number .. ".png" entity.wet_mining_graphics_set.working_visualisations[13].west_animation.layers[1].hr_version.filename = "__5dim_mining__/graphics/entities/electric-mining-drill/hr-electric-mining-drill-W/electric-mining-drill-W-wet-front-" .. inputs.number .. ".png" data:extend({entity, recipe, item}) -- Technology if inputs.tech then tech.name = "5d-mining-" .. inputs.tech.number tech.icon = item.icon tech.icon_size = 64 tech.unit.count = inputs.tech.count tech.unit.ingredients = inputs.tech.packs tech.prerequisites = inputs.tech.prerequisites tech.effects = { { type = "unlock-recipe", recipe = item.name } } data:extend({tech}) end end
local HighlighterFactory = require("searcho.lib.highlight").HighlighterFactory local bufferlib = require("searcho.lib.buffer") local M = {} local SearchHighlight = {} SearchHighlight.__index = SearchHighlight M.SearchHighlight = SearchHighlight function SearchHighlight.new(window_id) local bufnr = vim.api.nvim_win_get_buf(window_id) local tbl = {_hl_factory = HighlighterFactory.new("searcho", bufnr), _bufnr = bufnr} return setmetatable(tbl, SearchHighlight) end function SearchHighlight.reset(self) vim.cmd("nohlsearch") self:reset_current_match() end function SearchHighlight.reset_current_match(self) return self._hl_factory:reset() end function SearchHighlight.enable(self, input, start_row, start_col, end_row, end_col) self:_enable_match(input) self:_enable_current_match(start_row, start_col, end_row, end_col) end function SearchHighlight._enable_match(_, input) -- HACK if input == "\\v" then return end vim.cmd("let &hlsearch = &hlsearch") end function SearchHighlight._enable_current_match(self, start_row, start_col, end_row, end_col) local highlighter = self:reset_current_match() local text = bufferlib.get_text(self._bufnr, start_row - 1, start_col, end_row - 1, end_col) local strs = vim.split(text, "\n", true) highlighter:add_ranged_virtual(strs, "IncSearch", start_row - 1, start_col - 1, { virt_text_pos = "overlay", }) end return M
GUI = {} Menu = {} Menus = {} --==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==-- --==============================================================================================-- -- Settings -- --==============================================================================================-- --==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==-- GUI.maxVisOptions = 8 ------------------------ Max options to show on the menu -- GUI.titleText = {255, 255, 255, 255, 1} ------- Color of title text -- GUI.titleRect = {52, 73, 94, 255} ------------- Color of rectangle [title] -- GUI.optionText = {255, 255, 255, 255, 6} ------ Color of option text -- GUI.optionRect = {40, 40, 40, 190} ------------ Color of option rectangles -- GUI.scroller = {127, 140, 140, 240} ----------- Color of active option -- titleTextSize = {0.85, 0.65} ------------ {p1, Size} -- titleRectSize = {0.16, 0.085} ----------- {Width, Height} -- optionTextSize = {0.5, 0.5} ------------- {p1, Size} -- optionRectSize = {0.16, 0.035} ---------- {Width, Height} -- menuX = 0.9 ----------------------------- X position of the menu -- menuXOption = 0.075 --------------------- X postiion of Menu.Option text -- menuXOtherOption = 0.055 ---------------- X position of Bools, Arrays etc text -- menuYModify = 0.6500 -------------------- Default: 0.1174 ------ Top bar -- menuYOptionDiv = 18.56 ------------------ Default: 3.56 ------ Distance between buttons -- menuYOptionAdd = 0.675 ------------------ Default: 0.142 ------ Move buttons up and down -- --==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==-- --==============================================================================================-- -- Settings -- --==============================================================================================-- --==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==-- local menuOpen = false prevMenu = nil curMenu = nil local selectPressed = false local leftPressed = false local rightPressed = false currentOption = 1 local optionCount = 0 function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end function Menu.IsOpen() return menuOpen == true end function Menu.SetupMenu(menu, title) Menus[menu] = {} Menus[menu].title = title Menus[menu].optionCount = 0 Menus[menu].options = {} Menus[menu].previous = nil --currentOption = 1 end function Menu.addOption(menu, option) if not (Menus[menu].title == nil) then Menus[menu].optionCount = Menus[menu].optionCount + 1 Menus[menu].options[Menus[menu].optionCount] = option end end function Menu.Switch(prevmenu, menu) curMenu = menu prevMenu = prevmenu if prevmenu ~= nil and menu ~= "" then Menus[menu].previous = prevmenu end end function Menu.DisplayCurMenu() if not (curMenu == "") then menuOpen = true Menu.Title(Menus[curMenu].title) for k,v in pairs(Menus[curMenu].options) do v() end Menu.updateSelection() end end function GUI.Text(text, color, position, size, center) SetTextCentre(center) SetTextColour(color[1], color[2], color[3], color[4]) SetTextFont(color[5]) SetTextScale(size[1], size[2]) SetTextEntry("STRING") AddTextComponentString(text) DrawText(position[1], position[2]) end function GUI.Rect(color, position, size) DrawRect(position[1], position[2], size[1], size[2], color[1], color[2], color[3], color[4]) end function Menu.Title(title) GUI.Text(title, GUI.titleText, {menuX, menuYModify - 0.02241}, titleTextSize, true) GUI.Rect(GUI.titleRect, {menuX, menuYModify}, titleRectSize) Menu.PageCounter() end function Menu.PageCounter() GUI.Text(currentOption.."/"..Menus[curMenu].optionCount, GUI.optionText, {menuX + menuXOption - 0.02, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, false) GUI.Rect(GUI.optionRect, { menuX, (menuYOptionAdd + (optionCount / menuYOptionDiv) * menuYModify) }, optionRectSize) RequestStreamedTextureDict("commonmenu", true) DrawSprite("commonmenu", "shop_arrows_upanddown", menuX, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify + 0.015), 0.03, 0.03, 0.0, 255, 255, 255, 255) GUI.Rect(GUI.titleRect, { menuX, (menuYOptionAdd + (optionCount / menuYOptionDiv) * menuYModify + 0.015) }, {optionRectSize[1], optionRectSize[2] - 0.03}) end function Menu.Option(option) optionCount = optionCount + 1 local thisOption = nil if(currentOption == optionCount) then thisOption = true else thisOption = false end if(currentOption <= GUI.maxVisOptions and optionCount <= GUI.maxVisOptions) then GUI.Text(option, GUI.optionText, {menuX - menuXOption, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, false) GUI.Rect(GUI.optionRect, { menuX, (menuYOptionAdd + (optionCount / menuYOptionDiv) * menuYModify) }, optionRectSize) if(thisOption) then GUI.Rect(GUI.scroller, { menuX, (menuYOptionAdd + (optionCount / menuYOptionDiv) * menuYModify) }, optionRectSize) end elseif (optionCount > currentOption - GUI.maxVisOptions and optionCount <= currentOption) then GUI.Text(option, GUI.optionText, {menuX - menuXOption, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, false) GUI.Rect(GUI.optionRect, { menuX, (menuYOptionAdd + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify) }, optionRectSize) if(thisOption) then GUI.Rect(GUI.scroller, { menuX, (menuYOptionAdd + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify) }, optionRectSize) end end if (optionCount == currentOption and selectPressed) then return true end return false end function Menu.changeMenu(option, menu) if (Menu.Option(option)) then Menu.Switch(curMenu, menu) end if(currentOption <= GUI.maxVisOptions and optionCount <= GUI.maxVisOptions) then GUI.Text(">>", GUI.optionText, { menuX + menuXOtherOption, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, true) elseif(optionCount > currentOption - GUI.maxVisOptions and optionCount <= currentOption) then GUI.Text(">>", GUI.optionText, { menuX + 0.068, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, true) end if (optionCount == currentOption and selectPressed) then return true end return false end function Menu.Bool(option, bool, option2, option3, cb) Menu.Option(option) if(currentOption <= GUI.maxVisOptions and optionCount <= GUI.maxVisOptions) then if(bool) then GUI.Text(option2, GUI.optionText, { menuX + menuXOtherOption, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, true) else GUI.Text(option3, GUI.optionText, { menuX + menuXOtherOption, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, true) end elseif(optionCount > currentOption - GUI.maxVisOptions and optionCount <= currentOption) then if(bool) then GUI.Text(option2, GUI.optionText, { menuX + menuXOtherOption, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, true) else GUI.Text(option3, GUI.optionText, { menuX + menuXOtherOption, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, true) end end if (optionCount == currentOption and selectPressed) then cb(not bool) return true end return false end function Menu.CarBool(option, bool, option2, option3, cb) Menu.Option(option) local amount = 0 if string.len(option2) == 8 and option2 ~= "~g~OWNED" and option3 ~= "~g~OWNED" then -- 1 amount = 0.035 elseif string.len(option2) == 8 and option2 == "~g~OWNED" and option3 == "~g~OWNED" then -- 1 amount = 0.0175 elseif string.len(option2) == 9 then -- 10 amount = 0.032 elseif string.len(option2) == 10 and option2 ~= "~g~Insured" and option3 ~= "~g~Insured" then -- 100 amount = 0.0265 elseif string.len(option2) == 10 and option2 == "~g~Insured" and option3 == "~g~Insured" then -- 100 amount = 0.0165 elseif string.len(option2) == 11 then -- 1000 amount = 0.0215 elseif string.len(option2) == 12 then -- 10000 amount = 0.0165 elseif string.len(option2) == 13 then -- 100000 amount = 0.0115 elseif string.len(option2) == 14 then -- 1000000 amount = 0.0065 elseif string.len(option2) == 15 then -- 10000000 amount = 0.0015 elseif string.len(option2) == 4 then amount = 0.0265 end if(currentOption <= GUI.maxVisOptions and optionCount <= GUI.maxVisOptions) then if(bool) then GUI.Text(option2, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, false) else GUI.Text(option3, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, false) end elseif(optionCount > currentOption - GUI.maxVisOptions and optionCount <= currentOption) then if(bool) then GUI.Text(option2, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, false) else GUI.Text(option3, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, false) end end if (optionCount == currentOption and selectPressed) then cb(not bool) return true end return false end function Menu.GunBool(option, bool, option2, option3, cb) Menu.Option(option) local amount = 0 if string.len(option2) == 8 then -- 1 amount = 0.035 elseif string.len(option2) == 9 then -- 10 amount = 0.032 elseif string.len(option2) == 10 then -- 100 amount = 0.0265 elseif string.len(option2) == 11 then -- 1000 amount = 0.0215 elseif string.len(option2) == 12 then -- 10000 amount = 0.0165 elseif string.len(option2) == 13 then -- 100000 amount = 0.0115 elseif string.len(option2) == 14 then -- 1000000 amount = 0.0065 elseif string.len(option2) == 15 then -- 10000000 amount = 0.0015 end if(currentOption <= GUI.maxVisOptions and optionCount <= GUI.maxVisOptions) then if(bool) then GUI.Text(option2, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, false) else GUI.Text(option3, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, false) end elseif(optionCount > currentOption - GUI.maxVisOptions and optionCount <= currentOption) then if(bool) then GUI.Text(option2, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, false) else GUI.Text(option3, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, false) end end if (optionCount == currentOption and selectPressed) then cb(not bool) return true end return false end function Menu.GarageBool(option, bool, option2, option3, cb) Menu.Option(option) local amount = 0 if string.len(option2) == 8 then -- 1 amount = 0.035 elseif string.len(option2) == 9 then -- 10 amount = 0.032 elseif string.len(option2) == 10 then -- 100 amount = 0.0265 elseif string.len(option2) == 11 then -- 1000 amount = 0.0215 elseif string.len(option2) == 12 then -- 10000 amount = 0.0165 elseif string.len(option2) == 13 then -- 100000 amount = 0.0115 elseif string.len(option2) == 14 then -- 1000000 amount = 0.0065 elseif string.len(option2) == 15 then -- 10000000 amount = 0.0015 end if(currentOption <= GUI.maxVisOptions and optionCount <= GUI.maxVisOptions) then if(bool) then GUI.Text(option2, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, false) else GUI.Text(option3, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, false) end elseif(optionCount > currentOption - GUI.maxVisOptions and optionCount <= currentOption) then if(bool) then GUI.Text(option2, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, false) else GUI.Text(option3, GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, false) end end if (optionCount == currentOption and selectPressed) then cb(not bool) return true end return false end function Menu.TransferBool(option, bool, option2, option3, cb) Menu.Option(option) if(currentOption <= GUI.maxVisOptions and optionCount <= GUI.maxVisOptions) then if(bool) then GUI.Text(option2, GUI.optionText, { menuX + menuXOtherOption + 0.01, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, true) else GUI.Text(option3, GUI.optionText, { menuX + menuXOtherOption + 0.01, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, true) end elseif(optionCount > currentOption - GUI.maxVisOptions and optionCount <= currentOption) then if(bool) then GUI.Text(option2, GUI.optionText, { menuX + menuXOtherOption + 0.01, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, true) else GUI.Text(option3, GUI.optionText, { menuX + menuXOtherOption + 0.01, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, true) end end if (optionCount == currentOption and selectPressed) then cb(not bool) return true end return false end function Menu.Int(option, int, min, max, cb) Menu.Option(option); if (optionCount == currentOption) then if (leftPressed) then if(int > min) then int = int - 1 else int = max end-- : _int = max; end if (rightPressed) then if(int < max) then int = int + 1 else int = min end end end if (currentOption <= GUI.maxVisOptions and optionCount <= GUI.maxVisOptions) then GUI.Text(tostring(int), GUI.optionText, { menuX + menuXOtherOption, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, true) elseif (optionCount > currentOption - GUI.maxVisOptions and optionCount <= currentOption) then GUI.Text(tostring(int), GUI.optionText, { menuX + menuXOtherOption, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, true) end if (optionCount == currentOption and selectPressed) then cb(position) return true elseif (optionCount == currentOption and leftPressed) then cb(position) elseif (optionCount == currentOption and rightPressed) then cb(position) end return false end function Menu.StringArray(option, array, position, cb) Menu.Option(option); if (optionCount == currentOption) then local max = tablelength(array) local min = 1 if (leftPressed) then if(position > min) then position = position - 1 else position = max end end if (rightPressed) then if(position < max) then position = position + 1 else position = min end end end if (currentOption <= GUI.maxVisOptions and optionCount <= GUI.maxVisOptions) then GUI.Text(array[position], GUI.optionText, { menuX + menuXOtherOption, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, true) elseif (optionCount > currentOption - GUI.maxVisOptions and optionCount <= currentOption) then GUI.Text(array[position], GUI.optionText, { menuX + menuXOtherOption, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, true) end if (optionCount == currentOption and selectPressed) then cb(position) return true elseif (optionCount == currentOption and leftPressed) then cb(position) elseif (optionCount == currentOption and rightPressed) then cb(position) end return false end function Menu.GarageArray(option, array, position, cb) Menu.Option(option); local amount = 0 if position <= 9 then -- 1 amount = 0.043 elseif position >= 10 then amount = 0.0425 end if (optionCount == currentOption) then local max = tablelength(array) local min = 1 if (leftPressed) then if(position > min) then position = position - 1 else position = max end end if (rightPressed) then if(position < max) then position = position + 1 else position = min end end end if (currentOption <= GUI.maxVisOptions and optionCount <= GUI.maxVisOptions) then GUI.Text(array[position], GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + (optionCount / menuYOptionDiv) * menuYModify)}, optionTextSize, true) elseif (optionCount > currentOption - GUI.maxVisOptions and optionCount <= currentOption) then GUI.Text(array[position], GUI.optionText, { menuX + menuXOtherOption + amount, ((menuYOptionAdd - 0.018) + ((optionCount - (currentOption - GUI.maxVisOptions)) / menuYOptionDiv) * menuYModify)}, optionTextSize, true) end if (optionCount == currentOption and selectPressed) then cb(position) return true elseif (optionCount == currentOption and leftPressed) then cb(position) return true elseif (optionCount == currentOption and rightPressed) then cb(position) return true end return false end function Menu.updateSelection() selectPressed = false; leftPressed = false; rightPressed = false; if IsControlJustPressed(1, 173) then if(currentOption < optionCount) then currentOption = currentOption + 1 else currentOption = 1 end elseif IsControlJustPressed(1, 172) then if(currentOption > 1) then currentOption = currentOption - 1 else currentOption = optionCount end elseif IsControlJustPressed(1, 174) then leftPressed = true elseif IsControlJustPressed(1, 175) then rightPressed = true elseif IsControlJustPressed(1, 176) then selectPressed = true if isCustomsOpen then UpdateCar() end elseif IsControlJustPressed(1, 177) then if (prevMenu == nil) then Menu.Switch(nil, "") menuOpen = false if isCustomsOpen then isCustomsOpen = false closeCustoms() end currentOption = 1 end if not (prevMenu == nil) then if not Menus[prevMenu].previous == nil then currentOption = 1 Menu.Switch(nil, prevMenu) Citizen.Trace("IS NOT NIL BUT NIL? "..prevMenu) else --print(Menus[curMenu].optionCount) if Menus[prevMenu].optionCount < currentOption then currentOption = 1 end --print(Menus[prevMenu].optionCount) Menu.Switch(Menus[prevMenu].previous, prevMenu) end if isCustomsOpen then UpdateCar() end end end optionCount = 0 end
resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5' client_script 'carhud.lua'
local etcd = require "resty.etcd" local _M = {} local mt = {__index = _M} function _M.new(conf) conf = conf or {} local self = setmetatable({}, mt) local options = { http_host = conf.http_host or "http://127.0.0.1:4001", protocol = conf.protocol or "v2", key_prefix = conf.key_prefix or "", timeout = conf.timeout or 60, ssl_verify = conf.ssl_verify, } local client, err = etcd.new(options) if err then return nil, err end self.client = client self.protocol_is_v2 = options.protocol == "v2" return self, nil end -- set the key regardless of it's existence function _M:set(k, v, ttl) local res, err = self.client:set(k, v, ttl) if err then return err end end -- set the key only if the key doesn't exist function _M:add(k, v, ttl) local res, err = self.client:setnx(k, v, ttl) if err then return err end if res and res.body and res.body.errorCode == 105 then return "exists" end end function _M:delete(k) local res, err = self.client:delete(k) if err then return err end end function _M:get(k) local res, err = self.client:get(k) if err then return nil, err elseif res.status == 404 and res.body and res.body.errorCode == 100 then return nil, nil elseif res.status ~= 200 then return nil, "etcd returned status " .. res.status end local node = res.body.node -- is it already expired but not evited ? if node.expiration and not node.ttl and self.protocol_is_v2 then return nil, nil end return node.value end local empty_table = {} function _M:list(prefix) local res, err = self.client:get("/") if err then return nil, err elseif not res or not res.body or not res.body.node or not res.body.node.nodes then return empty_table, nil end local ret = {} -- offset 1 to strip leading "/" in original key local prefix_length = #prefix + 1 for _, node in ipairs(res.body.node.nodes) do local key = node.key if key then -- start from 2 to strip leading "/" if key:sub(2, prefix_length) == prefix then table.insert(ret, key:sub(2)) end end end return ret end return _M
--- Administration functions (topology related). -- -- @module cartridge.lua-api.topology local checks = require('checks') local errors = require('errors') local membership = require('membership') local pool = require('cartridge.pool') local topology = require('cartridge.topology') local confapplier = require('cartridge.confapplier') local lua_api_get_topology = require('cartridge.lua-api.get-topology') local lua_api_edit_topology = require('cartridge.lua-api.edit-topology') local ProbeServerError = errors.new_class('ProbeServerError') local RestartReplicationError = errors.new_class('RestartReplicationError') --- Get alias, uri and uuid of current instance. -- @function get_self -- @local -- @treturn table local function get_self() local myself = membership.myself() local state, err = confapplier.get_state() local app_info = require('cartridge.argparse').get_opts({ app_name = 'string', instance_name = 'string' }) local result = { uri = myself.uri, uuid = confapplier.get_instance_uuid(), demo_uri = os.getenv('TARANTOOL_DEMO_URI'), alias = myself.payload.alias, state = state, error = err and err.err or nil, app_name = app_info.app_name, instance_name = app_info.instance_name, } return result end --- Get servers list. -- Optionally filter out the server with the given uuid. -- @function get_servers -- @tparam[opt] string uuid -- @treturn[1] {ServerInfo,...} -- @treturn[2] nil -- @treturn[2] table Error description local function get_servers(uuid) checks('?string') local ret = {} local topology, err = lua_api_get_topology.get_topology() if topology == nil then return nil, err end if uuid then table.insert(ret, topology.servers[uuid]) else for _, v in pairs(topology.servers) do table.insert(ret, v) end end return ret end --- Get replicasets list. -- Optionally filter out the replicaset with given uuid. -- @function get_replicasets -- @tparam[opt] string uuid -- @treturn[1] {ReplicasetInfo,...} -- @treturn[2] nil -- @treturn[2] table Error description local function get_replicasets(uuid) checks('?string') local ret = {} local topology, err = lua_api_get_topology.get_topology() if topology == nil then return nil, err end if uuid then table.insert(ret, topology.replicasets[uuid]) else for _, v in pairs(topology.replicasets) do table.insert(ret, v) end end return ret end --- Discover an instance. -- @function probe_server -- @tparam string uri local function probe_server(uri) checks('string') local ok, err = membership.probe_uri(uri) if not ok then return nil, ProbeServerError:new('Probe %q failed: %s', uri, err) end return true end local function __set_servers_disabled_state(uuids, state) checks('table', 'boolean') local patch = {servers = {}} for _, uuid in pairs(uuids) do table.insert(patch.servers, { uuid = uuid, disabled = state, }) end local topology, err = lua_api_edit_topology.edit_topology(patch) if topology == nil then return nil, err end return topology.servers end --- Enable nodes after they were disabled. -- @function enable_servers -- @tparam {string,...} uuids -- @treturn[1] {ServerInfo,...} -- @treturn[2] nil -- @treturn[2] table Error description local function enable_servers(uuids) checks('table') return __set_servers_disabled_state(uuids, false) end --- Temporarily disable nodes. -- -- @function disable_servers -- @tparam {string,...} uuids -- @treturn[1] {ServerInfo,...} -- @treturn[2] nil -- @treturn[2] table Error description local function disable_servers(uuids) checks('table') return __set_servers_disabled_state(uuids, true) end --- Restart replication on specified instances. -- -- (added in v2.6.0-43) -- -- @function restart_replication -- @tparam {string, ...} uuids -- @treturn[1] boolean true -- @treturn[2] nil -- @treturn[2] table Error description local function restart_replication(uuids) checks('table') local topology_cfg = confapplier.get_readonly('topology') if topology_cfg == nil then return nil, RestartReplicationError:new( "Current instance isn't bootstrapped yet" ) end -- Prepare a server group to be operated local uri_list = {} local refined_uri_list = topology.refine_servers_uri(topology_cfg) for _, uuid in ipairs(uuids) do local srv = topology_cfg.servers[uuid] if not srv then return nil, RestartReplicationError:new( 'Server %s not in clusterwide config', uuid ) elseif topology.disabled(uuid, srv) then return nil, RestartReplicationError:new( 'Server %s is disabled, not suitable' .. ' for restarting replication', uuid ) end table.insert(uri_list, refined_uri_list[uuid]) end local retmap, errmap = pool.map_call( '_G.__cartridge_confapplier_restart_replication', {}, { uri_list = uri_list } ) for _, uri in ipairs(uri_list) do if retmap[uri] == nil then local err = errmap and errmap[uri] if err == nil then err = RestartReplicationError:new('Unknown error at %s', uri) end return nil, err end end return true end return { get_self = get_self, get_servers = get_servers, get_replicasets = get_replicasets, get_topology = lua_api_get_topology.get_topology, edit_topology = lua_api_edit_topology.edit_topology, probe_server = probe_server, enable_servers = enable_servers, disable_servers = disable_servers, restart_replication = restart_replication, }
local localizer = require("localization/localizer") local gameplay_data = require("resources/gameplay_data") -- class holding persistent information on the fighter, pc or npc local fighter_progression = new_class() --[[ Parameters character_type: character_types is the fighter representing a player or an npc? control_type: control_types is the fighter controlled by the player or some ai? fighter_info: fighter_info fighter info this was created with character_info: character_info cached reference to character info (derived from fighter_info) State level: int current level (only useful for npc) known_attack_ids: {int} known attack ids known_reply_ids: {int} known reply ids known_quote_match_ids: {int} known quote matches (only filled and used for pc for assist) received_attack_id_count_persistent_map: {int: int} count of new attacks received over past fights, indexed by attack id (as in fighter, but persistent) received_reply_id_count_persistent_map: {int: int} count of new replies received over past fights, indexed by reply id (as in fighter, but persistent) --]] function fighter_progression:init(character_type, some_fighter_info) -- Parameters self.character_type = character_type self.control_type = character_type == character_types.pc and control_types.human or control_types.ai self.fighter_info = some_fighter_info -- State self.level = some_fighter_info.initial_level self.max_hp = some_fighter_info.initial_max_hp self.known_attack_ids = copy_seq(some_fighter_info.initial_attack_ids) self.known_reply_ids = copy_seq(some_fighter_info.initial_reply_ids) self.known_quote_match_ids = {} self.received_attack_id_count_persistent_map = {} self.received_reply_id_count_persistent_map = {} end --#if log function fighter_progression:get_name() local character_info if self.character_type == character_types.pc then character_info = gameplay_data.pc_info else character_info = gameplay_data.npc_info_s[self.fighter_info.character_info_id] assert(character_info, "no character_info found for id: "..self.fighter_info.character_info_id) end return character_info.name end --#endif function fighter_progression:transfer_received_attack_id_count_map(added_count_map) fighter_progression.add_received_quote_id_count_map(self.received_attack_id_count_persistent_map, added_count_map) self:check_learn_quote(added_count_map, quote_types.attack) clear_table(added_count_map) end function fighter_progression:transfer_received_reply_id_count_map(added_count_map) fighter_progression.add_received_quote_id_count_map(self.received_reply_id_count_persistent_map, added_count_map) self:check_learn_quote(added_count_map, quote_types.reply) clear_table(added_count_map) end -- static (generic enough to be a table helper) function fighter_progression.add_received_quote_id_count_map(modified_count_map, added_count_map) for quote_id, counter in pairs(added_count_map) do -- sum counts (uninitialised count defaults to 0) local reception_count = modified_count_map[quote_id] or 0 reception_count = reception_count + counter modified_count_map[quote_id] = reception_count end end function fighter_progression:check_learn_quote(added_count_map, quote_type) local known_quote_ids local received_quote_id_count_map if quote_type == quote_types.attack then known_quote_ids = self.known_attack_ids received_quote_id_count_map = self.received_attack_id_count_persistent_map else -- quote_type == quote_types.reply known_quote_ids = self.known_reply_ids received_quote_id_count_map = self.received_reply_id_count_persistent_map end for quote_id, _ in pairs(added_count_map) do local received_quote = gameplay_data:get_quote(quote_type, quote_id) local learning_difficulty = received_quote.level - self.level local learning_repetition_threshold = gameplay_data.base_learning_repetition_threshold + learning_difficulty -- Check if we've received the quote enough times to learn it. -- Note that for quotes at very low level compared to the fighter, the threshold is negative, -- but we don't need to check if reception_count >= 1 since the added_count_map only -- contains counts of at least 1. -- The first members should not be nil as long as add_received_quote_id_count_map -- added the counters properly. if received_quote_id_count_map[quote_id] >= learning_repetition_threshold then add(known_quote_ids, quote_id) --#if log local quote_type_name = quote_type == quote_types.attack and "attack" or "reply" local quote_string = localizer:get_string(gameplay_data:get_quote(quote_type, quote_id).localized_string_id) log("fighter '"..self:get_name().."' learns "..quote_type_name.." quote "..quote_id..": \"".. quote_string.."\"", 'progression') --#endif end end end function fighter_progression:try_learn_quote_match(id) -- With fighter:auto_pick_reply v2, AI don't use known_quote_match_ids anyymore, -- and instead check for any matching reply directly from the DB. -- So learning quote matches is only used by PC so we can assist player in reply -- selection with UI hints. if self.character_type == character_types.pc then assert(id > 0, "cannot learn cancel quote match") if not contains(self.known_quote_match_ids, id) then add(self.known_quote_match_ids, id) log("pc fighter learns "..gameplay_data.quote_matches[id], 'progression') end end end return fighter_progression
--[[ MIT License Copyright (c) 2019 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. ]]-- lp = lp or {} local me = lp me.tag = "Core" -- global local _G = getfenv(0) --[[ Testing Hook GetLocale to return a fixed value. Deactivate in production! Note: This is used for testing only. If the locale doesn't match with the actual locale of the combatlog the Addon is unable to parse the log. ]]-- --[[ function _G.GetLocale() return "deDE" end ]]-- --[[Addon load]]-- function me.OnLoad() me.RegisterEvents() me.SetupSlashCmdList() end --[[ MainFrame OnEvent handler ]]-- function me.OnEvent() local messageType if event == "PLAYER_LOGIN" then me.logger.LogEvent(me.tag, "PLAYER_LOGIN") me.Initialize() elseif event == "CHAT_MSG_SPELL_FAILED_LOCALPLAYER" then me.logger.LogEvent(me.tag, "CHAT_MSG_SPELL_FAILED_LOCALPLAYER") me.eventManager.HandleEvent(arg1, event) elseif event == "CHAT_MSG_SPELL_SELF_DAMAGE" then me.logger.LogEvent(me.tag, "CHAT_MSG_SPELL_SELF_DAMAGE") me.eventManager.HandleEvent(arg1, event) elseif event == "CHAT_MSG_SPELL_HOSTILEPLAYER_DAMAGE" then me.logger.LogEvent(me.tag, "CHAT_MSG_SPELL_HOSTILEPLAYER_DAMAGE") me.eventManager.HandleEvent(arg1, event) elseif event == "CHAT_MSG_SPELL_HOSTILEPLAYER_BUFF" then me.logger.LogEvent(me.tag, "CHAT_MSG_SPELL_HOSTILEPLAYER_BUFF") me.eventManager.HandleEvent(arg1, event) elseif event == "CHAT_MSG_SPELL_PERIODIC_HOSTILEPLAYER_BUFFS" then me.logger.LogEvent(me.tag, "CHAT_MSG_SPELL_PERIODIC_HOSTILEPLAYER_BUFFS") me.eventManager.HandleEvent(arg1, event) elseif event == "CHAT_MSG_SPELL_AURA_GONE_OTHER" then me.logger.LogEvent(me.tag, "CHAT_MSG_SPELL_AURA_GONE_OTHER") me.eventManager.HandleEvent(arg1, event) elseif event == "CHAT_MSG_SPELL_PERIODIC_SELF_DAMAGE" then me.logger.LogEvent(me.tag, "CHAT_MSG_SPELL_PERIODIC_SELF_DAMAGE") me.eventManager.HandleEvent(arg1, event) elseif event == "CHAT_MSG_SPELL_PERIODIC_HOSTILEPLAYER_DAMAGE" then me.logger.LogEvent(me.tag, "CHAT_MSG_SPELL_PERIODIC_HOSTILEPLAYER_DAMAGE") me.eventManager.HandleEvent(arg1, event) elseif event == "CHAT_MSG_COMBAT_HOSTILE_DEATH" then me.logger.LogEvent(me.tag, "CHAT_MSG_COMBAT_HOSTILE_DEATH") me.eventManager.HandleEvent(arg1, event) end end --[[ register addon events ]]-- function me.RegisterEvents() -- register to player login event also fires on /reload this:RegisterEvent("PLAYER_LOGIN") end --[[ init function ]]-- function me.Initialize() --setup random seed math.randomseed(GetTime()) me.logger.LogDebug(me.tag, "Initialize addon") end --[[ Print cmd options for addon ]]-- local function ShowInfoMessage() local reload = "|cFFFFFF00reload|r - reload UI" local info = "|cFFFFFF00info|r - show this message" DEFAULT_CHAT_FRAME:AddMessage(string.format(LP_ENVIRONMENT.ADDON_NAME .. "|cFFFFFF00(%s)|r:", LP_ENVIRONMENT.ADDON_VERSION)) DEFAULT_CHAT_FRAME:AddMessage(reload) DEFAULT_CHAT_FRAME:AddMessage(info) end --[[ Setup slash command handler ]]-- function me.SetupSlashCmdList() SLASH_LOGPARSER1 = "/lp" SLASH_LOGPARSER2 = "/logparser" SlashCmdList["LOGPARSER"] = function(msg) me.logger.LogDebug(me.tag, "/lp passed argument: " .. msg) if msg == "" or msg == "info" then ShowInfoMessage() elseif msg == "rl" or msg == "reload" then ReloadUI() else me.logger.PrintUserError("Invalid argument passed") end end end
-- luacheck: std lua53 if _VERSION < 'Lua 5.3' then require ('compat53') end local Bits = require ('map.file.bits') local Flags = require ('map.file.flags') local W3I = {} local map_flags = { [0x00001] = 'hide_minimap_in_preview_screens', [0x00002] = 'modify_ally_priorities', [0x00004] = 'melee_map', [0x00008] = 'playable_map_size_was_large', [0x00010] = 'masked_areas_are_partially_visible', [0x00020] = 'fixed_player_settings_for_custom_forces', [0x00040] = 'use_custom_forces', [0x00080] = 'use_custom_techtree', [0x00100] = 'use_custom_abilities', [0x00200] = 'use_custom_upgrades', [0x00400] = 'has_opened_map_properties', [0x00800] = 'show_waves_on_cliff_shores', [0x01000] = 'show_waves_on_rolling_shores', [0x02000] = 'use_terrain_fog', [0x04000] = 'requires_expansion', [0x08000] = 'use_item_classification_system', [0x10000] = 'use_water_tinting_color', [0x20000] = 'use_accurate_probability', [0x40000] = 'use_custom_ability_skin' } local force_flags = { [0x01] = 'allied', [0x02] = 'allied_victory', [0x08] = 'share_vision', [0x10] = 'share_control', [0x20] = 'share_advanced_control' } local formats = { [18] = 'RoC', [25] = 'TFT', [28] = 'Lua', [31] = 'Reforged' } function W3I.unpack (input) assert (type (input) == 'string') local unpack = string.unpack local count local format, position = unpack ('< i4', input) assert (formats [format]) local output = { format = format, map = {}, camera = { {}, {}, {}, {} }, margins = {}, dimensions = {}, loading = {}, prologue = {} } output.saves, output.editor, position = unpack ('< i4 i4', input, position) if format >= 28 then output.version = {} output.version.major, output.version.minor, output.version.patch, output.version.build, position = unpack ('< i4 i4 i4 i4', input, position) end output.map.name, output.map.author, output.map.description, output.map.recommended, output.camera [1].x, output.camera [1].y, output.camera [2].x, output.camera [2].y, output.camera [3].x, output.camera [3].y, output.camera [4].x, output.camera [4].y, output.margins.left, output.margins.right, output.margins.top, output.margins.bottom, output.dimensions.width, output.dimensions.height, output.map.flags, output.tileset, position = unpack ( '< z z z z f f f f f f f f i4 i4 i4 i4 i4 i4 I4 c1', input, position) output.map.flags = Flags.unpack (map_flags, output.map.flags) if format == 18 then output.campaign = {} output.campaign.background, output.loading.text, output.loading.title, output.loading.subtitle, output.loading.background, output.prologue.text, output.prologue.title, output.prologue.subtitle, position = unpack ('< i4 z z z i4 z z z', input, position) else output.fog = { z = {}, color = {} } output.environment = { water = {} } output.loading.background, output.loading.model, output.loading.text, output.loading.title, output.loading.subtitle, output.game_data, output.prologue.model, output.prologue.text, output.prologue.title, output.prologue.subtitle, output.fog.index, output.fog.z.start, output.fog.z.finish, output.fog.density, output.fog.color.red, output.fog.color.green, output.fog.color.blue, output.fog.color.alpha, output.environment.weather, output.environment.sound, output.environment.light, output.environment.water.red, output.environment.water.green, output.environment.water.blue, output.environment.water.alpha, position = unpack ( '< i4 z z z z i4 z z z z i4 f f f B B B B c4 z c1 B B B B', input, position) end if format >= 28 then output.script, position = unpack ('< i4', input, position) end if format >= 31 then output.graphics, output.game_data_version, position = unpack ('< i4 i4', input, position) end output.players = {} count, position = unpack ('< i4', input, position) for index = 1, count do local player = { start = {}, ally = {} } output.players [index] = player player.index, player.type, player.race, player.start.fixed, player.name, player.start.x, player.start.y, player.ally.low, player.ally.high, position = unpack ('< i4 i4 i4 i4 z f f I4 I4', input, position) player.ally.low = Bits.unpack ('I4', player.ally.low) player.ally.high = Bits.unpack ('I4', player.ally.high) if format >= 31 then player.enemy = {} player.enemy.low, player.enemy.high, position = unpack ('< I4 I4', input, position) player.enemy.low = Bits.unpack ('I4', player.enemy.low) player.enemy.high = Bits.unpack ('I4', player.enemy.high) end end output.forces = {} count, position = unpack ('< i4', input, position) for index = 1, count do local force = {} output.forces [index] = force force.flags, force.players, force.name, position = unpack ('< I4 I4 z', input, position) force.flags = Flags.unpack (force_flags, force.flags) force.players = Bits.unpack ('I4', force.players) end output.upgrades = {} count, position = unpack ('< i4', input, position) for index = 1, count do local upgrade = {} output.upgrades [index] = upgrade upgrade.players, upgrade.id, upgrade.level, upgrade.availability, position = unpack ('< I4 c4 i4 i4', input, position) upgrade.players = Bits.unpack ('I4', upgrade.players) end output.tech = {} count, position = unpack ('< i4', input, position) for index = 1, count do local tech = {} output.tech [index] = tech tech.players, tech.id, position = unpack ('< I4 c4', input, position) tech.players = Bits.unpack ('I4', tech.players) end output.units = {} count, position = unpack ('< i4', input, position) for index = 1, count do local units = { rows = {} } output.units [index] = units units.index, units.name, units.columns, position = unpack ('< i4 z i4', input, position) local columns = units.columns units.type = { unpack (('i4'):rep (columns), input, position) } position = table.remove (units.type) count, position = unpack ('< i4', input, position) for row = 1, count do units.rows [row] = {} row = units.rows [row] row.chance, position = unpack ('< i4', input, position) row.id = { unpack (('c4'):rep (columns), input, position) } position = table.remove (row.id) end end if format >= 25 then output.item_tables = {} count, position = unpack ('< i4', input, position) for table = 1, count do local item_table = {} output.item_tables [table] = item_table item_table.index, item_table.name, count, position = unpack ('< i4 z i4', input, position) for set = 1, count do local items = {} item_table [set] = items count, position = unpack ('< i4', input, position) for index = 1, count do local item = {} items [index] = item item.chance, item.id, position = unpack ('< i4 c4', input, position) end end end end assert (#input == position - 1) return output end function W3I.pack (input) assert (type (input) == 'table') local pack = string.pack local output = {} local format = input.format or 31 assert (formats [format]) output [#output + 1] = pack ( '< i4 i4 i4', format, input.saves, input.editor) if format >= 28 then output [#output + 1] = pack ( '< i4 i4 i4 i4', input.version.major, input.version.minor, input.version.patch, input.version.build) end output [#output + 1] = pack ( '< z z z z f f f f f f f f i4 i4 i4 i4 i4 i4 I4 c1', input.map.name, input.map.author, input.map.description, input.map.recommended, input.camera [1].x, input.camera [1].y, input.camera [2].x, input.camera [2].y, input.camera [3].x, input.camera [3].y, input.camera [4].x, input.camera [4].y, input.margins.left, input.margins.right, input.margins.top, input.margins.bottom, input.dimensions.width, input.dimensions.height, Flags.pack (map_flags, input.map.flags), input.tileset) if format == 18 then output [#output + 1] = pack ( '< i4 z z z i4 z z z', input.campaign.background, input.loading.text, input.loading.title, input.loading.subtitle, input.loading.background, input.prologue.text, input.prologue.title, input.prologue.subtitle) else output [#output + 1] = pack ( '< i4 z z z z i4 z z z z i4 f f f B B B B c4 z c1 B B B B', input.loading.background, input.loading.model, input.loading.text, input.loading.title, input.loading.subtitle, input.game_data, input.prologue.model, input.prologue.text, input.prologue.title, input.prologue.subtitle, input.fog.index, input.fog.z.start, input.fog.z.finish, input.fog.density, input.fog.color.red, input.fog.color.green, input.fog.color.blue, input.fog.color.alpha, input.environment.weather, input.environment.sound, input.environment.light, input.environment.water.red, input.environment.water.green, input.environment.water.blue, input.environment.water.alpha) end if format >= 28 then output [#output + 1] = pack ('< i4', input.script) end if format >= 31 then output [#output + 1] = pack ( '< i4 i4', input.graphics, input.game_data_version) end output [#output + 1] = pack ('< i4', #input.players) for _, player in ipairs (input.players) do output [#output + 1] = pack ( '< i4 i4 i4 i4 z f f I4 I4', player.index, player.type, player.race, player.start.fixed, player.name, player.start.x, player.start.y, Bits.pack (player.ally.low), Bits.pack (player.ally.high)) if format == 31 then output [#output + 1] = pack ( '< I4 I4', Bits.pack (player.enemy.low), Bits.pack (player.enemy.high)) end end output [#output + 1] = pack ('< i4', #input.forces) for _, force in ipairs (input.forces) do output [#output + 1] = pack ( '< I4 I4 z', Flags.pack (force_flags, force.flags), Bits.pack (force.players), force.name) end output [#output + 1] = pack ('< i4', #input.upgrades) for _, upgrade in ipairs (input.upgrades) do output [#output + 1] = pack ( '< I4 c4 i4 i4', Bits.pack (upgrade.players), upgrade.id, upgrade.level, upgrade.availability) end output [#output + 1] = pack ('< i4', #input.tech) for _, tech in ipairs (input.tech) do output [#output + 1] = pack ( '< I4 c4', Bits.pack (tech.players), tech.id) end output [#output + 1] = pack ('< i4', #input.units) for _, units in ipairs (input.units) do output [#output + 1] = pack ( '< i4 z i4 i4' .. ('i4'):rep (units.columns), units.index, units.name, units.columns, table.unpack (units.type), #units.rows) for _, row in ipairs (units.rows) do output [#output + 1] = pack ( '< i4' .. ('c4'):rep (units.columns), row.chance, table.unpack (row.id)) end end if format >= 25 then output [#output + 1] = pack ('< i4', #input.item_tables) for _, item_table in ipairs (input.item_tables) do output [#output + 1] = pack ( '< i4 z i4', item_table.index, item_table.name, #item_table) for _, set in ipairs (item_table) do output [#output + 1] = pack ('< i4', #set) for _, item in ipairs (set) do output [#output + 1] = pack ( '< i4 c4', item.chance, item.id) end end end end return table.concat (output) end return W3I
local function loadMapData() local map = game.GetMap():lower(); if (map ~= "rp_evocity_v2d") then MsgN("Elevatr doesn't know ", map, "!"); return end return { SearchArea = { Vector(-7000, -9000, 2800), Vector(-7300, -9500, 60) }; Stops = { { Name = "Ground"; Pos = Vector(-7114, -9382, 134.0679); Ang = Angle( 0, 90, 0); }; { Name = "Jail"; Pos = Vector(-7114, -9382, 902.4282); Ang = Angle( 0, 90, 0); }; { Name = "Admin"; Pos = Vector(-7121, -9401, 1543.0226); Ang = Angle( 0, 0, 0); }; { Name = "Mayor"; Pos = Vector(-7123, -9401, 2680.1448); Ang = Angle( 0, 0, 0); }; }; Control = { Pos = Vector(83.4, -2.492188, 9); Ang = Angle(0, 90, 90); }; }; end local function fuckWithTrackPoints(points) local top = -math.huge; local bottom = math.huge; local topEnt, bottomEnt; for _, ent in pairs(points) do local pos = ent:GetPos(); if (pos.z > top) then topEnt = ent; top = pos.z; end if (pos.z < bottom) then bottomEnt = ent; bottom = pos.z; end end -- Cut out all the other stops topEnt:SetKeyValue("target", bottomEnt:GetName()); bottomEnt:SetKeyValue("target", topEnt:GetName()); -- Make them re-evaluate topEnt:Activate(); bottomEnt:Activate(); end -- Funny names make the code better function DoYouEvenLiftBro() local mapdata = loadMapData(); if (not mapdata) then return; end local points = {}; local lift; for _, ent in pairs(ents.FindInBox(unpack(mapdata.SearchArea))) do local class = ent:GetClass(); if (class == "path_track") then table.insert(points, ent); elseif (class == "func_tracktrain") then lift = ent; elseif (class == "func_button") then -- What could possibly go wrong -- TODO: Some way to get the outputs? ent:Remove(); end end if (not IsValid(lift)) then error("Could not find lift!"); elseif (#points < 3) then error("" .. #points .. " is not enough Vpoints!"); end fuckWithTrackPoints(points); local controller = ents.Create("gmod_evolift"); controller:SetPos(lift:LocalToWorld(mapdata.Control.Pos)); controller:SetAngles(mapdata.Control.Ang); controller:SetLift(lift); controller:SetStops(mapdata.Stops); controller:Spawn(); controller:Activate(); end hook.Add("InitPostEntity", "Lift Spawner", DoYouEvenLiftBro); hook.Add("PostCleanupMap", "Lift Spawner", DoYouEvenLiftBro);
object_tangible_food_bar_drink_bar_s05 = object_tangible_food_bar_shared_drink_bar_s05:new { } ObjectTemplates:addTemplate(object_tangible_food_bar_drink_bar_s05, "object/tangible/food/bar/drink_bar_s05.iff")
require("mods") require("modutil") local function modprint(...) --print(type(...) == "table" and unpack(...) or ...) end local mod_config_path = "mod_config_data/" ModIndex = Class(function(self) self.startingup = false self.cached_data = {} self.savedata = { known_mods = { }, known_api_version = 0, } end) --[[ known_mods = { [modname] = { enabled = true, disabled_bad = true, disabled_old = true, modinfo = { version = "1.2", api_version = 2, old = true, failed = false, }, } } --]] function ModIndex:GetModIndexName() local name = "modindex" if BRANCH ~= "release" then name = name .. "_"..BRANCH end return name end function ModIndex:GetModConfigurationPath(modname) if modname then return mod_config_path..self:GetModConfigurationName(modname) else return mod_config_path end end function ModIndex:GetModConfigurationName(modname) local name = "modconfiguration_"..modname if BRANCH ~= "release" then name = name .. "_"..BRANCH end return name end function ModIndex:BeginStartupSequence(callback) self.startingup = true local filename = "boot_"..self:GetModIndexName() TheSim:GetPersistentString(filename, function(load_success, str) if load_success and str == "loading" then local modsenabled = self:GetModsToLoad() if #modsenabled > 0 then self.badload = true print("ModIndex: Detected bad load, disabling all mods.") self:DisableAllMods() self:Save(nil) -- write to disk that all mods were disabled! end callback() else print("ModIndex: Beginning normal load sequence.\n") SavePersistentString(filename, "loading", false, callback) end end) end function ModIndex:EndStartupSequence(callback) self.startingup = false local filename = "boot_"..self:GetModIndexName() SavePersistentString(filename, "done", false, callback) print("ModIndex: Load sequence finished successfully.\n") end function ModIndex:WasLoadBad() return self.badload == true end function ModIndex:GetModNames() local names = {} for name,_ in pairs(self.savedata.known_mods) do table.insert(names, name) end return names end function ModIndex:Save(callback) if PLATFORM == "PS4" then return end local newdata = { known_mods = {} } newdata.known_api_version = MOD_API_VERSION for name, data in pairs(self.savedata.known_mods) do newdata.known_mods[name] = {} newdata.known_mods[name].enabled = data.enabled newdata.known_mods[name].disabled_bad = data.disabled_bad newdata.known_mods[name].disabled_old = data.disabled_old newdata.known_mods[name].disabled_incompatible_with_mode = data.disabled_incompatible_with_mode newdata.known_mods[name].seen_api_version = MOD_API_VERSION newdata.known_mods[name].modinfo = data.modinfo end --print("\n\n---SAVING MOD INDEX---\n\n") --dumptable(newdata) --print("\n\n---END SAVING MOD INDEX---\n\n") local data = DataDumper(newdata, nil, false) local insz, outsz = SavePersistentString(self:GetModIndexName(), data, ENCODE_SAVES, callback) end function ModIndex:GetModsToLoad(usecached) local cached = usecached or false local ret = {} if not cached then local moddirs = TheSim:GetModDirectoryNames() for i,moddir in ipairs(moddirs) do if (self:IsModEnabled(moddir) or self:IsModForceEnabled(moddir)) then table.insert(ret, moddir) end end else if self.savedata and self.savedata.known_mods then for modname, moddata in pairs(self.savedata.known_mods) do if (self:IsModEnabled(modname) or self:IsModForceEnabled(modname)) then table.insert(ret, modname) end end end end for i,modname in ipairs(ret) do if self:IsModStandalone(modname) then print("\n\n"..ModInfoname(modname).." Loading a standalone mod! No other mods will be loaded.\n") return { modname } end end return ret end function ModIndex:GetModInfo(modname) return self.savedata.known_mods[modname].modinfo or {} end function ModIndex:UpdateModInfo() modprint("Updating all mod info.") local modnames = TheSim:GetModDirectoryNames() for modname,moddata in pairs(self.savedata.known_mods) do if not table.contains(modnames, modname) then self.savedata.known_mods[modname] = nil end end for i,modname in ipairs(modnames) do if not self.savedata.known_mods[modname] then self.savedata.known_mods[modname] = {} end self.savedata.known_mods[modname].modinfo = self:LoadModInfo(modname) end end function ModIndex:LoadModInfo(modname) modprint(string.format("Updating mod info for '%s'", modname)) local info = self:InitializeModInfo(modname) if info.old and self:IsModNewlyOld(modname) then modprint(" It's using an old api_version.") self:DisableBecauseOld(modname) elseif info.failed then modprint(" But there was an error loading it.") self:DisableBecauseBad(modname) else -- we've already "dealt" with this in the past; if the user -- chooses to enable it, then try loading it! end self.savedata.known_mods[modname].modinfo = info for i,v in pairs(self.savedata.known_mods[modname].modinfo) do -- print(i,v) end return info end function ModIndex:InitializeModInfo(modname) local env = {} local fn = kleiloadlua("../mods/"..modname.."/modinfo.lua") local modinfo_message = "" if type(fn) == "string" then print("Error loading mod: "..ModInfoname(modname).."!\n "..fn.."\n") --table.insert( self.failedmods, {name=modname,error=fn} ) env.failed = true elseif not fn then modinfo_message = modinfo_message.."No modinfo.lua, using defaults... " env.old = true else local status, r = RunInEnvironment(fn,env) if status == false then print("Error loading mod: "..ModInfoname(modname).."!\n "..r.."\n") --table.insert( self.failedmods, {name=modname,error=r} ) env.failed = true elseif env.api_version == nil or env.api_version < MOD_API_VERSION then local old = "Mod "..modname.." was built for an older version of the game and requires updating. (api_version is version "..tostring(env.api_version)..", game is version "..MOD_API_VERSION..".)" modinfo_message = modinfo_message.."Old API! (mod: "..tostring(env.api_version).." game: "..MOD_API_VERSION..") " env.old = true elseif env.api_version > MOD_API_VERSION then local old = "api_version for "..modname.." is in the future, please set to the current version. (api_version is version "..env.api_version..", game is version "..MOD_API_VERSION..".)" print("Error loading mod: "..ModInfoname(modname).."!\n "..old.."\n") --table.insert( self.failedmods, {name=modname,error=old} ) env.failed = true else local checkinfo = { "name", "description", "author", "version", "forumthread", "api_version", "dont_starve_compatible", "reign_of_giants_compatible", "configuration_options" } local missing = {} for i,v in ipairs(checkinfo) do if env[v] == nil then if v == "dont_starve_compatible" then -- Print a warning but let the mod load print("WARNING loading modinfo.lua: "..modname.." does not specify if it is compatible with the base game. It may not work properly.") elseif v == "reign_of_giants_compatible" then -- Print a warning but let the mod load print("WARNING loading modinfo.lua: "..modname.." does not specify if it is compatible with Reign of Giants. It may not work properly.") elseif v == "configuration_options" then -- Do nothing. It's perfectly fine not to have config options! else table.insert(missing, v) end end end if #missing > 0 then local e = "Error loading modinfo.lua. These fields are required: " .. table.concat(missing, ", ") print (e) --table.insert( self.failedmods, {name=modname,error=e} ) env.failed = true else -- everything loaded okay! end end end env.modinfo_message = modinfo_message -- If modinfo hasn't been updated to specify compatibility yet, set it to true for both modes and set a flag if env.dont_starve_compatible == nil then env.dont_starve_compatible = true env.dont_starve_compatibility_specified = false end if env.reign_of_giants_compatible == nil then env.reign_of_giants_compatible = true env.reign_of_giants_compatibility_specified = false end return env end function ModIndex:GetModActualName(fancyname) for i,v in pairs(self.savedata.known_mods) do if v and v.modinfo and v.modinfo.name then if v.modinfo.name == fancyname then return i end end end end function ModIndex:GetModFancyName(modname) local knownmod = self.savedata.known_mods[modname] if knownmod and knownmod.modinfo and knownmod.modinfo.name then return knownmod.modinfo.name else return modname end end function ModIndex:Load(callback) self:UpdateModSettings() local filename = self:GetModIndexName() TheSim:GetPersistentString(filename, function(load_success, str) if load_success == true then local success, savedata = RunInSandbox(str) if success and string.len(str) > 0 then self.savedata = savedata for k,info in pairs(self.savedata.known_mods) do info.was_enabled = info.enabled end print ("loaded "..filename) --print("\n\n---LOADING MOD INDEX---\n\n") --dumptable(self.savedata) --print("\n\n---END LOADING MOD INDEX---\n\n") else print ("Could not load "..filename) end else print ("Could not load "..filename) end callback() end) end function ModIndex:IsModCompatibleWithMode(modname, dlcmode) local known_mod = self.savedata.known_mods[modname] local reignofgiants = dlcmode or IsDLCEnabled(REIGN_OF_GIANTS) if known_mod then if reignofgiants then return known_mod.modinfo.reign_of_giants_compatible else return known_mod.modinfo.dont_starve_compatible end end return false end function ModIndex:HasModConfigurationOptions(modname) local modinfo = self:GetModInfo(modname) if modinfo and modinfo.configuration_options and type(modinfo.configuration_options) == "table" and #modinfo.configuration_options > 0 then return true end return false end function ModIndex:UpdateConfigurationOptions(config_options, savedata) for i,v in pairs(savedata) do for j,k in pairs(config_options) do if v.name == k.name and v.saved ~= nil then k.saved = v.saved end end end end -- Just returns the table itself function ModIndex:GetModConfigurationOptions(modname) local known_mod = self.savedata.known_mods[modname] if known_mod then return known_mod.modinfo.configuration_options end end -- Loads the actual file from disk function ModIndex:LoadModConfigurationOptions(modname) local known_mod = self.savedata.known_mods[modname] -- Try to find saved config settings first local filename = self:GetModConfigurationPath(modname) TheSim:GetPersistentString(filename, function(load_success, str) if load_success == true then local success, savedata = RunInSandbox(str) if success and string.len(str) > 0 then -- Carry over saved data from old versions when possible if self:HasModConfigurationOptions(modname) then self:UpdateConfigurationOptions(known_mod.modinfo.configuration_options, savedata) else known_mod.modinfo.configuration_options = savedata end print ("loaded "..filename) else print ("Could not load "..filename) end else print ("Could not load "..filename) end -- callback() end) if known_mod and known_mod.modinfo and known_mod.modinfo.configuration_options then return known_mod.modinfo.configuration_options end return nil end function ModIndex:SaveConfigurationOptions(callback, modname, configdata) if PLATFORM == "PS4" or not configdata then return end -- Save it to disk local name = self:GetModConfigurationPath(modname) local data = DataDumper(configdata, nil, false) local cb = function() callback() -- And reload it to make sure there's parity after it's been saved self:LoadModConfigurationOptions(modname) end local insz, outsz = SavePersistentString(name, data, ENCODE_SAVES, cb) end function ModIndex:IsModEnabled(modname) local known_mod = self.savedata.known_mods[modname] return known_mod and known_mod.enabled end function ModIndex:IsModForceEnabled(modname) return self.modsettings.forceenable[modname] end function ModIndex:IsModStandalone(modname) local known_mod = self.savedata.known_mods[modname] return known_mod and known_mod.modinfo and known_mod.modinfo.standalone == true end function ModIndex:IsModInitPrintEnabled() return self.modsettings.initdebugprint end -- Note: Installed means enabled + ran in this terminology function ModIndex:WasModEnabled(modname) local known_mod = self.savedata.known_mods[modname] return known_mod and known_mod.was_enabled end function ModIndex:Disable(modname) if not self.savedata.known_mods[modname] then self.savedata.known_mods[modname] = {} end self.savedata.known_mods[modname].enabled = false end function ModIndex:DisableAllMods() for k,v in pairs(self.savedata.known_mods) do self:Disable(k) end end function ModIndex:DisableBecauseBad(modname) if not self.savedata.known_mods[modname] then self.savedata.known_mods[modname] = {} end self.savedata.known_mods[modname].disabled_bad = true self.savedata.known_mods[modname].enabled = false end function ModIndex:DisableBecauseOld(modname) if not self.savedata.known_mods[modname] then self.savedata.known_mods[modname] = {} end self.savedata.known_mods[modname].disabled_old = true self.savedata.known_mods[modname].enabled = false end function ModIndex:DisableBecauseIncompatibleWithMode(modname) if not self.savedata.known_mods[modname] then self.savedata.known_mods[modname] = {} end self.savedata.known_mods[modname].disabled_incompatible_with_mode = true self.savedata.known_mods[modname].enabled = false end function ModIndex:Enable(modname) if not self.savedata.known_mods[modname] then self.savedata.known_mods[modname] = {} end self.savedata.known_mods[modname].enabled = true self.savedata.known_mods[modname].disabled_bad = false self.savedata.known_mods[modname].disabled_old = false self.savedata.known_mods[modname].disabled_incompatible_with_mode = false end function ModIndex:IsModNewlyBad(modname) local known_mod = self.savedata.known_mods[modname] if known_mod and known_mod.modinfo.failed then -- After a mod is disabled it can no longer fail; -- in addition, the index is saved when a mod fails. -- So we just have to check if the mod failed in the index -- and that indicates what happened last time. return true end return false end function ModIndex:KnownAPIVersion(modname) local known_mod = self.savedata.known_mods[modname] if not known_mod or not known_mod.modinfo then return -2 -- If we've never seen the mod before, we assume it's REALLY old elseif not known_mod.modinfo.api_version then return -1 -- If we've seen it but it has no info, it's just "Old" else return known_mod.modinfo.api_version end end function ModIndex:IsModNewlyOld(modname) if self:KnownAPIVersion(modname) < MOD_API_VERSION and self.savedata.known_mods[modname] and self.savedata.known_mods[modname].seen_api_version and self.savedata.known_mods[modname].seen_api_version < MOD_API_VERSION then return true end return false end function ModIndex:IsModNew(modname) return not self.savedata.known_mods[modname] or not self.savedata.known_mods[modname].modinfo end function ModIndex:IsModKnownBad(modname) return self.savedata.known_mods[modname] and self.savedata.known_mods[modname].disabled_bad end -- When the user changes settings it messes directly with the index data, so make a backup function ModIndex:CacheSaveData() self.cached_data = {} self.cached_data.savedata = deepcopy(self.savedata) self.cached_data.modsettings = deepcopy(self.modsettings) return self.cached_data end -- If the user cancels their mod changes, restore the index to how it was prior the changes. function ModIndex:RestoreCachedSaveData(ext_data) if ext_data then self.savedata = ext_data.savedata self.modsettings = ext_data.modsettings elseif self.cached_data then self.savedata = self.cached_data.savedata self.modsettings = self.cached_data.modsettings end end function ModIndex:UpdateModSettings() self.modsettings = { forceenable = {} } local function ForceEnableMod(modname) print("WARNING: Force-enabling mod '"..ModInfoname(modname).."' from modsettings.lua! If you are not developing a mod, please use the in-game menu instead.") self.modsettings.forceenable[modname] = true end local function EnableModDebugPrint() self.modsettings.initdebugprint = true end local env = { ForceEnableMod = ForceEnableMod, EnableModDebugPrint = EnableModDebugPrint, } local filename = "../mods/modsettings.lua" local fn = kleiloadlua( filename ) assert(fn, "could not load modsettings: "..filename) if type(fn)=="string" then error("Error loading modsettings:\n"..fn) end setfenv(fn, env) fn() end KnownModIndex = ModIndex()
-- ARGV[1] = queue name -- ARGV[2] = batch name -- ARGV[3] = max batch for i=0,ARGV[3] do redis.call("RPOPLPUSH",ARGV[1],ARGV[2]) end local element = redis.call("LRANGE",ARGV[2],0,-1) return element
--[[ LuCI - SGI-Module for WSAPI Description: Server Gateway Interface for WSAPI FileId: $Id: wsapi.lua 2656 2008-07-23 18:52:12Z Cyrus $ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("luci.sgi.wsapi", package.seeall) local ltn12 = require("luci.ltn12") require("luci.http") require("luci.dispatcher") require("luci.http.protocol") function run(wsapi_env) local r = luci.http.Request( wsapi_env, ltn12.source.file(wsapi_env.input), ltn12.sink.file(wsapi_env.error) ) local res, id, data1, data2 = true, 0, nil, nil local headers = {} local status = 200 local x = coroutine.create(luci.dispatcher.httpdispatch) local active = true while id < 3 do res, id, data1, data2 = coroutine.resume(x, r) if not res then status = 500 headers["Content-Type"] = "text/plain" local err = {id} return status, headers, function() local x = table.remove(err) return x end end if id == 1 then status = data1 elseif id == 2 then headers[data1] = data2 end end local function iter() local res, id, data = coroutine.resume(x) if id == 4 and active then return data elseif id == 5 then active = false return "" else return "" end if coroutine.status(x) == "dead" then return nil end end return status, headers, iter end
hatoffsetindex = {} hatoffsetindex["idleanim"] = "idle" hatoffsetindex["run"] = "running" hatoffsetindex["runfast"] = "running" hatoffsetindex["slide"] = "sliding" hatoffsetindex["jump"] = "jumping" hatoffsetindex["fall"] = "falling" hatoffsetindex["climb"] = "climbing" hatoffsetindex["swim"] = "swimming" hatoffsetindex["swimpush"] = "swimming" hatoffsetindex["duck"] = "ducking" hatoffsetindex["fly"] = "flyjump" hatoffsetindex["capefly"] = "capefly" hatoffsetindex["float"] = "jumping" hatoffsetindex["die"] = "dead" hatoffsetindex["grownogun"] = "grow" hatoffsets = {} hatoffsets["idle"] = {0, 0} hatoffsets["running"] = {{0, 0}, {0, 0}, {-1, -1}} hatoffsets["sliding"] = {0, 0} hatoffsets["jumping"] = {0, -1} hatoffsets["falling"] = {0, 0} hatoffsets["climbing"] = {{0, 0}, {0, -1}} hatoffsets["fence"] = {{0, 0}, {0, 0}} hatoffsets["swimming"] = {{1, -1}, {1, -1}, {1, -1}, {1, -1}, {1, -1}} hatoffsets["ducking"] = {0, -3} hatoffsets["dead"] = {1, -2} hatoffsets["grow"] = {-6, 0} bighatoffsets = {} bighatoffsets["idle"] = {-4, -2} bighatoffsets["fire"] = {-5, -4} bighatoffsets["running"] = {{-5, -4}, {-4, -3}, {-3, -2}} bighatoffsets["sliding"] = {-5, -2} bighatoffsets["jumping"] = {-4, -4} bighatoffsets["falling"] = {-4, -2} bighatoffsets["climbing"] = {{-4, -4}, {-4, -4}} bighatoffsets["fence"] = {{-4, -4}, {-4, -4}} bighatoffsets["swimming"] = {{-5, -4}, {-5, -4}, {-5, -4}, {-5, -4}, {-5, -4}} bighatoffsets["ducking"] = {-5, -12} bighatoffsets["flyjump"] = {-4, -2} bighatoffsets["capefly"] = {{-10, -10}, {-11, -15}, {-10, -19}, {-11, -21}, {-9, -22}, {-9, -24}} bighatoffsets["dead"] = false skinnyhatoffsets = {} skinnyhatoffsets["idle"] = {1, 0} skinnyhatoffsets["running"] = {{2, -2}, {1, -1}, {3, 0}} skinnyhatoffsets["sliding"] = {-1, -3} skinnyhatoffsets["jumping"] = {2, -2} skinnyhatoffsets["falling"] = {1, 0} skinnyhatoffsets["climbing"] = {{2, 0}, {4, -2}} skinnyhatoffsets["fence"] = {{2, 0}, {2, 0}} skinnyhatoffsets["swimming"] = {{0, 0}, {0, -1}, {-2, -1}, {0, -1}, {0, -1}} skinnyhatoffsets["ducking"] = {1, -13} skinnyhatoffsets["dead"] = false skinnyhat = {}
return { up = function() local utils = require('migrator.utils') local owners = box.schema.space.create("owners", { if_not_exists = true }) owners:format({ { name = "id", type = "uuid" }, { name = "first_name", type = "string" }, { name = "last_name", type = "string" }, { name = "address", type = "string" }, { name = "city", type = "string" }, { name = "telephone", type = "string" }, { name = "bucket_id", type = "unsigned" }, { name = "pets", type = "map", is_nullable = true } }) owners:create_index("primary", { parts = { { field = "id" } }, if_not_exists = true }) owners:create_index("bucket_id", { parts = { { field = "bucket_id" } }, unique = false, if_not_exists = true }) owners:create_index("last_name", { parts = { { field = "last_name" } }, unique = false, if_not_exists = true }) utils.register_sharding_key('owners', {'bucket_id'}) return true end }
--[[ Test loading the hms (body joints predictor) networks (LSTM + ConvNet3D). ]] require 'torch' require 'paths' require 'string' require 'nn' require 'nngraph' require 'image' require 'cutorch' require 'cunn' require 'cudnn' torch.manualSeed(4) torch.setdefaulttensortype('torch.FloatTensor') paths.dofile('../projectdir.lua') utils = paths.dofile('../util/utils.lua') local opts = paths.dofile('../options.lua') opt = opts.parse(arg) opt.dataset = 'ucf_sports' opt.nFeats = 256 opt.num_activities = 10 opt.nLayers = 2 opt.batchSize = 2 opt.seq_length = 20 opt.GPU = 1 opt.nGPU = 1 local nets = {'hms-lstm', 'hms-convnet3d'} for k, netType in ipairs(nets) do opt.netType = netType print(('\nLoad network: %s [%d/%d]'):format(netType, k, #nets)) local model_features, model_hms, model_classifier, criterion, params = paths.dofile('../model.lua') opt.params = params print('==> Features network:') print(model_features) print('==> hms network:') print(model_hms) print('==> Classifier network:') print(model_classifier) print('############################') print('# process some input data') print('############################') local batch_feats_imgs = {} for ibatch=1, opt.batchSize do local seq_feats = {} for i=1, opt.seq_length do local img = torch.Tensor(1,3,256,256):uniform():cuda() local features = model_hms:forward(img) table.insert(seq_feats, features) end -- convert table into a single tensor table.insert(batch_feats_imgs, nn.Unsqueeze(1):cuda():forward(nn.JoinTable(1):cuda():forward(seq_feats))) end -- convert table into a single tensor local inputs = nn.JoinTable(1):cuda():forward(batch_feats_imgs) -- classify the sequence of images local res = model_classifier:forward(inputs) print(#res) end
--!strict local NONE = require(script.Parent.None) return function<T>(schema: T, input: any): T local options = {} for key, value in pairs(schema) do options[key] = if value == NONE then nil else value end if type(input) ~= "table" then return options::any end for key, _ in pairs(schema::any) do if input[key] ~= nil or input[key] ~= NONE then options[key] = input[key] end end return options::any end
ESX = nil blip = nil blips = {} RegisterCommand("co", function(source, args, rawcommand) local pos = GetEntityCoords(PlayerPedId()) print(pos.x..", "..pos.y..", "..pos.z) end, false) Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end while ESX.GetPlayerData().job == nil do Citizen.Wait(10) end PlayerData = ESX.GetPlayerData() if PlayerData.job.name == 'police' then arme = false end end) RegisterNetEvent('esx:setJob') AddEventHandler('esx:setJob', function(job) PlayerData.job = job if PlayerData.job.name == 'police' then arme = false end end) RMenu.Add("lspd", "lspds", RageUI.CreateMenu("~b~L.S.P.D","Menu LSPD")) RMenu:Get("lspd", "lspds").Closed = function()end RMenu:Get('lspd', 'lspds'):SetRectangleBanner(0, 0, 0, 255) -----Sous-Menu---------- RMenu.Add("lspd", "lspd_main", RageUI.CreateSubMenu(RMenu:Get("lspd", "lspds"), "~b~L.S.P.D", "LSPD")) RMenu:Get("lspd", "lspd_main").Closed = function()end -----Sous-Menu2------- RMenu.Add("lspd", "lspd_main1", RageUI.CreateSubMenu(RMenu:Get("lspd", "lspds"), "~b~L.S.P.D", "LSPD")) RMenu:Get("lspd", "lspd_main1").Closed = function()end -----Sous-Menu3------- RMenu.Add("lspd", "lspd_main2", RageUI.CreateSubMenu(RMenu:Get("lspd", "lspds"), "~b~L.S.P.D", "LSPD")) RMenu:Get("lspd", "lspd_main2").Closed = function()end -----Sous-Menu4------- RMenu.Add("lspd", "lspd_main3", RageUI.CreateSubMenu(RMenu:Get("lspd", "lspds"), "~b~L.S.P.D", "LSPD")) RMenu:Get("lspd", "lspd_main3").Closed = function()end Citizen.CreateThread(function() while true do if IsControlJustReleased(0, 167) and not isDead and PlayerData.job and PlayerData.job.name == 'police' and not ESX.UI.Menu.IsOpen('default', GetCurrentResourceName(), 'police_actions') then OpenPoliceActionsMenu() end -----------------Menu Sub--------------- RageUI.IsVisible(RMenu:Get("lspd","lspds"),true,true,true,function() RageUI.Separator("~b~↓ Jobs - Police ↓") RageUI.ButtonWithStyle("Intéraction Citoyen", "LSPD", {}, true,function(h,a,s) if s then end end,RMenu:Get("lspd","lspd_main")) RageUI.ButtonWithStyle("Intéraction Véhicule", "LSPD", {}, true,function(h,a,s) if s then end end,RMenu:Get("lspd","lspd_main1")) RageUI.ButtonWithStyle("Intéraction Service", "LSPD", {}, true,function(h,a,s) if s then end end,RMenu:Get("lspd","lspd_main2")) RageUI.ButtonWithStyle("Demande De Renfort", "LSPD", {}, true,function(h,a,s) if s then end end,RMenu:Get("lspd","lspd_main3")) end, function()end, 1) ----------------------Menu Véhicule-------------------- RageUI.IsVisible(RMenu:Get("lspd","lspd_main1"),true,true,true,function() RageUI.Separator("~b~↓ Gestion - Véhicule ↓") RageUI.ButtonWithStyle("~b~Déverouiller le Véhicule", "LSPD", {RightBadge = RageUI.BadgeStyle.Car}, true,function(h,a,s) if s then TriggerEvent('esx_mechanicjob:onHijack') end end) end, function()end, 1) -----------------------------Menu Renfort----------------- RageUI.IsVisible(RMenu:Get("lspd","lspd_main3"),true,true,true,function() RageUI.Separator("~b~↓ Gestion - Renfort ↓") RageUI.ButtonWithStyle("~b~👨🏻‍💻 Petite demande", "LSPD", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) coords = GetEntityCoords(PlayerPedId()) if s then local raison = 'petit' TriggerServerEvent('renfort', coords, raison) end end) RageUI.ButtonWithStyle("~b~👨🏻‍💻 Demande importante", "LSPD", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) coords = GetEntityCoords(PlayerPedId()) if s then local raison = 'importante' TriggerServerEvent('renfort', coords, raison) end end) RageUI.ButtonWithStyle("~b~👨🏻‍💻 Demande importante", "LSPD", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) coords = GetEntityCoords(PlayerPedId()) if s then local raison = 'omgad' TriggerServerEvent('renfort', coords, raison) end end) end, function()end, 1) ----------------------------------------MENU Service ------------------------------- RageUI.IsVisible(RMenu:Get("lspd","lspd_main2"),true,true,true,function() RageUI.Separator("~b~↓ Gestion - Service ↓") RageUI.ButtonWithStyle("~b~Prendre Son Service", "Prendre Son Service", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) if s then local info = 'prise' TriggerServerEvent('police:PriseEtFinservice', info) end end) RageUI.ButtonWithStyle("~b~Fin De Service", "Fin De Service", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) if s then local info = 'fin' TriggerServerEvent('police:PriseEtFinservice', info) end end) end, function()end, 1) -----------------------------MENU 1 ----------------------------- RageUI.IsVisible(RMenu:Get("lspd","lspd_main"),true,true,true,function() RageUI.Separator("~b~↓ Intéraction - Police ↓") RageUI.ButtonWithStyle("~b~Ménotter", "Menotter La perssone la plus proche de vous.", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) if s then TriggerServerEvent('esx_policejob:handcuff', GetPlayerServerId(closestPlayer)) end end) RageUI.ButtonWithStyle("~b~Démenotter", "", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) if s then TriggerEvent('esx_policejob:unrestrain') end end) RageUI.ButtonWithStyle("~b~Attacher", "", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) if s then TriggerServerEvent('esx_policejob:drag', GetPlayerServerId(closestPlayer)) end end) RageUI.ButtonWithStyle("~r~Facture", "Donnez une Facture", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) if s then OpenBillingMenu() end end) RageUI.ButtonWithStyle("~r~Mettre Dans le Véhicule", "Donnez une Facture", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) if s then TriggerServerEvent('esx_policejob:putInVehicle', GetPlayerServerId(closestPlayer)) end end) RageUI.ButtonWithStyle("~r~Sortis Du Véhicule", "Donnez une Facture", {RightBadge = RageUI.BadgeStyle.Tick}, true,function(h,a,s) if s then TriggerServerEvent('esx_policejob:OutVehicle', GetPlayerServerId(closestPlayer)) end end) end, function()end, 1) Citizen.Wait(0) end end) ----------------------------------------- function OpenPoliceActionsMenu() RageUI.Visible(RMenu:Get('lspd', 'lspds'), not RageUI.Visible(RMenu:Get('lspd', 'lspds'))) end RegisterNetEvent('esx_policejob:drag') AddEventHandler('esx_policejob:drag', function(copId) if isHandcuffed then dragStatus.isDragged = not dragStatus.isDragged dragStatus.CopId = copId end end) function OpenBillingMenu() ESX.UI.Menu.Open( 'dialog', GetCurrentResourceName(), 'billing', { title = "Facture" }, function(data, menu) local amount = tonumber(data.value) local player, distance = ESX.Game.GetClosestPlayer() if player ~= -1 and distance <= 3.0 then menu.close() if amount == nil then ESX.ShowColoredNotification("~r~ERREUR~s~: ~g~Montant invalide", 25) else TriggerServerEvent('esx_billing:sendBill', GetPlayerServerId(player), 'society_police', _U('billing'), amount) Citizen.Wait(100) ESX.ShowColoredNotification("Vous avez bien envoyer une facture", 25) end else ESX.ShowColoredNotification("~r~ERREUR~s~: ~g~Aucun joueur à proximitée", 25) end end, function(data, menu) menu.close() end ) end RegisterNetEvent('esx_policejob:unrestrain') AddEventHandler('esx_policejob:unrestrain', function() if isHandcuffed then local playerPed = PlayerPedId() isHandcuffed = false ClearPedSecondaryTask(playerPed) SetEnableHandcuffs(playerPed, false) DisablePlayerFiring(playerPed, false) SetPedCanPlayGestureAnims(playerPed, true) FreezeEntityPosition(playerPed, false) DisplayRadar(true) -- end timer if Config.EnableHandcuffTimer and handcuffTimer.active then ESX.ClearTimeout(handcuffTimer.task) end end end) RegisterNetEvent('esx_policejob:putInVehicle') AddEventHandler('esx_policejob:putInVehicle', function() if isHandcuffed then local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) if IsAnyVehicleNearPoint(coords, 5.0) then local vehicle = GetClosestVehicle(coords, 5.0, 0, 71) if DoesEntityExist(vehicle) then local maxSeats, freeSeat = GetVehicleMaxNumberOfPassengers(vehicle) for i=maxSeats - 1, 0, -1 do if IsVehicleSeatFree(vehicle, i) then freeSeat = i break end end if freeSeat then TaskWarpPedIntoVehicle(playerPed, vehicle, freeSeat) dragStatus.isDragged = false end end end end end) RegisterNetEvent('esx_policejob:OutVehicle') AddEventHandler('esx_policejob:OutVehicle', function() local playerPed = PlayerPedId() if IsPedSittingInAnyVehicle(playerPed) then local vehicle = GetVehiclePedIsIn(playerPed, false) TaskLeaveVehicle(playerPed, vehicle, 64) end end) RegisterNetEvent('esx_mechanicjob:onHijack') AddEventHandler('esx_mechanicjob:onHijack', function() local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) if IsAnyVehicleNearPoint(coords.x, coords.y, coords.z, 5.0) then local vehicle if IsPedInAnyVehicle(playerPed, false) then vehicle = GetVehiclePedIsIn(playerPed, false) else vehicle = GetClosestVehicle(coords.x, coords.y, coords.z, 5.0, 0, 71) end local chance = math.random(100) local alarm = math.random(100) if DoesEntityExist(vehicle) then if alarm <= 33 then SetVehicleAlarm(vehicle, true) StartVehicleAlarm(vehicle) end TaskStartScenarioInPlace(playerPed, 'WORLD_HUMAN_WELDING', 0, true) Citizen.CreateThread(function() Citizen.Wait(10000) if chance <= 66 then SetVehicleDoorsLocked(vehicle, 1) SetVehicleDoorsLockedForAllPlayers(vehicle, false) ClearPedTasksImmediately(playerPed) ESX.ShowNotification('Véhicule Ouvert') else ESX.ShowNotification('Ouverture A échouer') ClearPedTasksImmediately(playerPed) end end) end end end) RegisterNetEvent('police:InfoService') AddEventHandler('police:InfoService', function(service, nom) if service == 'prise' then PlaySoundFrontend(-1, "Start_Squelch", "CB_RADIO_SFX", 1) ESX.ShowAdvancedNotification('LSPD INFORMATIONS', '~b~Prise de service', 'Agent: ~g~'..nom..'\n~w~Code: ~g~10-8\n~w~Information: ~g~Prise de service.', 'CHAR_CALL911', 8) Wait(1000) PlaySoundFrontend(-1, "End_Squelch", "CB_RADIO_SFX", 1) elseif service == 'fin' then PlaySoundFrontend(-1, "Start_Squelch", "CB_RADIO_SFX", 1) ESX.ShowAdvancedNotification('LSPD INFORMATIONS', '~b~Fin de service', 'Agent: ~g~'..nom..'\n~w~Code: ~g~10-10\n~w~Information: ~g~Fin de service.', 'CHAR_CALL911', 8) Wait(1000) PlaySoundFrontend(-1, "End_Squelch", "CB_RADIO_SFX", 1) elseif service == 'pause' then PlaySoundFrontend(-1, "Start_Squelch", "CB_RADIO_SFX", 1) ESX.ShowAdvancedNotification('LSPD INFORMATIONS', '~b~Pause de service', 'Agent: ~g~'..nom..'\n~w~Code: ~g~10-6\n~w~Information: ~g~Pause de service.', 'CHAR_CALL911', 8) Wait(1000) PlaySoundFrontend(-1, "End_Squelch", "CB_RADIO_SFX", 1) elseif service == 'standby' then PlaySoundFrontend(-1, "Start_Squelch", "CB_RADIO_SFX", 1) ESX.ShowAdvancedNotification('LSPD INFORMATIONS', '~b~Mise en standby', 'Agent: ~g~'..nom..'\n~w~Code: ~g~10-12\n~w~Information: ~g~Standby, en attente de dispatch.', 'CHAR_CALL911', 8) Wait(1000) PlaySoundFrontend(-1, "End_Squelch", "CB_RADIO_SFX", 1) elseif service == 'control' then PlaySoundFrontend(-1, "Start_Squelch", "CB_RADIO_SFX", 1) ESX.ShowAdvancedNotification('LSPD INFORMATIONS', '~b~Control routier', 'Agent: ~g~'..nom..'\n~w~Code: ~g~10-48\n~w~Information: ~g~Control routier en cours.', 'CHAR_CALL911', 8) Wait(1000) PlaySoundFrontend(-1, "End_Squelch", "CB_RADIO_SFX", 1) elseif service == 'refus' then PlaySoundFrontend(-1, "Start_Squelch", "CB_RADIO_SFX", 1) ESX.ShowAdvancedNotification('LSPD INFORMATIONS', '~b~Refus d\'obtempérer', 'Agent: ~g~'..nom..'\n~w~Code: ~g~10-30\n~w~Information: ~g~Refus d\'obtempérer / Délit de fuite en cours.', 'CHAR_CALL911', 8) Wait(1000) PlaySoundFrontend(-1, "End_Squelch", "CB_RADIO_SFX", 1) elseif service == 'crime' then PlaySoundFrontend(-1, "Start_Squelch", "CB_RADIO_SFX", 1) ESX.ShowAdvancedNotification('LSPD INFORMATIONS', '~b~Crime en cours', 'Agent: ~g~'..nom..'\n~w~Code: ~g~10-31\n~w~Information: ~g~Crime en cours / poursuite en cours.', 'CHAR_CALL911', 8) Wait(1000) PlaySoundFrontend(-1, "End_Squelch", "CB_RADIO_SFX", 1) end end) RegisterNetEvent('renfort:setBlip') AddEventHandler('renfort:setBlip', function(coords, raison) if raison == 'petit' then PlaySoundFrontend(-1, "Start_Squelch", "CB_RADIO_SFX", 1) PlaySoundFrontend(-1, "OOB_Start", "GTAO_FM_Events_Soundset", 1) ESX.ShowAdvancedNotification('LSPD INFORMATIONS', '~b~Demande de renfort', 'Demande de renfort demandé.\nRéponse: ~g~CODE-2\n~w~Importance: ~g~Légère.', 'CHAR_CALL911', 8) Wait(1000) PlaySoundFrontend(-1, "End_Squelch", "CB_RADIO_SFX", 1) color = 2 elseif raison == 'importante' then PlaySoundFrontend(-1, "Start_Squelch", "CB_RADIO_SFX", 1) PlaySoundFrontend(-1, "OOB_Start", "GTAO_FM_Events_Soundset", 1) ESX.ShowAdvancedNotification('LSPD INFORMATIONS', '~b~Demande de renfort', 'Demande de renfort demandé.\nRéponse: ~g~CODE-3\n~w~Importance: ~o~Importante.', 'CHAR_CALL911', 8) Wait(1000) PlaySoundFrontend(-1, "End_Squelch", "CB_RADIO_SFX", 1) color = 47 elseif raison == 'omgad' then PlaySoundFrontend(-1, "Start_Squelch", "CB_RADIO_SFX", 1) PlaySoundFrontend(-1, "OOB_Start", "GTAO_FM_Events_Soundset", 1) PlaySoundFrontend(-1, "FocusIn", "HintCamSounds", 1) ESX.ShowAdvancedNotification('LSPD INFORMATIONS', '~b~Demande de renfort', 'Demande de renfort demandé.\nRéponse: ~g~CODE-99\n~w~Importance: ~r~URGENTE !\nDANGER IMPORTANT', 'CHAR_CALL911', 8) Wait(1000) PlaySoundFrontend(-1, "End_Squelch", "CB_RADIO_SFX", 1) PlaySoundFrontend(-1, "FocusOut", "HintCamSounds", 1) color = 1 end blipId = AddBlipForCoord(coords) SetBlipSprite(blipId, 161) SetBlipScale(blipId, 1.2) SetBlipColour(blipId, color) BeginTextCommandSetBlipName("STRING") AddTextComponentString('Demande renfort') EndTextCommandSetBlipName(blipId) table.insert(blips, blipId) Wait(80 * 1000) for i, blipId in pairs(blips) do RemoveBlip(blipId) end end)
local cute = require("cute") local shapes = require("src.shapes") notion("Can execute tests in subfolders", function () check("exterminate").is("exterminate") end)
ITEM.name = "Tuborg GREEN, 330ml" ITEM.description = "A bottle of beer" ITEM.longdesc = "The story of Tuborg starts in Hellerup, north of Copenhagen, where the Tuborg Brewery brewed Denmark’s first pilsner-type beer in 1880 and packaged it in bottles with a distinctive green label. It instantly became popular with the Danes.\nTuborg Green is a bottom-fermented lager beer. It's brewed on lager malt, a slightly roasted, bright type of malt which results in the well-known mild, fresh taste and aroma of flowers and cereal. The beer is medium rich and lively with a moderate bitterness in the aftertaste. Today, Tuborg has grown to become an international brand enjoyed in more than 70 countries around the world and known for its exceptional quality and refreshing taste, even in Ukraine, where the beer is also brewed." ITEM.model = "models/lostsignalproject/items/consumable/beer.mdl" ITEM.price = 45 ITEM.width = 1 ITEM.height = 2 ITEM.weight = 0.330 ITEM.flatweight = 0.150 ITEM.thirst = 8 ITEM.quantity = 1 ITEM.alcohol = 10 ITEM.addictionLightAlcohol = true ITEM.sound = "stalkersound/inv_flask.mp3" ITEM.img = ix.util.GetMaterial("vgui/hud/items/drink/bottlebeer_4.png") function ITEM:PopulateTooltipIndividual(tooltip) ix.util.PropertyDesc(tooltip, "Light Alcohol", Color(64, 224, 208)) end ITEM:Hook("use", function(item) item.player:EmitSound(item.sound or "items/battery_pickup.wav") item.player:AddBuff("buff_radiationremoval", 10, { amount = 0.15 }) item.player:GetCharacter():SatisfyAddictions("CheapAlcohol") ix.chat.Send(item.player, "iteminternal", "takes a swig of their "..item.name..".", false) end) ITEM:DecideFunction()
target("libco") set_kind("$(kind)") set_basename("co") add_files("**.cc") add_options("with_openssl") add_options("with_libcurl") if has_config("with_libcurl") then add_packages("libcurl") add_packages("openssl") elseif has_config("with_openssl") then add_packages("openssl") end if is_plat("windows") then add_files("__/StackWalker.cpp") add_files("co/detours/creatwth.cpp") add_files("co/detours/detours.cpp") add_files("co/detours/image.cpp") add_files("co/detours/modules.cpp") add_files("co/detours/disasm.cpp") if is_arch("x64") then add_files("co/context/context_x64.asm") else add_files("co/context/context_x86.asm") end else includes("check_cincludes.lua") check_cincludes("HAS_EXECINFO_H", "execinfo.h") add_files("co/context/context.S") end
-- I have little to no idea of what the hell I'm even doing to be honest local composer = require( "composer" ) composer.gotoScene( "game" )
----------------------------------------------------------------------------------------------------------------------------------------- -- GETHEALTH ----------------------------------------------------------------------------------------------------------------------------------------- function tvRP.getHealth() return GetEntityHealth(PlayerPedId()) end ----------------------------------------------------------------------------------------------------------------------------------------- -- SETHEALTH ----------------------------------------------------------------------------------------------------------------------------------------- function tvRP.setHealth(health) SetEntityHealth(PlayerPedId(),parseInt(health)) end ----------------------------------------------------------------------------------------------------------------------------------------- -- SETFRIENDLYFIRE ----------------------------------------------------------------------------------------------------------------------------------------- function tvRP.setFriendlyFire(flag) NetworkSetFriendlyFireOption(flag) SetCanAttackFriendly(PlayerPedId(),flag,flag) end ----------------------------------------------------------------------------------------------------------------------------------------- -- NOCAUTEVAR ----------------------------------------------------------------------------------------------------------------------------------------- local nocauteado = false local deathtimer = 600 local deathextratimer = 1800 local bodybag = nil ----------------------------------------------------------------------------------------------------------------------------------------- -- NOCAUTEADO ----------------------------------------------------------------------------------------------------------------------------------------- Citizen.CreateThread(function() while true do Citizen.Wait(5) local ped = PlayerPedId() if GetEntityHealth(ped) <= 101 and deathtimer >= 0 then local x,y,z = table.unpack(GetEntityCoords(ped)) if not nocauteado then NetworkResurrectLocalPlayer(x,y,z,GetEntityHeading(ped),true,false) deathtimer = 600 deathextratimer = deathtimer + 1800 nocauteado = true vRPserver._updateHealth(101) SetEntityHealth(ped,101) SetEntityInvincible(ped,true) if IsPedInAnyVehicle(ped) then TaskLeaveVehicle(ped,GetVehiclePedIsIn(ped),4160) end TriggerEvent("DLGames:tuneOff",true) TriggerServerEvent("vrp_inventory:Cancel") else if deathtimer > 0 then DrawText3Ds(x,y,z-0.5,"~r~"..deathtimer.." ~w~ML DE SANGUE, AGUARDE POR ATENDIMENTO MEDICO",340) else if deathextratimer > 0 then DrawText3Ds(x,y,z-0.5,"PRESSIONE ~g~E ~w~PARA ACEITAR SUA MORTE, VOCE TEM ~r~"..deathextratimer.." ~w~ML DE SANGUE",340) end end SetPedToRagdoll(ped,1000,1000,0,0,0,0) SetEntityHealth(ped,101) BlockWeaponWheelThisFrame() DisableControlAction(0,21,true) DisableControlAction(0,22,true) DisableControlAction(0,23,true) DisableControlAction(0,24,true) DisableControlAction(0,25,true) DisableControlAction(0,29,true) DisableControlAction(0,32,true) DisableControlAction(0,33,true) DisableControlAction(0,34,true) DisableControlAction(0,35,true) DisableControlAction(0,47,true) DisableControlAction(0,56,true) DisableControlAction(0,58,true) DisableControlAction(0,73,true) DisableControlAction(0,75,true) DisableControlAction(0,137,true) DisableControlAction(0,140,true) DisableControlAction(0,141,true) DisableControlAction(0,142,true) DisableControlAction(0,143,true) DisableControlAction(0,166,true) DisableControlAction(0,167,true) DisableControlAction(0,168,true) DisableControlAction(0,169,true) DisableControlAction(0,170,true) DisableControlAction(0,177,true) DisableControlAction(0,182,true) DisableControlAction(0,187,true) DisableControlAction(0,188,true) DisableControlAction(0,189,true) DisableControlAction(0,190,true) DisableControlAction(0,243,true) --DisableControlAction(0,245,true) DisableControlAction(0,257,true) DisableControlAction(0,263,true) DisableControlAction(0,264,true) DisableControlAction(0,268,true) DisableControlAction(0,269,true) DisableControlAction(0,270,true) DisableControlAction(0,271,true) DisableControlAction(0,288,true) DisableControlAction(0,289,true) DisableControlAction(0,311,true) DisableControlAction(0,344,true) --[[if not IsEntityPlayingAnim(ped,"missarmenian2","corpse_search_exit_ped",3) then tvRP.playAnim(false,{"missarmenian2","corpse_search_exit_ped"},true) end]] end end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- CHECK PED ARMOUR ----------------------------------------------------------------------------------------------------------------------------------------- Citizen.CreateThread(function() while true do Citizen.Wait(2000) local ped = PlayerPedId() if GetPedArmour(ped) < 1 then SetPedComponentVariation(ped,9,0,0,2) end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- BUTTONTIMER ----------------------------------------------------------------------------------------------------------------------------------------- Citizen.CreateThread(function() while true do Citizen.Wait(5) local ped = PlayerPedId() if GetEntityHealth(ped) <= 101 and deathtimer <= 0 then if deathextratimer <= 0 then tvRP.personDeath() TriggerEvent("resetBleeding") TriggerEvent("resetDiagnostic") TriggerServerEvent("clearInventory") deathtimer = 600 deathextratimer = 1800 nocauteado = false ClearPedBloodDamage(ped) SetEntityInvincible(ped,false) DoScreenFadeOut(1000) SetEntityHealth(ped,150) SetPedArmour(ped,0) Citizen.Wait(1000) SetEntityCoords(ped,-1038.68+0.0001,-2738.62+0.0001,13.82+0.0001,1,0,0,1) FreezeEntityPosition(ped,true) SetTimeout(5000,function() FreezeEntityPosition(ped,false) Citizen.Wait(1000) SetEntityVisible(ped,true,true) DoScreenFadeIn(1000) end) else if IsControlJustPressed(0,38) and IsInputDisabled(0) then tvRP.personDeath() TriggerEvent("resetBleeding") TriggerEvent("resetDiagnostic") TriggerServerEvent("clearInventory") deathtimer = 600 deathextratimer = 1800 nocauteado = false ClearPedBloodDamage(ped) SetEntityInvincible(ped,false) DoScreenFadeOut(1000) SetEntityHealth(ped,150) SetPedArmour(ped,0) Citizen.Wait(1000) SetEntityCoords(ped,-1038.68+0.0001,-2738.62+0.0001,13.82+0.0001,1,0,0,1) FreezeEntityPosition(ped,true) SetTimeout(5000,function() FreezeEntityPosition(ped,false) Citizen.Wait(1000) SetEntityVisible(ped,true,true) DoScreenFadeIn(1000) end) end end end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- HEALTHRECHARGE ----------------------------------------------------------------------------------------------------------------------------------------- Citizen.CreateThread(function() while true do Citizen.Wait(100) SetPlayerHealthRechargeMultiplier(PlayerId(),0) end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- DEATHTIMER ----------------------------------------------------------------------------------------------------------------------------------------- Citizen.CreateThread(function() while true do Citizen.Wait(1000) if nocauteado and deathtimer > 0 then deathtimer = deathtimer - 1 end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- DEATHEXTRATIMER ----------------------------------------------------------------------------------------------------------------------------------------- Citizen.CreateThread(function() while true do Citizen.Wait(1000) if nocauteado and deathextratimer > 0 then deathextratimer = deathextratimer - 1 end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- PERSON DEATH EVENT ----------------------------------------------------------------------------------------------------------------------------------------- RegisterNetEvent("personDeath") AddEventHandler("personDeath",function() if deathtimer > 0 or deathextratimer > 0 then deathtimer = 0 deathextratimer = 0 end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- RESET TIMER EVENT ----------------------------------------------------------------------------------------------------------------------------------------- RegisterNetEvent("resetTimer") AddEventHandler("resetTimer",function() if deathtimer > 0 then deathtimer = 600 else if deathextratimer > 0 then deathtimer = 600 end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- ISINCOMA ----------------------------------------------------------------------------------------------------------------------------------------- function tvRP.isInComa() return nocauteado end ----------------------------------------------------------------------------------------------------------------------------------------- -- NETWORKRESSURECTION ----------------------------------------------------------------------------------------------------------------------------------------- function tvRP.killGod() nocauteado = false local ped = PlayerPedId() local x,y,z = table.unpack(GetEntityCoords(ped)) NetworkResurrectLocalPlayer(x,y,z,GetEntityHeading(ped),true,false) ClearPedBloodDamage(ped) SetEntityInvincible(ped,false) SetEntityHealth(ped,110) ClearPedTasks(ped) ClearPedSecondaryTask(ped) end ----------------------------------------------------------------------------------------------------------------------------------------- -- NETWORKPRISON ----------------------------------------------------------------------------------------------------------------------------------------- function tvRP.PrisionGod() local ped = PlayerPedId() if GetEntityHealth(ped) <= 101 then nocauteado = false TriggerEvent("resetBleeding") TriggerEvent("resetDiagnostic") ClearPedBloodDamage(ped) SetEntityInvincible(ped,false) SetEntityHealth(ped,150) ClearPedTasks(ped) ClearPedSecondaryTask(ped) end end ----------------------------------------------------------------------------------------------------------------------------------------- -- PERSON DEATH ----------------------------------------------------------------------------------------------------------------------------------------- function tvRP.personDeath() RequestModel("xm_prop_body_bag") while not HasModelLoaded("xm_prop_body_bag") do Citizen.Wait(10) end local ped = PlayerPedId() local x,y,z = table.unpack(GetEntityCoords(ped)) bodybag = CreateObject(GetHashKey("xm_prop_body_bag"),x,y,z,true,true,true) PlaceObjectOnGroundProperly(bodybag) SetModelAsNoLongerNeeded(bodybag) Citizen.InvokeNative(0xAD738C3085FE7E11,bodybag,true,true) SetEntityAsNoLongerNeeded(bodybag) SetEntityVisible(ped,false,false) end ----------------------------------------------------------------------------------------------------------------------------------------- -- DRAWTEXT3D ----------------------------------------------------------------------------------------------------------------------------------------- function DrawText3Ds(x,y,z,text,size) local onScreen,_x,_y = World3dToScreen2d(x,y,z) SetTextFont(4) SetTextScale(0.35,0.35) SetTextColour(255,255,255,150) SetTextEntry("STRING") SetTextCentre(1) AddTextComponentString(text) DrawText(_x,_y) local factor = (string.len(text))/size DrawRect(_x,_y+0.0125,0.01+factor,0.03,0,0,0,80) end
local client_async = require "websocket.client_async" local log = require "nakama.util.log" local b64 = require "nakama.util.b64" local uri = require "nakama.util.uri" local json = require "nakama.util.json" local uuid = require "nakama.util.uuid" local b64_encode = b64.encode local b64_decode = b64.decode local uri_encode_component = uri.encode_component local uri_decode_component = uri.decode_component local uri_encode = uri.encode local uri_decode = uri.decode uuid.seed() local M = {} local function get_mac_address() local ifaddrs = sys.get_ifaddrs() for _,interface in ipairs(ifaddrs) do if interface.mac then return interface.mac end end return nil end function M.uuid() local mac = get_mac_address() if not mac then log("Unable to get hardware mac address for UUID") end return uuid(mac) end function M.http(config, url_path, query_params, method, post_data, callback) local query_string = "" if next(query_params) then for query_key,query_value in pairs(query_params) do if type(query_value) == "table" then for _,v in ipairs(query_value) do query_string = ("%s%s%s=%s"):format(query_string, (#query_string == 0 and "?" or "&"), query_key, uri_encode_component(tostring(v))) end else query_string = ("%s%s%s=%s"):format(query_string, (#query_string == 0 and "?" or "&"), query_key, uri_encode_component(tostring(query_value))) end end end local url = ("%s%s%s"):format(config.http_uri, url_path, query_string) local headers = {} headers["Accept"] = "application/json" headers["Content-Type"] = "application/json" if config.bearer_token then headers["Authorization"] = ("Bearer %s"):format(config.bearer_token) elseif config.username then local credentials = b64_encode(config.username .. ":" .. config.password) headers["Authorization"] = ("Basic %s"):format(credentials) end local options = { timeout = config.timeout } log("HTTP", method, url) log("DATA", post_data) http.request(url, method, function(self, id, result) if result.response then log(result.response) result.response = json.decode(result.response) end callback(result.response) end, headers, post_data, options) end function M.socket_create(config, on_message) assert(config, "You must provide a config") assert(on_message, "You must provide a message handler") local socket = {} socket.config = config socket.scheme = config.use_ssl and "wss" or "ws" socket.cid = 0 socket.requests = {} socket.ws = client_async({ connect_timeout = config.timeout, -- optional timeout (in seconds) when connecting }) socket.timer_handle = timer.delay(0.1, true, function(self, handle, time_elapsed) socket.ws:step() end) socket.ws:on_disconnected(function() log("Disconnected") if socket.on_disconnect then socket.on_disconnect() end end) socket.ws:on_message(function(message) log("Received message", message) message = json.decode(message) if not message.cid then on_message(socket, message) return end local callback = socket.requests[message.cid] if not callback then log("Unable to find callback for cid", message.cid) return end socket.requests[message.cid] = nil callback(message) end) return socket end function M.socket_connect(socket, callback) assert(socket) assert(callback) assert(socket and socket.ws, "You must provide a socket") local url = ("%s://%s:%d/ws?token=%s"):format(socket.scheme, socket.config.host, socket.config.port, uri.encode_component(socket.config.bearer_token)) --const url = `${scheme}${this.host}:${this.port}/ws?lang=en&status=${encodeURIComponent(createStatus.toString())}&token=${encodeURIComponent(session.token)}`; log(url) socket.ws:on_connected(function(ok, err) callback(ok, err) end) socket.ws:connect(url) end function M.socket_send(socket, message, callback) assert(socket and socket.ws, "You must provide a socket") assert(message, "You must provide a message to send") socket.cid = socket.cid + 1 message.cid = tostring(socket.cid) socket.requests[message.cid] = callback local data = json.encode(message) -- Fix encoding of match_create_message to send {} instead of [] if message.match_create ~= nil then data = string.gsub(data, "%[%]", "{}") end socket.ws:send(data) end return M
--[[============================================================================= # FileName: util.lua # Desc: 工具函数 # Author: hanxi # Email: hanxi.com@gmail.com # HomePage: http://hanxi.cnblogs.com # Version: 0.0.1 # LastChange: 2013-08-22 10:09:03 # History: =============================================================================]] require("HXUtil") --require("Deprecated") require("AudioEngine")
local Alignment = {} local triggers = {} local function setup(args) local tempTriggers = {} tempTriggers.Alignment = tempRegexTrigger("^(?:> )?You (\\w+) believe in (\\w+)\\." ,[[ local conviction = matches[2] local alignment = matches[3] local arguments = {conviction = conviction ,alignment = alignment} Events.raiseEvent("alignmentEvent", arguments) ]]) triggers = tempTriggers end local function unsetup(args) for i,v in pairs(triggers) do killTrigger(v) end triggers = {} end local function resetup(args) unsetup(args) setup(args) end Alignment = { setup = setup ,unsetup = unsetup ,resetup = resetup } return Alignment
local t = require "tests.luaunit" -- XML module tests local X = require "openLuup.xml" local N = 0 -- total test count local D = [[ <?xml version="1.0"?> <root xmlns="urn:schemas-upnp-org:device-1-0"> <specVersion> <major>1</major> <minor>0</minor> </specVersion> <device> <deviceType>urn:schemas-upnp-org:device:altui:1</deviceType> <staticJson>D_ALTUI.json</staticJson> <friendlyName>ALTUI</friendlyName> <manufacturer>Amg0</manufacturer> <manufacturerURL>http://www.google.fr/</manufacturerURL> <modelDescription>AltUI for Vera UI7</modelDescription> <modelName>AltUI for Vera UI7</modelName> <modelNumber>1</modelNumber> <protocol>cr</protocol> <handleChildren>0</handleChildren> <serviceList> <service> <serviceType>urn:schemas-upnp-org:service:altui:1</serviceType> <serviceId>urn:upnp-org:serviceId:altui1</serviceId> <controlURL>/upnp/control/ALTUI1</controlURL> <eventSubURL>/upnp/event/ALTUI1</eventSubURL> <SCPDURL>S_ALTUI.xml</SCPDURL> </service> </serviceList> <implementationList> <implementationFile>I_ALTUI.xml</implementationFile> </implementationList> </device> </root> ]] local I = [[ <?xml version="1.0"?> <implementation> <functions> </functions> <files>L_ALTUI.lua</files> <startup>initstatus</startup> <actionList> <action> <serviceId>urn:upnp-org:serviceId:altui1</serviceId> <name>SetDebug</name> <run> setDebugMode(lul_device,lul_settings.newDebugMode) </run> </action> <action> <serviceId>urn:upnp-org:serviceId:altui1</serviceId> <name>Reset</name> <run> resetDevice(lul_device,true) </run> </action> </actionList> </implementation> ]] --- XML decode validity tests local function invalid (x, y) N = N + 1 local lua, msg = X.decode (x) t.assertIsNil (lua) t.assertEquals (msg, y) end local function valid (x, v) N = N + 1 local lua, msg = X.decode (x) t.assertEquals (lua, v) t.assertIsNil (msg) end -- INVALID TestDecodeInvalid = {} function TestDecodeInvalid:test_decode () -- invalid code just returns the original string as error message invalid ("rubbish", "rubbish") invalid ("<foo", "<foo") invalid ("<foo></bung>", "<foo></bung>") end -- VALID TestDecodeValid = {} function TestDecodeValid:test_decode () valid ('<foo a="b">garp</foo>', {foo="garp"}) valid ([[ <foo> <garp>bung1</garp> <garp>bung2</garp> </foo> ]], {foo={garp= {"bung1","bung2"}}}) valid ('<a>&lt;&gt;&quot;&apos;&amp;</a>', {a = [[<>"'&]]}) end --- XML encode validity tests local function invalid (x) N = N + 1 local lua, msg = X.encode (x) t.assertFalse (lua) t.assertIsString (msg) end local function valid (lua, v) N = N + 1 local xml, msg = X.encode (lua) t.assertIsString (xml) t.assertEquals (xml:gsub ("%s+", ' '), v) t.assertIsNil (msg) end -- INVALID TestEncodeInvalid = {} function TestEncodeInvalid:test_encode () invalid "a string" invalid (42) invalid (true) invalid (function() end) invalid {"hello"} end -- VALID TestEncodeValid = {} --function TestEncodeValid:test_literals () -- valid (true, "true") -- valid (false, "false") -- valid (nil, 'null') --end function TestEncodeValid:test_numerics () local Inf = "8.88e888" valid ({number = 42}, " <number>42</number> ") end function TestEncodeValid:test_strings () valid ({string="easy"}, " <string>easy</string> ") valid ({ctrl="\n"}, " <ctrl> </ctrl> ") -- need to check the special conversion characters valid ({UTF8= "1234 UTF-8 ß$¢€"}, " <UTF8>1234 UTF-8 ß$¢€</UTF8> ") end function TestEncodeValid:test_tables () -- valid ({1, nil, 3}, '[1,null,3]') -- next is tricky because of sorting and pretty printing -- valid ({ array = {1,2,3}, string = "is a str", num = 42, boolean = true}, -- '{"array":[1,2,3],"string":"is a str","num":42,"boolean":true}') end -- Longer round-trip file tests local function round_trip_ok (x) local lua1, msg = X.decode (x) t.assertIsTable (lua1) t.assertIsNil (msg) local x2,msg2 = X.encode (lua1) -- not equal to x, necessary, because of formatting and sorting t.assertIsString (x2) t.assertIsNil (msg) local lua2, msg3 = X.decode (x2) -- ...so go round once again t.assertIsTable (lua2) t.assertIsNil (msg3) local x3,msg4 = X.encode (lua2) t.assertIsString (x3) t.assertIsNil (msg4) t.assertEquals (x3, x2) -- should be the same this time around end TestEncodeDecode = {} function TestEncodeDecode:test_round_trip () round_trip_ok (I) round_trip_ok (D) round_trip_ok "<a>&lt;&gt;&quot;&apos;&amp;</a>" end ------------------- if multifile then return end t.LuaUnit.run "-v" print ("TOTAL number of tests run = ", N) ------------------- -- visual round-trip test print "----- encode(decode(...)) -----" print "Round-trip XML:" print ((X.encode(X.decode(I)))) print "-----------" local a = [[<>"'&]] local b = X.encode {a = a} local c = X.decode (b) print (a) print (b) print (c.a) print 'done'
function init() connect(g_game, {onGameStart = online, onGameEnd = offline}) if g_game.isOnline() then online() end end function terminate() disconnect(g_game, {onGameStart = online, onGameEnd = offline}) offline() end function online() g_keyboard.bindKeyDown('Ctrl+R', toggleMount) end function offline() g_keyboard.unbindKeyDown('Ctrl+R') end function toggleMount() local player = g_game.getLocalPlayer() if player then player:toggleMount() end end function mount() local player = g_game.getLocalPlayer() if player then player:mount() end end function dismount() local player = g_game.getLocalPlayer() if player then player:dismount() end end
--[[ This module defines all AST shapes. It also servers as a documentation for AST nodes schemas. These shapes are used for shape checking in tests and when manually creating AST nodes. ]] local aster = require 'nelua.aster' local shaper = aster.shaper -- Block containing a list of statements. aster.register('Block', shaper.array_of(shaper.Node)) -- Number literal. aster.register('Number', { shaper.string + shaper.number, -- value shaper.string + shaper.falsy, -- literal type }) -- String literal. aster.register('String', { shaper.string, -- value shaper.string + shaper.falsy, -- literal type }) -- Boolean literal, (e.g `true` and `false`). aster.register('Boolean', { shaper.boolean -- true or false }) -- Nil literal, (e.g `nil`). aster.register('Nil', {}) -- Variable arguments literal, (e.g `...`). aster.register('Varargs', {}) -- List of statements that evaluates to an expression. aster.register('DoExpr', { shaper.Block -- statements block }) -- Preprocess code to be executed and removed. aster.register('Preprocess', { shaper.string -- code }) -- Preprocess expression to be replaced by an ASTNode containing an expression. aster.register('PreprocessExpr', { shaper.string -- code }) -- Preprocess expression to be replaced by a string containing a name. aster.register('PreprocessName', { shaper.string -- code }) local name = shaper.string + shaper.PreprocessName -- Initializer list pair field. aster.register('Pair', { shaper.Node + name, -- field name or expr shaper.Node, -- value expr }) -- Initializer list (e.g `{}`), used for initialing tables, records and arrays. aster.register('InitList', shaper.array_of(shaper.Pair + shaper.Node)) -- pair or exprs -- Indexing with `.`. aster.register('DotIndex', { name, -- name shaper.Node, -- expr }) -- Indexing with `:`. aster.register('ColonIndex', { name, -- name shaper.Node, -- expr }) -- Indexing with brackets (e.g `[key]`). aster.register('KeyIndex', { shaper.Node, -- key expr shaper.Node, -- expr }) -- Annotation used in a variable, type or function declaration. aster.register('Annotation', { name, -- name shaper.array_of(shaper.Node) + shaper.falsy, -- annotation arguments }) -- Identifier. aster.register('Id', { name -- name }) -- Identifier declaration. aster.register('IdDecl', { name + shaper.DotIndex, -- name shaper.Node + shaper.falsy, -- type expr shaper.array_of(shaper.Annotation) + shaper.falsy, -- annotations }) -- Expression surround by parenthesis (e.g `(expr)`) aster.register('Paren', { shaper.Node -- expr }) -- Type expression (e.g `@typeexpr`). aster.register('Type', { shaper.Node -- type expr }) -- Variable arguments type, used in function declaration arguments only. aster.register('VarargsType', { shaper.one_of{"varautos", "varanys", "cvarargs"} + shaper.falsy }) -- Function type. aster.register('FuncType', { shaper.array_of(shaper.Node), -- arguments types shaper.array_of(shaper.Node) + shaper.falsy, -- returns types }) -- Record field. aster.register('RecordField', { name, -- name shaper.Node, -- type expr }) -- Record type. aster.register('RecordType', shaper.array_of(shaper.RecordField)) -- fields -- Union field. aster.register('UnionField', { name + shaper.falsy, -- name shaper.Node, -- type expr }) -- Union type. aster.register('UnionType', shaper.array_of(shaper.UnionField)) -- fields -- Variant type. aster.register('VariantType', shaper.array_of(shaper.Node)) -- types exprs -- Enum field. aster.register('EnumField', { name, -- name shaper.Node + shaper.falsy, -- value expr }) -- Enum type. aster.register('EnumType', { shaper.Node + shaper.falsy, -- primitive type expr shaper.array_of(shaper.EnumField), -- field types }) -- Array type. aster.register('ArrayType', { shaper.Node, -- subtype type expr shaper.Node + shaper.falsy, -- size expr }) -- Pointer type. aster.register('PointerType', { shaper.Node + shaper.falsy, -- subtype type expr }) -- Optional type. aster.register('OptionalType', { shaper.Node -- subtype type expr }) -- Generic type. aster.register('GenericType', { shaper.Id + shaper.DotIndex, -- name shaper.array_of(shaper.Node), -- arguments (type expr or expr) }) -- Anonymous function (function without a name). aster.register('Function', { shaper.array_of(shaper.IdDecl + shaper.VarargsType), -- typed arguments shaper.array_of(shaper.Node) + shaper.falsy, -- typed returns shaper.array_of(shaper.Annotation) + shaper.falsy, shaper.Node, -- block }) -- Call. aster.register('Call', { shaper.array_of(shaper.Node), -- arguments exprs shaper.Node, -- caller expr }) -- Call a method. aster.register('CallMethod', { name, -- method name shaper.array_of(shaper.Node), -- arguments exprs shaper.Node, -- caller expr }) -- Unary operator. aster.register('UnaryOp', { shaper.one_of{"not", "unm", "len", "bnot", "ref", "deref"}, -- op name shaper.Node, -- right expr }) -- Binary operator. aster.register('BinaryOp', { shaper.Node, --- left expr shaper.one_of{"or", "and", "eq", "ne", "le", "lt", "ge", "gt", "bor", "bxor", "band", "shl", "shr", "asr", "concat", "add", "sub", "mul", "div", "idiv", "tdiv", "mod", "tmod", "pow"}, -- op name shaper.Node, -- right expr }) -- Return statement. aster.register('Return', shaper.array_of(shaper.Node)) -- returned exprs -- If statement. aster.register('If', { shaper.array_of(shaper.Node + shaper.Block), -- ifs (expr followed by block) shaper.Block + shaper.falsy, -- else block }) -- Switch statement. aster.register('Switch', { shaper.Node, -- switch expr shaper.array_of(shaper.array_of(shaper.Node) + shaper.Block), -- cases (exprs followed by block} shaper.Block + shaper.falsy, -- else block }) -- Do statement. aster.register('Do', { shaper.Block, -- statements block }) -- Defer statement. aster.register('Defer', { shaper.Block -- statements block }) -- While statement. aster.register('While', { shaper.Node, -- expr shaper.Block, -- statements block }) -- Repeat statement. aster.register('Repeat', { shaper.Block, -- statements block shaper.Node, -- expr }) -- Numeric for statement. aster.register('ForNum', { shaper.IdDecl, -- iterated var shaper.Node, -- begin expr shaper.one_of{"eq", "ne", "le", "lt", "ge", "gt"} + shaper.falsy, -- compare operator shaper.Node, -- end expr shaper.Node + shaper.falsy, -- increment expr shaper.Block, -- block }) -- For in statement. aster.register('ForIn', { shaper.array_of(shaper.IdDecl), -- iteration vars shaper.array_of(shaper.Node), -- in exprs shaper.Block, -- statements block }) -- Break statement. aster.register('Break', {}) -- Continue statement. aster.register('Continue', {}) -- Label statement. aster.register('Label', { name, -- label name }) -- Goto statement. aster.register('Goto', { name, -- label name }) -- Variable declaration statement. aster.register('VarDecl', { shaper.one_of{"local","global"}, -- scope shaper.array_of(shaper.IdDecl), -- var names with types shaper.array_of(shaper.Node) + shaper.falsy, -- exprs of initial values }) -- Variable assignment statement. aster.register('Assign', { shaper.array_of(shaper.Node), -- var exprs shaper.array_of(shaper.Node), -- values exprs }) -- Function definition statement. aster.register('FuncDef', { shaper.one_of{"local","global"} + shaper.falsy, -- scope shaper.IdDecl + shaper.Id + shaper.DotIndex + shaper.ColonIndex, -- name shaper.array_of(shaper.IdDecl + shaper.VarargsType), -- typed arguments shaper.array_of(shaper.Node) + shaper.falsy, -- typed returns shaper.array_of(shaper.Annotation) + shaper.falsy, shaper.Block, -- statements block }) -- This is used only internally. aster.register('PragmaCall', { shaper.string, -- name shaper.table, -- arguments exprs })
-- We write save data to the general purpose buffer, until a save platform -- is triggered. -- DEBUG_BEGIN g_debug = false -- DEBUG_END g_card_fade = 8 poke(0x5f5c, 15) -- set the initial delay before repeating. poke(0x5f5d, 15) -- set the repeating delay. function _init() music(0, 3000) g_tl = ztable([[ x=64, y=64, i=@2, u=nf, d=@1, tl_max_time=2.5; -- logo i=@3, u=@4, d=@5; -- game ]], logo_draw, function() sfx'63' end, game_init, game_update, game_draw ) end function game_init(a) batch_call_new(acts_loop, [[ confined,room_end; confined,kill; confined,delete ]]) for x=-16, 40, 8 do _g.cloud(x) end _g.fader_in(.5, nf, nf) g_cur_room = tabcpy(ztable[[ x:-16; y:0; w:48; h:16; ]]) g_pl = _g.pl(8, 10) _g.texter(8, 11.5) g_main_view = _g.view(16, 16, 3, g_pl) g_main_view:center_view() end function game_update(a) if t() % 4 == 0 then _g.cloud(-24) end batch_call_new( acts_loop, [[ act,update; drawable_obj,reset_off; mov,move; pl,move_check,@1; tcol,coll_tile,@2; rel,rel_update; vec,vec_update; kill_too_high,check_height; bounded,check_bounds; anim,anim_update; timed,tick; view,update_view; ]], g_act_arrs['col'], function(x, y) return x >= g_cur_room.x and x < g_cur_room.x+g_cur_room.w and y >= g_cur_room.y and y < g_cur_room.y+g_cur_room.h and fget(mget(x, y), 6) end ) batch_call_new(acts_loop, [[act, clean]]) end function cycle(period) return time()%period/period end function game_draw(a) fade(g_card_fade) map_draw(g_main_view, 8, 8) end function logo_draw(a) local logo_opacity = 8+cos(a.tl_tim/a.tl_max_time)*4-4 fade(logo_opacity) camera(logo_opacity > 1 and rnd_one()) zspr(108, a.x, a.y, 4, 2) fade'0' camera() end function _update60() -- DEBUG_BEGIN if g_debug then poke(0x5f42,15) -- glitch sound else poke(0x5f42,0) -- no glitch sound end -- DEBUG_END -- DEBUG_BEGIN if btnp'5' and btn'4' then g_debug = not g_debug end -- DEBUG_END tl_node(g_tl) end function _draw() cls() -- DEBUG_BEGIN if g_debug then rect(0,0,127,127,8) end -- DEBUG_END call_not_nil(g_tl, 'd', g_tl) end -- CAMERA STUFF function shiftx(view) return (view.x-view.off_x-8)*8 end function shifty(view) return (view.y-view.off_y-8)*8 end function camera_to_view(view) camera(shiftx(view), shifty(view)) end function map_draw(view, x, y) if view then local rx = x - view.w/2 local ry = y - view.h/2 view.off_x = -(16-view.w)/2+rx view.off_y = -(16-view.h)/2+ry local x1, x2 = rx*8+4, (rx+view.w)*8-5 local y1, y2 = ry*8+4, (ry+view.h)*8-5 camera_to_view(view) zclip(x1, y1, x2, y2) zcls(g_cur_room.c) scr_map(48, 1, g_cur_room.x, g_cur_room.y, g_cur_room.w, g_cur_room.h) scr_map(g_cur_room.x, g_cur_room.y, g_cur_room.x, g_cur_room.y, g_cur_room.w, g_cur_room.h) batch_call_new(acts_loop, [[ pre_drawable, d; pre_drawable_1, d; pre_drawable_2, d; ]]) isorty(g_act_arrs.drawable) batch_call_new(acts_loop, [[ drawable, d; drawable_1, d; drawable_2, d; post_drawable, d; post_drawable_1, d; post_drawable_2, d; ]]) local tr_water = 115 for x=-128,128+128,4 do local function wave(a, p) return a+a*sin(x/64+cycle(4)+p) end rectfill(x,tr_water-wave(2+sin(cycle(2)),0),x+3,tr_water,1) rectfill(x,tr_water-wave(2+sin(cycle(4)),0.2+0.1*sin(cycle(6))),x+3,tr_water,12) end rectfill(-128, tr_water, 128*3, 128, 12) -- DEBUG_BEGIN if g_debug then acts_loop('dim', 'debug_rect') end -- DEBUG_END clip() camera() -- zrect(x1, y1, x2, y2) -- DEBUG_BEGIN if g_debug then -- rect(g_cur_room.x, g_cur_room.y, 20, 20, 8) end -- DEBUG_END end end
local games = require("Games") local misc = require("Misc") local mafia = {} local jester3, chicagoPD, jungle local known_setups = "Jester3 (!start Mafia Jester3)\nChicago PD (!start Mafia Chicago)\nJungle of Bullshit (!start Mafia Jungle)\nWin Lose Banana (!start Mafia Banana)" --############################################################################################################################################# --# Main Functions # --############################################################################################################################################# function mafia.startGame(message) local players = misc.shuffleTable(misc.indexifyTable(misc.shallowCopy(message.mentionedUsers))) local args = message.content:split(" ") args[3] = string.lower(args[3]) if args[3] == "jester3" then jester3(message.channel, players) elseif args[3] == "chicago" then chicagoPD(message.channel, players) elseif args[3] == "jungle" then jungle(message.channel, players) elseif args[3] == "banana" then banana(message.channel, players) else message.channel:send("I don't know that setup, homie!\nKnown setups:\n" .. known_setups) end end function mafia.commandHandler(message, state) end function mafia.dmHandler(message, state) end --############################################################################################################################################# --# Game Functions # --############################################################################################################################################# function banana(channel, players) if #players ~= 3 then channel:send("Win Lose Banana takes exactly 3 players!") return end players[1]:send("You are the Banana! 🍌") players[2]:send("You are the Loser! 😖") channel:send(players[3].name .. " is the Winner! Try to pick the Banana!") end function jungle(channel, players) if #players < 5 then channel:send("Jungle of Bullshit takes at least 5 players!") return end local scumlist = "" for idx,player in pairs(players) do if idx > 2 then scumlist = scumlist .. ", " .. player.name end end scumlist = scumlist:sub(3) for idx,player in pairs(players) do if idx == 1 or idx == 2 then player:send("You are a **Townie**! You win when all mafiosi are dead.\nIf you get lynched on Day 1, you are not killed and instead kill all but two other players.") else player:send("You are a **Mafia Goon**! You win if a townie is lynched on Day 2, or if nothing can stop this from happening.\nIf you get lynched on Day 1, you must confirm one townie as being town, and kill all but one of your fellow mafiosi.") player:send("Your fellow scum are: " .. scumlist) end end end function jester3(channel, players) if #players ~= 3 then channel:send("Jester3 takes exactly 3 players!") return end local roles = misc.shuffleTable({"Vanilla Townie", "Mayor", "Super Saint", "Oracle", "Jester"}) local descs = { ["Mafia Goon"] = "You are a **Mafia Goon**! You win if a townie is lynched.", ["Vanilla Townie"] = "You are a **Vanilla Townie**! You win if the Mafia Goon is lynched.", ["Mayor"] = "You are a **Mayor**! You win if the Mafia Goon is lynched. You can reveal yourself as Mayor; if you've been revealed, your vote instantly lynches the player it's on.", ["Super Saint"] = "You are a **Super Saint**! You win if the Mafia Goon is lynched. If you're lynched, the last player to vote for you is lynched instead.", ["Oracle"] = "You are an **Oracle**! You win if the Mafia Goon is lynched. You get to see one role that isn't in the game.", ["Jester"] = "You are a **Jester**! You win (and everyone else loses) if you're lynched." } local jesterRule = "\nIf there's a Jester, and the other two players vote for each other, both players win and the Jester loses." local oracleText = "**There is no " .. roles[3] .. " in this game.**" players[1]:send(descs["Mafia Goon"] .. jesterRule) players[2]:send(descs[roles[1]] .. jesterRule) players[3]:send(descs[roles[2]] .. jesterRule) if roles[1] == "Oracle" then players[2]:send(oracleText) elseif roles[2] == "Oracle" then players[3]:send(oracleText) end end function chicagoPD(channel, players) if #players ~= 4 then channel:send("Chicago PD takes exactly 3 players!") return end local roles = misc.shuffleTable({"Secret Agent", "Cop", "Cop", "Goon", "Gunner", "Dealer"}) local descs = { ["Police Chief"] = "You are the **Police Chief**, aligned with the police.", ["Secret Agent"] = "You are a **Secret Agent**, aligned with the police. You can reveal yourself as Secret Agent; if you've been revealed, your vote instantly lynches the player it's on, and other players cannot vote.", ["Cop"] = "You are a **Cop**, aligned with the police.", ["Goon"] = "You are a **Goon**, aligned with the mafia.", ["Gunner"] = "You are a **Gunner**, aligned with the mafia. With a Gunner in the game, players are lynched with only two votes instead of three; **you must reveal yourself when this happens!**", ["Dealer"] = "You are a **Dealer**, aligned with the mafia. If there's a Goon/Gunner and a Cop in the game, the Cop is aligned with the mafia (but is not informed of this)." } players[1]:send(descs["Police Chief"]) players[2]:send(descs[roles[1]]) players[2]:send(descs[roles[2]]) players[2]:send(descs[roles[3]]) end return mafia
--local DEBUG = true local g_DbgPerfData = {} if ( DEBUG ) then function DbgPrint ( fmt, ... ) outputDebugString ( fmt:format ( ... ), 3 ) end function DbgDump ( str, title ) local bytes = { str:byte ( 1, str:len () ) } local buf = ""; for i, byte in ipairs ( bytes ) do buf = buf..( " %02X" ):format ( byte ) end DbgPrint ( ( title or "dump" )..":"..buf ) end function DbgPerfInit ( channel ) g_DbgPerfData[channel or 1] = getTickCount () end function DbgPerfCp ( title, channel, ... ) local dt = getTickCount () - g_DbgPerfData[channel or 1] local args = { ... } args[#args + 1] = dt --DbgPrint ( title.." has taken %u ms", unpack ( args ) ) g_DbgPerfData[channel or 1] = getTickCount () end else local function DbgDummy () end DbgPrint = DbgDummy DbgDump = DbgDummy DbgPerfInit = DbgDummy DbgPerfCp = DbgDummy end
class("S1mple_Timer") function S1mple_Timer:__init() self.clocks = {} AddTickCallback(function () self:updateClocks() end) end function S1mple_Timer:updateClocks() for i,v in pairs(self.clocks) do if v and GetGameTimer() > v.t then if v.r > 0 then self.clocks[i].r = v.r-1 v.c() self.clocks[i].t = v.t+v.i else self.clocks[i] = nil end end end end function S1mple_Timer:AddTimer(time,callback,reoccuring,interval) if time and callback then self.clocks[#self.clocks+1] = {t = time+GetGameTimer(),c = callback, r = reoccuring and reoccuring or 1,i = interval or 1} end end
require "android" android.makeToast("Hello, Android!")
local util = require 'util' local lovetoys = require 'lovetoys.lovetoys' local rot = require 'rot' local Component = lovetoys.Component.create('Actor') function Component:initialize(speed) self.speed = speed or 100 self.eventQueue = rot.EventQueue() self.added = false end function Component:getSpeed() return self.speed end function Component:repeating() return true end function Component:delay() return nil end function Component:update(entity) end function Component:clear() self.eventQueue:clear() end function Component:schedule(action, time) self.eventQueue:add(action, time or 100) end function Component:reschedule(action, time) if action then self.eventQueue:remove(action) self:schedule(action, time) end end function Component:act() local result local action = self.eventQueue:get() if type(action) == 'function' then result = action(self) end return result end return Component
for i,v in pairs(game.Players:GetPlayers()) do if v.Participating.Value == true then i = Instance.new("IntValue", script.Parent) i.Name = "Punching_" ..v.Name.. "" script.TaskGUI:Clone().Parent = v.PlayerGui scriptclone = script.PressedScript:Clone() scriptclone.Parent = v.PlayerGui cameragiverclone = script.CameraGive:Clone() cameragiverclone.Parent = v.PlayerGui cameragiverclone.Disabled = false end end m = Instance.new("Message", game.Workspace) m.Text = "The screen will show a bar that is constantly moving!" wait(3) m.Text = "Press the space bar to punch!" wait(3) m.Text = "The more power you punch with, the more score you get!" wait(3) m.Text = "If you punch with more power, there will be less wait time until your next punch!" wait(3) m.Text = "If you punch with maximum power, an addition 50 points will be awarded!" wait(3) m.Text = "You have 60 seconds to score as many points as possible!" wait(3) m.Text = "The player with the most amount of 60 seconds wins!" wait(3) m:Destroy() h = Instance.new("Hint", game.Workspace) for i = 5, 1, -1 do h.Text = "The minigame begins in " ..i.. " seconds..." wait(1) end for i,v in pairs(game.Players:GetPlayers()) do if v.Participating.Value == true then if v.PlayerGui:findFirstChild("PressedScript") then v.PlayerGui:findFirstChild("PressedScript").Disabled = false end end end h.Text = "Begin!" script.Parent.Playing.Value = true wait(4) for i = 60, 1, -1 do h.Text = "There are " ..i.. " seconds left in the minigame." wait(1) end h:Destroy() m = Instance.new("Message", game.Workspace) m.Text = "Stop!" for i,v in pairs(game.Players:GetPlayers()) do if v.Participating.Value == true then if v.PlayerGui:findFirstChild("PressedScript") then v.PlayerGui:findFirstChild("PressedScript"):Destroy() end end end wait(2) m:Destroy() for i,v in pairs(game.Players:GetPlayers()) do if v.Participating.Value == true then if v.PlayerGui:findFirstChild("TaskGUI") then v.PlayerGui:findFirstChild("TaskGUI"):Destroy() end end end currentwinners = {} highestscore = 0 winnernumber = 1 for i,v in pairs(script.Parent:GetChildren()) do if string.sub(v.Name, 1, 9) == "Punching_" then playername = string.sub(v.Name, 10) if game.Players[playername] then if v.Value == highestscore then s = Instance.new("StringValue", script.Parent) s.Name = "Winner" ..winnernumber.. "" s.Value = playername winnernumber = winnernumber + 1 elseif v.Value > highestscore then winnernumber = 1 for i,v in pairs(script.Parent:GetChildren()) do if string.sub(v.Name, 1, 6) == "Winner" then v:Destroy() end end s = Instance.new("StringValue", script.Parent) s.Name = "Winner" ..winnernumber.. "" s.Value = playername winnernumber = winnernumber + 1 highestscore = v.Value end end end end for i,v in pairs(game.Players:GetPlayers()) do if v.Participating.Value == true then v:LoadCharacter() end end for i,v in pairs(game.Players:GetPlayers()) do if v.Participating.Value == true then camerarestoreclone = script.CameraRestore:Clone() camerarestoreclone.Parent = v.PlayerGui camerarestoreclone.Disabled = false end end script.Disabled = true
-- can be used for both /proc/cmdline, and /proc/[pid]/cmdline local sutil= require("lj2procfs.string-util") local function decoder(path) -- open the file -- return full contents as a string local f = io.open(path) local str = f:read("*a") local tbl = {} -- can possibly be a string of '\0' delimited values for _, str in sutil.mstrziter(str) do table.insert(tbl,str) end return tbl; end return { decoder = decoder; }
local Plugin = script.Parent.Parent.Parent.Parent local Libs = Plugin.Libs local Roact = require(Libs.Roact) local Utility = require(Plugin.Core.Util.Utility) local Constants = require(Plugin.Core.Util.Constants) local ContextGetter = require(Plugin.Core.Util.ContextGetter) local ContextHelper = require(Plugin.Core.Util.ContextHelper) local withTheme = ContextHelper.withTheme local withModal = ContextHelper.withModal local getModal = ContextGetter.getModal local Components = Plugin.Core.Components local Foundation = Components.Foundation local BorderedFrame = require(Foundation.BorderedFrame) local VerticalList = require(Foundation.VerticalList) local PreciseButton = require(Foundation.PreciseButton) local RoundedBorderedFrame = require(Foundation.RoundedBorderedFrame) local LabeledFieldTemplate = require(Foundation.LabeledFieldTemplate) local ColorSelector = Roact.PureComponent:extend("ColorSelector") local ColorSlider do local DraggerButton = Roact.PureComponent:extend("DraggerButton") function DraggerButton:init() self:setState( { isHovered = false, isPressed = false } ) self.onMouseButton1Down = function(rbx, x, y) local dragBegan = self.props.dragBegan local modal = getModal(self) if dragBegan then dragBegan(x, y) end self:setState( { isPressed = true } ) modal.onButtonPressed(self) end self.onInputEnded = function(rbx, inputObject) local modal = getModal(self) if self.state.isPressed and inputObject.UserInputType == Enum.UserInputType.MouseButton1 then -- I can't do this after onClick for some reason... self:setState( { isPressed = false } ) local disabled = self.props.disabled local dragEnded = self.props.dragEnded if (not disabled and not (modal.isShowingModal(self.props.modalIndex)) or (modal.isAnyButtonPressed() and not modal.isButtonPressed(self))) then if dragEnded then dragEnded(inputObject.Position.X, inputObject.Position.Y) end end modal.onButtonReleased() end end self.onMouseEnterDragButton = function() if not self.state.isHovered then self:setState( { isHovered = true } ) end end self.onMouseLeaveDragButton = function() if self.state.isHovered then self:setState( { isHovered = false } ) end end self.onMouseButton1DownDragButton = function(rbx, x, y) local modal = getModal(self) if not self.state.isPressed and not (modal.isShowingModal(self.props.modalIndex) or (modal.isAnyButtonPressed() and not modal.isButtonPressed(self))) then local dragBegan = self.props.dragBegan if dragBegan then dragBegan(x, y) end self:setState( { isPressed = true } ) modal.onButtonPressed(self) end end self.onInputEndedDragButton = function(rbx, inputObject) local modal = getModal(self) if self.state.isPressed and inputObject.UserInputType == Enum.UserInputType.MouseButton1 then -- I can't do this after onClick for some reason... self:setState( { isPressed = false } ) local disabled = self.props.disabled local dragEnded = self.props.dragEnded if (not disabled and not (modal.isShowingModal(self.props.modalIndex)) or (modal.isAnyButtonPressed() and not modal.isButtonPressed(self))) then if dragEnded then dragEnded(inputObject.Position.X, inputObject.Position.Y) end end modal.onButtonReleased() end end self.onMouseMovedPortalDetector = function(rbx, x, y) local dragMoved = self.props.dragMoved if dragMoved then dragMoved(x, y) end end end DraggerButton.defaultProps = { Position = UDim2.new(0, 0, 0, 0), Size = UDim2.new(0, 100, 0, 100), Font = Constants.FONT, checked = false } function DraggerButton:render() local props = self.props local Position = props.Position local isPressed = self.state.isPressed local AnchorPoint = props.AnchorPoint local Size = props.Size local ZIndex = props.ZIndex local percent = props.percent return withTheme( function(theme) return Roact.createElement( "TextButton", { Text = "", ZIndex = ZIndex, BackgroundTransparency = 1, Size = Size, Position = Position, AnchorPoint = AnchorPoint, [Roact.Event.MouseButton1Down] = self.onMouseButton1Down, [Roact.Event.InputEnded] = self.onInputEnded }, { Arrow = Roact.createElement( "ImageLabel", { Position = UDim2.new(percent, 0, 0.5, -5), AnchorPoint = Vector2.new(0.5, 0.5), Size = UDim2.new(0, 11, 0, 11), Image = "rbxassetid://3645512604", BackgroundTransparency = 1 } ), DragButton = Roact.createElement( "TextButton", { Text = "", Size = UDim2.new(0, Constants.SLIDER_BUTTON_WIDTH, 0, Constants.SLIDER_BUTTON_HEIGHT), Position = UDim2.new(percent, 0, 0.5, 0), BackgroundTransparency = 1, AnchorPoint = Vector2.new(0.5, 0.5), [Roact.Event.MouseEnter] = self.onMouseEnterDragButton, [Roact.Event.MouseLeave] = self.onMouseLeaveDragButton, [Roact.Event.MouseButton1Down] = self.onMouseButton1DownDragButton, [Roact.Event.InputEnded] = self.onInputEndedDragButton } ), Portal = isPressed and withModal( function(modalTarget) return Roact.createElement( Roact.Portal, { target = modalTarget }, { Detector = Roact.createElement( "TextButton", { Text = "", Size = UDim2.new(1, 0, 1, 0), BackgroundTransparency = 1, ZIndex = 10, [Roact.Event.MouseMoved] = self.onMouseMovedPortalDetector } ) } ) end ) } ) end ) end function DraggerButton:willUnmount() if self.state.isPressed then local modal = getModal(self) modal.onButtonReleased() end end ColorSlider = Roact.PureComponent:extend("ColorSlider") function ColorSlider:init() self:setState( { dragPos = Vector2.new(0, 0), isFocused = false } ) self.sliderRef = Roact.createRef() self.lastValidText = tostring(self.props.value) or "" self.formatValue = function(value) return string.format("%d", value) end local modal = getModal(self) self.onFocused = function(rbx) local isFocused = self.state.isFocused if (modal.isShowingModal(self.props.modalIndex) or modal.isAnyButtonPressed()) then self.focusDebounce = true rbx:ReleaseFocus(false) self.focusDebounce = false return end local value = self.props.value if not isFocused then rbx.Text = self.formatValue(value) self:setState( { isFocused = true } ) end end self.onFocusLost = function(rbx, enterPressed, input) local isFocused = self.state.isFocused local minValue = 0 local maxValue = 255 local value = self.props.value local onValueChanged = self.props.onValueChanged if isFocused and not self.focusDebounce then self:setState( { isFocused = false } ) local num = tonumber(rbx.Text) local text if num then num = Utility.Round(math.clamp(num, minValue, maxValue), 1) text = tostring(num) else text = nil end if text ~= nil then self.changeDebounce = true rbx.Text = self.formatValue(text) local inputValue = tonumber(text) if value ~= inputValue and onValueChanged then onValueChanged(inputValue) end self.changeDebounce = false else self.changeDebounce = true rbx.Text = self.formatValue(value) self.changeDebounce = false end end end self.onMouseEnter = function() local isHovered = self.state.isHovered if not isHovered then self:setState( { isHovered = true } ) end end self.onMouseLeave = function() local isHovered = self.state.isHovered if isHovered then self:setState( { isHovered = false } ) end end local function validateTextChange(text) if string.len(text) > 3 then return false end return text:match("^[-%d]*$") ~= nil end self.onTextChanged = function(rbx) if self.changeDebounce then return end if not self.state.isFocused then return end local newText = rbx.Text if not validateTextChange(newText) then self.changeDebounce = true rbx.Text = self.lastValidText self.changeDebounce = false else self.lastValidText = newText end end self.dragMoved = function(x, y) local props = self.props local value = props.value local onValueChanged = props.onValueChanged local minValue = 0 local maxValue = 255 local valueSnap = 1 local slider = self.sliderRef.current local pos, size = slider.AbsolutePosition.X, slider.AbsoluteSize.X local left, right = pos, pos + size local percent = math.clamp((x - left) / (right - left), 0, 1) local dragValue = Utility.Lerp(minValue, maxValue, percent) dragValue = Utility.Round(dragValue, valueSnap) dragValue = math.clamp(dragValue, minValue, maxValue) if value ~= dragValue and onValueChanged then onValueChanged(dragValue) end end self.dragBegan = function(x, y) local props = self.props local value = props.value local onValueChanged = props.onValueChanged local minValue = 0 local maxValue = 255 local valueSnap = 1 local slider = self.sliderRef.current local pos, size = slider.AbsolutePosition.X, slider.AbsoluteSize.X local left, right = pos, pos + size local percent = math.clamp((x - left) / (right - left), 0, 1) local dragValue = Utility.Lerp(minValue, maxValue, percent) dragValue = Utility.Round(dragValue, valueSnap) dragValue = math.clamp(dragValue, minValue, maxValue) if value ~= dragValue and onValueChanged then onValueChanged(dragValue) end end self.dragEnded = function(x, y) local props = self.props local value = props.value local onValueChanged = props.onValueChanged local minValue = 0 local maxValue = 255 local valueSnap = 1 local slider = self.sliderRef.current local pos, size = slider.AbsolutePosition.X, slider.AbsoluteSize.X local left, right = pos, pos + size local percent = math.clamp((x - left) / (right - left), 0, 1) local dragValue = Utility.Lerp(minValue, maxValue, percent) dragValue = Utility.Round(dragValue, valueSnap) dragValue = math.clamp(dragValue, minValue, maxValue) if value ~= dragValue and onValueChanged then onValueChanged(dragValue) end end end ColorSlider.defaultProps = { Size = UDim2.new(1, 0, 0, Constants.INPUT_FIELD_BOX_HEIGHT), Position = UDim2.new(0, 0, 0, 0), TextSize = Constants.FONT_SIZE_MEDIUM, valueIsIntegral = false, textboxIsEditable = true } function ColorSlider:willUpdate(nextProps, _) self.lastValidText = tostring(self.props.value) or "" end function ColorSlider:render() local props = self.props local textboxWidthPixel = 40 local minValue = 0 local maxValue = 255 local value = props.value or minValue local color = props.color local shaderColor = props.shaderColor local label = props.label local LayoutOrder = props.LayoutOrder return withTheme( function(theme) return withModal( function() local modal = getModal(self) local fieldTheme = theme.textField local textPadding = Constants.INPUT_FIELD_TEXT_PADDING local fontSize = Constants.FONT_SIZE_MEDIUM local font = Constants.FONT local inputColor = fieldTheme.box.textColor local isHovered = self.state.isHovered local isFocused = self.state.isFocused local boxState if isFocused then boxState = "Focused" elseif isHovered and not (modal.isShowingModal(self.props.modalIndex) or modal.isAnyButtonPressed()) then boxState = "Hovered" else boxState = "Default" end local borderColor if boxState == "Focused" then borderColor = fieldTheme.box.borderColor.Selected elseif boxState == "Hovered" then borderColor = fieldTheme.box.borderColor.Hover else borderColor = fieldTheme.box.borderColor.Default end local backgroundColor if boxState == "Focused" then backgroundColor = fieldTheme.box.backgroundColor.Selected elseif boxState == "Hovered" then backgroundColor = fieldTheme.box.backgroundColor.Hover else backgroundColor = fieldTheme.box.backgroundColor.Default end local placeholderColor = fieldTheme.box.placeholderColor local children = {} if props[Roact.Children] then for key, child in next, props[Roact.Children] do children[key] = child end end children.Input = Roact.createElement( "TextBox", { BackgroundTransparency = 1, Size = UDim2.new(1, -textPadding * 2, 1, 0), Position = UDim2.new(0, textPadding, 0, 0), Font = font, TextSize = fontSize, TextColor3 = inputColor, TextXAlignment = Enum.TextXAlignment.Center, ClearTextOnFocus = false, Text = self.formatValue(value), PlaceholderColor3 = placeholderColor, [Roact.Event.Focused] = self.onFocused, [Roact.Event.FocusLost] = self.onFocusLost, [Roact.Event.MouseEnter] = self.onMouseEnter, [Roact.Event.MouseLeave] = self.onMouseLeave, [Roact.Change.Text] = self.onTextChanged } ) local textbox = Roact.createElement( RoundedBorderedFrame, { Size = UDim2.new(0, textboxWidthPixel, 1, 0), Position = UDim2.new(0, 0, 0, 0), AnchorPoint = Vector2.new(0, 0), BackgroundColor3 = backgroundColor, BorderColor3 = borderColor }, children ) local fillPercent = math.clamp((value - minValue) / (maxValue - minValue), 0, 1) local spacingBetweenBarAndTextBox = 4 local slider = Roact.createElement( "Frame", { Size = UDim2.new(1, -textboxWidthPixel - Constants.SLIDER_BUTTON_WIDTH - spacingBetweenBarAndTextBox, 0, 0), Position = UDim2.new(0, textboxWidthPixel + spacingBetweenBarAndTextBox + Constants.SLIDER_BUTTON_WIDTH / 2, 0.5, 0), AnchorPoint = Vector2.new(0, 0.5), BackgroundTransparency = 1, [Roact.Ref] = self.sliderRef }, { Frame = Roact.createElement( BorderedFrame, { BorderColor3 = theme.borderColor, Size = UDim2.new(1, 2, 0, 14), Position = UDim2.new(0, -1, 0.5, 0), AnchorPoint = Vector2.new(0, 0.5) } ), BarBack = Roact.createElement( "Frame", { BorderSizePixel = 0, Size = UDim2.new(1, 0, 0, 12), Position = UDim2.new(0, 0, 0.5, 0), AnchorPoint = Vector2.new(0, 0.5), BackgroundColor3 = color, ZIndex = 2 }, { Shader = Roact.createElement( "ImageLabel", { BackgroundTransparency = 1, Image = "rbxassetid://3111228327", Size = UDim2.new(1, 0, 1, 0), ImageColor3 = shaderColor } ) } ), Dragger = Roact.createElement( DraggerButton, { Size = UDim2.new(1, 0, 0, 20), Position = UDim2.new(0, 0, 0.5, 0), AnchorPoint = Vector2.new(0, 0.5), ZIndex = 3, percent = fillPercent, dragMoved = self.dragMoved, dragBegan = self.dragBegan, dragEnded = self.dragEnded, modalIndex = props.modalIndex } ) } ) local boxPadding = Constants.INPUT_FIELD_BOX_PADDING local boxHeight = Constants.INPUT_FIELD_BOX_HEIGHT return Roact.createElement( LabeledFieldTemplate, { label = label, LayoutOrder = LayoutOrder }, { Slider = Roact.createElement( "Frame", { BackgroundTransparency = 1, Size = UDim2.new(1, -boxPadding, 0, boxHeight), Position = UDim2.new(0, boxPadding, 0.5, 0), AnchorPoint = Vector2.new(0, 0.5) }, { Textbox = textbox, Slider = slider } ) } ) end ) end ) end end function ColorSelector:init() self.state = { valuePressed = false, chromaPressed = false } self.onRedSliderChanged = function(newRed) local props = self.props local h, s, v = props.h, props.s, props.v local color = Color3.fromHSV(h, s, v) local _, g, b = color.r, color.g, color.b local newColor = Color3.new(newRed / 255, g, b) h, s, v = Color3.toHSV(newColor) if self.props.onColorChanged then self.props.onColorChanged { h = h, s = s, v = v } end end self.onGreenSliderChanged = function(newGreen) local props = self.props local h, s, v = props.h, props.s, props.v local color = Color3.fromHSV(h, s, v) local r, _, b = color.r, color.g, color.b local newColor = Color3.new(r, newGreen / 255, b) h, s, v = Color3.toHSV(newColor) if self.props.onColorChanged then self.props.onColorChanged { h = h, s = s, v = v } end end self.onBlueSliderChanged = function(newBlue) local props = self.props local h, s, v = props.h, props.s, props.v local color = Color3.fromHSV(h, s, v) local r, g, _ = color.r, color.g, color.b local newColor = Color3.new(r, g, newBlue / 255) h, s, v = Color3.toHSV(newColor) if self.props.onColorChanged then self.props.onColorChanged { h = h, s = s, v = v } end end self.onButton1DownChroma = function(rbx, x, y) local modal = getModal(self) local detector = self.chromaDetectorRef.current local topLeft = detector.AbsolutePosition local size = detector.AbsoluteSize x, y = x - topLeft.X, y - topLeft.Y local h = math.clamp(x / size.X, 0, 1) local s = 1 - math.clamp(y / size.Y, 0, 1) local v = self.props.v if self.props.onColorChanged then self.props.onColorChanged { h = h, s = s, v = v } end self:setState { chromaPressed = true } modal.onButtonPressed(self) end self.onInputEndedChroma = function(rbx, inputObject) local modal = getModal(self) if self.state.chromaPressed and inputObject.UserInputType == Enum.UserInputType.MouseButton1 then -- I can't do this after onClick for some reason... self:setState( { chromaPressed = false } ) modal.onButtonReleased() end end self.onMouseMovedChroma = function(rbx, x, y) local detector = self.chromaDetectorRef.current local topLeft = detector.AbsolutePosition local size = detector.AbsoluteSize x, y = x - topLeft.X, y - topLeft.Y local h = math.clamp(x / size.X, 0, 1) local s = 1 - math.clamp(y / size.Y, 0, 1) local v = self.props.v if self.props.onColorChanged then self.props.onColorChanged { h = h, s = s, v = v } end end self.onMouseButton1DownValue = function(rbx, x, y) local modal = getModal(self) local detector = self.valueDetectorRef.current local topLeft = detector.AbsolutePosition local size = detector.AbsoluteSize y = y - topLeft.Y local h, s = self.props.h, self.props.s local v = 1 - math.clamp(y / size.Y, 0, 1) if self.props.onColorChanged then self.props.onColorChanged { h = h, s = s, v = v } end self:setState { valuePressed = true } modal.onButtonPressed(self) end self.onInputEndedValue = function(rbx, inputObject) local modal = getModal(self) if self.state.valuePressed and inputObject.UserInputType == Enum.UserInputType.MouseButton1 then -- I can't do this after onClick for some reason... self:setState( { valuePressed = false } ) modal.onButtonReleased() end end self.onMouseMovedValue = function(rbx, _, y) local detector = self.valueDetectorRef.current local topLeft = detector.AbsolutePosition local size = detector.AbsoluteSize y = y - topLeft.Y local h, s = self.props.h, self.props.s local v = 1 - math.clamp(y / size.Y, 0, 1) if self.props.onColorChanged then self.props.onColorChanged { h = h, s = s, v = v } end end self.chromaDetectorRef = Roact.createRef() self.valueDetectorRef = Roact.createRef() end local function Round(n, multiple) multiple = multiple or 1 return (math.floor(n / multiple + 1 / 2) * multiple) end ColorSelector.defaultProps = { modalIndex = 0 } function ColorSelector:render() return withTheme( function(theme) local props = self.props local textured = props.textured local color = Color3.fromHSV(self.props.h, self.props.s, self.props.v) local texture = props.texture local modalIndex = props.modalIndex local r, g, b = color.r, color.g, color.b local r_int, g_int, b_int = Round(r * 255), Round(g * 255), Round(b * 255) return Roact.createElement( "Frame", { BackgroundTransparency = 1, Size = UDim2.new(1, 0, 0, 188), LayoutOrder = props.LayoutOrder }, { ColorBox = Roact.createElement( "Frame", { BackgroundTransparency = 1, Size = UDim2.new(1, 0, 0, 102), LayoutOrder = 1 }, { ColorSquare = Roact.createElement( BorderedFrame, { Size = UDim2.new(1, -26, 1, 0), BorderColor3 = theme.borderColor }, { Chroma = Roact.createElement( "ImageLabel", { BackgroundTransparency = 1, Size = UDim2.new(1, -2, 1, -2), Position = UDim2.new(0, 1, 0, 1), Image = "rbxassetid://181615068", ClipsDescendants = true }, { Shader = Roact.createElement( "Frame", { BorderSizePixel = 0, BackgroundColor3 = Color3.new(0, 0, 0), BackgroundTransparency = self.props.v, Size = UDim2.new(1, 0, 1, 0) } ), Circle = Roact.createElement( "ImageLabel", { Position = (function() local h, s = self.props.h, self.props.s return UDim2.new(h, 0, 1 - s, 0) end)(), AnchorPoint = Vector2.new(0.5, 0.5), Size = UDim2.new(0, 13, 0, 13), Image = "rbxassetid://3645522059", BackgroundTransparency = 1, ZIndex = 2 } ), Detector = Roact.createElement( PreciseButton, { Size = UDim2.new(1, 0, 1, 0), BackgroundTransparency = 1, [Roact.Event.MouseButton1Down] = self.onButton1DownChroma, [Roact.Event.InputEnded] = self.onInputEndedChroma, [Roact.Ref] = self.chromaDetectorRef }, { ChromaPortal = self.state.chromaPressed and withModal( function(modalTarget) return Roact.createElement( Roact.Portal, { target = modalTarget }, { Detector = Roact.createElement( "TextButton", { Text = "", Size = UDim2.new(1, 0, 1, 0), BackgroundTransparency = 1, ZIndex = 10, [Roact.Event.MouseMoved] = self.onMouseMovedChroma } ) } ) end ) } ) } ) } ), ValueSquare = Roact.createElement( BorderedFrame, { Size = UDim2.new(0, 14, 1, 0), Position = UDim2.new(1, -8, 0, 0), AnchorPoint = Vector2.new(1, 0), BorderColor3 = theme.borderColor, BackgroundColor3 = Color3.fromHSV(self.props.h, self.props.s, 1) }, { ValueShader = Roact.createElement( "ImageLabel", { Size = UDim2.new(1, -2, 1, -2), Position = UDim2.new(0, 1, 0, 1), Image = "rbxassetid://3108067184", BackgroundTransparency = 1 }, { Arrow = Roact.createElement( "ImageLabel", { Position = (function() local v = self.props.v return UDim2.new(0.5, 5, 1 - v, 0) end)(), AnchorPoint = Vector2.new(0.5, 0.5), Size = UDim2.new(0, 11, 0, 11), Image = "rbxassetid://3645508323", BackgroundTransparency = 1 } ), Detector = Roact.createElement( PreciseButton, { Size = UDim2.new(1, 0, 1, 0), BackgroundTransparency = 1, [Roact.Event.MouseButton1Down] = self.onMouseButton1DownValue, [Roact.Event.InputEnded] = self.onInputEndedValue, [Roact.Ref] = self.valueDetectorRef }, { ValuePortal = self.state.valuePressed and withModal( function(modalTarget) return Roact.createElement( Roact.Portal, { target = modalTarget }, { Detector = Roact.createElement( "TextButton", { Text = "", Size = UDim2.new(1, 0, 1, 0), BackgroundTransparency = 1, ZIndex = 10, [Roact.Event.MouseMoved] = self.onMouseMovedValue } ) } ) end ) } ) } ) } ) } ), PreviewBox = Roact.createElement( "Frame", { Size = UDim2.new(1, 0, 0, 82), Position = UDim2.new(0, 0, 0, 106), BackgroundTransparency = 1 }, { PreviewImageBox = Roact.createElement( BorderedFrame, { Size = UDim2.new(0, 82, 0, 82), Position = UDim2.new(0, 0, 0, 0), AnchorPoint = Vector2.new(0, 0), BorderColor3 = theme.borderColor, BackgroundColor3 = color }, (function() if not textured then return {} end local children = {} children.Clipper = Roact.createElement( "Frame", { BackgroundTransparency = 1, Size = UDim2.new(1, -2, 1, -2), Position = UDim2.new(0, 1, 0, 1), ClipsDescendants = true }, { PreviewImage = Roact.createElement( "ImageLabel", { BorderSizePixel = 0, BackgroundTransparency = 0, BackgroundColor3 = color, Image = texture or "", ImageColor3 = color, ScaleType = Enum.ScaleType.Tile, TileSize = UDim2.new(0, 60, 0, 60), Size = UDim2.new(0, 180, 0, 180), Position = UDim2.new(0, -50, 0, -50) } ), ShadeLeft = Roact.createElement( "Frame", { BorderSizePixel = 0, Size = UDim2.new(0.125, 0, 1, 0), BackgroundColor3 = Color3.new(0, 0, 0), BackgroundTransparency = 0.5, ZIndex = 2 } ), ShadeRight = Roact.createElement( "Frame", { BorderSizePixel = 0, Size = UDim2.new(0.125, 0, 1, 0), Position = UDim2.new(0.875, 0, 0, 0), BackgroundColor3 = Color3.new(0, 0, 0), BackgroundTransparency = 0.5, ZIndex = 2 } ), ShadeTop = Roact.createElement( "Frame", { BorderSizePixel = 0, Size = UDim2.new(0.75, 0, 0.125, 0), Position = UDim2.new(0.125, 0, 0, 0), BackgroundColor3 = Color3.new(0, 0, 0), BackgroundTransparency = 0.5, ZIndex = 2 } ), ShadeBottom = Roact.createElement( "Frame", { BorderSizePixel = 0, Size = UDim2.new(0.75, 0, 0.125, 0), Position = UDim2.new(0.125, 0, 0.875, 0), BackgroundColor3 = Color3.new(0, 0, 0), BackgroundTransparency = 0.5, ZIndex = 2 } ) } ) return children end)() ), SliderFrame = Roact.createElement( "Frame", { BackgroundTransparency = 1, Position = UDim2.new(0, 86, 0, 0), Size = UDim2.new(1, -86, 1, 0) }, { SliderList = Roact.createElement( VerticalList, { width = UDim.new(1, 0), ElementPaddingPixel = 4, VerticalAlignment = Enum.VerticalAlignment.Center, Position = UDim2.new(0, 0, 0.5, 0), AnchorPoint = Vector2.new(0, 0.5) }, { RedSlider = Roact.createElement( ColorSlider, { value = r_int, color = Color3.new(1, g, b), shaderColor = Color3.new(0, g, b), LayoutOrder = 1, onValueChanged = self.onRedSliderChanged, label = "R", modalIndex = modalIndex } ), GreenSlider = Roact.createElement( ColorSlider, { value = g_int, color = Color3.new(r, 1, b), shaderColor = Color3.new(r, 0, b), LayoutOrder = 2, onValueChanged = self.onGreenSliderChanged, label = "G", modalIndex = modalIndex } ), BlueSlider = Roact.createElement( ColorSlider, { value = b_int, color = Color3.new(r, g, 1), shaderColor = Color3.new(r, g, 0), LayoutOrder = 3, onValueChanged = self.onBlueSliderChanged, label = "B", modalIndex = modalIndex } ) } ) } ) } ) } ) end ) end function ColorSelector:willUnmount() if self.state.chromaPressed or self.state.valuePressed then local modal = getModal(self) modal.onButtonReleased() end end return ColorSelector
local RunService = game:GetService("RunService") local Selection = game:GetService("Selection") local Modules = script.Parent.Parent.Parent.Parent local Roact = require(Modules.Roact) local StudioComponents = require(Modules.StudioComponents) local ComponentManager = require(script.Parent.Parent.Parent.ComponentManager) local BaseProperty = require(script.Parent.BaseProperty) local InstanceSelect = Roact.Component:extend("InstanceSelect") --[[ OnChanged = () => string ]] function InstanceSelect:init() self.fieldRef = Roact.createRef() self.lastGoodInput = self.props.Value self:setState({ Instance = self.props.Instance, Selecting = false, }) end function InstanceSelect:render() local requiredKind = self.props.ClassName or self.props.IsA local instance = self.props.Instance return Roact.createElement(BaseProperty, { Text = ("%s (%s)"):format(self.props.Key, requiredKind or "any"), }, { InstanceSelector = Roact.createElement(StudioComponents.Button, { Size = UDim2.new(1, 0, 1, 0), Text = instance and instance:GetFullName() or "<none>", TextXAlignment = Enum.TextXAlignment.Left, BorderSizePixel = 0, TextTruncate = Enum.TextTruncate.AtEnd, OnActivated = function() if self.state.Selecting then return end self:setState({ Selecting = true, }) local oldSelection = Selection:Get() ComponentManager._global:pauseSelection() Selection:Set({}) Selection.SelectionChanged:Wait() local newSelected = Selection:Get()[1] if newSelected then local valid = true if self.props.IsA then valid = newSelected:IsA(self.props.IsA) end if self.props.ClassName then valid = newSelected.ClassName == self.props.ClassName end if valid then self:setState({ Instance = newSelected, }) self.props.OnChanged(newSelected) end end RunService.Heartbeat:Wait() Selection:Set(oldSelection) ComponentManager._global:unpauseSelection() self:setState({ Selecting = false, }) end, LayoutOrder = 0, Selected = self.state.Selecting, }), }) end return InstanceSelect
local Analytics = {} local isDevice = (system.getInfo("environment") == "device") local platform = system.getInfo("platform") local platform_list = {"android", "ios"} local firebaseAnalytics = nil local isInit = false local isPlatformAllowed function Analytics.init() if isDevice then if isPlatformAllowed() then firebaseAnalytics = require "plugin.firebaseAnalytics" isInit = pcall(firebaseAnalytics.init) end end end function Analytics.logEvent(eventId, params) assert(eventId, "bad argument #1 to 'logEvent' (string expected, got no value)") assert(params, "bad argument #2 to 'logEvent' (table expected, got no value)") if isInit then firebaseAnalytics.logEvent(eventId, params) end end function Analytics.setUserProperties(name, property) assert(name, "bad argument #1 to 'setUserProperties' (string expected, got no value)") assert(property, "bad argument #2 to 'setUserProperties' (string expected, got no value)") if isInit then firebaseAnalytics.setUserProperties(name, property) end end function Analytics.setCurrentScreen(screenName, screenClass) assert(screenName, "bad argument #1 to 'setCurrentScreen' (string expected, got no value)") assert(screenClass, "bad argument #2 to 'setCurrentScreen' (string expected, got no value)") if isInit then firebaseAnalytics.setCurrentScreen(screenName, screenClass) end end function Analytics.addPaymentInfo() local params = {} if isInit then firebaseAnalytics.logEvent("add_payment_info", params) end end function Analytics.addToCart(item_id, item_name, item_categoty, quantity, params) assert(item_id, "bad argument #1 to 'addToCart' (string expected, got no value)") assert(item_name, "bad argument #2 to 'addToCart' (string expected, got no value)") assert(item_categoty, "bad argument #3 to 'addToCart' (string expected, got no value)") assert(quantity, "bad argument #4 to 'addToCart' (number expected, got no value)") local params = params or {} params.item_id = item_id params.item_name = item_name params.item_categoty = item_categoty params.quantity = quantity if isInit then firebaseAnalytics.logEvent("add_to_cart", params) end end function Analytics.addToWishlist(item_id, item_name, item_categoty, quantity, params) assert(item_id, "bad argument #1 to 'addToWishlist' (string expected, got no value)") assert(item_name, "bad argument #2 to 'addToWishlist' (string expected, got no value)") assert(item_categoty, "bad argument #3 to 'addToWishlist' (string expected, got no value)") assert(quantity, "bad argument #4 to 'addToWishlist' (number expected, got no value)") local params = params or {} params.item_id = item_id params.item_name = item_name params.item_categoty = item_categoty params.quantity = quantity if isInit then firebaseAnalytics.logEvent("add_to_wishlist", params) end end function Analytics.appOpen() local params = {} if isInit then firebaseAnalytics.logEvent("app_open", params) end end function Analytics.beginCheckout(value, currency, params) assert(value, "bad argument #1 to 'beginCheckout' (number expected, got no value)") assert(currency, "bad argument #2 to 'beginCheckout' (string expected, got no value)") local params = params or {} params.value = value params.currency = currency if isInit then firebaseAnalytics.logEvent("begin_checkout", params) end end function Analytics.campaignDetails(source, medium, campaing, params) assert(source, "bad argument #1 to 'campaignDetails' (string expected, got no value)") assert(medium, "bad argument #2 to 'campaignDetails' (string expected, got no value)") assert(campaing, "bad argument #3 to 'campaignDetails' (string expected, got no value)") local params = params or {} params.source = source params.medium = medium params.campaing = campaing if isInit then firebaseAnalytics.logEvent("campaign_details", params) end end function Analytics.checkoutProgress(checkout_step, checkout_option) assert(checkout_step, "bad argument #1 to 'checkoutProgress' (string expected, got no value)") assert(checkout_option, "bad argument #2 to 'checkoutProgress' (string expected, got no value)") local params = {} params.checkout_step = checkout_step params.checkout_option = checkout_option if isInit then firebaseAnalytics.logEvent("checkout_progress", params) end end function Analytics.earnVirtualCurrency(virtual_currency_name, value) assert(virtual_currency_name, "bad argument #1 to 'earnVirtualCurrency' (string expected, got no value)") assert(value, "bad argument #2 to 'earnVirtualCurrency' (number expected, got no value)") local params = {} params.virtual_currency_name = virtual_currency_name params.value = value if isInit then firebaseAnalytics.logEvent("earn_virtual_currency", params) end end function Analytics.ecommercePurchase(value, currency, params) assert(value, "bad argument #1 to 'ecommercePurchase' (number expected, got no value)") assert(currency, "bad argument #2 to 'ecommercePurchase' (string expected, got no value)") local params = params or {} params.currency = currency params.value = value if isInit then firebaseAnalytics.logEvent("ecommerce_purchase", params) end end function Analytics.generateLead(value, currency) assert(value, "bad argument #1 to 'generateLead' (number expected, got no value)") assert(currency, "bad argument #2 to 'generateLead' (string expected, got no value)") local params = {} params.currency = currency params.value = value if isInit then firebaseAnalytics.logEvent("generate_lead", params) end end function Analytics.joinGroup(group_id) assert(group_id, "bad argument #1 to 'joinGroup' (string expected, got no value)") local params = {} params.group_id = group_id if isInit then firebaseAnalytics.logEvent("join_group", params) end end function Analytics.levelUp(level, character) assert(level, "bad argument #1 to 'levelUp' (number expected, got no value)") local params = {} params.level = level params.character = character if isInit then firebaseAnalytics.logEvent("level_up", params) end end function Analytics.login() local params = {} if isInit then firebaseAnalytics.logEvent("login", params) end end function Analytics.postScore(score, level, character) assert(score, "bad argument #1 to 'postScore' (number expected, got no value)") local params = {} params.score = score params.level = level params.character = character if isInit then firebaseAnalytics.logEvent("post_score", params) end end function Analytics.presentOffer(item_id, item_name, item_categoty, quantity, params) assert(item_id, "bad argument #1 to 'presentOffer' (string expected, got no value)") assert(item_name, "bad argument #2 to 'presentOffer' (string expected, got no value)") assert(item_categoty, "bad argument #3 to 'presentOffer' (string expected, got no value)") assert(quantity, "bad argument #4 to 'presentOffer' (number expected, got no value)") local params = params or {} params.item_id = item_id params.item_name = item_name params.item_categoty = item_categoty params.quantity = quantity if params.value then assert(params.currency, "bad argument #5 to 'presentOffer' (string (currency) expected, got no value)") end if isInit then firebaseAnalytics.logEvent("present_offer", params) end end function Analytics.purchaseRefund(value, currency, transaction_id) assert(value, "bad argument #1 to 'purchaseRefund' (number expected, got no value)") assert(currency, "bad argument #2 to 'purchaseRefund' (string expected, got no value)") local params = {} params.value = value params.currency = currency params.transaction_id = transaction_id if isInit then firebaseAnalytics.logEvent("purchase_refund", params) end end function Analytics.removeFromCart(item_id, item_name, item_categoty, quantity, params) assert(item_id, "bad argument #1 to 'removeFromCart' (string expected, got no value)") assert(item_name, "bad argument #2 to 'removeFromCart' (string expected, got no value)") assert(item_categoty, "bad argument #3 to 'removeFromCart' (string expected, got no value)") assert(quantity, "bad argument #4 to 'removeFromCart' (number expected, got no value)") local params = params or {} params.item_id = item_id params.item_name = item_name params.item_categoty = item_categoty params.quantity = quantity if isInit then firebaseAnalytics.logEvent("remove_from_cart", params) end end function Analytics.search(search_term, params) assert(search_term, "bad argument #1 to 'search' (string expected, got no value)") local params = params or {} params.search_term = search_term if isInit then firebaseAnalytics.logEvent("search", params) end end function Analytics.selectContent(content_type, item_id) assert(content_type, "bad argument #1 to 'selectContent' (string expected, got no value)") assert(item_id, "bad argument #2 to 'selectContent' (string expected, got no value)") local params = {} params.content_type = content_type params.item_id = item_id if isInit then firebaseAnalytics.logEvent("select_content", params) end end function Analytics.setCheckoutOption(checkout_step, checkout_option) assert(checkout_step, "bad argument #1 to 'setCheckoutOption' (string expected, got no value)") assert(checkout_option, "bad argument #2 to 'setCheckoutOption' (string expected, got no value)") local params = {} params.checkout_step = checkout_step params.checkout_option = checkout_option if isInit then firebaseAnalytics.logEvent("set_checkout_option", params) end end function Analytics.share(content_type, item_id) assert(content_type, "bad argument #1 to 'share' (string expected, got no value)") assert(item_id, "bad argument #2 to 'share' (string expected, got no value)") local params = {} params.content_type = content_type params.item_id = item_id if isInit then firebaseAnalytics.logEvent("share", params) end end function Analytics.signUp(sign_up_method) assert(sign_up_method, "bad argument #1 to 'signUp' (string expected, got no value)") local params = {} params.sign_up_method = sign_up_method if isInit then firebaseAnalytics.logEvent("sign_up", params) end end function Analytics.spendVirtualCurrency(item_name, virtual_currency_name, value) assert(item_name, "bad argument #1 to 'spendVirtualCurrency' (string expected, got no value)") assert(virtual_currency_name, "bad argument #2 to 'spendVirtualCurrency' (string expected, got no value)") assert(value, "bad argument #3 to 'spendVirtualCurrency' (number expected, got no value)") local params = {} params.item_name = item_name params.virtual_currency_name = virtual_currency_name params.value = value if isInit then firebaseAnalytics.logEvent("spend_virtual_currency", params) end end function Analytics.tutorialBegin() local params = {} if isInit then firebaseAnalytics.logEvent("tutorial_begin", params) end end function Analytics.tutorialComplete() local params = {} if isInit then firebaseAnalytics.logEvent("tutorial_complete", params) end end function Analytics.unlockAchievement(achievement_id) assert(achievement_id, "bad argument #1 to 'unlockAchievement' (string expected, got no value)") local params = {} params.achievement_id = achievement_id if isInit then firebaseAnalytics.logEvent("unlock_achievement", params) end end function Analytics.viewItem(item_id, item_name, item_categoty, params) assert(item_id, "bad argument #1 to 'viewItem' (string expected, got no value)") assert(item_name, "bad argument #2 to 'viewItem' (string expected, got no value)") assert(item_categoty, "bad argument #3 to 'viewItem' (string expected, got no value)") local params = params or {} params.item_id = item_id params.item_name = item_name params.item_categoty = item_categoty if isInit then firebaseAnalytics.logEvent("view_item", params) end end function Analytics.viewItemList(item_categoty) assert(item_categoty, "bad argument #1 to 'viewItemList' (string expected, got no value)") local params = {} params.item_categoty = item_categoty if isInit then firebaseAnalytics.logEvent("view_item_list", params) end end function Analytics.viewSearchResult(search_term) assert(search_term, "bad argument #1 to 'viewSearchResult' (string expected, got no value)") local params = {} params.search_term = search_term if isInit then firebaseAnalytics.logEvent("view_search_results", params) end end function isPlatformAllowed() local isAllowed = false for i = 1, #platform_list do if platform == platform_list[i] then isAllowed = true break end end return isAllowed end return Analytics
local host_immunity = GetModConfigData( "host_immunity" ) local afk_time = GetModConfigData( "afk_time" ) local max_afk_time = GetModConfigData( "max_afk_time" ) local max_afk_action = GetModConfigData( "max_afk_action" ) local stop_death = GetModConfigData( "stop_death" ) local stop_hunger = GetModConfigData( "hunger_decrease" ) local stop_sanity = GetModConfigData( "stop_sanity" ) local last_move = { } local function OnPlayerPostInit( inst ) if inst:HasTag( "player" ) and not inst:HasTag( "CLASSIFIED" ) then inst:AddComponent( "afk" ) inst.components.afk.host_immunity = host_immunity inst.components.afk.min_afk_time = afk_time inst.components.afk.max_afk_time = max_afk_time inst.components.afk.max_afk_action = max_afk_action inst.components.afk.stop_death = stop_death inst.components.afk.stop_hunger = stop_hunger inst.components.afk.stop_sanity = stop_sanity end end if GLOBAL.TheNet:GetIsServer( ) then AddPrefabPostInitAny( OnPlayerPostInit ) end
local M = {} local Highlighter = {} Highlighter.__index = Highlighter function Highlighter.add(self, hl_group, row, start_col, opts) opts.hl_group = hl_group vim.api.nvim_buf_set_extmark(self._bufnr, self._ns, row, start_col, opts) end function Highlighter.add_virtual(self, chunks, row, start_col, opts) opts.virt_text = chunks vim.api.nvim_buf_set_extmark(self._bufnr, self._ns, row, start_col, opts) end function Highlighter.add_ranged_virtual(self, strs, hl_group, start_row, start_col, opts) local args = {} local count = #strs if count == 1 then local str = strs[1] table.insert(args, {{{str, hl_group}}, start_row, start_col, opts}) elseif count > 1 then local eol = vim.opt.listchars:get().eol or "" local row = start_row for _, str in ipairs(strs) do table.insert(args, {{{str .. eol, hl_group}}, row, 0, opts}) row = row + 1 end args[1][3] = start_col args[#args][1][1][1] = strs[#strs] end args = vim.tbl_filter(function(arg) return arg[1][1][1] ~= "" end, args) for _, arg in ipairs(args) do self:add_virtual(unpack(arg)) end end local HighlighterFactory = {} HighlighterFactory.__index = HighlighterFactory M.HighlighterFactory = HighlighterFactory function HighlighterFactory.new(key, bufnr) vim.validate({key = {key, "string"}, bufnr = {bufnr, "number", true}}) local ns = vim.api.nvim_create_namespace(key) local tbl = {_ns = ns, _bufnr = bufnr} return setmetatable(tbl, HighlighterFactory) end function HighlighterFactory.create(self, bufnr) bufnr = bufnr or self._bufnr local highlighter = {_bufnr = bufnr, _ns = self._ns} return setmetatable(highlighter, Highlighter) end function HighlighterFactory.reset(self, bufnr) bufnr = bufnr or self._bufnr local highlighter = self:create(bufnr) vim.api.nvim_buf_clear_namespace(bufnr, self._ns, 0, -1) return highlighter end return M
require 'util' local manhattan = curry(function(a,b) return math.abs(a.x - b.x) + math.abs(a.y - b.y) end) local input = '06 - Input.txt' local coords = keyBy(map(lines_from(input), function(v,k,t) local point = { x = tonumber(v:match('(%d+),')), y = tonumber(v:match(', (%d+)')), raw = v} return point end),'raw') for x=1,1 do for y=1,1 do local dist = map(coords, function(v) v.dist = manhattan({x=x,y=y}, v) return v end) local grp = sort(groupBy(dist,'dist'),function(t,a,b) return a < b end) for k,v in pairs(grp) do print('Dist ['..k..'] '..#v) end --[[ local closest = minBy(map(coords,function(v) v.dist = manhattan({x=x,y=y},v) return v end),'dist')]] --print(closest.x..' '..closest.y) end end
-- my task dofile("sendtemp.lua")
module(..., package.seeall) --====================================================================-- -- Test: Json module --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- -- Testing Setup --====================================================================-- local json function suite_setup() json = require 'json' end function test_jsonModule() assert_not_nil( json, "json module required" ) end
local L = LibStub("AceLocale-3.0"):NewLocale("BuloLayer", "enUS", true, true) L = L or {} L["Layer Hopper"] = true L["BuloLayer"] = true L["optionsDesc"] = [=[Layer Hopper Config (You can type /lh config to open this). Auto inviting will be disabled automatically if inside an instance or battleground and when in a battleground queue. ]=] L["Auto Invite"] = true L["autoInviteDesc"] = "Enable auto invites for layer switch requests in the guild (if you turn this off you cannot be used by other guildies to switch layers)." L["Minimap Button"] = true L["minimapDesc"] = [=[Enable minimap button (allows for quick layer hop requests and shows current layer). Will require a /reload if hiding the button.]=] L["layer unknown"] = true L["layer %s"] = true -- Chat Messages L["noGuildErr"] = "Layer Hopper only works when you have joined a guild." L["inGroupErr"] = "Can't request layer hop while in a group." L["unknownLayerErr"] = "Can't request layer hop until your layer is known. Target any NPC or mob to get current layer." L["inInstanceErr"] = "Can't request layer hop while in an instance or battleground." L["oldVersionErr"] = "You are running an old version of Layer Hopper, please update from curseforge!" L["rankTooLow"] = "Can't request layer data reset unless you are class lead or higher rank." L["requestingHop"] = "Requesting layer hop from layer %s to another layer." L["minimapShown"] = "Minimap button shown." L["minimapHidden"] = "Minimap button hidden. (you will need to type /reload to show changes)" L["playerRequestedLayerReset"] = "%s requested a reset of layer data for the guild." L["resettingLayerData"] = "Resetting layer data in the guild..." L["printPlayerLayer"] = "%s: %s - %s - layer id: %s" -- PlayerName: layer 1 - v1.5.2 - layer id: 14 -- Console L["configConsole"] = "Open/close configuration window" L["layerHopConsole"] = "Request a layer hop" L["listLayersConsole"] = "List layers and versions for all guildies" L["resetLayersConsole"] = "Reset layer data for all guildies. (can only be done by class lead rank or above)" L["toggleMinimapConsole"] = "Toggle minimap button." -- Minimap Icon Text L["paused"] = "Resetting layer data for the guild. Should only take a few more seconds..." L["unknownLayer"] = [=[Unknown Layer. Target any NPC or mob to get current layer. (layer id: %s, min: %s, max: %s)]=] L["minMaxUnknown"] = "Min/max layer IDs are unknown." L["rangeTooSmall"] = "Min/max layer ID range is not large enough." L["needMoreData"] = [=[Need more data from guild to determine current layer. (layer id: %s, min: %s, max: %s)]=] L["currentLayer"] = [=[Current Layer: %s (layer id: %s, min: %s, max: %s)]=] L["minimapLeftClickAction"] = "Left click to request a layer hop." L["minimapRightClickAction"] = "Right click to access Layer Hopper settings." L["minimapOtherOptions"] = "/lh to see other options" -- Mob Error L["mobErrTitle"] = "YOU HAVE ENCOUNTERED A MOB THAT BREAKS LAYER HOPPER!" L["mobErrName"] = "MOB NAME: %s" L["mobErrGUID"] = "MOB GUID: %s" L["mobErrZone"] = "ZONE: %s" L["mobErrGithub"] = "PLEASE SEND THIS INFORMATION TO KUTANO (OR REPORT ON GITHUB github.com/psynct/BuloLayer)!"
AddCSLuaFile() CustomizableWeaponry.registeredSoundNames = {} CustomizableWeaponry.reloadSoundVolume = 60 -- default settings CustomizableWeaponry.reloadSoundTable = { channel = CHAN_AUTO, volume = 1, level = CustomizableWeaponry.reloadSoundVolume, pitchstart = 100, pitchend = 100, name = "noName", sound = "path/to/sound" } CustomizableWeaponry.fireSoundTable = { channel = CHAN_AUTO, volume = 1, level = 97, pitchstart = 92, pitchend = 112, name = "noName", sound = "path/to/sound" } CustomizableWeaponry.regularSoundTable = { channel = CHAN_AUTO, volume = 1, level = 65, pitchstart = 92, pitchend = 112, name = "noName", sound = "path/to/sound" } -- "<" makes the sound directional, refer to https://developer.valvesoftware.com/wiki/Soundscripts#Sound_Characters function CustomizableWeaponry:makeSoundDirectional(snd) if type(snd) == "table" then for key, sound in ipairs(snd) do snd[key] = "<" .. sound end else snd = "<" .. snd end return snd end function CustomizableWeaponry:addFireSound(name, snd, volume, soundLevel, channel, pitchStart, pitchEnd, noDirection) -- use defaults if no args are provided volume = volume or 1 soundLevel = soundLevel or 97 channel = channel or CHAN_AUTO pitchStart = pitchStart or 92 pitchEnd = pitchEnd or 112 if not noDirection then snd = self:makeSoundDirectional(snd) end self.fireSoundTable.name = name self.fireSoundTable.sound = snd self.fireSoundTable.channel = channel self.fireSoundTable.volume = volume self.fireSoundTable.level = soundLevel self.fireSoundTable.pitchstart = pitchStart self.fireSoundTable.pitchend = pitchEnd sound.Add(self.fireSoundTable) -- precache the registered sounds if type(self.fireSoundTable.sound) == "table" then for k, v in pairs(self.fireSoundTable.sound) do util.PrecacheSound(v) end else util.PrecacheSound(snd) end -- store all registered sound names so that we can retrieve them with findFireSound (in case someone names their firing sound in a lowercase manner and then uses upper case in the SWEP file) self.registeredSoundNames[string.lower(name)] = name end function CustomizableWeaponry:addReloadSound(name, snd, noDirection) if not noDirection then snd = self:makeSoundDirectional(snd) end self.reloadSoundTable.name = name self.reloadSoundTable.sound = snd sound.Add(self.reloadSoundTable) -- precache the registered sounds if type(self.reloadSoundTable.sound) == "table" then for k, v in pairs(self.reloadSoundTable.sound) do util.PrecacheSound(v) end else util.PrecacheSound(snd) end end function CustomizableWeaponry:addRegularSound(name, snd, level, noDirection) if not noDirection then snd = self:makeSoundDirectional(snd) end level = level or 65 self.regularSoundTable.name = name self.regularSoundTable.sound = snd self.regularSoundTable.level = level sound.Add(self.regularSoundTable) -- precache the registered sounds if type(self.regularSoundTable.sound) == "table" then for k, v in pairs(self.regularSoundTable.sound) do util.PrecacheSound(v) end else util.PrecacheSound(snd) end end function CustomizableWeaponry:findFireSound(snd) snd = string.lower(snd) if self.registeredSoundNames[snd] then return self.registeredSoundNames[snd] end -- welp return nil end
------------------------------ -- library ------------------------------ require 'torch' require 'xlua' require 'optim' require 'cunn' ------------------------------ -- function ------------------------------ function valid() collectgarbage() print("") -- Load valid images print(" => Load valid images") path.mkdir("preprocess") local prepro_list = getFilename("preprocess") local seed = opt.seed assert(contains(prepro_list, "valid_data_s" .. seed .. ".set")) local valid_data = torch.load("preprocess/valid_data_s" .. seed .. ".set") assert(contains(prepro_list, "valid_data_s" .. seed .. ".set")) local valid_label = torch.load("preprocess/valid_label_s" .. seed .. ".set") assert(contains(prepro_list, "trfolders.set")) local trfolders = torch.load("preprocess/trfolders.set") for i=1,3 do valid_data[{{},i,{},{}}]:add(-res_mean[i]):div(res_std[i]) end collectgarbage() local valid_confusion = optim.ConfusionMatrix(trfolders) -- local vars local valid_size = valid_data:size(1) valid_score = 0 -- set model to evaluate mode model:evaluate() -- test over test data print(sys.COLORS.green .. '==> validating on valid set:') for t = 1,valid_size,opt.batchSize do -- disp progress xlua.progress(t, valid_size) local local_batchSize = math.min(opt.batchSize, valid_size - t + 1) local inputs = torch.Tensor(local_batchSize, 3, 224, 224) local targets = torch.Tensor(local_batchSize) for local_count, i in ipairs( tablex.range(t, t+local_batchSize-1) ) do -- get new sample local img_ = valid_data[i] inputs[{local_count}] = crop_imgs(img_) targets[{local_count}] = valid_label[i] end inputs = inputs:cuda() targets = targets:cuda() local preds = model:forward(inputs) collectgarbage() -- calc valid score local err = criterion:forward(preds, targets) valid_score = valid_score + err * local_batchSize valid_confusion:batchAdd(preds, targets) end xlua.progress(valid_size, valid_size) -- print valid score valid_score = valid_score / valid_size print('\tvalid_score: ' .. string.format("%.4f", valid_score)) -- print total valid valid_confusion:updateValids() print('\tvalid_accuracy: ' .. string.format("%.1f", valid_confusion.totalValid * 100) .. " [%]") end
cmd = torch.CmdLine() cmd:text() cmd:text() cmd:text('Training a simple network') cmd:text() cmd:text('Options') cmd:option('-seed',123,'initial random seed') cmd:option('-booloption',false,'boolean option') cmd:option('-stroption','mystring','string option') cmd:text() -- parse input params params = cmd:parse(arg) params.rundir = cmd:string('experiment', params, {dir=true}) paths.mkdir(params.rundir) -- create log file cmd:log(params.rundir .. '/log', params)
vim.g.mapleader = " " -- when in terminal mode(:term), map ESC to exit instead of the default c-\ c-n vim.api.nvim_set_keymap("t", "<Esc>", [[<C-\><C-n>]], {noremap = true, silent = true}) -- create new file vim.api.nvim_set_keymap("n", "<Leader>fn", [[<Cmd> DashboardNewFile<CR>]], {noremap = true, silent = true}) -- eval current lua file vim.api.nvim_set_keymap("n", "<Leader>rr", [[<Cmd> luafile %<CR>]], {noremap = true, silent = true}) -- keep everything centered vim.api.nvim_set_keymap("n", "n", "nzzzv", {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "N", "Nzzzv", {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "J", "mzJ`z", {noremap = true, silent = true}) -- undo break points --vim.api.nvim_set_keymap("i", ".", [[.<c-g>u]], {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "<Leader>hw", [[<Cmd> HopWord<CR>]], {noremap = true, silent = true}) -- open/close nvim tree vim.api.nvim_set_keymap("n", "<Leader>k", [[<Cmd> NvimTreeToggle<CR>]], {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "<Leader>[", [[<Cmd> bp<CR>]], {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "<Leader>]", [[<Cmd> bn<CR>]], {noremap = true, silent = true}) -- map Y to yank curr line position up until the end, similar with D, C, etc vim.api.nvim_set_keymap("n", "Y", "y$", {noremap = true, silent = true}) -- text move support vim.api.nvim_set_keymap("v", "J", ":m '>+1<CR>gv=gv", {noremap = true, silent = true}) vim.api.nvim_set_keymap("v", "K", ":m '<-2<CR>gv=gv", {noremap = true, silent = true}) vim.api.nvim_set_keymap("i", "<C-j>", "<esc>:m .+1<CR>==i", {noremap = true, silent = true}) vim.api.nvim_set_keymap("i", "<C-k>", "<esc>:m .-2<CR>==i", {noremap = true, silent = true}) -- telescope mappings vim.api.nvim_set_keymap("n", "<Leader>ff", "<cmd>Telescope find_files<cr>", {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "<Leader>b", ":Telescope buffers<cr>", {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "<Leader>ag", ":Telescope live_grep<cr>", {noremap = true, silent = true}) -- git fugitive mappings vim.api.nvim_set_keymap("n", "<Leader>gs", ":Gstatus<cr>", {noremap = true, silent = true}) -- git merge accept right vim.api.nvim_set_keymap("n", "<Leader>j", ":diffget //3", {noremap = true, silent = true}) -- git merge accept left vim.api.nvim_set_keymap("n", "<Leader>f", ":diffget //2", {noremap = true, silent = true}) -- when in terminal mode(:term), map ESC to exit instead of the default c-\ c-n vim.api.nvim_set_keymap("t", "<Esc>", [[<C-\><C-n>]], {noremap = true, silent = true}) -- create new file vim.api.nvim_set_keymap("n", "<Leader>fn", [[<Cmd> DashboardNewFile<CR>]], {noremap = true, silent = true}) -- eval current lua file vim.api.nvim_set_keymap("n", "<Leader>rr", [[<Cmd> luafile %<CR>]], {noremap = true, silent = true}) -- show current line git blame vim.api.nvim_set_keymap("n", "<Leader>gb", [[<Cmd> Gitsigns blame_line<CR>]], {noremap = true, silent = true}) -- keep everything centered vim.api.nvim_set_keymap("n", "n", "nzzzv", {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "N", "Nzzzv", {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "J", "mzJ`z", {noremap = true, silent = true}) -- undo break points --vim.api.nvim_set_keymap("i", ".", [[.<c-g>u]], {noremap = true, silent = true}) -- open/close nvim tree vim.api.nvim_set_keymap("n", "<Leader>k", [[<Cmd> NvimTreeToggle<CR>]], {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "<Leader>[", [[<Cmd> bp<CR>]], {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "<Leader>]", [[<Cmd> bn<CR>]], {noremap = true, silent = true}) -- map Y to yank curr line position up until the end, similar with D, C, etc vim.api.nvim_set_keymap("n", "Y", "y$", {noremap = true, silent = true}) -- text move support vim.api.nvim_set_keymap("v", "J", ":m '>+1<CR>gv=gv", {noremap = true, silent = true}) vim.api.nvim_set_keymap("v", "K", ":m '<-2<CR>gv=gv", {noremap = true, silent = true}) vim.api.nvim_set_keymap("i", "<C-j>", "<esc>:m .+1<CR>==i", {noremap = true, silent = true}) vim.api.nvim_set_keymap("i", "<C-k>", "<esc>:m .-2<CR>==i", {noremap = true, silent = true}) -- telescope mappings vim.api.nvim_set_keymap("n", "<Leader>ff", "<cmd>Telescope find_files<cr>", {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "<Leader>b", ":Telescope buffers<cr>", {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "<Leader>ag", ":Telescope live_grep<cr>", {noremap = true, silent = true}) -- git fugitive mappings vim.api.nvim_set_keymap("n", "<Leader>gs", ":Gstatus<cr>", {noremap = true, silent = true}) -- git merge accept right vim.api.nvim_set_keymap("n", "<Leader>j", ":diffget //3", {noremap = true, silent = true}) -- git merge accept left vim.api.nvim_set_keymap("n", "<Leader>f", ":diffget //2", {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "K", ":Lspsaga hover_doc", {noremap = true, silent = true}) vim.api.nvim_set_keymap("n", "<Leader>uw", ":Lspsaga lsp_finder<CR>", {noremap = true, silent = true})
-- English localization file for enUS and enGB. local L = LibStub("AceLocale-3.0"):NewLocale("DrinkIt", "enUS", true) L["Created macro:"] = true L["Can't create new macro:"] = true L["Make enough space in your general macro section."] = true L["mage"] = true L["conjure"] = true L["conjured"] = true L["refreshment"] = true L["food & drink"] = true L["food"] = true L["drink"] = true L["water"] = true L["warlock"] = true L["healthstone"] = true L["first aid"] = true L["armor"] = true L["consumable"] = true L["miscellaneous"] = true L["potion"] = true L["bandage"] = true L["reagent"] = true L["restores"] = true L["restore"] = true L["heals"] = true L["remain seated"] = true L["spend at least"] = true L["well fed"] = true L["battleground"] = true L["health"] = true L["life"] = true L["damage"] = true L["mana"] = true
local mesecons_mod = minetest.get_modpath("mesecons") -- How far lights can be from a plant. 0 = infinite local height_max = 2 local grow_light_rules = { {x = 1, y = 0, z = 0}, {x = -1, y = 0, z = 0}, {x = 0, y = -1, z = 0}, {x = 0, y = 1, z = 0}, {x = 0, y = 0, z = -1}, {x = 0, y = 0, z = 1}, } function hydroponics.toggle_light(pos, toggle_state, dug) if toggle_state then minetest.set_node(pos, {name = "hydroponics:grow_light_on"}) elseif not dug then minetest.set_node(pos, {name = "hydroponics:grow_light_off"}) end local p = {x = pos.x, y = pos.y - 1, z = pos.z} local n = minetest.get_node(p) local height = 0 while n.name == "air" and height ~= height_max do if toggle_state then minetest.set_node(p, {name = "air", param1 = 238}) else minetest.set_node(p, {name = "air", param1 = 0}) end p = {x = p.x, y = p.y - 1, z = p.z} n = minetest.get_node(p) height = height + 1 end end minetest.register_node("hydroponics:grow_light_off", { description = "Hydroponic Grow Light", tiles = { "hydroponics_grow_light_ts.png", "hydroponics_grow_light_b_off.png", "hydroponics_grow_light_ts.png" }, groups = {snappy = 2}, sounds = default.node_sound_stone_defaults(), on_punch = function(pos, node, puncher, pointed_thing) if not mesecons_mod then hydroponics.toggle_light(pos, true) else return end end, after_dig_node = function(pos, node, digger) hydroponics.toggle_light(pos, false, true) end, mesecons = { effector = { rules = grow_light_rules, action_on = function (pos, node) hydroponics.toggle_light(pos, true) end, action_off = function (pos, node) hydroponics.toggle_light(pos, false) end, }, }, }) minetest.register_node("hydroponics:grow_light_on", { description = "Hydroponic Grow Light (On)", tiles = { "hydroponics_grow_light_ts.png", "hydroponics_grow_light_b_on.png", "hydroponics_grow_light_ts.png" }, light_source = 14, drop = "hydroponics:grow_light_off", groups = {snappy = 2, not_in_creative_inventory = 1}, sounds = default.node_sound_stone_defaults(), on_punch = function(pos, node, puncher, pointed_thing) if not mesecons_mod then hydroponics.toggle_light(pos, false) else return end end, after_dig_node = function(pos, node, digger) hydroponics.toggle_light(pos, false, true) end, mesecons = { effector = { rules = grow_light_rules, action_on = function (pos, node) hydroponics.toggle_light(pos, true) end, action_off = function (pos, node) hydroponics.toggle_light(pos, false) end, }, }, }) minetest.register_craft({ output = "hydroponics:grow_light_off", recipe = { { "default:steel_ingot", "default:steel_ingot", "default:steel_ingot" }, { "default:steel_ingot", "default:torch", "default:steel_ingot" }, { "default:steel_ingot", "default:torch", "default:steel_ingot" }, }, })