content
stringlengths
5
1.05M
function HUDBGBox_recreate(panel, config) if not alive(panel) then log(debug.traceback()) return end panel:configure({ x = config.x, y = config.y, w = config.w, h = config.h, }) if config.name then config.alpha = Holo.Options:GetValue("HUDAlpha") or 0.25 config.frame_style = Holo:GetFrameStyle(config.name) local frame_color = Holo:GetFrameColor(config.name, true) if frame_color then config.frame_color = frame_color end config.color = Holo:GetColor("Colors/" .. config.name) end local color = config.color panel:child("bg"):configure({ alpha = config.alpha or Holo.Options:GetValue("HUDAlpha"), color = color or Color(0, 0, 0), }) HUDBGBox_create_frame(panel, config.frame_color, config.frame_style) end function HUDBGBox_create(panel, params, config) params = params or {} config = config or params local box_panel = panel:panel(params) local color = config.color local bg = box_panel:rect({ name = "bg", halign = "grow", valign = "grow", alpha = config.alpha or 0.25, color = color or Color(0, 0, 0), layer = -1 }) HUDBGBox_create_frame(box_panel, color == Color(1, 1, 0) and color or color == Color(1, 0, 0) and color) return box_panel end function HUDBGBox_create_frame(box_panel, color, style) color = color or Holo:GetColor("Colors/Frame") style = style or Holo.Options:GetValue("FrameStyle") local width = 1 if alive(box_panel:child("left_top")) then box_panel:remove(box_panel:child("left_top")) end if alive(box_panel:child("left_bottom")) then box_panel:remove(box_panel:child("left_bottom")) end if alive(box_panel:child("right_top")) then box_panel:remove(box_panel:child("right_top")) end if alive(box_panel:child("right_bottom")) then box_panel:remove(box_panel:child("right_bottom")) end local none = Holo.FrameStyles local opt = { halign = "left", valign = "top", rotation = 360, color = color, visible = style ~= none, layer = 10, } opt.name = "left_top" local left_top = box_panel:bitmap(opt) opt.name = "left_bottom" opt.valign = "bottom" local left_bottom = box_panel:bitmap(opt) opt.name = "right_top" opt.halign = "right" local right_top = box_panel:bitmap(opt) opt.name = "right_bottom" opt.valign = "bottom" local right_bottom = box_panel:bitmap(opt) if style == 1 then right_bottom:set_image("ui/holo/frame", 8,8,8,8) left_bottom:set_image("ui/holo/frame", 0,8,8,8) left_top:set_image("ui/holo/frame", 0,0,8,8) right_top:set_image("ui/holo/frame", 8,0,8,8) local s = 8 right_bottom:set_size(s,s) left_bottom:set_size(s,s) left_top:set_size(s,s) right_top:set_size(s,s) elseif style ~= none then local vis = style == 6 left_bottom:set_size(box_panel:w(), width) right_bottom:set_size(width, box_panel:h()) right_top:set_size(box_panel:w(), width) left_top:set_size(width, box_panel:h()) left_bottom:set_halign("grow") right_top:set_halign("grow") left_bottom:set_visible(vis or style == 2) left_top:set_visible(vis or style == 3) right_bottom:set_visible(vis or style == 4) right_top:set_visible(vis or style == 5) end right_bottom:set_rightbottom(box_panel:size()) right_top:set_right(box_panel:w()) left_bottom:set_bottom(box_panel:h()) end if Holo.Options:GetValue("TopHUD") and Holo:ShouldModify("HUD", "Objective") then function HUDObjectives:UpdateHolo() self.ObjPanel = self._panel or self._hud_panel:child("objectives_panel") self.ObjText = self.ObjPanel:child("objective_text") or self._bg_box:child("objective_text") self.AmountText = self.ObjPanel:child("amount_text") or self._bg_box:child("amount_text") if self.ObjPanel:child("icon_objectivebox") then self.ObjPanel:child("icon_objectivebox"):hide() end local box_height = 28 HUDBGBox_recreate(self._bg_box, { name = "Objective", x = 0, h = box_height, }) self.ObjText:configure({ color = Holo:GetColor("TextColors/Objective"), font_size = box_height - 6, vertical = "center", h = box_height, font = "fonts/font_large_mf" }) self:PosObjectives() end Holo:Post(HUDObjectives, "init", function(self) self:UpdateHolo() Holo:AddUpdateFunc(callback(self, self, "UpdateHolo")) end) function HUDObjectives:PosObjectives() if not WolfHUD then Holo.Utils:SetPosition(self.ObjPanel, "Objective") end end function HUDObjectives:activate_objective(data) self.AmountText:hide() self.AmountText:set_alpha(0) self._active_objective_id = data.id self._has_amount = data.amount ~= nil local amount = self._has_amount and (data.current_amount or 0) .. "/" .. data.amount self.ObjText:set_text(string.format("%s %s", utf8.to_upper(data.text), amount or "")) local _,_,w,_ = self.ObjText:text_rect() self._bg_box:stop() if not data.no_reset or not self.ObjPanel:visible() then self._bg_box:set_w(0) self.ObjText:set_w(0) self.ObjText:show() self.ObjPanel:show() self.ObjPanel:stop() self.ObjPanel:animate(callback(self, self, "_animate_activate_objective")) end self.ObjText:set_y(1) self.ObjText:set_x(4) self.ObjPanel:set_w(w + 8) play_value(self.ObjText, "w", w) play_value(self._bg_box, "w", w + 8) self:PosObjectives() end Holo:Post(HUDObjectives, "remind_objective", function(self) self._bg_box:child("bg"):stop() self.AmountText:stop() self.ObjText:stop() play_value(self.AmountText, "alpha", 0.25, {time = 1, callback = function() play_value(self.AmountTextt, "alpha", 1, {time = 1}) end}) play_value(self.ObjText, "alpha", 0.25, {time = 1, callback = function() play_value(self.ObjText, "alpha", 1, {time = 1}) end}) end) Holo:Post(HUDObjectives, "update_amount_objective", function(self, data) data.no_reset = true self:activate_objective(data) end) end
script.Parent.Fixer.Touched:connect(function(Hit) if Hit.Parent:FindFirstChild("Humanoid") then local Player = game.Players:GetPlayerFromCharacter(Hit.Parent) Hit.Parent.Humanoid:UnequipTools() if Player then Player.Backpack:ClearAllChildren() end Hit.Parent.Humanoid.WalkSpeed = 16 Hit.Parent.Humanoid.JumpPower = 50 end end) local DeeBee = true script.Parent.Prize.Reward.Touched:connect(function(Hit) if DeeBee then DeeBee = false local Player = game.Players:GetPlayerFromCharacter(Hit.Parent) if Player and Player:FindFirstChild("GoldClovers") and Player:FindFirstChild("TrialMode") then if Player.TrialMode.Value ~= "John" then Player.TrialMode.Value = "John" script.Parent.Prize:Destroy() game.ReplicatedStorage.Hint:FireClient(Player,"You got 30 Gold Clovers for beating John Doe's trial!") Player.GoldClovers.Value = Player.GoldClovers.Value + 30 game.BadgeService:AwardBadge(Player.userId,700526907) else script.Parent.Prize:Destroy() end end wait(0.1) DeeBee = true end end)
--property.lua --[[ local Object = class() prop = property(Object) prop:reader("id", 0) prop:accessor("name", "") --]] local WRITER = 1 local READER = 2 local ACCESSOR = 3 local pack = function(...) return {n = select('#',...), ...} end local function unequal(a, b) if type(a) ~= "table" then return a ~= b end for k, v in pairs(a) do if b[k] ~= v then return true end end return false end local function on_prop_changed(object, name, value) local f_prop_changed = object.on_prop_changed if f_prop_changed then f_prop_changed(object, value, name) end end local function prop_accessor(class, name, default, mode, watch) class.__props[name] = pack(default, mode, watch) if bit.band(mode, READER) == READER then class["get_" .. name] = function(self) return self[name] end if type(default) == "boolean" then class["is_" .. name] = class["get_" .. name] end end if bit.band(mode, WRITER) == WRITER then class["set_" .. name] = function(self, value, ...) local n = select("#", ...) if n > 0 then print("set prop args is so more!") end if unequal(self[name], value) then self[name] = value if watch then on_prop_changed(self, name, value) end end end end end local property_reader = function(self, name, default) prop_accessor(self.__class, name, default, READER) end local property_writer = function(self, name, default, watch) prop_accessor(self.__class, name, default, WRITER, watch) end local property_accessor = function(self, name, default, watch) prop_accessor(self.__class, name, default, ACCESSOR, watch) end function property(class) local prop = { __class = class, reader = property_reader, writer = property_writer, accessor = property_accessor } return prop end
--[[-- Tree container prototype. Note that Functions listed below are only available from the Tree prototype returned by requiring this module, because Container objects cannot have object methods. Prototype Chain --------------- table `-> Object `-> Container `-> Tree @classmod std.tree @see std.container ]] local base = require "std.base" local operator = require "std.operator" local Container = require "std.container" {} local ielems, ipairs, leaves, pairs, prototype = base.ielems, base.ipairs, base.leaves, base.pairs, base.prototype local last, len = base.last, base.len local reduce = base.reduce local Tree -- forward declaration --- Tree iterator. -- @tparam function it iterator function -- @tparam tree|table tr tree or tree-like table -- @treturn string type ("leaf", "branch" (pre-order) or "join" (post-order)) -- @treturn table path to node (`{i1, ...in}`) -- @treturn node node local function _nodes (it, tr) local p = {} local function visit (n) if type (n) == "table" then coroutine.yield ("branch", p, n) for i, v in it (n) do p[#p + 1] = i visit (v) table.remove (p) end coroutine.yield ("join", p, n) else coroutine.yield ("leaf", p, n) end end return coroutine.wrap (visit), tr end local function clone (t, nometa) local r = {} if not nometa then setmetatable (r, getmetatable (t)) end local d = {[t] = r} local function copy (o, x) for i, v in pairs (x) do if type (v) == "table" then if not d[v] then d[v] = {} if not nometa then setmetatable (d[v], getmetatable (v)) end o[i] = copy (d[v], v) else o[i] = d[v] end else o[i] = v end end return o end return copy (r, t) end local function merge (t, u) for ty, p, n in _nodes (pairs, u) do if ty == "leaf" then t[p] = n end end return t end --[[ ============ ]]-- --[[ Tree Object. ]]-- --[[ ============ ]]-- local function X (decl, fn) return require "std.debug".argscheck ("std.tree." .. decl, fn) end --- Tree prototype object. -- @object Tree -- @string[opt="Tree"] _type object name -- @see std.container -- @see std.object.__call -- @usage -- local std = require "std" -- local Tree = std.tree {} -- local tr = Tree {} -- tr[{"branch1", 1}] = "leaf1" -- tr[{"branch1", 2}] = "leaf2" -- tr[{"branch2", 1}] = "leaf3" -- print (tr[{"branch1"}]) --> Tree {leaf1, leaf2} -- print (tr[{"branch1", 2}]) --> leaf2 -- print (tr[{"branch1", 3}]) --> nil -- --> leaf1 leaf2 leaf3 -- for leaf in std.tree.leaves (tr) do -- io.write (leaf .. "\t") -- end Tree = Container { _type = "Tree", --- Deep retrieval. -- @static -- @function __index -- @tparam Tree tr a tree -- @param i non-table, or list of keys `{i1, ...i_n}` -- @return `tr[i1]...[i_n]` if *i* is a key list, `tr[i]` otherwise -- @todo the following doesn't treat list keys correctly -- e.g. tr[{{1, 2}, {3, 4}}], maybe flatten first? -- @usage -- del_other_window = keymap[{"C-x", "4", KEY_DELETE}] __index = X ("__index (Tree, any)", function (tr, i) if prototype (i) == "table" then return reduce (operator.deref, tr, ielems, i) else return rawget (tr, i) end end), --- Deep insertion. -- @static -- @function __newindex -- @tparam Tree tr a tree -- @param i non-table, or list of keys `{i1, ...i_n}` -- @param[opt] v value -- @usage -- function bindkey (keylist, fn) keymap[keylist] = fn end __newindex = X ("__newindex (Tree, any, any?)", function (tr, i, v) if prototype (i) == "table" then for n = 1, len (i) - 1 do if prototype (tr[i[n]]) ~= "Tree" then rawset (tr, i[n], Tree {}) end tr = tr[i[n]] end rawset (tr, last (i), v) else rawset (tr, i, v) end end), _functions = { --- Make a deep copy of a tree, including any metatables. -- @static -- @function clone -- @tparam table t tree or tree-like table -- @tparam boolean nometa if non-`nil` don't copy metatables -- @treturn Tree|table a deep copy of *tr* -- @see std.table.clone -- @usage -- tr = {"one", {two=2}, {{"three"}, four=4}} -- copy = clone (tr) -- copy[2].two=5 -- assert (tr[2].two == 2) clone = X ("clone (table, boolean|:nometa?)", clone), --- Tree iterator which returns just numbered leaves, in order. -- @static -- @function ileaves -- @tparam Tree|table tr tree or tree-like table -- @treturn function iterator function -- @treturn Tree|table the tree *tr* -- @see inodes -- @see leaves -- @usage -- --> t = {"one", "three", "five"} -- for leaf in ileaves {"one", {two=2}, {{"three"}, four=4}}, foo="bar", "five"} -- do -- t[#t + 1] = leaf -- end ileaves = X ("ileaves (table)", function (t) return leaves (ipairs, t) end), --- Tree iterator over numbered nodes, in order. -- -- The iterator function behaves like @{nodes}, but only traverses the -- array part of the nodes of *tr*, ignoring any others. -- @static -- @function inodes -- @tparam Tree|table tr tree or tree-like table to iterate over -- @treturn function iterator function -- @treturn tree|table the tree, *tr* -- @see nodes inodes = X ("inodes (table)", function (t) return _nodes (ipairs, t) end), --- Tree iterator which returns just leaves. -- @static -- @function leaves -- @tparam table t tree or tree-like table -- @treturn function iterator function -- @treturn table *t* -- @see ileaves -- @see nodes -- @usage -- for leaf in leaves {"one", {two=2}, {{"three"}, four=4}}, foo="bar", "five"} -- do -- t[#t + 1] = leaf -- end -- --> t = {2, 4, "five", "foo", "one", "three"} -- table.sort (t, lambda "=tostring(_1) < tostring(_2)") leaves = X ("leaves (table)", function (t) return leaves (pairs, t) end), --- Destructively deep-merge one tree into another. -- @static -- @function merge -- @tparam table t destination tree -- @tparam table u table with nodes to merge -- @treturn table *t* with nodes from *u* merged in -- @see std.table.merge -- @usage -- merge (dest, {{exists=1}, {{not = {present = { inside = "dest" }}}}}) merge = X ("merge (table, table)", merge), --- Tree iterator over all nodes. -- -- The returned iterator function performs a depth-first traversal of -- `tr`, and at each node it returns `{node-type, tree-path, tree-node}` -- where `node-type` is `branch`, `join` or `leaf`; `tree-path` is a -- list of keys used to reach this node, and `tree-node` is the current -- node. -- -- Note that the `tree-path` reuses the same table on each iteration, so -- you must `table.clone` a copy if you want to take a snap-shot of the -- current state of the `tree-path` list before the next iteration -- changes it. -- @static -- @function nodes -- @tparam Tree|table tr tree or tree-like table to iterate over -- @treturn function iterator function -- @treturn Tree|table the tree, *tr* -- @see inodes -- @usage -- -- tree = +-- node1 -- -- | +-- leaf1 -- -- | '-- leaf2 -- -- '-- leaf 3 -- tree = Tree { Tree { "leaf1", "leaf2"}, "leaf3" } -- for node_type, path, node in nodes (tree) do -- print (node_type, path, node) -- end -- --> "branch" {} {{"leaf1", "leaf2"}, "leaf3"} -- --> "branch" {1} {"leaf1", "leaf"2") -- --> "leaf" {1,1} "leaf1" -- --> "leaf" {1,2} "leaf2" -- --> "join" {1} {"leaf1", "leaf2"} -- --> "leaf" {2} "leaf3" -- --> "join" {} {{"leaf1", "leaf2"}, "leaf3"} -- os.exit (0) nodes = X ("nodes (table)", function (t) return _nodes (pairs, t) end), }, } return Tree
--------------------------------------------------------------- -- A doubly linked list Node -- -- @classmod LNode -- @author jose@josellausas.com --------------------------------------------------------------- local LNode = {} LNode.__index = LNode --------------------------------------------------------------- -- Creates a new node containing the data -- @constructor -- -- @param data **(any)** The data -- @return **(Node)** New Node --------------------------------------------------------------- function LNode.new(data) local self = {} self.next = nil self.prev = nil -- Weak table references self.ref = {} setmetatable(self.ref, { __mode = 'v' }) self.ref.data = data setmetatable(self, LNode) return self end function LNode:setData(data) self.ref.data = data end --------------------------------------------------------------- -- Returns the next node -- -- @return **(Node)** The next node (can be nil) --------------------------------------------------------------- function LNode:getNext() return self.next end --------------------------------------------------------------- -- Returns the previous node. Can be nil -- -- @return **(Node)** The previous node --------------------------------------------------------------- function LNode:getPrev() return self.prev end --------------------------------------------------------------- -- Returns the data -- -- @return **(Node)** The data contained by this node --------------------------------------------------------------- function LNode:getData() return self.ref.data end return LNode
local drawableSpriteStruct = require("structs.drawable_sprite") local colors = require("consts.xna_colors") local utils = require("utils") local introCar = {} local barrierTexture = "scenery/car/barrier" local bodyTexture = "scenery/car/body" local pavementTexture = "scenery/car/pavement" local wheelsTexture = "scenery/car/wheels" introCar.name = "introCar" introCar.placements = { name = "intro_car", data = { hasRoadAndBarriers = false } } function introCar.sprite(room, entity) local sprites = {} local x, y = entity.x, entity.y local hasRoadAndBarriers = entity.hasRoadAndBarriers local bodySprite = drawableSpriteStruct.fromTexture(bodyTexture, entity) bodySprite:setJustification(0.5, 1.0) bodySprite.depth = 1 local wheelSprite = drawableSpriteStruct.fromTexture(wheelsTexture, entity) wheelSprite:setJustification(0.5, 1.0) wheelSprite.depth = 3 table.insert(sprites, bodySprite) table.insert(sprites, wheelSprite) if hasRoadAndBarriers then utils.setSimpleCoordinateSeed(x, y) local pavementWidth = x - 48 local columns = math.floor(pavementWidth / 8) for column = 0, columns - 1 do local choice = column >= columns - 2 and (column ~= columns - 2 and 3 or 2) or math.random(0, 2) local pavementSprite = drawableSpriteStruct.fromTexture(pavementTexture, entity) pavementSprite:addPosition(column * 8 - x, 0) pavementSprite.depth = -10001 pavementSprite:setJustification(0.0, 0.0) pavementSprite:useRelativeQuad(choice * 8, 0, 8, 8) table.insert(sprites, pavementSprite) end local barrier1Sprite = drawableSpriteStruct.fromTexture(barrierTexture, entity) barrier1Sprite:addPosition(32, 0) barrier1Sprite:setJustification(0.0, 1.0) barrier1Sprite.depth = -10 local barrier2Sprite = drawableSpriteStruct.fromTexture(barrierTexture, entity) barrier2Sprite:addPosition(41, 0) barrier2Sprite:setJustification(0.0, 1.0) barrier2Sprite.depth = 5 barrier2Sprite.color = colors.DarkGray table.insert(sprites, barrier1Sprite) table.insert(sprites, barrier2Sprite) end return sprites end function introCar.selection(room, entity) local bodySprite = drawableSpriteStruct.fromTexture(bodyTexture, entity) local wheelSprite = drawableSpriteStruct.fromTexture(wheelsTexture, entity) bodySprite:setJustification(0.5, 1.0) wheelSprite:setJustification(0.5, 1.0) return utils.rectangle(utils.coverRectangles({bodySprite:getRectangle(), wheelSprite:getRectangle()})) end return introCar
local function main() -- Varitables local w, h = term.getSize() local lang = multishell.getLanguage() local theme = multishell.loadTheme() local peripheralList = peripheral.getNames() local formattedPeripheralList = {} local menu = 0 local selectedId = 0 local selected = 0 local selectedPeripheral = 0 local listX local listY local selectedList local listMaxX local dropdown = false multishell.setTitle(multishell.getFocus(), lang.applications.peripherals.title) local function searchPeripheralsForName(name) for i, v in pairs(formattedPeripheralList) do if v.name == name then return i end end return nil end local function findInTable(tbl, name) for i, v in pairs(tbl) do if v == name then return i end end return nil end local function setSetting(name, value) local f = fs.open("/zOS/Configuration/configuration.txt", "r") local configData = textutils.unserialize(f.readAll()) f.close() local f = fs.open("/zOS/Configuration/configuration.txt", "w") configData[name] = value f.write(textutils.serialize(configData)) f.close() return true end local function updateFormattedPeripheralList() -- Load peripherals file local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "r") formattedPeripheralList = textutils.unserialize(peripheralsFile.readAll()) peripheralsFile.close() local updateRequest = {} local newTable = {} peripheralList = peripheral.getNames() for i, v in pairs(peripheralList) do table.insert(updateRequest, v) end for i, v in pairs(formattedPeripheralList) do if not findInTable(peripheralList, v.name) then table.insert(updateRequest, v.name) end end for i, v in pairs(updateRequest) do local tbl = {} local item = searchPeripheralsForName(v) if formattedPeripheralList[item] == nil then tbl = { name = v, customName = v, type = peripheral.getType(v), connected = true, } else tbl = { name = v, customName = formattedPeripheralList[item].customName, type = peripheral.getType(v) or formattedPeripheralList[item].type, connected = true, } if peripheral.getType(v) == nil or peripheral.getType(v) == "nil" or peripheral.getType(v) == "" then tbl = { name = v, customName = formattedPeripheralList[item].customName, type = formattedPeripheralList[item].type, connected = false, } if tbl.type == "computer" or tbl.type == "turtle" and tbl.connected == false then tbl.id = formattedPeripheralList[item].id tbl.label = formattedPeripheralList[item].label tbl.isOn = formattedPeripheralList[item].isOn elseif tbl.type == "drive" and tbl.connected == true then if formattedPeripheralList[item].diskType == "Audio" then tbl.diskType = "Audio" tbl.label = formattedPeripheralList[item].label elseif formattedPeripheralList[item].diskType == "Data" then tbl.diskType = "Data" tbl.id = formattedPeripheralList[item].id tbl.label = formattedPeripheralList[item].label tbl.mountPath = formattedPeripheralList[item].mountPath elseif formattedPeripheralList[item].diskType == "No disk" then tbl.diskType = "No disk" end end else tbl = formattedPeripheralList[item] end end -- comupters if tbl.type == "computer" and tbl.connected == true or tbl.type == "turtle" and tbl.connected == true then local computer = peripheral.wrap(tbl.name) tbl.id = computer.getID() tbl.label = computer.getLabel() or "None" tbl.isOn = computer.isOn() elseif tbl.type == "drive" and tbl.connected == true then local drive = peripheral.wrap(tbl.name) if drive.hasAudio() then tbl.diskType = "Audio" tbl.label = drive.getAudioTitle() elseif drive.hasData() then tbl.diskType = "Data" tbl.id = drive.getDiskID() tbl.label = drive.getDiskLabel() or "None" tbl.mountPath = drive.getMountPath() elseif drive.isDiskPresent() == false then tbl.diskType = "No disk" end elseif tbl.type == "monitor" and tbl.connected == true then if tbl.primary == nil then tbl.primary = false end if tbl.textScale == nil then tbl.textScale = 1 end end newTable[i] = tbl end -- Save peripherals file local formattedPeripheralsString = textutils.serialize(newTable) local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "w") peripheralsFile.write(formattedPeripheralsString) peripheralsFile.close() formattedPeripheralList = newTable end local function removeDisconnectedPeripheral(id) -- Load peripherals file local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "r") formattedPeripheralList = textutils.unserialize(peripheralsFile.readAll()) peripheralsFile.close() local newTable = formattedPeripheralList newTable[id] = nil -- Save peripherals file local formattedPeripheralsString = textutils.serialize(newTable) local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "w") peripheralsFile.write(formattedPeripheralsString) peripheralsFile.close() formattedPeripheralList = newTable updateFormattedPeripheralList() end local function renamePeripheral(id, name) -- Load peripherals file local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "r") newFPL = textutils.unserialize(peripheralsFile.readAll()) peripheralsFile.close() local newTable = newFPL newTable[id].customName = name -- Save peripherals file local formattedPeripheralsString = textutils.serialize(newTable) local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "w") peripheralsFile.write(formattedPeripheralsString) peripheralsFile.close() formattedPeripheralList = newTable end local function draw(selected) menu = 1 term.setBackgroundColor(theme.background) term.clear() peripheralList = peripheral.getNames() -- Update in case any new peripherals were added since last draw updateFormattedPeripheralList() -- Draw top term.setCursorPos(1,1) term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightGray) term.clearLine() if selected == 1 then term.setBackgroundColor(colors.lightGray) term.setTextColor(colors.gray) end write(lang.applications.peripherals.peripheralDD.name) term.setCursorPos(1+string.len(lang.applications.peripherals.peripheralDD.name),1) term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightGray) if selected == 2 then term.setBackgroundColor(colors.lightGray) term.setTextColor(colors.gray) end write(lang.applications.peripherals.monitorDD.name) -- Draw key term.setCursorPos(2,2) term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightGray) term.clearLine() term.write(lang.applications.peripherals.key.name) term.setCursorPos(w/2,2) term.write(lang.applications.peripherals.key.type) term.setTextColor(theme.text) -- Draw peripheral list for i, v in pairs(formattedPeripheralList) do term.setCursorPos(2,i+2) term.setBackgroundColor(theme.background) if selectedPeripheral == i then term.setBackgroundColor(colors.lightGray) end term.setTextColor(theme.text) if v.primary == true then term.setTextColor(colors.green) end term.clearLine() if v.connected == false then term.setTextColor(colors.red) end term.write(v.customName) term.setCursorPos(w/2,i+2) term.write(v.type) end end local function drawDropdown(x,y,list,selected) menu = 1 listX = x listY = y selectedList = list dropdown = true draw(selected) term.setCursorPos(x,y) local maxLength = 0 for i, v in ipairs(list) do if string.len(v.text) > maxLength then maxLength = string.len(v.text) end end listMaxX = maxLength paintutils.drawFilledBox(x,y,x+maxLength+1,y+#list-1, colors.gray) for i, v in pairs(list) do term.setTextColor(colors.lightGray) if v.condition() == true then term.setTextColor(colors.white) end term.setCursorPos(x+1,y+i-1) print(v.text) end end local function loadPeripheral(id) term.setBackgroundColor(theme.background) term.clear() menu = 2 selectedId = id local data = formattedPeripheralList[id] -- Draw topbar term.setCursorPos(2,1) term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightGray) term.clearLine() term.write(data.type.." "..data.name) term.setCursorPos(w-1, 1) term.setTextColor(colors.white) term.write("\215") local posAdd = 0 -- Check if peripheral is not currently connected term.setBackgroundColor(theme.background) if data.connected == false then posAdd = 3 term.setCursorPos(2,3) term.setTextColor(colors.red) term.write(lang.applications.peripherals.itemMenu.peripheralNotConnected) term.setBackgroundColor(colors.red) term.setTextColor(colors.white) term.setCursorPos(2,4) term.write(lang.applications.peripherals.itemMenu.removeButton) end -- Draw application information term.setBackgroundColor(theme.background) term.setTextColor(theme.text) term.setCursorPos(2,3+posAdd) term.write(lang.applications.peripherals.itemMenu.name:format(data.name)) term.setCursorPos(2,4+posAdd) term.write(lang.applications.peripherals.itemMenu.type:format(data.type)) -- Stuff for computers if data.type == "computer" or data.type == "turtle" then -- Draw computer information term.setCursorPos(2,5+posAdd) term.write(lang.applications.peripherals.itemMenu.computer.id:format(data.id)) term.setCursorPos(2,6+posAdd) term.write(lang.applications.peripherals.itemMenu.computer.label:format(data.label)) term.setCursorPos(2,7+posAdd) term.write(lang.applications.peripherals.itemMenu.computer.isOn:format(tostring(data.isOn))) -- Draw buttons if data.connected == true then if data.isOn == true then -- Code for computers that are on -- Reboot term.setCursorPos(2,9+posAdd) term.setTextColor(colors.black) term.setBackgroundColor(colors.orange) term.write(lang.applications.peripherals.itemMenu.computer.reboot) -- Shutdown term.setCursorPos(3+string.len(lang.applications.peripherals.itemMenu.computer.reboot), 9+posAdd) term.setBackgroundColor(colors.red) term.setTextColor(colors.white) term.write(lang.applications.peripherals.itemMenu.computer.shutdown) elseif data.isOn == false then -- Code for computers that are off -- Turn on term.setCursorPos(2,9+posAdd) term.setTextColor(colors.black) term.setBackgroundColor(colors.lime) term.write(lang.applications.peripherals.itemMenu.computer.turnOn) end end elseif data.type == "drive" then if data.diskType == "No disk" then term.setCursorPos(2,5+posAdd) term.write(lang.applications.peripherals.itemMenu.drive.noDisk) elseif data.diskType == "Data" then term.setCursorPos(2,5+posAdd) term.write(lang.applications.peripherals.itemMenu.drive.diskType:format(data.diskType)) term.setCursorPos(2,6+posAdd) term.write(lang.applications.peripherals.itemMenu.drive.id:format(data.id)) term.setCursorPos(2,7+posAdd) term.write(lang.applications.peripherals.itemMenu.drive.label:format(data.label)) term.setCursorPos(2,8+posAdd) term.write(lang.applications.peripherals.itemMenu.drive.mountPath:format(data.mountPath)) -- Eject term.setCursorPos(2,10+posAdd) term.setTextColor(colors.white) term.setBackgroundColor(colors.red) term.write(lang.applications.peripherals.itemMenu.drive.eject) -- Open in files term.setCursorPos(3+string.len(lang.applications.peripherals.itemMenu.drive.eject), 10+posAdd) term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightGray) term.write(lang.applications.peripherals.itemMenu.drive.openInFiles) elseif data.diskType == "Audio" then term.setCursorPos(2,5+posAdd) term.write(lang.applications.peripherals.itemMenu.drive.diskType:format(data.diskType)) term.setCursorPos(2,6+posAdd) term.write(lang.applications.peripherals.itemMenu.drive.songName:format(data.label)) -- Eject term.setCursorPos(2,8+posAdd) term.setTextColor(colors.white) term.setBackgroundColor(colors.red) term.write(lang.applications.peripherals.itemMenu.drive.eject) -- Play term.setCursorPos(3+string.len(lang.applications.peripherals.itemMenu.drive.eject), 8+posAdd) term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightGray) term.write(lang.applications.peripherals.itemMenu.drive.play) -- Stop term.setCursorPos(4+string.len(lang.applications.peripherals.itemMenu.drive.eject)+string.len(lang.applications.peripherals.itemMenu.drive.play), 8+posAdd) term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightGray) term.write(lang.applications.peripherals.itemMenu.drive.stop) end elseif data.type == "monitor" then term.setCursorPos(2,6) term.write("Text Scale") term.setCursorPos(2,7) term.setBackgroundColor(colors.lightGray) term.setTextColor(colors.gray) term.write(" - ") term.setCursorPos(8,7) term.write(" + ") if string.len(tostring(data.textScale)) == 3 then term.setCursorPos(5,7) term.write(data.textScale) elseif string.len(tostring(data.textScale)) == 1 then term.setCursorPos(5,7) term.write(" "..data.textScale.." ") end end end local function textDialog(title,message) paintutils.drawFilledBox(w/2-15,h/2-4,w/2+16,h/2+4,colors.white) paintutils.drawBox(w/2-15,h/2-4,w/2+16,h/2+4,colors.lightGray) paintutils.drawLine(w/2-15,h/2-4,w/2+16,h/2-4,colors.gray) term.setCursorPos(w/2-14,h/2-4) term.setTextColor(colors.lightGray) term.write(title) local lineChar = 1 local str = message local line = "" term.setTextColor(colors.gray) term.setBackgroundColor(colors.white) pos = h/2-3 for i = 1, string.len(str) do if lineChar == 31 then lineChar = 1 line = "" pos = pos + 1 end line = line .. string.sub(str, i, i) term.setCursorPos(w/2-14, pos) term.write(line) lineChar = lineChar + 1 end paintutils.drawLine(w/2-13,h/2+2,w/2+14,h/2+2,colors.gray) term.setCursorPos(w/2-12,h/2+2) term.setTextColor(colors.lightGray) local text = read() draw() return text end local peripheralDropdown = { { text = lang.applications.peripherals.peripheralDD.rename, condition = function() return selectedPeripheral ~= 0 end, action = function() if selectedPeripheral ~= 0 then local name = textDialog("Rename", "Enter a new name for the peripheral") renamePeripheral(selectedPeripheral, name) updateFormattedPeripheralList() draw() end end }, { text = lang.applications.peripherals.peripheralDD.remove, condition = function() return selectedPeripheral ~= 0 and formattedPeripheralList[selectedPeripheral].connected == false end, action = function() if selectedPeripheral ~= 0 then if formattedPeripheralList[selectedPeripheral].connected == false then removeDisconnectedPeripheral(selectedPeripheral) selectedPeripheral = 0 draw() end end end }, { text = lang.applications.peripherals.peripheralDD.resetName, condition = function() return selectedPeripheral ~= 0 and formattedPeripheralList[selectedPeripheral].name ~= formattedPeripheralList[selectedPeripheral].customName end, action = function() if selectedPeripheral ~= 0 then if formattedPeripheralList[selectedPeripheral].name ~= formattedPeripheralList[selectedPeripheral].customName then renamePeripheral(selectedPeripheral, formattedPeripheralList[selectedPeripheral].name) updateFormattedPeripheralList() draw() end end end }, } local monitorDropdown = { { text = lang.applications.peripherals.monitorDD.setPrimary, condition = function() if selectedPeripheral ~= 0 then return formattedPeripheralList[selectedPeripheral].type == "monitor" and formattedPeripheralList[selectedPeripheral].connected == true and formattedPeripheralList[selectedPeripheral].primary == false else return false end end, action = function() if selectedPeripheral ~= 0 then if formattedPeripheralList[selectedPeripheral].type == "monitor" and formattedPeripheralList[selectedPeripheral].connected == true and formattedPeripheralList[selectedPeripheral].primary == false then -- Load peripherals file local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "r") newFPL = textutils.unserialize(peripheralsFile.readAll()) peripheralsFile.close() for i, v in pairs(newFPL) do if v.type == "monitor" then if v.primary == true then v.primary = false end end end newFPL[selectedPeripheral].primary = true -- Save peripherals file local formattedPeripheralsString = textutils.serialize(newFPL) local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "w") peripheralsFile.write(formattedPeripheralsString) peripheralsFile.close() formattedPeripheralList = newFPL draw() end end end }, { text = ddText, condition = function() return true end, action = function() if multishell.getSetting('bootToMonitor') == true then setSetting('bootToMonitor', false) elseif multishell.getSetting('bootToMonitor') == false then setSetting('bootToMonitor', true) end draw() end } } draw() -- Application loop while true do local e = {os.pullEvent()} if e[1] == 'mouse_click' then local m, x, y = e[2], e[3], e[4] if menu == 1 then if dropdown == true then local found = false for i, v in pairs(selectedList) do if x >= listX and x <= listX+listMaxX and y == listY+i-1 then v.action() found = true end end if found == false then dropdown = false selectedList = nil menu = 1 --draw() end end for i, v in pairs(formattedPeripheralList) do if y == i+2 and dropdown == false then if selectedPeripheral == i then loadPeripheral(i) selectedPeripheral = 0 else selectedPeripheral = i draw() end end end if y == 1 and x >= 1 and x <= string.len(lang.applications.peripherals.peripheralDD.name) then drawDropdown(1,2,peripheralDropdown, 1) elseif y == 1 and x >= string.len(lang.applications.peripherals.peripheralDD.name) and x <= string.len(lang.applications.peripherals.peripheralDD.name)+string.len(lang.applications.peripherals.monitorDD.name) then if multishell.getSetting('bootToMonitor') == true then monitorDropdown[2].text = lang.applications.peripherals.monitorDD.bootToMonitorEnabled else monitorDropdown[2].text = lang.applications.peripherals.monitorDD.bootToMonitorDisabled end drawDropdown(string.len(lang.applications.peripherals.peripheralDD.name),2,monitorDropdown, 2) end elseif menu == 2 then local data = formattedPeripheralList[selectedId] if x == w-1 and y == 1 then draw() elseif data.connected == true then if data.type == "computer" or data.type == "turtle" then if data.isOn == true then if x >= 2 and x <= 2+string.len(lang.applications.peripherals.itemMenu.computer.reboot) and y == 9 then local computer = peripheral.wrap(data.name) computer.reboot() sleep(0.1) peripheralList = peripheral.getNames() updateFormattedPeripheralList() loadPeripheral(selectedId) elseif x >= 3+string.len(lang.applications.peripherals.itemMenu.computer.reboot) and x <= 3+string.len(lang.applications.peripherals.itemMenu.computer.reboot)+string.len(lang.applications.peripherals.itemMenu.computer.shutdown) and y == 9 then local computer = peripheral.wrap(data.name) computer.shutdown() sleep(0.1) peripheralList = peripheral.getNames() updateFormattedPeripheralList() loadPeripheral(selectedId) end elseif data.isOn == false then if x >= 2 and x <= 2+string.len(lang.applications.peripherals.itemMenu.computer.turnOn) and y == 9 then local computer = peripheral.wrap(data.name) computer.turnOn() sleep(0.1) peripheralList = peripheral.getNames() updateFormattedPeripheralList() loadPeripheral(selectedId) end end elseif data.type == "drive" then if data.diskType == "Audio" then if x >= 2 and x <= string.len(lang.applications.peripherals.itemMenu.drive.eject) and y == 8 then peripheral.call(data.name, "ejectDisk") sleep(0.1) peripheralList = peripheral.getNames() updateFormattedPeripheralList() loadPeripheral(selectedId) elseif x >= 3+string.len(lang.applications.peripherals.itemMenu.drive.eject) and x <= 3+string.len(lang.applications.peripherals.itemMenu.drive.eject)+string.len(lang.applications.peripherals.itemMenu.drive.play) and y == 8 then peripheral.call(data.name, "playAudio") sleep(0.1) peripheralList = peripheral.getNames() updateFormattedPeripheralList() loadPeripheral(selectedId) elseif x >= 4+string.len(lang.applications.peripherals.itemMenu.drive.eject)+string.len(lang.applications.peripherals.itemMenu.drive.openInFiles) and x <= 4+string.len(lang.applications.peripherals.itemMenu.drive.eject)+string.len(lang.applications.peripherals.itemMenu.drive.play)+string.len(lang.applications.peripherals.itemMenu.drive.stop) and y == 8 then peripheral.call(data.name, "stopAudio") sleep(0.1) peripheralList = peripheral.getNames() updateFormattedPeripheralList() loadPeripheral(selectedId) end elseif data.diskType == "Data" then if x >= 2 and x <= string.len(lang.applications.peripherals.itemMenu.drive.eject) and y == 10 then peripheral.call(data.name, "ejectDisk") sleep(0.1) peripheralList = peripheral.getNames() updateFormattedPeripheralList() loadPeripheral(selectedId) elseif x >= 3+string.len(lang.applications.peripherals.itemMenu.drive.eject) and x <= 3+string.len(lang.applications.peripherals.itemMenu.drive.eject)+string.len(lang.applications.peripherals.itemMenu.drive.openInFiles) and y == 10 then multishell.setFocus(multishell.launch({ ['shell'] = shell, ['multishell'] = multishell, }, "/zOS/Applications/zFile.lua", "/"..data.mountPath.."/")) os.queueEvent('multishell_redraw') end end elseif data.type == "monitor" then if x >= 2 and x <= 4 and y == 7 then if data.textScale ~= 0.5 then term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightGray) term.setCursorPos(2,7) term.write(" - ") -- Load peripherals file local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "r") newFPL = textutils.unserialize(peripheralsFile.readAll()) peripheralsFile.close() for i, v in pairs(newFPL) do if i == selectedId then v.textScale = v.textScale - 0.5 end end -- Save peripherals file local formattedPeripheralsString = textutils.serialize(newFPL) local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "w") peripheralsFile.write(formattedPeripheralsString) peripheralsFile.close() formattedPeripheralList = newFPL sleep(0.1) loadPeripheral(selectedId) end elseif x >= 8 and x <= 10 and y == 7 then if data.textScale ~= 5 then term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightGray) term.setCursorPos(8,7) term.write(" + ") -- Load peripherals file local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "r") newFPL = textutils.unserialize(peripheralsFile.readAll()) peripheralsFile.close() for i, v in pairs(newFPL) do if i == selectedId then v.textScale = v.textScale + 0.5 end end -- Save peripherals file local formattedPeripheralsString = textutils.serialize(newFPL) local peripheralsFile = fs.open('zOS/Configuration/peripherals.txt', "w") peripheralsFile.write(formattedPeripheralsString) peripheralsFile.close() formattedPeripheralList = newFPL sleep(0.1) loadPeripheral(selectedId) end end end elseif data.connected == false then if x >= 2 and x <= 2+string.len(lang.applications.peripherals.itemMenu.removeButton) and y == 4 then draw() removeDisconnectedPeripheral(selectedId) draw() end end end end end end local ok, err = pcall(main) if not ok then if err ~= 'Terminated' then local w, h = term.getSize() paintutils.drawFilledBox(w/2-15,h/2-4,w/2+16,h/2+4,colors.white) paintutils.drawBox(w/2-15,h/2-4,w/2+16,h/2+4,colors.lightGray) paintutils.drawLine(w/2-15,h/2-4,w/2+16,h/2-4,colors.gray) term.setCursorPos(w/2-14,h/2-4) term.setTextColor(colors.lightGray) term.write("Application error") local lineChar = 1 local str = "An application error has occured and the program you were using has been forced to close. Here's the error: ".. err local line = "" term.setTextColor(colors.gray) term.setBackgroundColor(colors.white) pos = h/2-3 for i = 1, string.len(str) do if lineChar == 31 then lineChar = 1 line = "" pos = pos + 1 end line = line .. string.sub(str, i, i) term.setCursorPos(w/2-14, pos) term.write(line) lineChar = lineChar + 1 end term.setCursorPos(w/2-14,h/2+3) term.write('Press any key to exit') sleep(0.5) os.pullEvent('char') end end
print("guard") local a do local b print("guard") b = f() a = b end return a
description 'GTA V Blips' client_script 'blips.lua'
local Permissions = require(game.ReplicatedStorage.Helpers.Permissions) return function (registry) registry:RegisterHook("BeforeRun", function(context) if context.Group == "Admin" and not Permissions:IsAdmin(context.Executor.UserId) then return "You can't run this command." end end) end
FFI = require("ffi") FFI.type = {} FFI.type.VOID = 0 FFI.type.UINT8 = 1 FFI.type.SINT8 = 2 FFI.type.UINT16 = 3 FFI.type.SINT16 = 4 FFI.type.UINT32 = 5 FFI.type.SINT32 = 6 FFI.type.UINT64 = 7 FFI.type.SINT64 = 8 FFI.type.FLOAT = 9 FFI.type.DOUBLE = 10 FFI.type.UCHAR = 11 FFI.type.SCHAR = 12 FFI.type.USHORT = 13 FFI.type.SSHORT = 14 FFI.type.UINT = 15 FFI.type.SINT = 16 FFI.type.ULONG = 17 FFI.type.SLONG = 18 FFI.type.LONGDOUBLE = 19 FFI.type.POINTER = 20 FFI.cache = {} FFI.load = function(path) if FFI.cache[path] then return FFI.cache[path] else print("Loading: "..path) local lib = FFI.dlopen(path) if lib then FFI.cache[path] = {ref = lib, fn= {}} end return FFI.cache[path] end end FFI.unload = function(path) local lib = FFI.cache[path] if lib then FFI.dlclose(lib.ref) FFI.cache[path] = false end end FFI.unloadAll = function() for k,v in pairs(FFI.cache) do FFI.dlclose(v.ref) end FFI.cache = {} end FFI.lookup = function(lib, name) local fn = lib.fn[name] if fn then return fn end fn = FFI.dlsym(lib.ref, name) if fn then lib.fn[name] = fn return fn end return nil end
class 'AgentCore' function AgentCore:__init( args ) -- Bare minimum intiialization here self.position = args.position self.angle = args.angle or Angle() self.debug = {} self.timer = Timer() self.time = 250 self.vehicle = args.vehicle self.fov = AddTriangle( self.position, 10 ) self.flagged_for_deletion = false local vehicle_id = nil if self.vehicle then vehicle_id = self.vehicle:GetId() end -- network object self.network_object = WorldNetworkObject.Create( self.position, { class = 'NPC', -- the name of the class that will handle this WNO on client type = 'Actor', -- will be handled by the ActorManager on the client angle = self.angle, speed = args.speed or 0, model_id = args.model_id, health = args.health or 100, max_health = args.health or 100, goal = args.goal, in_vehicle = vehicle_id, name = args.name } ) local id = self.network_object:GetId() -- stream self.cell = {} self.cell.x, self.cell.y = GetCellXYFromPosition( self.position ) AddActorToCell( self, self.cell.x, self.cell.y ) -- network self.sync_tick = 6 self.net_tick = self.sync_tick -- logic self.logic_controller = {} -- identity self.faction = args.faction -- configure self:ConfigureNPC( args ) -- enter object into lookup table AM.actors_id[id] = self end function AgentCore:Tick( frame_time ) local network_object = self.network_object if not network_object or not IsValid( network_object ) then return end if self.dead then if self.dead_timer:GetSeconds() > 15 then self:Remove() end return end -- if this npc is flagged for deletion, don't run logic this frame if self.flagged_for_deletion then return end -- net_tick logic self:CalcNetTick() -- run defined logic controllers local lc = self.logic_controller -- logic controllers -- When the agent enters a vehicle, its onfoot logic controller will be -- replaced with logic that suits the vehicle type. The previous logic -- is destroyed during this time and needs to be recreated when the agent -- leaves the vehicle. -- lc[1] = MOVEMENT, IE: OnFoot, [Land/Sea/Heli/Plane]Driver -- lc[2] = ROLE LOGIC, IE: Guard, Driver, Patrol, Pursue, Gunner, Pedestrian -- lc[3] = Team Logic Controller, if this exists, [1] and [2] aren't run here if not lc[3] then local controller = lc[1] if controller then controller:Tick( self, frame_time ) end local controller = lc[2] if controller then controller:Tick( self, frame_time ) end end self.fov:SetPosition( self.position ) self.fov:SetAngle( self.angle ) end function AgentCore:ConfigureNPC( args ) local network_object = self.network_object if not network_object or not IsValid( network_object ) then return end local goal = args.goal self.goal = goal if network_object:GetValue( 'goal' ) ~= goal then network_object:SetNetworkValue( 'goal', goal ) end -- cleanup old logic for i=1,4 do local controller = self.logic_controller[i] if controller then if controller.Remove then controller:Remove() end self.logic_controller[i] = nil end end -- set new logic if goal == AiGoal.Wander then -- movement local movement = AgentOnFoot( self ) self.logic_controller[1] = movement -- wander logic local logic = AgentWander( self ) self.logic_controller[2] = logic -- logic tick rate self.time = 250 elseif goal == AiGoal.Panic then -- movement local movement = AgentOnFootPanic( self ) self.logic_controller[1] = movement -- wander logic local logic = AgentPanic( self ) self.logic_controller[2] = logic -- logic tick rate self.time = 100 elseif goal == AiGoal.Traffic then -- movement local movement = AgentVehicleDriver( self, args ) self.logic_controller[1] = movement -- traffic logic local logic = AgentTraffic( self, args ) self.logic_controller[2] = logic -- logic tick rate self.time = 100 elseif goal == AiGoal.TaxiDriver then -- movement local movement = AgentVehicleDriver( self, args ) self.logic_controller[1] = movement -- traffic logic local logic = TaxiDriver( self, args ) self.logic_controller[2] = logic -- logic tick rate self.time = 100 elseif goal == AiGoal.Guard then -- movement -- guard logic local logic = AgentGuard( self, args ) self.logic_controller[2] = logic -- logic tick rate self.time = 500 elseif goal == AiGoal.Pursue then -- movement local movement = AgentOnFoot( self ) self.logic_controller[1] = movement -- pursue logic local logic = AgentPursue( self, args ) self.logic_controller[2] = logic -- logic tick rate self.time = 100 elseif goal == AiGoal.HeliGuard then -- movement local movement = AgentHeliPilot( self, args ) self.logic_controller[1] = movement -- guard logic local logic = AgentGuard( self, args ) self.logic_controller[2] = logic -- logic tick rate self.time = 100 elseif goal == AiGoal.Zombie then -- movement local movement = AgentOnFoot( self ) self.logic_controller[1] = movement -- zombie logic local logic = AgentZombie( self ) self.logic_controller[2] = logic -- logic tick rate self.time = 100 elseif goal == AiGoal.RescueObjective then -- movement local movement = AgentOnFoot( self ) self.logic_controller[1] = movement -- role logic local logic = AgentRescue( self ) self.logic_controller[2] = logic -- logic tick rate self.time = 100 end end function AgentCore:CalcNetTick() self.net_tick = self.net_tick + 1 if self.net_tick == self.sync_tick + 1 then self.net_tick = 1 end end function AgentCore:SetStreamDistance( n ) self.network_object:SetStreamDistance( n ) end function AgentCore:GetPosition() local network_object = self.network_object if network_object and IsValid( network_object ) then return network_object:GetPosition() end return self.position end function AgentCore:GetHealth() local network_object = self.network_object local health = 0 if network_object and IsValid( network_object ) then health = network_object:GetValue('health') or 0 end return health end function AgentCore:GetId() local network_object = self.network_object if network_object and IsValid( network_object ) then return network_object:GetId() end end function AgentCore:Damage( attacker, weapon ) if self.network_object and IsValid( self.network_object ) then if self.immune then return end local is_npc = ( attacker.__type ~= 'Player' ) local health = self.network_object:GetValue( 'health' ) if health <= 0 then return end local damage = weapon.damage -- shotgun modifier if weapon.is_shotgun then local distance = attacker:GetPosition():Distance( self:GetPosition() ) local ratio = 1 - distance / 60 local base_damage = Copy( weapon.damage ) damage = ceil(base_damage * ( 8*ratio )) end if damage and damage > 0 then health = health - damage self.network_object:SetNetworkValue( 'health', health ) if health <= 0 then -- player heat level if attacker.__type == 'Player' then if self.faction == Faction.Citizen or self.faction == Faction.PanauMilitary then H:IncreasePlayerHeatLevel( attacker, 100 ) end end self:Kill( attacker ) else local logic_lc = self.logic_controller[2] H:IncreasePlayerHeatLevel( attacker, damage*.5 ) if logic_lc then if logic_lc.HurtEvent then logic_lc:HurtEvent( attacker, damage ) end end end end end end function AgentCore:Hurt( attacker, damage ) -- use this function to deal damage to the agent without using the weapon system if self.immune then return end local network_object = self.network_object if not network_object or not IsValid( network_object ) then return end local health = network_object:GetValue( 'health' ) if health <= 0 then return end local new_health = health - damage network_object:SetNetworkValue( 'health', new_health ) if new_health <= 0 then self:Kill( attacker ) end end function AgentCore:Kill( attacker ) local movement_lc = self.logic_controller[1] if movement_lc then movement_lc.movement.speed = 0 end self.dead_timer = Timer() self.dead = true local network_object = self.network_object if network_object and IsValid(network_object) then local health = network_object:GetValue('health') if health > 0 then network_object:SetNetworkValue( 'health', 0 ) end end end function AgentCore:HitByVehicle( t ) local impulse = t.impulse local health_damage = impulse / 10 local hit_angle = t.angle local current_velocity = self.velocity or Vector3() local new_velocity = current_velocity + (hit_angle * (Vector3.Forward * impulse)) local movement_lc = self.logic_controller[1] if movement_lc then movement_lc.collisionVelocity = new_velocity movement_lc.collisionMode = true end end function AgentCore:VehicleCollision( t ) local impulse = t.impulse local health_damage = impulse / 10 -- vehicle health local vehicle = self.vehicle if vehicle and IsValid(vehicle) then vehicle:SetHealth( vehicle:GetHealth() - health_damage ) end -- angle / velocity calculation local hit_angle = t.angle local current_velocity = self.velocity or Vector3() local new_velocity = current_velocity + (hit_angle * (Vector3.Forward * impulse)) local movement_lc = self.logic_controller[1] if movement_lc then movement_lc.collisionVelocity = new_velocity movement_lc.collisionMode = true end end function AgentCore:CalculateCell( position ) if not position then position = self.network_object:GetPosition() end local current_x, current_y = self.cell.x, self.cell.y local cell_x, cell_y = GetCellXYFromPosition( position ) if cell_x ~= current_x or cell_y ~= current_y then -- move from one cell to the other RemoveActorFromCell( self, current_x, current_y ) AddActorToCell( self, cell_x, cell_y ) -- update saved cell info self.cell.x = cell_x self.cell.y = cell_y -- traffic if self.goal == AiGoal.Traffic then local new_cells_players = GetConnectedCellsInfo( cell_x, cell_y ) if new_cells_players == 0 and not IsPositionInCellPlayersFoV( position, GetCell( cell_x, cell_y ) ) then -- new cell doesn't contain players or isn't connected to a cell with players in it -- remove traffic from system self:Remove() else -- new cell contains players or is connected to a cell with players in it -- update traffic cell local spawnset = self.spawnset RemoveVehicleTrafficFromCell( spawnset, current_x, current_y ) AddVehicleTrafficToCell( spawnset, cell_x, cell_y ) spawnset.cell.x = cell_x spawnset.cell.y = cell_y local cell = GetCell( cell_x, cell_y ) if #cell.vehicle_traffic > CellVehicleTrafficLimit then if not self.spawnset.marked_for_removal then self.spawnset.marked_for_removal = true table.insert( DelayedTrafficRemove, self ) end end end end -- update vehicle if driving local vehicle = self.vehicle if vehicle and IsValid(vehicle) then RemoveVehicleFromCell( vehicle, current_x, current_y ) AddVehicleToCell( vehicle, cell_x, cell_y ) end end end function AgentCore:GiveWeapon( slot, weapon ) if not self.inventory then self.inventory = {} end self.inventory[slot] = weapon self.equipped_weapon = weapon self.network_object:SetNetworkValue( 'equipped_weapon', weapon.id ) end function AgentCore:EquipWeaponSlot( slot ) self.equipped_weapon = self.inventory[slot] if self.equipped_weapon then self.network_object:SetNetworkValue( 'equipped_weapon', self.equipped_weapon.id ) else self.network_object:SetNetworkValue( 'equipped_weapon', nil ) end end function AgentCore:GetEquippedWeapon( ... ) return self.equipped_weapon end function AgentCore:Remove() local network_object = self.network_object if network_object and IsValid( network_object ) then for i=1,4 do if self.logic_controller[i] then if self.logic_controller[i].Remove then self.logic_controller[i]:Remove() end self.logic_controller[i] = nil end end if AM then AM.actors_id[network_object:GetId()] = nil AM:RemoveNPC( self ) end network_object:Remove() if self.spawnset then self.spawnset:Remove() end RemoveActorFromCell( self, self.cell.x, self.cell.y ) self = nil return true end return false end
--[[-------------------------------------------------------------------------- * * Mello Trainer * (C) Michael Goodwin 2017 * http://github.com/thestonedturtle/mellotrainer/releases * * This menu used the Scorpion Trainer as a framework to build off of. * https://github.com/pongo1231/ScorpionTrainer * (C) Emre Cürgül 2017 * * A lot of useful functionality has been converted from the lambda menu. * https://lambda.menu * (C) Oui 2017 * * Additional Contributors: * WolfKnight (https://forum.fivem.net/u/WolfKnight) * ---------------------------------------------------------------------------]] function createAllMapBlips() open1 = AddBlipForCoord(2448.48, 4977.57, 57.4330); open2 = AddBlipForCoord(-71.5885, 6264.2, 31.2179); --cluckin bell open3 = AddBlipForCoord(3620.4, 3743.74, 28.6901); --humane labs open4 = AddBlipForCoord(1121.54, 2641.9, 41.2971); --motel open5 = AddBlipForCoord(2330.66, 2573.8, 46.7123); --battery garage open6 = AddBlipForCoord(1391.94, 1146.21, 118.749); --farm mansion open7 = AddBlipForCoord(-3092.93, 346.163, 14.4409); --beach condo open8 = AddBlipForCoord(-774.938, 310.977, 85.6981); --eclipse tower open9 = AddBlipForCoord(241.353, 361.132, 121.082); --epsilon off-street storage room open10 = AddBlipForCoord(-107.61, -9.10006, 78.8356); --small apt open11 = AddBlipForCoord(-1044.94, -230.653, 39.0144); --life invader open12 = AddBlipForCoord(-632.481, -238.269, 38.0723); --vangelico jewellery open13 = AddBlipForCoord(-583.175, -282.91, 35.4548); --unfinished building open14 = AddBlipForCoord(-1012.51, -480.672, 39.9707); --solomons open15 = AddBlipForCoord(-1896.4, -570.371, 11.8312); --beach condo2 open16 = AddBlipForCoord(137.559, -613.671, 44.2187); --iaa open17 = AddBlipForCoord(104.346, -744.276, 45.7547); --fib open18 = AddBlipForCoord(-74.4777, -681.664, 33.8156); --union depository parking lot open19 = AddBlipForCoord(289.682, -584.825, 43.2609); --hospital interior entrance open20 = AddBlipForCoord(718.132, -976.571, 24.909); -- lester kuruma heist setup warehouse open21 = AddBlipForCoord(-61.1991, -1093.43, 26.4959); --bring stolen cars here, premium deluxe motor sports open22 = AddBlipForCoord(-1353.12, -1127.52, 4.06726); --medium apartment open23 = AddBlipForCoord(-1149.36, -1522.7, 10.6281); --cousin floyd's apartment open24 = AddBlipForCoord(-610.156, -1608.65, 26.8976); --rogers salvage scrap open25 = AddBlipForCoord(-253.885, -2027.53, 29.946); --fame or shame audition open26 = AddBlipForCoord(-14.3065, -1442.07, 31.1011); --franklins open27 = AddBlipForCoord(239.485, -1380.89, 33.7418); --alt hospital entrance open28 = AddBlipForCoord(486.97, -1314.74, 29.234); --hayes auto garage open29 = AddBlipForCoord(257.477, -1722.68, 29.6541); --lamars? open30 = AddBlipForCoord(132.582, -2203.08, 7.18643); --torture garage open31 = AddBlipForCoord(959.647, -2185.74, 30.5073); --cattle butchery open32 = AddBlipForCoord(1083.29, -1974.89, 32.4946); --metal refinery open33 = AddBlipForCoord(1275.04, -1721.64, 54.6551); --lesters open34 = AddBlipForCoord(-622.681, 58.0646, 43.2455); --one of the high class apts i forget name -- open35 = AddBlipForCoord(5321.08, -5188.19, 83.5188); --north yankton bank SetBlipSprite(open1, 357); SetBlipSprite(open2, 357); SetBlipSprite(open3, 357); SetBlipSprite(open4, 357); SetBlipSprite(open5, 357); SetBlipSprite(open6, 357); SetBlipSprite(open7, 357); SetBlipSprite(open8, 357); SetBlipSprite(open9, 357); SetBlipSprite(open10, 357); SetBlipSprite(open11, 357); SetBlipSprite(open12, 357); SetBlipSprite(open13, 357); SetBlipSprite(open14, 357); SetBlipSprite(open15, 357); SetBlipSprite(open16, 357); SetBlipSprite(open17, 357); SetBlipSprite(open18, 357); SetBlipSprite(open19, 357); SetBlipSprite(open20, 357); SetBlipSprite(open21, 357); SetBlipSprite(open22, 357); SetBlipSprite(open23, 357); SetBlipSprite(open24, 357); SetBlipSprite(open25, 357); SetBlipSprite(open26, 357); SetBlipSprite(open27, 357); SetBlipSprite(open28, 357); SetBlipSprite(open29, 357); SetBlipSprite(open30, 357); SetBlipSprite(open31, 357); SetBlipSprite(open32, 357); SetBlipSprite(open33, 357); SetBlipSprite(open34, 357); -- SetBlipSprite(open35, 367); SetBlipColour(open1, 0); SetBlipColour(open2, 0); SetBlipColour(open3, 0); SetBlipColour(open4, 0); SetBlipColour(open5, 0); SetBlipColour(open6, 0); SetBlipColour(open7, 0); SetBlipColour(open8, 0); SetBlipColour(open9, 0); SetBlipColour(open10, 0); SetBlipColour(open11, 0); SetBlipColour(open12, 0); SetBlipColour(open13, 0); SetBlipColour(open14, 0); SetBlipColour(open15, 0); SetBlipColour(open16, 0); SetBlipColour(open17, 0); SetBlipColour(open18, 0); SetBlipColour(open19, 0); SetBlipColour(open20, 0); SetBlipColour(open21, 0); SetBlipColour(open22, 0); SetBlipColour(open23, 0); SetBlipColour(open24, 0); SetBlipColour(open25, 0); SetBlipColour(open26, 0); SetBlipColour(open27, 0); SetBlipColour(open28, 0); SetBlipColour(open29, 0); SetBlipColour(open30, 0); SetBlipColour(open31, 0); SetBlipColour(open32, 0); SetBlipColour(open33, 0); SetBlipColour(open34, 0); -- SetBlipColour(open35, 24); SetBlipAsShortRange(open1, 1); SetBlipAsShortRange(open2, 1); SetBlipAsShortRange(open3, 1); SetBlipAsShortRange(open4, 1); SetBlipAsShortRange(open5, 1); SetBlipAsShortRange(open6, 1); SetBlipAsShortRange(open7, 1); SetBlipAsShortRange(open8, 1); SetBlipAsShortRange(open9, 1); SetBlipAsShortRange(open10, 1); SetBlipAsShortRange(open11, 1); SetBlipAsShortRange(open12, 1); SetBlipAsShortRange(open13, 1); SetBlipAsShortRange(open14, 1); SetBlipAsShortRange(open15, 1); SetBlipAsShortRange(open16, 1); SetBlipAsShortRange(open17, 1); SetBlipAsShortRange(open18, 1); SetBlipAsShortRange(open19, 1); SetBlipAsShortRange(open20, 1); SetBlipAsShortRange(open21, 1); SetBlipAsShortRange(open22, 1); SetBlipAsShortRange(open23, 1); SetBlipAsShortRange(open24, 1); SetBlipAsShortRange(open25, 1); SetBlipAsShortRange(open26, 1); SetBlipAsShortRange(open27, 1); SetBlipAsShortRange(open28, 1); SetBlipAsShortRange(open29, 1); SetBlipAsShortRange(open30, 1); SetBlipAsShortRange(open31, 1); SetBlipAsShortRange(open32, 1); SetBlipAsShortRange(open33, 1); SetBlipAsShortRange(open34, 1); -- SetBlipAsShortRange(open35, 1); --shirt icons --71 pale yellow --ponsonbys1 = AddBlipForCoord(-712.407, -153.909, 44.9965); --ponsonbys2 = AddBlipForCoord(-158.312, -305.009, 81.6358); --ponsonbys3 = AddBlipForCoord(-1455.1, -233.229, 53.6423); SetBlipSprite(ponsonbys1, 73); SetBlipSprite(ponsonbys2, 73); SetBlipSprite(ponsonbys3, 73); SetBlipColour(ponsonbys1, 71); SetBlipColour(ponsonbys2, 71); SetBlipColour(ponsonbys3, 71); SetBlipAsShortRange(ponsonbys1, 1); SetBlipAsShortRange(ponsonbys2, 1); SetBlipAsShortRange(ponsonbys3, 1); --shirt icons --71 pale yellow --discount1 = AddBlipForCoord(80.665, -1391.67, 34.8334); --discount2 = AddBlipForCoord(1687.98, 4820.54, 45.9631); --discount3 = AddBlipForCoord(-1098.12, 2709.18, 19.1079); --discount4 = AddBlipForCoord(1197.97, 2704.22, 43.0591); --discount5 = AddBlipForCoord(-0.823129, 6514.77, 36.1644); SetBlipSprite(discount1, 73); SetBlipSprite(discount2, 73); SetBlipSprite(discount3, 73); SetBlipSprite(discount4, 73); SetBlipSprite(discount5, 73); SetBlipColour(discount1, 71); SetBlipColour(discount2, 71); SetBlipColour(discount3, 71); SetBlipColour(discount4, 71); SetBlipColour(discount5, 71); SetBlipAsShortRange(discount1, 1); SetBlipAsShortRange(discount2, 1); SetBlipAsShortRange(discount3, 1); SetBlipAsShortRange(discount4, 1); SetBlipAsShortRange(discount5, 1); --shirt icons --71 pale yellow --binco1 = AddBlipForCoord(-818.52, -1077.54, 15.4707); --binco2 = AddBlipForCoord(419.633, -809.586, 36.2622); SetBlipSprite(binco1, 73); SetBlipSprite(binco2, 73); SetBlipColour(binco1, 71); SetBlipColour(binco2, 71); SetBlipAsShortRange(binco1, 1); SetBlipAsShortRange(binco2, 1); --shirt icons --71 pale yellow --suburban1 = AddBlipForCoord(-1199.71, -776.697, 26.2131); --suburban2 = AddBlipForCoord(618.287, 2752.56, 48.5239); --suburban3 = AddBlipForCoord(126.786, -212.513, 59.8468); --suburban4 = AddBlipForCoord(-3168.87, 1055.28, 27.6547); SetBlipSprite(suburban1, 73); SetBlipSprite(suburban2, 73); SetBlipSprite(suburban3, 73); SetBlipSprite(suburban4, 73); SetBlipColour(suburban1, 71); SetBlipColour(suburban2, 71); SetBlipColour(suburban3, 71); SetBlipColour(suburban4, 71); SetBlipAsShortRange(suburban1, 1); SetBlipAsShortRange(suburban2, 1); SetBlipAsShortRange(suburban3, 1); SetBlipAsShortRange(suburban4, 1); --lsc --10 --icey grape --lsc1 = AddBlipForCoord(-1145.29, -1991.23, 13.1622); --lsc2 = AddBlipForCoord(723.129, -1089.07, 31.1061); --lsc3 = AddBlipForCoord(-354.526, -135.274, 59.9924); --lsc4 = AddBlipForCoord(1174.8, 2644.42, 43.5054); --lsc5 = AddBlipForCoord(110.046, 6623.03, 39.2303); --beekers --lsc6 = AddBlipForCoord(-207.123, -1310.3, 31.296); --bennys shop SetBlipSprite(lsc1, 72); SetBlipSprite(lsc2, 72); SetBlipSprite(lsc3, 72); SetBlipSprite(lsc4, 72); SetBlipSprite(lsc5, 72); SetBlipSprite(lsc6, 72); SetBlipColour(lsc1, 10); SetBlipColour(lsc2, 10); SetBlipColour(lsc3, 10); SetBlipColour(lsc4, 10); SetBlipColour(lsc5, 10); SetBlipColour(lsc6, 10); SetBlipAsShortRange(lsc1, 1); SetBlipAsShortRange(lsc2, 1); SetBlipAsShortRange(lsc3, 1); SetBlipAsShortRange(lsc4, 1); SetBlipAsShortRange(lsc5, 1); SetBlipAsShortRange(lsc6, 1); --tattoos --41 --flesh --tattoo1 = AddBlipForCoord(321.737, 179.474, 127.758); --tattoo2 = AddBlipForCoord(1861.78, 3750.06, 37.2415); --tattoo3 = AddBlipForCoord(-290.16, 6199.09, 35.6482); --tattoo4 = AddBlipForCoord(-1156.55, -1420.59, 1126.49); --tattoo5 = AddBlipForCoord(1322.4, -1651.04, 57.4641); --tattoo6 = AddBlipForCoord(-3196.48, 1074.81, 25.4839); SetBlipSprite(tattoo1, 75); SetBlipSprite(tattoo2, 75); SetBlipSprite(tattoo3, 75); SetBlipSprite(tattoo4, 75); SetBlipSprite(tattoo5, 75); SetBlipSprite(tattoo6, 75); SetBlipColour(tattoo1, 41); SetBlipColour(tattoo2, 41); SetBlipColour(tattoo3, 41); SetBlipColour(tattoo4, 41); SetBlipColour(tattoo5, 41); SetBlipColour(tattoo6, 41); SetBlipAsShortRange(tattoo1, 1); SetBlipAsShortRange(tattoo2, 1); SetBlipAsShortRange(tattoo3, 1); SetBlipAsShortRange(tattoo4, 1); SetBlipAsShortRange(tattoo5, 1); SetBlipAsShortRange(tattoo6, 1); --gun --6 -- red --ammo1 = AddBlipForCoord(1697.88, 3753.23, 39.1827); --ammo2 = AddBlipForCoord(244.749, -45.6379, 83.3083); --ammo3 = AddBlipForCoord(843.485, -1025.05, 37.0438); --ammo4 = AddBlipForCoord(-325.984, 6077.07, 37.1471); --ammo5 = AddBlipForCoord(-664.477, -944.667, 21.7855); --ammo6 = AddBlipForCoord(-1313.87, -391.032, 43.3075); --ammo7 = AddBlipForCoord(-1112.89, 2690.44, 18.5839); --ammo8 = AddBlipForCoord(-3165.23, 1082.86, 25.4796); --ammo9 = AddBlipForCoord(2569.69, 302.509, 117.451); --ammo10 = AddBlipForCoord(812.434, -2148.97, 39.4198); --shooting range icon --ammo11 = AddBlipForCoord(17.7044, -1114.19, 42.373); --shooting range icon SetBlipSprite(ammo1, 110); SetBlipSprite(ammo2, 110); SetBlipSprite(ammo3, 110); SetBlipSprite(ammo4, 110); SetBlipSprite(ammo5, 110); SetBlipSprite(ammo6, 110); SetBlipSprite(ammo7, 110); SetBlipSprite(ammo8, 110); SetBlipSprite(ammo9, 110); SetBlipSprite(ammo10, 313); SetBlipSprite(ammo11, 313); SetBlipColour(ammo1, 6); SetBlipColour(ammo2, 6); SetBlipColour(ammo3, 6); SetBlipColour(ammo4, 6); SetBlipColour(ammo5, 6); SetBlipColour(ammo6, 6); SetBlipColour(ammo7, 6); SetBlipColour(ammo8, 6); SetBlipColour(ammo9, 6); SetBlipColour(ammo10, 6); SetBlipColour(ammo11, 6); SetBlipAsShortRange(ammo1, 1); SetBlipAsShortRange(ammo2, 1); SetBlipAsShortRange(ammo3, 1); SetBlipAsShortRange(ammo4, 1); SetBlipAsShortRange(ammo5, 1); SetBlipAsShortRange(ammo6, 1); SetBlipAsShortRange(ammo7, 1); SetBlipAsShortRange(ammo8, 1); SetBlipAsShortRange(ammo9, 1); SetBlipAsShortRange(ammo10, 1); SetBlipAsShortRange(ammo11, 1); --barber --15 --light blue --barber1 = AddBlipForCoord(-822.051, -187.093, 48.1654); --barber2 = AddBlipForCoord(133.515, -1710.83, 36.5914); --barber3 = AddBlipForCoord(-1287.14, -1116.47, 10.1592); --barber4 = AddBlipForCoord(1933.07, 3726.17, 36.7415); --barber5 = AddBlipForCoord(1208.28, -470.83, 71.8597); --barber6 = AddBlipForCoord(-30.4352, -147.733, 62.3003); --barber7 = AddBlipForCoord(-280.715, 6231.77, 37.1876); SetBlipSprite(barber1, 71); SetBlipSprite(barber2, 71); SetBlipSprite(barber3, 71); SetBlipSprite(barber4, 71); SetBlipSprite(barber5, 71); SetBlipSprite(barber6, 71); SetBlipSprite(barber7, 71); SetBlipColour(barber1, 15); SetBlipColour(barber2, 15); SetBlipColour(barber3, 15); SetBlipColour(barber4, 15); SetBlipColour(barber5, 15); SetBlipColour(barber6, 15); SetBlipColour(barber7, 15); SetBlipAsShortRange(barber1, 1); SetBlipAsShortRange(barber2, 1); SetBlipAsShortRange(barber3, 1); SetBlipAsShortRange(barber4, 1); SetBlipAsShortRange(barber5, 1); SetBlipAsShortRange(barber6, 1); SetBlipAsShortRange(barber7, 1); --store --43 --light green --store1 = AddBlipForCoord(-1486.71, -381.852, 40.1634); --store2 = AddBlipForCoord(-1224.04, -906.344, 12.3264); --store3 = AddBlipForCoord(-711.191, -912.376, 19.2156); --store4 = AddBlipForCoord(29.5184, -1344.23, 29.497); --store5 = AddBlipForCoord(-48.8503, -1753.41, 29.421); --store6 = AddBlipForCoord(1159.23, -322.147, 69.205); --store7 = AddBlipForCoord(1138.09, -981.366, 46.4158); --store8 = AddBlipForCoord(378.322, 327.247, 103.566); --store9 = AddBlipForCoord(1699.92, 4927.63, 42.0637); --store10 = AddBlipForCoord(1965.32, 3739.66, 31.6488); --store11 = AddBlipForCoord(-2974.7, 390.901, 15.0319); --store12 = AddBlipForCoord(2683.1, 3282.11, 55.2406); SetBlipSprite(store1, 52); SetBlipSprite(store2, 52); SetBlipSprite(store3, 52); SetBlipSprite(store4, 52); SetBlipSprite(store5, 52); SetBlipSprite(store6, 52); SetBlipSprite(store7, 52); SetBlipSprite(store8, 52); SetBlipSprite(store9, 52); SetBlipSprite(store10, 52); SetBlipSprite(store11, 52); SetBlipSprite(store12, 52); SetBlipColour(store1, 43); SetBlipColour(store2, 43); SetBlipColour(store3, 43); SetBlipColour(store4, 43); SetBlipColour(store5, 43); SetBlipColour(store6, 43); SetBlipColour(store7, 43); SetBlipColour(store8, 43); SetBlipColour(store9, 43); SetBlipColour(store10, 43); SetBlipColour(store11, 43); SetBlipColour(store12, 43); SetBlipAsShortRange(store1, 1); SetBlipAsShortRange(store2, 1); SetBlipAsShortRange(store3, 1); SetBlipAsShortRange(store4, 1); SetBlipAsShortRange(store5, 1); SetBlipAsShortRange(store6, 1); SetBlipAsShortRange(store7, 1); SetBlipAsShortRange(store8, 1); SetBlipAsShortRange(store9, 1); SetBlipAsShortRange(store10, 1); SetBlipAsShortRange(store11, 1); SetBlipAsShortRange(store12, 1); --cops --54 --dark blue --policestation1 = AddBlipForCoord(430.568, -979.734, 43.6916); --4 --policestation2 = AddBlipForCoord(642.056, 0.739643, 82.7867); --1 --policestation4 = AddBlipForCoord(-445.692, 6014.96, 31.7164); --5 --los santos sheriff --policestation5 = AddBlipForCoord(-635.936, -121.363, 38.9876); --2 firestation --policestation6 = AddBlipForCoord(1853.78, 3685.63, 43.2671);--county sherff --policestation7 = AddBlipForCoord(-378.117, 6117.44, 35.4394); --firestation --policestation8 = AddBlipForCoord(1696.98, 3586.01, 34.8975); --firestation --policestation9 = AddBlipForCoord(360.454, -1584.85, 29.2919); --davis sheriff --policestation10 = AddBlipForCoord(827.447, -1290.29, 28.2407); --lspd --policestation11 = AddBlipForCoord(-1108.19, -845.159, 19.3169); --vespucci police dep SetBlipSprite(policestation1, 60); SetBlipSprite(policestation2, 60); SetBlipSprite(policestation4, 60); SetBlipSprite(policestation5, 60); SetBlipSprite(policestation6, 60); SetBlipSprite(policestation7, 60); SetBlipSprite(policestation8, 60); SetBlipSprite(policestation9, 60); SetBlipSprite(policestation10, 60); SetBlipSprite(policestation11, 60); SetBlipColour(policestation1, 54); SetBlipColour(policestation2, 54); SetBlipColour(policestation4, 54); SetBlipColour(policestation5, 59); --fire station red SetBlipColour(policestation6, 54); SetBlipColour(policestation7, 59); --fire station red SetBlipColour(policestation8, 59); --fire station red SetBlipColour(policestation9, 54); SetBlipColour(policestation10, 54); SetBlipColour(policestation11, 54); SetBlipAsShortRange(policestation1, 1); SetBlipAsShortRange(policestation2, 1); SetBlipAsShortRange(policestation4, 1); SetBlipAsShortRange(policestation5, 1); SetBlipAsShortRange(policestation6, 1); SetBlipAsShortRange(policestation7, 1); SetBlipAsShortRange(policestation8, 1); SetBlipAsShortRange(policestation9, 1); SetBlipAsShortRange(policestation10, 1); SetBlipAsShortRange(policestation11, 1); --banks --2 --money green --bank1 = AddBlipForCoord(246.205, 215.997, 106.287); --pac --bank2 = AddBlipForCoord(-1212.97, -330.251, 37.787); --fleeca --bank3 = AddBlipForCoord(149.762, -1040.02, 29.3741); --fleeca --bank4 = AddBlipForCoord(-75.015, -818.215, 326.176); --maze --bank5 = AddBlipForCoord(-112.424, 6465.32, 37.2196); --blaine --bank6 = AddBlipForCoord(-1379.25, -504.262, 33.1574); --blaine --bank7 = AddBlipForCoord(-2966.27, 482.97, 15.6927); --fleeca SetBlipSprite(bank1, 108); SetBlipSprite(bank2, 108); SetBlipSprite(bank3, 108); SetBlipSprite(bank4, 431); --tower SetBlipSprite(bank5, 108); SetBlipSprite(bank6, 431); --tower SetBlipSprite(bank7, 108); SetBlipColour(bank1, 2); SetBlipColour(bank2, 2); SetBlipColour(bank3, 2); SetBlipColour(bank4, 2); SetBlipColour(bank5, 2); SetBlipColour(bank6, 2); SetBlipColour(bank7, 2); SetBlipAsShortRange(bank1, 1); SetBlipAsShortRange(bank2, 1); SetBlipAsShortRange(bank3, 1); SetBlipAsShortRange(bank4, 1); SetBlipAsShortRange(bank5, 1); SetBlipAsShortRange(bank6, 1); SetBlipAsShortRange(bank7, 1); --cablecar --47 --orange --cablecar1 = AddBlipForCoord(-742.192, 5594.84, 50.6404); --cablecar2 = AddBlipForCoord(446.409, 5571.24, 795.165); SetBlipSprite(cablecar1, 36); SetBlipSprite(cablecar2, 36); SetBlipColour(cablecar1, 47); SetBlipColour(cablecar2, 47); SetBlipAsShortRange(cablecar1, 1); SetBlipAsShortRange(cablecar2, 1); --carwash --15 --greenishblue --carwash1 = AddBlipForCoord(-699.612, -933.865, 24.1095); --carwash2 = AddBlipForCoord(24.6443, -1397.63, 33.9966); SetBlipSprite(carwash1, 100); SetBlipSprite(carwash2, 100); SetBlipColour(carwash1, 15); SetBlipColour(carwash2, 15); SetBlipAsShortRange(carwash1, 1); SetBlipAsShortRange(carwash2, 1); --airplay icon --57 --sky blue airport1 = AddBlipForCoord(-1333.18, -3044.55, 13.9443); --flight school icon airport2 = AddBlipForCoord(1381.67, 3130.1, 40.8185); --sandy shores airport3 = AddBlipForCoord(2044.32, 4768.07, 40.7285); SetBlipSprite(airport1, 90); SetBlipSprite(airport2, 90); SetBlipSprite(airport3, 90); SetBlipColour(airport1, 57); SetBlipColour(airport2, 57); SetBlipColour(airport3, 57); SetBlipAsShortRange(airport1, 1); SetBlipAsShortRange(airport2, 1); SetBlipAsShortRange(airport3, 1); --stripclub --8 --pink --stripclub = AddBlipForCoord(135.023, -1297.88, 35.0099); SetBlipSprite(stripclub, 121); SetBlipColour(stripclub, 8); SetBlipAsShortRange(stripclub, 1); --helipad --53 --white blue helipad = AddBlipForCoord(-736.423, -1456.24, 5.00053); SetBlipSprite(helipad, 64); SetBlipColour(helipad, 53); SetBlipAsShortRange(helipad, 1); --boats --53 --white blue --boat1 = AddBlipForCoord(-843.455, -1367.09, 1.60517); --marina -- boat2 = AddBlipForCoord(-2080.47, -1019.38, 8.97115); --yachte -- boat3 = AddBlipForCoord(3080.01, -4711.38, 15.3039); --carrier SetBlipSprite(boat1, 410); -- SetBlipSprite(boat2, 410); -- SetBlipSprite(boat3, 410); SetBlipColour(boat1, 53); -- SetBlipColour(boat2, 53); -- SetBlipColour(boat3, 53); SetBlipAsShortRange(boat1, 1); -- SetBlipAsShortRange(boat2, 1); -- SetBlipAsShortRange(boat3, 1); --music note --82 --lght green rebel = AddBlipForCoord(736.153, 2583.14, 79.6342); SetBlipSprite(rebel, 136); SetBlipScale(rebel, 0.9); SetBlipColour(rebel, 82); SetBlipAsShortRange(rebel, 1); --theater --16 --cream --theater1 = AddBlipForCoord(297.221, 196.986, 104.333); --theater2 = AddBlipForCoord(-1422.41, -209.281, 5452.14); --theater3 = AddBlipForCoord(395.852, -712.105, 85.6129); SetBlipSprite(theater1, 135); SetBlipSprite(theater2, 135); SetBlipSprite(theater3, 135); SetBlipColour(theater1, 16); SetBlipColour(theater2, 16); SetBlipColour(theater3, 16); SetBlipAsShortRange(theater1, 1); SetBlipAsShortRange(theater2, 1); SetBlipAsShortRange(theater3, 1); --Hospital --3 --blue --hospital1 = AddBlipForCoord(355.202, -591.237, 74.1657); --hospital2 = AddBlipForCoord(337.301, -1396.2, 32.5092); --hospital3 = AddBlipForCoord(-473.578, -339.958, 91.0076); SetBlipSprite(hospital1, 61); SetBlipSprite(hospital2, 61); SetBlipSprite(hospital3, 61); SetBlipColour(hospital1, 3); SetBlipColour(hospital2, 3); SetBlipColour(hospital3, 3); SetBlipAsShortRange(hospital1, 1); SetBlipAsShortRange(hospital2, 1); SetBlipAsShortRange(hospital3, 1); --impound = AddBlipForCoord(-f, -f, f); --SetBlipSprite(impound, 225); --SetBlipScale(impound, 0.8); --SetBlipAsShortRange(impound, 1); --safehouse = AddBlipForCoord(-f, -f, f); --SetBlipSprite(safehouse, 40); --SetBlipAsShortRange(safehouse, 1); --garage = AddBlipForCoord(-f, -f, f); --SetBlipSprite(garage, 357); --SetBlipAsShortRange(garage, 1); --basejump = AddBlipForCoord(-f, -f, f); --SetBlipSprite(basejump, 94); --SetBlipAsShortRange(basejump, 1); --bar --27 --purple --bar1 = AddBlipForCoord(-562.456, 281.841, 91.7978); --bar2 = AddBlipForCoord(-1389.57, -587.167, 35.1147); SetBlipSprite(bar1, 93); SetBlipSprite(bar2, 93); SetBlipColour(bar1, 10); SetBlipColour(bar2, 10); SetBlipAsShortRange(bar1, 1); SetBlipAsShortRange(bar2, 1); --club --32 --mblue comedy = AddBlipForCoord(-436.48, 270.831, 89.8888); SetBlipSprite(comedy, 102); SetBlipColour(comedy, 32); SetBlipAsShortRange(comedy, 1); --pill --36 --light yellow --drugs = AddBlipForCoord(1391.77, 3608.72, 38.9419); SetBlipSprite(drugs, 51); SetBlipScale(drugs, 0.8); SetBlipColour(drugs, 36); SetBlipAsShortRange(drugs, 1); --weed --2-- green marijuana1 = AddBlipForCoord(2208.78, 5578.23, 53.7351); marijuana2 = AddBlipForCoord(-1171.82, -1573.06, 4.66363); SetBlipSprite(marijuana1, 140); SetBlipSprite(marijuana2, 140); SetBlipColour(marijuana1, 2); SetBlipColour(marijuana2, 2); SetBlipAsShortRange(marijuana1, 1); SetBlipAsShortRange(marijuana2, 1); -- SET_BLIP_HIGH_DETAIL(marijuana2, 1); -- altruist --31 --light brown altruist = AddBlipForCoord(-1170.84, 4926.65, 224.295); SetBlipSprite(altruist, 269); SetBlipColour(altruist, 31); SetBlipAsShortRange(altruist, 1); --sub --46 --yellow sub = AddBlipForCoord(-1597.59, 5251.11, 1.50652); SetBlipSprite(sub, 308); SetBlipColour(sub, 46); SetBlipAsShortRange(sub, 1); --masks --75 --evil red --masks = AddBlipForCoord(-1336.09, -1278.12, 11.5885); SetBlipSprite(masks, 362); SetBlipColour(masks, 75); SetBlipAsShortRange(masks, 1); --ferriswheel --77 --nice blue fairground = AddBlipForCoord(-1664.16, -1126.2, 13.2325); SetBlipSprite(fairground, 266); SetBlipColour(fairground, 77); SetBlipAsShortRange(fairground, 1); --golf --36 --canary yellow golf = AddBlipForCoord(-1325.35, 60.5766, 53.5388); SetBlipSprite(golf, 109); SetBlipColour(golf, 36); SetBlipAsShortRange(golf, 1); --tennis --24 --tennis ball green tennis = AddBlipForCoord(-1618.94, 265.868, 59.5503); SetBlipSprite(tennis, 122); SetBlipColour(tennis, 24); SetBlipAsShortRange(tennis, 1); --darts --76 --dark red --darts = AddBlipForCoord(1992.32, 3050.51, 54.5371); SetBlipSprite(darts, 103); SetBlipColour(darts, 76); SetBlipAsShortRange(darts, 1); --playboy --8 --pink playboy = AddBlipForCoord(-1494.08, 144.034, 55.6527); SetBlipSprite(playboy, 176); SetBlipScale(playboy, 0.8); SetBlipColour(playboy, 8); SetBlipAsShortRange(playboy, 1); --fib --44 --burnt orange --fib = AddBlipForCoord(150.126, -754.591, 262.865); SetBlipSprite(fib, 106); SetBlipScale(fib, 0.8); SetBlipColour(fib, 44); SetBlipAsShortRange(fib, 1); end function destroyAllMapBlips() RemoveBlip(open1) open1 = nil; RemoveBlip(open2) open2 = nil; RemoveBlip(open3) open3 = nil; RemoveBlip(open4) open4 = nil; RemoveBlip(open5) open5 = nil; RemoveBlip(open6) open6 = nil; RemoveBlip(open7) open7 = nil; RemoveBlip(open8) open8 = nil; RemoveBlip(open9) open9 = nil; RemoveBlip(open10) open10 = nil; RemoveBlip(open11) open11 = nil; RemoveBlip(open12) open12 = nil; RemoveBlip(open13) open13 = nil; RemoveBlip(open14) open14 = nil; RemoveBlip(open15) open15 = nil; RemoveBlip(open16) open16 = nil; RemoveBlip(open17) open17 = nil; RemoveBlip(open18) open18 = nil; RemoveBlip(open19) open19 = nil; RemoveBlip(open20) open20 = nil; RemoveBlip(open21) open21 = nil; RemoveBlip(open22) open22 = nil; RemoveBlip(open23) open23 = nil; RemoveBlip(open24) open24 = nil; RemoveBlip(open25) open25 = nil; RemoveBlip(open26) open26 = nil; RemoveBlip(open27) open27 = nil; RemoveBlip(open28) open28 = nil; RemoveBlip(open29) open29 = nil; RemoveBlip(open30) open30 = nil; RemoveBlip(open31) open31 = nil; RemoveBlip(open32) open32 = nil; RemoveBlip(open33) open33 = nil; RemoveBlip(open34) open34 = nil; --RemoveBlip(open35) --open35 = nil; RemoveBlip(ponsonbys1) ponsonbys1 = nil; RemoveBlip(ponsonbys2) ponsonbys2 = nil; RemoveBlip(ponsonbys3) ponsonbys3 = nil; RemoveBlip(discount1) discount1 = nil; RemoveBlip(discount2) discount2 = nil; RemoveBlip(discount3) discount3 = nil; RemoveBlip(discount4) discount4 = nil; RemoveBlip(discount5) discount5 = nil; RemoveBlip(binco1) binco1 = nil; RemoveBlip(binco2) binco2 = nil; RemoveBlip(suburban1) suburban1 = nil; RemoveBlip(suburban2) suburban2 = nil; RemoveBlip(suburban3) suburban3 = nil; RemoveBlip(suburban4) suburban4 = nil; RemoveBlip(lsc1) lsc1 = nil; RemoveBlip(lsc2) lsc2 = nil; RemoveBlip(lsc3) lsc3 = nil; RemoveBlip(lsc4) lsc4 = nil; RemoveBlip(lsc5) lsc5 = nil; RemoveBlip(lsc6) lsc6 = nil; RemoveBlip(tattoo1) tattoo1 = nil; RemoveBlip(tattoo2) tattoo2 = nil; RemoveBlip(tattoo3) tattoo3 = nil; RemoveBlip(tattoo4) tattoo4 = nil; RemoveBlip(tattoo5) tattoo5 = nil; RemoveBlip(tattoo6) tattoo6 = nil; RemoveBlip(ammo1) ammo1 = nil; RemoveBlip(ammo2) ammo2 = nil; RemoveBlip(ammo3) ammo3 = nil; RemoveBlip(ammo4) ammo4 = nil; RemoveBlip(ammo5) ammo5 = nil; RemoveBlip(ammo6) ammo6 = nil; RemoveBlip(ammo7) ammo7 = nil; RemoveBlip(ammo8) ammo8 = nil; RemoveBlip(ammo9) ammo9 = nil; RemoveBlip(ammo10) ammo10 = nil; RemoveBlip(ammo11) ammo11 = nil; RemoveBlip(barber1) barber1 = nil; RemoveBlip(barber2) barber2 = nil; RemoveBlip(barber3) barber3 = nil; RemoveBlip(barber4) barber4 = nil; RemoveBlip(barber5) barber5 = nil; RemoveBlip(barber6) barber6 = nil; RemoveBlip(barber7) barber7 = nil; RemoveBlip(store1) store1 = nil; RemoveBlip(store2) store2 = nil; RemoveBlip(store3) store3 = nil; RemoveBlip(store4) store4 = nil; RemoveBlip(store5) store5 = nil; RemoveBlip(store6) store6 = nil; RemoveBlip(store7) store7 = nil; RemoveBlip(store8) store8 = nil; RemoveBlip(store9) store9 = nil; RemoveBlip(store10) store10 = nil; RemoveBlip(store11) store11 = nil; RemoveBlip(store12) store12 = nil; RemoveBlip(policestation1) policestation1 = nil; RemoveBlip(policestation2) policestation2 = nil; RemoveBlip(policestation4) policestation4 = nil; RemoveBlip(policestation5) policestation5 = nil; RemoveBlip(policestation6) policestation6 = nil; RemoveBlip(policestation7) policestation7 = nil; RemoveBlip(policestation8) policestation8 = nil; RemoveBlip(policestation9) policestation9 = nil; RemoveBlip(policestation10) policestation10 = nil; RemoveBlip(policestation11) policestation11 = nil; RemoveBlip(bank1) bank1 = nil; RemoveBlip(bank2) bank2 = nil; RemoveBlip(bank3) bank3 = nil; RemoveBlip(bank4) bank4 = nil; RemoveBlip(bank5) bank5 = nil; RemoveBlip(bank6) bank6 = nil; RemoveBlip(bank7) bank7 = nil; RemoveBlip(cablecar1) cablecar1 = nil; RemoveBlip(cablecar2) cablecar2 = nil; RemoveBlip(carwash1) carwash1 = nil; RemoveBlip(carwash2) carwash2 = nil; RemoveBlip(airport1) airport1 = nil; RemoveBlip(airport2) airport2 = nil; RemoveBlip(airport3) airport3 = nil; RemoveBlip(stripclub) stripclub = nil; RemoveBlip(helipad) helipad = nil; RemoveBlip(boat1) boat1 = nil; RemoveBlip(rebel) rebel = nil; RemoveBlip(theater1) theater1 = nil; RemoveBlip(theater2) theater2 = nil; RemoveBlip(theater3) theater3 = nil; RemoveBlip(hospital1) hospital1 = nil; RemoveBlip(hospital2) hospital2 = nil; RemoveBlip(hospital3) hospital3 = nil; RemoveBlip(bar1) bar1 = nil; RemoveBlip(bar2) bar2 = nil; RemoveBlip(comedy) comedy = nil; RemoveBlip(drugs) drugs = nil; RemoveBlip(marijuana1) marijuana1 = nil; RemoveBlip(marijuana2) marijuana2 = nil; RemoveBlip(altruist) altruist = nil; RemoveBlip(sub) sub = nil; RemoveBlip(masks) masks = nil; RemoveBlip(fairground) fairground = nil; RemoveBlip(golf) golf = nil; RemoveBlip(tennis) tennis = nil; RemoveBlip(darts) darts = nil; RemoveBlip(playboy) playboy = nil; RemoveBlip(fib) fib = nil; end local currentstate = false -- Prevent creating multiple blips. function toggleMapBlips(toggle) if(toggle)then if(not currentstate)then createAllMapBlips() currentstate = true end else if(currentstate)then destroyAllMapBlips() currentstate = false end end end
--[[ Perspective v2.0.2 A library for easily and smoothly integrating a virtual camera into your game. Based on modified version of the Dusk camera system. v2.0.2 adds a more stable tracking system and re-implements scrollX and scrollY --]] local lib_perspective = {} -------------------------------------------------------------------------------- -- Localize -------------------------------------------------------------------------------- local display_newGroup = display.newGroup local display_remove = display.remove local type = type local table_insert = table.insert local math_huge = math.huge local math_nhuge = -math.huge local clamp = function(v, l, h) return (v < l and l) or (v > h and h) or v end -------------------------------------------------------------------------------- -- Create View -------------------------------------------------------------------------------- lib_perspective.createView = function(layerCount) ------------------------------------------------------------------------------ -- Create view, internal object, and layers ------------------------------------------------------------------------------ local view = display_newGroup() view.damping = 1 view.snapWhenFocused = true -- Do we instantly snap to the object when :setFocus() is called? local isTracking local internal -- So we can access it from inside the declaration internal = { trackingLevel = 1, damping = 1, scaleBoundsToScreen = true, xScale = 1, yScale = 1, addX = display.contentCenterX, addY = display.contentCenterY, bounds = { xMin = math_nhuge, xMax = math_huge, yMin = math_nhuge, yMax = math_huge }, scaledBounds = { xMin = math_nhuge, xMax = math_huge, yMin = math_nhuge, yMax = math_huge }, trackFocus = true, focus = nil, viewX = 0, viewY = 0, getViewXY = function() if internal.focus then return internal.focus.x, internal.focus.y else return internal.viewX, internal.viewY end end, layer = {}, updateAddXY = function() internal.addX = display.contentCenterX / view.xScale internal.addY = display.contentCenterY / view.yScale end } local layers = {} ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Internal Methods ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Scale Bounds ------------------------------------------------------------------------------ internal.scaleBounds = function(doX, doY) if internal.scaleBoundsToScreen then local xMin = internal.bounds.xMin local xMax = internal.bounds.xMax local yMin = internal.bounds.yMin local yMax = internal.bounds.yMax local doX = doX and not ((xMin == math_nhuge) or (xMax == math_huge)) local doY = doY and not ((yMin == math_nhuge) or (yMax == math_huge)) if doX then local scaled_xMin = xMin / view.xScale local scaled_xMax = xMax - (scaled_xMin - xMin) if scaled_xMax < scaled_xMin then local hopDist = scaled_xMin - scaled_xMax local halfDist = hopDist * 0.5 scaled_xMax = scaled_xMax + halfDist scaled_xMin = scaled_xMin - halfDist end internal.scaledBounds.xMin = scaled_xMin internal.scaledBounds.xMax = scaled_xMax end if doY then local scaled_yMin = yMin / view.yScale local scaled_yMax = yMax - (scaled_yMin - yMin) if scaled_yMax < scaled_yMin then local hopDist = scaled_yMin - scaled_yMax local halfDist = hopDist * 0.5 scaled_yMax = scaled_yMax + halfDist scaled_yMin = scaled_yMin - halfDist end internal.scaledBounds.yMin = scaled_yMin internal.scaledBounds.yMax = scaled_yMax end else camera.scaledBounds.xMin, camera.scaledBounds.xMax, camera.scaledBounds.yMin, camera.scaledBounds.yMax = camera.bounds.xMin, camera.bounds.xMax, camera.bounds.yMin, camera.bounds.yMax end end ------------------------------------------------------------------------------ -- Process Viewpoint ------------------------------------------------------------------------------ internal.processViewpoint = function() if internal.damping ~= view.damping then internal.trackingLevel = 1 / view.damping internal.damping = view.damping end if internal.trackFocus then local x, y = internal.getViewXY() if view.xScale ~= internal.xScale or view.yScale ~= internal.yScale then internal.updateAddXY() end if view.xScale ~= internal.xScale then internal.xScale = view.xScale internal.scaleBounds(true, false) end if view.yScale ~= internal.yScale then internal.yScale = view.yScale internal.scaleBounds(false, true) end x = clamp(x, internal.scaledBounds.xMin, internal.scaledBounds.xMax) y = clamp(y, internal.scaledBounds.yMin, internal.scaledBounds.yMax) internal.viewX, internal.viewY = x, y end end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Public Methods ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Append Layer ------------------------------------------------------------------------------ view.appendLayer = function() local layer = display_newGroup() layer.xParallax, layer.yParallax = 1, 1 view:insert(layer) layer:toBack() table_insert(layers, layer) layer._perspectiveIndex = #layers internal.layer[#layers] = { x = 0, y = 0, xOffset = 0, yOffset = 0 } function layer:setCameraOffset(x, y) internal.layer[layer._perspectiveIndex].xOffset, internal.layer[layer._perspectiveIndex].yOffset = x, y end end ------------------------------------------------------------------------------ -- Add an Object to the Camera ------------------------------------------------------------------------------ function view:add(obj, l, isFocus) local l = l or 4 layers[l]:insert(obj) obj._perspectiveLayer = l if isFocus then view:setFocus(obj) end -- Move an object to a layer function obj:toLayer(newLayer) if layer[newLayer] then layer[newLayer]:insert(obj) obj._perspectiveLayer = newLayer end end --Move an object back a layer function obj:back() if layer[obj._perspectiveLayer + 1] then layer[obj._perspectiveLayer + 1]:insert(obj) obj._perspectiveLayer = obj.layer + 1 end end --Moves an object forwards a layer function obj:forward() if layer[obj._perspectiveLayer - 1] then layer[obj._perspectiveLayer - 1]:insert(obj) obj._perspectiveLayer = obj.layer - 1 end end --Moves an object to the very front of the camera function obj:toCameraFront() layer[1]:insert(obj) obj._perspectiveLayer = 1 obj:toFront() end --Moves an object to the very back of the camera function obj:toCameraBack() layer[#layers]:insert(obj) obj._perspectiveLayer = #layers obj:toBack() end end ------------------------------------------------------------------------------ -- Main Tracking Function ------------------------------------------------------------------------------ function view:trackFocus() local display = require("display") internal.processViewpoint() local viewX, viewY = internal.viewX, internal.viewY layers[1].xParallax, layers[1].yParallax = 1, 1 for i = 1, #layers do local addX, addY = internal.addX, internal.addY local layerX, layerY = internal.layer[i].x, internal.layer[i].y local diffX = (-viewX - layerX) local diffY = (-viewY - layerY) local incrX = diffX local incrY = diffY internal.layer[i].x = layerX + incrX - display.contentWidth*0.2 internal.layer[i].y = layerY + incrY layers[i].x = (layers[i].x - (layers[i].x - (internal.layer[i].x + addX) * layers[i].xParallax) * internal.trackingLevel) layers[i].y = (layers[i].y - (layers[i].y - (internal.layer[i].y + addY) * layers[i].yParallax) * internal.trackingLevel) end view.scrollX, view.scrollY = layers[1].x, layers[1].y end ------------------------------------------------------------------------------ -- Set the Camera Bounds ------------------------------------------------------------------------------ function view:setBounds(x1, x2, y1, y2) local xMin, xMax, yMin, yMax if x1 ~= nil then if not x1 then xMin = math_nhuge else xMin = x1 end end if x2 ~= nil then if not x2 then xMax = math_huge else xMax = x2 end end if y1 ~= nil then if not y1 then yMin = math_nhuge else yMin = y1 end end if y2 ~= nil then if not y2 then yMax = math_huge else yMax = y2 end end internal.bounds.xMin = xMin internal.bounds.xMax = xMax internal.bounds.yMin = yMin internal.bounds.yMax = yMax internal.scaleBounds(true, true) end ------------------------------------------------------------------------------ -- Miscellaneous Functions ------------------------------------------------------------------------------ -- Begin auto-tracking function view:track() if not isTracking then Runtime:addEventListener("enterFrame", view.trackFocus) isTracking = true end end -- Stop auto-tracking function view:cancel() if isTracking then Runtime:removeEventListener("enterFrame", view.trackFocus) isTracking = false end end -- Remove an object from the view function view:remove(obj) if obj and obj._perspectiveLayer then layers[obj._perspectiveLayer]:remove(obj) end end -- Set the view's focus function view:setFocus(obj) if obj then internal.focus = obj end if view.snapWhenFocused then view.snap() end end -- Snap the view to the focus point function view:snap() local t = internal.trackingLevel local d = internal.damping internal.trackingLevel = 1 internal.damping = view.damping view:trackFocus() internal.trackingLevel = t internal.damping = d end -- Move the view to a point function view:toPoint(x, y) view:cancel() local newFocus = {x = x, y = y} view:setFocus(newFocus) view:track() return newFocus end -- Get a layer of the view function view:layer(n) return layers[n] end -- Destroy the view function view:destroy() view:cancel() for i = 1, #layers do for o = 1, layers[i].numChildren do layers[i]:remove(layers[i][o]) end end display_remove(view) view = nil return true end -- Set layer parallax function view:setParallax(...) for i = 1, #arg do if type(arg[i]) == "table" then layers[i].xParallax, layers[i].yParallax = arg[i][1], arg[i][2] else layers[i].xParallax, layers[i].yParallax = arg[i], arg[i] end end end -- Get number of layers function view:layerCount() return #layers end ------------------------------------------------------------------------------ -- Build Layers ------------------------------------------------------------------------------ for i = layerCount or 8, 1, -1 do view.appendLayer() end return view end return lib_perspective
local M = { __prefix = 'app', __fetched_methods = {'name'}, __parse_methods = {'author'}, } M.version = function(self) local version = self:parse('app.version') if version == '' then version = self:numerify(self:fetch('app.version')) end return version end local Base = require "faker.base" return Base(M)
Schema.name = "Metro 2030 Roleplay" Schema.author = "Dunkersplay" Schema.description = "Welcome to the Underground." ix.currency.model = "models/ninja/signalvariance/weapons/akm_mag.mdl" ix.container.Register("models/devcon/mrp/props/cabinet_closed.mdl", { name = "Storage Locker", description = "A rusted metallic storage locker.", width = 10, height = 6, }) ix.container.Register("models/z-o-m-b-i-e/metro_2033/mebel_outdoor/m33_shkaf_02.mdl", { name = "Wooden Closet", description = "A worn storage closet, intended for storage.", width = 3, height = 6, }) ix.container.Register("models/z-o-m-b-i-e/st/equipment_cache/st_equipment_seif_04.mdl", { name = "Rusted Safe", description = "A rusted safe, appearing to still be functional.", width = 4, height = 2, }) ix.container.Register("models/maxibammo/556.mdl", { name = "Rusted Ammo Box", description = "A rusted old ammo crate, useful for storing things.", width = 3, height = 2 }) -- attribute manipulation should be done with methods from the ix.attributes library ix.char.RegisterVar("attributes", { field = "attributes", fieldType = ix.type.text, default = {}, index = 4, category = "attributes", isLocal = true, OnDisplay = function(self, container, payload) local maximum = hook.Run("GetDefaultAttributePoints", LocalPlayer(), payload) or 10 if (maximum < 1) then return end local attributes = container:Add("DPanel") attributes:Dock(TOP) local y local total = 0 payload.attributes = {} local maxAttributes = ix.config.Get("maxAttributes", 30) -- total spendable attribute points local totalBar = attributes:Add("ixAttributeBar") totalBar:SetMax(maximum) totalBar:SetValue(10) totalBar:Dock(TOP) totalBar:DockMargin(2, 2, 2, 2) totalBar:SetText(L("attribPointsLeft")) totalBar:SetReadOnly(true) totalBar:SetColor(Color(20, 120, 20, 255)) y = totalBar:GetTall() + 4 for k, v in SortedPairsByMemberValue(ix.attributes.list, "name") do payload.attributes[k] = maxAttributes / 2 local bar = attributes:Add("ixAttributeBar") bar:SetMax(ix.config.Get("maxAttributes", 60)) bar:SetValue(maxAttributes / 2) bar:Dock(TOP) bar:DockMargin(2, 2, 2, 2) bar:SetText(L(v.name)) bar.OnChanged = function(this, difference) if ((total + difference) > maximum) then return false end if (difference == 1) then if (totalBar:GetValue() == 0) then return false end end total = total + difference payload.attributes[k] = payload.attributes[k] + difference totalBar:SetValue(totalBar.value - difference) end if (v.noStartBonus) then bar:SetReadOnly() end y = y + bar:GetTall() + 4 end attributes:SetTall(y) return attributes end, OnValidate = function(self, value, data, client) if (value != nil) then if (istable(value)) then local count = 0 for _, v in pairs(value) do count = count + v end if (count > (hook.Run("GetDefaultAttributePoints", client, count) or 10)) then return false, "unknownError" end else return false, "unknownError" end end end, ShouldDisplay = function(self, container, payload) return !table.IsEmpty(ix.attributes.list) end }) function Schema:CanAutoFormatMessage(speaker, chatType, text) return chatType == "ic" or chatType == "w" or chatType == "y" or chatType == "radio" or chatType == "radio_eavesdrop" or chatType == "radio_eavesdrop" end function Schema:InitializedChatClasses() do local CLASS = {} CLASS.color = Color(75, 150, 50) CLASS.format = "%s radios in \"%s\"" function CLASS:CanHear(speaker, listener) local character = listener:GetCharacter() local inventory = character:GetInventory() local bHasRadio = false for k, v in pairs(inventory:GetItemsByUniqueID("handheld_radio", true)) do if (v:GetData("enabled", false) and speaker:GetCharacter():GetData("frequency") == character:GetData("frequency")) then bHasRadio = true break end end return bHasRadio end function CLASS:OnChatAdd(speaker, text) chat.AddText(self.color, string.format(self.format, speaker:Name(), text)) end ix.chat.Register("radio", CLASS) end do local CLASS = {} CLASS.color = Color(255, 255, 175) CLASS.format = "%s radios in \"%s\"" function CLASS:GetColor(speaker, text) if (LocalPlayer():GetEyeTrace().Entity == speaker) then return Color(175, 255, 175) end return self.color end function CLASS:CanHear(speaker, listener) if (ix.chat.classes.radio:CanHear(speaker, listener)) then return false end local chatRange = ix.config.Get("chatRange", 280) return (speaker:GetPos() - listener:GetPos()):LengthSqr() <= (chatRange * chatRange) end function CLASS:OnChatAdd(speaker, text) chat.AddText(self.color, string.format(self.format, speaker:Name(), text)) end ix.chat.Register("radio_eavesdrop", CLASS) end ix.chat.Register("itclose", { OnChatAdd = function(self, speaker, text) chat.AddText(Color(142, 68, 173), "*** "..text) end, CanHear = ix.config.Get("chatRange", 280) * 0.25, prefix = {"/ItClose","/DoClose"}, description = "@cmdItClose", indicator = "chatPerforming", deadCanChat = true }) ix.chat.Register("itfar", { OnChatAdd = function(self, speaker, text) chat.AddText(Color(142, 68, 173), "*** "..text) end, CanHear = ix.config.Get("chatRange", 280) * 2, prefix = {"/ItFar","/DoFar"}, description = "@cmdItFar", indicator = "chatPerforming", deadCanChat = true }) ix.chat.Register("meclose", { format = "*** %s %s", GetColor = ix.chat.classes.ic.GetColor, CanHear = ix.config.Get("chatRange", 280) * 0.25, prefix = {"/Mel", "/ActionClose"}, description = "@cmdMeClose", indicator = "chatPerforming", deadCanChat = true }) ix.chat.Register("mefar", { format = "*** %s %s", GetColor = ix.chat.classes.ic.GetColor, CanHear = ix.config.Get("chatRange", 280) * 2, prefix = {"/Med", "/ActionFar"}, description = "@cmdMeFar", indicator = "chatPerforming", deadCanChat = true }) end function Schema:ZeroNumber(number, length) local amount = math.max(0, length - string.len(number)) return string.rep("0", amount)..tostring(number) end -- Include netstream ix.util.Include("libs/thirdparty/sh_netstream2.lua") ix.util.Include("sh_configs.lua") ix.util.Include("sh_commands.lua") ix.util.Include("cl_schema.lua") ix.util.Include("cl_hooks.lua") ix.util.Include("sh_hooks.lua") ix.util.Include("sh_voices.lua") ix.util.Include("sh_anims.lua") ix.util.Include("sv_schema.lua") ix.util.Include("sv_hooks.lua") ix.flag.Add("v", "Access to light blackmarket goods.") ix.flag.Add("V", "Access to heavy blackmarket goods.")
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('StoryBit', { ActivationEffects = { PlaceObj('PauseExpedition', nil), }, Category = "PlanetaryAnomaly", Effects = {}, Enabled = true, Image = "UI/Messages/Events/24_dome_in_ruins.tga", Prerequisites = { PlaceObj('SupplyMissionsEnabled', nil), PlaceObj('CheckColonistCount', { 'Amount', 20, }), }, ScriptDone = true, Text = T(920606145587, --[[StoryBit RedMars_1 Text]] 'After climbing the slope of a huge crater we have faced an astonishing sight – down below we saw the remains of a facility. Clearly a man-made one. The dust didn’t manage to hide the rocket landing pads, the spherical concrete buildings and – what’s most disturbing – the large port-holes on the ground which resemble rocket silos too much to be sure.\n\n<if(is_commander("politician"))>[<commander_profile>] You\'ve heard rumors about Cold War military projects on Mars. It\'s intriguing, but it can also be quite dangerous.</if>'), TextReadyForValidation = true, TextsDone = true, Title = T(982593047746, --[[StoryBit RedMars_1 Title]] "Red Mars"), Trigger = "PlanetaryAnomalyEvent", VoicedText = T(762880757544, --[[voice:narrator]] "The expedition was sent to investigate a spectrographic trace of rich metals deposit, but found something much more interesting – and troubling!"), group = "Expeditions", id = "RedMars_1", PlaceObj('StoryBitReply', { 'Text', T(313142929429, --[[StoryBit RedMars_1 Text]] "Leave and forget about it."), 'OutcomeText', "custom", 'CustomOutcomeText', T(562011922315, --[[StoryBit RedMars_1 CustomOutcomeText]] "The expedition will return"), }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Effects', { PlaceObj('ResumeExpedition', nil), }, }), PlaceObj('StoryBitReply', { 'Text', T(629772509563, --[[StoryBit RedMars_1 Text]] "Leave the site, but upload its coordinates in the international database."), }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Enables', { "RedMars_2", }, 'Effects', { PlaceObj('ResumeExpedition', nil), }, }), PlaceObj('StoryBitReply', { 'Text', T(739189473025, --[[StoryBit RedMars_1 Text]] "Approach the facilities and investigate."), }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'VoicedText', T(403120348851, --[[voice:narrator]] "We approached the mysterious facility with apprehension, but nothing bad happened. It appears that the location has been abandoned decades ago."), 'Text', T(712762981128, --[[StoryBit RedMars_1 Text]] "The facility has been picked almost clean, but there are still traces of evidence what happened here. People lived here, and research was conducted. The silos are empty, but there are signs that at least two of the five hosted nuclear devices. The labs are the most amazing part of the facility – most of the equipment and the computer systems were too heavy and unwieldy to be moved out of the planet.\n\n<effect>A new Breakthrough tech has become available. The expedition will return shortly."), 'Enables', { "RedMars_3", }, 'Effects', { PlaceObj('DiscoverTech', { 'Field', "Breakthroughs", }), PlaceObj('ResumeExpedition', nil), }, }), })
include("sv_capturetheflag.lua") util.AddNetworkString("FlagCaptured") util.AddNetworkString("FlagDropped") util.AddNetworkString("FlagTaken") local function HandleFlagDropped(len, ply) chat.AddText(unpack(net.ReadTable())) if (teamid == 1) then usflagTaken = false elseif (teamid == 2) then tflagTaken = false end -- local team_flag = ents.FindByName(team_ents[net.ReadInt(16)]) -- Re Enable Body Group For Team's Flag -- team_flag:SetBodygroup(0, 0) -- may have to set it to 1 idk end net.Receive("FlagDropped", HandleFlagDropped) local function HandleFlagTaken(len, ply) chat.AddText(unpack(net.ReadTable())) if (teamid == 1) then usflagTaken = true elseif (teamid == 2) then tflagTaken = true end end net.Receive("FlagTaken", HandleFlagTaken) local function HandleFlagCaptured(len, ply) chat.AddText(unpack(net.ReadTable())) local teamid = net.ReadInt(16) if (teamid == 1) then usflagTaken = false elseif (teamid == 2) then tflagTaken = false end -- local team_flag = ents.FindByName(team_ents[net.ReadInt(16)]) -- Re Enable Body Group For Team's Flag -- team_flag:SetBodygroup(0, 0) -- may have to set it to 1 idk end net.Receive("CaptureFlag", HandleFlagCaptured)
object_tangible_collection_deathtrooper_epsilon_locator_beacon_01 = object_tangible_collection_shared_deathtrooper_epsilon_locator_beacon_01:new { gameObjectType = 8211,} ObjectTemplates:addTemplate(object_tangible_collection_deathtrooper_epsilon_locator_beacon_01, "object/tangible/collection/deathtrooper_epsilon_locator_beacon_01.iff")
local game = {} local skynet = require "skynet" local conf = require "config" local clusterid = tonumber(skynet.getenv("clusterid")) local config = conf[clusterid] -- 百人的逻辑都差不多 其实可以写在一起的 如果人少 放在一起没什么关系 人多需要分开的时候方便拆开 -- 游戏初始化 function game.on_init() local gamename = config.subrooms[game.super._subroomid].gamename local game_hook = require("game_" .. gamename) game_hook.super = game.super setmetatable(game, { __index = game_hook }) game_hook.on_init() end return game
GameListSubtitles["OnlineOfflineCapabilitiesFlag"] = function(Content) return string.format("Online Flag: %08X, Offline Flag: %08X%08X", Content.CapabilitiesOnline, Content.CapabilitiesOffline.HighPart, Content.CapabilitiesOffline.LowPart) end GameListSubtitles["OnlineCapabilities"] = function(Content) minmulti = bit32.rshift(bit32.band(Content.CapabilitiesOnline, 0x00FF0000), 16) maxmulti = bit32.rshift(bit32.band(Content.CapabilitiesOnline, 0xFF000000), 24) minco = bit32.band(Content.CapabilitiesOnline, 0x000000FF) maxco = bit32.rshift(bit32.band(Content.CapabilitiesOnline, 0x0000FF00), 8) return string.format("Online Players: %i-%i, %i-%i", minmulti, maxmulti, minco, maxco) end GameListSubtitles["OnlineMultiplayer"] = function(Content) minimum = bit32.rshift(bit32.band(Content.CapabilitiesOnline, 0x00FF0000), 16) maximum = bit32.rshift(bit32.band(Content.CapabilitiesOnline, 0xFF000000), 24) return string.format("Online Multiplayer: %i-%i", minimum, maximum) end GameListSubtitles["OnlineCo-Op"] = function(Content) minimum = bit32.band(Content.CapabilitiesOnline, 0x000000FF) maximum = bit32.rshift(bit32.band(Content.CapabilitiesOnline, 0x0000FF00), 8) return string.format("Online Co-Op: %i-%i", minimum, maximum) end
--[[ © 2018 Thriving Ventures AB do not share, re-distribute or modify without permission of its author (gustaf@thrivingventures.com). _______ _ _ _ _____ |__ __(_) | | | |_ _| | | _ __ _ ___ _ __ | | | | | | | | | |/ _` |/ _ \ '__| | | | | | | | | | | (_| | __/ | | |__| |_| |_ |_| |_|\__, |\___|_| \____/|_____| __/ | |___/ ]] local panel = {} surface.CreateFont("tiger.base.search", { font = "Arial", size = 12, weight = 400 }) surface.CreateFont("tiger.base.footer", { font = "Arial", size = 14, weight = 400 }) surface.CreateFont("tiger.base.section", { font = "Helvetica", size = 14, weight = 400 }) serverguard.themes.CreateDefault("tiger_base_bg", Color(232, 231, 239), "tiger.base") serverguard.themes.CreateDefault("tiger_base_outline", Color(190, 190, 190), "tiger.base") serverguard.themes.CreateDefault("tiger_base_footer_bg", Color(255, 255, 255), "tiger.base") serverguard.themes.CreateDefault("tiger_base_footer_label", Color(31, 153, 228), "tiger.base") serverguard.themes.CreateDefault("tiger_base_footer_hint", Color(141, 142, 134), "tiger.base") -- Section. serverguard.themes.CreateDefault("tiger_base_section_icon", Color(141, 142, 134), "tiger.base") serverguard.themes.CreateDefault("tiger_base_section_icon_selected", Color(31, 153, 228), "tiger.base") serverguard.themes.CreateDefault("tiger_base_section_label", Color(141, 142, 134), "tiger.base") serverguard.themes.CreateDefault("tiger_base_section_label_selected", Color(31, 153, 228), "tiger.base") serverguard.themes.CreateDefault("tiger_base_section_outline", Color(190, 190, 190), "tiger.base") serverguard.themes.CreateDefault("tiger_base_section_selected", Color(232, 231, 239), "tiger.base") function panel:Init() local theme = serverguard.themes.GetCurrent() self.sections = {} self.searchString = "" self.lastSection = nil self:DockPadding(162, 22, 22, 46) self.sectionList = self:Add("tiger.list") self.sectionList:DockPadding(0, 0, 0, 0) self.sectionList.list:SetUseSizeLimit(false) function self.sectionList:Paint(w, h) local theme = serverguard.themes.GetCurrent() draw.SimpleRect(0, 0, w, h, theme.tiger_list_bg) draw.SimpleRect(w - 1, 0, 1, h, theme.tiger_list_outline) end self.bFooterEnabled = true self.bUseSmallPanels = false self.updatePanel = self:Add("Panel") self.updatePanel:SetMouseInputEnabled(true) self.updatePanel.OnMousePressed = function(_self, keyCode) if (self.updateNotify) then self.updateNotify = false self.updatePanel:SetCursor("none") self.updatePanel:SetToolTipSG() timer.Simple(3, function() self.updateNotify = nil end) end end self.copyright = self:Add("DLabel") self.copyright:SetMouseInputEnabled(true) self.copyright:SetText("Thriving Ventures AB") self.copyright:SetCursor("hand") self.copyright:SetToolTipSG("Click here to visit the ServerGuard website!") self.copyright:SetFont("tiger.base.footer") self.copyright:SetTextColor(theme.tiger_base_footer_label) function self.copyright:DoClick() gui.OpenURL("http://gmodserverguard.com/?utm_source=serverguard&utm_medium=organic&utm_content=footerlink&utm_campaign=serverguard") end self:SetupSearchPanel() end function panel:SetupSearchPanel() self.searchPanel = vgui.Create("Panel", self) self.searchPanel:SetSize(128, 22) self.searchPanel:Dock(TOP) self.searchPanel:SetVisible(false) function self.searchPanel:Paint(width, height) local theme = serverguard.themes.GetCurrent() local color = theme.tiger_list_panel_list_hover draw.SimpleRect(0, 0, width - 1, height, color) end self.searchPanel.label = self.searchPanel:Add("DLabel") self.searchPanel.label:SetTextColor(Color(0, 0, 0)) self.searchPanel.label:SetSize(self.searchPanel:GetWide(), self.searchPanel:GetTall()) self.searchPanel.label:SetContentAlignment(5) self.searchPanel.label:SetFont("tiger.base.search") self.searchPanel.label:SetText("") serverguard.themes.AddPanel(self.searchPanel.label, "tiger_list_panel_label_hover") end function panel:OnKeyCodePressed(keyCode) local key = input.GetKeyName(keyCode) if (not key) then return end local matches = self:GetSearchMatches(self.searchString) local matchAmount = #matches local bUseSmallPanels = self:GetUseSmallPanels() local nextMatchAmount = #self:GetSearchMatches(self.searchString .. key) if (key == "BACKSPACE") then self.searchString = string.sub(self.searchString, 1, #self.searchString - 1) elseif (key == "ENTER" and matchAmount == 1) then -- HACK because docking is awfully implemented. local id = 0 local y = 0 for k, v in SortedPairs(self.sections) do if (k == matches[1].name) then y = id * 120 break end id = id + 1 end self:ResetSearch() if (id == 0) then self.sectionList.list.VBar:SetScroll(-100) else self.sectionList.list.VBar:SetScroll(id * 120) end matches[1].icon:DoClick() return elseif (key == "SPACE" or string.match(key, "[a-z]")) then if (key == "SPACE") then key = " " end self.searchString = self.searchString .. key end self.searchPanel.label:SetText(self.searchString) if (string.len(self.searchString) > 0 and not self.lastSearch) then self.searchPanel:SetVisible(true) self.sectionList.list.VBar:SetScroll(-100) self.lastSearch = true elseif (string.len(self.searchString) < 1) then self.searchPanel:SetVisible(false) if (self.lastSearch) then self.sectionList.list.VBar:SetScroll(-100) end self.lastSearch = nil end for k, v in pairs(self.sections) do if (IsValid(v)) then if (not string.StartWith(string.lower(k), self.searchString)) then v:SetSize(0, 0) else if (not bUseSmallPanels) then v:SetSize(128, 120) else v:SetSize(64, 80) end end end end end function panel:ResetSearch() local bUseSmallPanels = self:GetUseSmallPanels() for k, v in pairs(self.sections) do if (IsValid(v)) then if (not bUseSmallPanels) then v:SetSize(128, 120) else v:SetSize(64, 80) end end end self.searchString = "" self.lastSearch = nil self.searchPanel:SetVisible(false) self.searchPanel.label:SetText("") end function panel:GetSearchMatches(searchString) local matches = {} for k, v in pairs(self.sections) do if (string.StartWith(string.lower(k), searchString)) then table.insert(matches, v) end end return matches end function panel:GetFooterEnabled() return self.bFooterEnabled end function panel:SetFooterEnabled(bValue) local bRealValue = tobool(bValue) self.updatePanel:SetVisible(bValue) self.copyright:SetVisible(bValue) self:DockPadding(162, 22, 22, ((bRealValue and 46) or 22)) self.bFooterEnabled = bRealValue end function panel:GetUseSmallPanels() return self.bUseSmallPanels end -- should only ever be called immediately after creation function panel:UseSmallPanels(bValue) local bRealValue = tobool(bValue) self.bUseSmallPanels = bRealValue self:DockPadding(76, 12, 12, ((self:GetFooterEnabled() and 36) or 12)) end function panel:SetUpdateNotification(bToggled) local theme = serverguard.themes.GetCurrent() local themeCopy = table.Copy(theme) self.updateNotify = tobool(bToggled) self.updateTarget = Color(255, 210, 0) self.updateCurrent = themeCopy.tiger_base_footer_bg if (bToggled) then self.updatePanel:SetCursor("hand") self.updatePanel:SetToolTipSG("Version " .. serverguard.GetLatestVersion() .. " of ServerGuard is now available!\nIt is recommended to update this server's version of ServerGuard.") else self.updatePanel:SetCursor("none") self.updatePanel:SetToolTipSG() end end function panel:AddSection(name, material, callback, flag) local base = vgui.Create("Panel") if (self:GetUseSmallPanels()) then base:SetSize(64, 80) else base:SetSize(128, 120) end base:Dock(TOP) base.flag = flag base.name = name local function ShortenText(text, font, max_w) local split = string.ToTable(text) local res = "" for k, v in pairs(split) do if (util.GetTextSize(font, res .. v .. "...") > max_w) then return res .. "..." else res = res .. v end end return res end local function DrawWrappedText(text, font, w, h, color, align_h, align_v, max_w) local explode = string.Explode(" ", text) local currentText = "" local line = 0 local y = select(2, util.GetTextSize(font, " ")) for k, v in pairs(explode) do if (util.GetTextSize(font, currentText .. " " .. v) > max_w) then if (currentText ~= "") then draw.SimpleText(currentText, font, w, h + y * line, color, align_h, align_v) currentText = "" line = line + 1 elseif (currentText == "" and k == #explode) then draw.SimpleText(ShortenText(v, font, max_w), font, w, h + y * line, color, align_h, align_v) break end end currentText = currentText .. " " .. v if (k == #explode and currentText ~= "") then draw.SimpleText(currentText, font, w, h + y * line, color, align_h, align_v) end end end function base:Paint(w, h) local theme = serverguard.themes.GetCurrent() if (self.selected) then draw.SimpleRect(0, 0, w, h, theme.tiger_base_section_selected) draw.SimpleRect(0, 0, w, 1, theme.tiger_base_section_outline) draw.SimpleRect(0, h - 1, w, 1, theme.tiger_base_section_outline) DrawWrappedText(name, "tiger.base.section", w / 2, h - 24, theme.tiger_base_section_label_selected, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, w) if (self.icon:GetColor() ~= theme.tiger_base_section_icon_selected) then self.icon:SetColor(theme.tiger_base_section_icon_selected) end else DrawWrappedText(name, "tiger.base.section", w / 2, h - 24, theme.tiger_base_section_label, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, w) if (self.icon:GetColor() ~= theme.tiger_base_section_icon) then self.icon:SetColor(theme.tiger_base_section_icon) end end end if (base.flag) then function base:Think() local hasPermission = false if (type(self.permissions) == "table") then for k, v in pairs(self.permissions) do if (serverguard.player:HasPermission(LocalPlayer(), v)) then hasPermission = true break end end else hasPermission = serverguard.player:HasPermission(LocalPlayer(), self.permissions) end if (not hasPermission) then if (not self.icon:GetDisabled()) then local theme = serverguard.themes.GetCurrent() self.icon:SetDisabled(true) self.icon:SetColor(theme.tiger_base_section_icon) self.icon:SetToolTipSG("You do not have permission to view this!") self.section:SetVisible(false) end else if (self.icon:GetDisabled()) then self.icon:SetDisabled(false) self.icon:SetToolTipSG(nil) end end end end base.icon = base:Add("DImageButton") if (self:GetUseSmallPanels()) then base.icon:SetPos(16, 14) else base.icon:SetPos(32, 20) end base.icon:SetImage(material) if (self:GetUseSmallPanels()) then base.icon:SetSize(32, 32) else base.icon:SetSize(64, 64) end function base.icon.DoClick() if (IsValid(self.lastSection)) then self.lastSection.selected = false self.lastSection.section:SetVisible(false) end base.selected = true base.section:SetVisible(true) base.section:callback() self.lastSection = base end base.icon.OnMousePressed = base.icon.DoClick self.sectionList:AddPanel(base) local section = self:Add("Panel") section:Dock(FILL) section:SetVisible(false) section.callback = callback base.section = section section:callback() self.sections[name] = base end function panel:GetSections() return self.sections end function panel:SetSectionSelected(uniqueID) if (not self.sections[uniqueID]) then return end self.sections[uniqueID].icon.DoClick() end function panel:PerformLayout() local w, h = self:GetSize() self.sectionList:SetPos(1, 1) self.sectionList:SetSize(((self:GetUseSmallPanels() and 64) or 128), h - ((self:GetFooterEnabled() and 27) or 2)) self.copyright:SizeToContents() self.copyright:SetPos(8, self:GetTall() - (self.copyright:GetTall() + self.copyright:GetTall() / 2)) self.updatePanel:SetSize(self:GetWide(), 26) self.updatePanel:SetPos(0, self:GetTall() - 26) end function panel:Rebuild() local lastSection if (IsValid(self.lastSection)) then lastSection = self.lastSection.name self.lastSection.selected = false self.lastSection.section:SetVisible(false) self.lastSection.section:Remove() end for k, v in pairs(self.sections) do if (IsValid(v)) then if (IsValid(v.section)) then v.section:SetVisible(false) v.section:Remove() end v:SetVisible(false) v:Remove() end end self.sectionList:Clear() self:SetupSearchPanel() self.sectionList:AddPanel(self.searchPanel) for k, data in util.SortedPairsByMemberValue(serverguard.menu:GetStored(), "name") do if (data.permissions ~= nil) then if (serverguard.player:HasPermission(LocalPlayer(), data.permissions)) then self:AddSection(data.name, data.material, function(base) if (base.created) then data:Update(base) else data:Create(base) data:Update(base) for v, data_s in util.SortedPairsByMemberValue(serverguard.menu:GetStored()[data.name].submenus, "name") do base.base:AddSection(data_s.name, data_s.material, function(categoryBase) if (categoryBase.created) then data_s:Update(categoryBase) else data_s:Create(categoryBase) data_s:Update(categoryBase) categoryBase.created = true end end) end base.created = true end end, data.flag) end else self:AddSection(data.name, data.material, function(base) if (base.created) then data:Update(base) else data:Create(base) data:Update(base) for v, data_s in util.SortedPairsByMemberValue(serverguard.menu:GetStored()[data.name].submenus, "name") do if (data_s.permissions == nil or serverguard.player:HasPermission(LocalPlayer(), data_s.permissions)) then base.base:AddSection(data_s.name, data_s.material, function(categoryBase) if (categoryBase.created) then data_s:Update(categoryBase) else data_s:Create(categoryBase) data_s:Update(categoryBase) categoryBase.created = true end end) end end base.created = true end end, data.flag) end end self:InvalidateLayout(true) self:ResetSearch() if (lastSection) then self:SetSectionSelected(lastSection) end end function panel:Think() local mousex = math.Clamp(gui.MouseX(), 1, ScrW() - 1) local mousey = math.Clamp(gui.MouseY(), 1, ScrH() - 1) if (self.Dragging) then local x = mousex - self.Dragging[1] local y = mousey - self.Dragging[2] x = math.Clamp(x, 0, ScrW() - self:GetWide()) y = math.Clamp(y, 0, ScrH() - self:GetTall()) self:SetPos(x, y) end if (self.Hovered) then if (gui.MouseY() < self.y + 20) then self:SetCursor("sizeall") return end end self:SetCursor("arrow") if (self:IsVisible()) then for k, data in pairs(serverguard.menu:GetStored()) do if (data.permissions == nil or serverguard.player:HasPermission(LocalPlayer(), data.permissions)) then if (isfunction(data.Think)) then data:Think() end end for v, data_s in pairs(serverguard.menu:GetStored()[data.name].submenus) do if (data_s.permissions == nil or serverguard.player:HasPermission(LocalPlayer(), data_s.permissions)) then if (isfunction(data_s.Think)) then data_s:Think() end end end end end end function panel:OnMousePressed() if (gui.MouseY() < self.y + 20) then self.Dragging = {gui.MouseX() - self.x, gui.MouseY() - self.y} self:MouseCapture(true) return end end function panel:OnMouseReleased() self.Dragging = nil self:MouseCapture(false) end function panel:OnCursorEntered() self.Hovered = true end function panel:OnCursorExited() self.Hovered = false end function panel:Paint(width, height) local theme = serverguard.themes.GetCurrent() draw.RoundedBox(4, 0, 0, width, height, theme.tiger_base_outline) draw.RoundedBox(2, 1, 1, width - 2, height - 2, theme.tiger_base_bg) if (self:GetFooterEnabled()) then local footerBG = theme.tiger_base_footer_bg if (self.updateNotify == true) then if (self.updateCurrent ~= self.updateTarget) then for k, v in pairs(self.updateCurrent) do local animateSpeed = math.abs(self.updateTarget[k] - self.updateCurrent[k]) * FrameTime() + 1 self.updateCurrent[k] = math.Approach(self.updateCurrent[k], self.updateTarget[k], animateSpeed) end end footerBG = self.updateCurrent elseif (self.updateNotify == false) then if (self.updateCurrent ~= theme.tiger_base_footer_bg[k]) then for k, v in pairs(self.updateCurrent) do local animateSpeed = math.abs(theme.tiger_base_footer_bg[k] - self.updateCurrent[k]) * FrameTime() + 1 self.updateCurrent[k] = math.Approach(self.updateCurrent[k], theme.tiger_base_footer_bg[k], animateSpeed) end end footerBG = self.updateCurrent end draw.SimpleRect(2, height - 26, width - 4, 24, footerBG) draw.SimpleRect(1, height - 26, width - 2, 1, theme.tiger_base_outline) else draw.SimpleRect(1, height - 1, width - 2, 1, theme.tiger_base_outline) end DisableClipping(true) for i = 1, 2 do local color = Color(0, 0, 0, (255 / i) * 0.2) surface.SetDrawColor(color) -- Right shadow. surface.DrawRect(width - 1 + i, 1, 1, height - 1) -- Top shadow. surface.DrawRect(1, -i, width - 1, 1) -- Left shadow. surface.DrawRect(-i, 0, 1, height) -- Bottom shadow. surface.DrawRect(1, height, width - 1, i) end DisableClipping(false) end vgui.Register("tiger.base", panel, "EditablePanel")
local NilCommand = require('command/nil') local EntityFactory = require('model/entity/factory') local DialogueFactory = require('model/dialogue/factory') -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local OfferCommand = NilCommand:NilCommand() OfferCommand.__index = OfferCommand -------------------------------------------------------------------------------- function OfferCommand:OfferCommand(id, items) local o = NilCommand:NilCommand() setmetatable(o, self) o._id = id o._items = items o._type = 'OfferCommand' o._dialogue = DialogueFactory.CreateOfferDialogue( EntityFactory.CreateMob(o._id), EntityFactory.CreatePlayer(), o._items) o._dialogue:SetSuccessCallback(function() o._on_success() end) o._dialogue:SetFailureCallback(function() o._on_failure() end) return o end -------------------------------------------------------------------------------- function OfferCommand:OnIncomingData(id, pkt) return self._dialogue:OnIncomingData(id, pkt) end -------------------------------------------------------------------------------- function OfferCommand:OnOutgoingData(id, pkt) return self._dialogue:OnOutgoingData(id, pkt) end -------------------------------------------------------------------------------- function OfferCommand:__call(state) self._dialogue:Start() end return OfferCommand
player_manager.AddValidModel( "papyrus", "models/player/antitoxic/papyrus_pm/papyrus_pm.mdl" ); list.Set( "PlayerOptionsModel", "papyrus", "models/player/antitoxic/papyrus_pm/papyrus_pm.mdl" );
local helpers = require "spec.helpers" -- Note: remove the below hack when https://github.com/Kong/kong/pull/6952 is merged local stream_available, _ = pcall(require, "kong.tools.stream_api") local spec_path = debug.getinfo(1).source:match("@?(.*/)") local nginx_conf if stream_available then nginx_conf = spec_path .. "/fixtures/prometheus/custom_nginx.template" else nginx_conf = "./spec/fixtures/custom_nginx.template" end -- Note ends local t = pending local pok = pcall(require, "kong.enterprise_edition.licensing") if pok then t = describe end t("Plugin: prometheus (exporter) enterprise licenses", function() local admin_client setup(function() local bp = helpers.get_db_utils() bp.plugins:insert { protocols = { "http", "https", "grpc", "grpcs", "tcp", "tls" }, name = "prometheus", } assert(helpers.start_kong { nginx_conf = nginx_conf, plugins = "bundled, prometheus", }) admin_client = helpers.admin_client() end) teardown(function() if admin_client then admin_client:close() end helpers.stop_kong() end) it("exports enterprise licenses", function() local res = assert(admin_client:send { method = "GET", path = "/metrics", }) local body = assert.res_status(200, res) assert.matches('kong_enterprise_license_signature %d+', body) assert.matches('kong_enterprise_license_expiration %d+', body) assert.matches('kong_enterprise_license_features{feature="ee_plugins"}', body, nil, true) assert.matches('kong_enterprise_license_features{feature="write_admin_api"}', body, nil, true) assert.matches('kong_enterprise_license_errors 0', body, nil, true) assert.matches('kong_nginx_metric_errors_total 0', body, nil, true) end) end)
-- get the set of video encoder friendly output sizes from suppl.lua local keys = { size = function(cell, val, opts) local lut = suppl_size_lut(true, true) if lut[val] then opts.width = lut[val][1] opts.height = lut[val][2] return true end cell:set_error(string.format( "No matching preset to %s for option key 'size'", val)) end, -- the different quality modes are not stable in the engine yet quality = function(cell, val, opts) return true end -- other options are the layouting formula, clocking (fixed-rate, ...) } local function compose(fmt, ...) -- use some kind of format string rather than trying to lock down this interface local list = string.split(fmt, ":") local cell = eval_scope.cell local opts = { width = 720, height = 480 } for _, v in ipairs(list) do local key, val = string.split_first(v, "=") if keys[key] then if not keys[key](cell, val, opts) then return end else cell:set_error("Uknown key '" .. key .. "'") return end end return {"compose", opts, ...} end local function fmt_helper(instr) -- split into opts, remove the helpers that have a matching key already return { "quality={default,fp16,565}", "size={480p,720p,1080p,4k}", "policy={ro_bin,rw_bin}" } end return function(types) return { handler = compose, args = {types.FACTORY, types.STRING, types.VIDEO, types.VARARG}, type_helper = {fmt_helper}, name = {"options", "source"}, argc = 2, help = "Create a composition cell out of one or many video inputs.", } end
-- taken from http://luaforge.net/projects/luacairo/ local cairo = require"lcairo" local CAIRO = cairo print(cairo.version_string()) print("CAIRO.HAS_IMAGE_SURFACE: ", CAIRO.HAS_IMAGE_SURFACE) local w = 320 local h = 240 local outfile = 'cairo_test1.png' local cslud = cairo.image_surface_create(CAIRO.FORMAT_RGB24, w, h) local crlud = cairo.create(cslud) -- give ownership, default is no ownership transfer local cr = cairo.ContextFromLUD(crlud, true) local cs = cairo.SurfaceFromLUD(cslud, true) print(cr) print(cs) -- local dev = cairo.Device(cs) -- print(dev) -- print(dev:get_type()) print(cairo.surface_get_type(cs)) print(cr:status_to_string(cr:status())) print(cr:has_current_point()) print(cairo.has_current_point(crlud)) print(cairo.has_current_point(cr)) do local fo = cairo.FontOptions() --not allowed cairo.font_options_destroy(fo) fo:destroy() end cr:set_source_rgb(1, 1, 1) cr:paint() cr:set_source_rgb(0, 0, 0) cr:set_line_width(5) cr:set_line_cap(CAIRO.LINE_CAP_ROUND) cr:move_to(w/4, h/4) cr:line_to(3*w/4, 3*h/4) cr:stroke() cr:move_to(3*w/4, h/4) cr:line_to(w/4, 3*h/4) cr:stroke() --cairo.surface_write_to_png(cs, outfile) cs:write_to_png(outfile)
-- example config for teamviewer sandbox. -- for teamviewer 12 and earlier: -- you need to use i386-based debian chroot downloaded with download-debian-chroot.sh script and prepared with debian-setup.cfg.lua config. -- using debian-sandbox.cfg.lua config file as base -- if using x86_64 host env you must also use i386 session management utilities by running "sandboxer-download-extra" command. -- you must also manually install libpng12-0 package from debian jessie (it was removed in stretch distro). -- see https://packages.debian.org/jessie/libpng12-0 for download links, and install package into debian chroot manually with "dpkg -i" command. -- NOTE: teamviewer 13 and up is not fully supported: -- teamviewer's complicated online=detection logic is not working as intended inside sandbox env. -- this makes it impossible to remote control this computer and login to teamviewer account. -- outgoing remote control connections, however, should work. -- for teamviewer 13 and up: -- tested with "teamviewer 14" on ubuntu 18.04 x86_64 chroot downloaded with download-ubuntu-chroot.sh script. -- external chroot must be prepared with debian-setup.cfg.lua config (using "sandboxer debian-setup.cfg.lua fakeroot_shell" command) -- use "tv-setup checklibs" to find out what dependencies must be installed in chroot to run teamviewer -- redefine defaults.recalculate function, that will be called by base config defaults.recalculate_orig=defaults.recalculate function defaults.recalculate() tunables.datadir=loader.path.combine(loader.workdir,"userdata-teamviewer") defaults.recalculate_orig() end defaults.recalculate() -- load base config dofile(loader.path.combine(loader.workdir,"debian-sandbox.cfg.lua")) -- remove some unneded features and mounts loader.table.remove_value(sandbox.features,"dbus") -- remove some mounts from base config loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devsnd_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devdri_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sys_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devinput_mount) loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devshm_mount) -- enable resolvconf feature table.insert(sandbox.features,"resolvconf") loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.resolvconf_mount) -- optional mount for directory with teamviewer tarxz archives table.insert(sandbox.setup.mounts,{prio=99,"bind-try",loader.path.combine(loader.workdir,"installs"),"/home/sandboxer/installs"}) teamviewer={ exec="/home/sandboxer/teamviewer/teamviewer", path="/home/sandboxer/teamviewer", args={}, term_signal=defaults.signals.SIGTERM, attach=false, pty=false, exclusive=true, desktop={ name = "TeamViewer (in sandbox)", comment = "Remote control and meeting solution, sandbox uid "..config.sandbox_uid, icon = loader.path.combine(tunables.datadir,"home","sandboxer","teamviewer","tv_bin","desktop","teamviewer_256.png"), terminal = false, startupnotify = false, categories="Network;Application;" }, } teamviewer_checklibs={ exec="/home/sandboxer/teamviewer/tv-setup", path="/home/sandboxer/teamviewer", args={"checklibs"}, term_signal=defaults.signals.SIGTERM, attach=true, pty=true, } teamviewer_install_tarxz={ exec="/bin/bash", path="/home/sandboxer", args={"-c","rm -rf $HOME/teamviewer && img=`find ./installs -name \"teamviewer*.tar.xz\"|sort|tail -n1` && ( xz -d -c \"$img\" | tar xvf - )"}, term_signal=defaults.signals.SIGTERM, attach=true, pty=false, exclusive=true, }
local g, cmd = vim.g, vim.cmd g.ascii = { " ", " ", " ", " ", " ", " _| _| _|_|_|_| _|_| _| _| _|_|_| _| _| ", " _|_| _| _| _| _| _| _| _| _|_| _|_| ", " _| _| _| _|_|_| _| _| _| _| _| _| _| _| ", " _| _|_| _| _| _| _| _| _| _| _| ", " _| _| _|_|_|_| _|_| _| _|_|_| _| _| ", " ", " ", " ", " ", " " } g.startify_custom_header = "startify#center(g:ascii)" -- g.startify_custom_header = 'startify#center(g:void)' g.startify_lists = { {type = "sessions", header = {"  Sessions"}}, {type = "files", header = {"  Files"}}, {type = "bookmarks", header = {"  Bookmarks"}}, {type = "commands", header = {" גּ Commands"}} } -- { type ='dir', header = {' MRU in '. getcwd() } }, g.startify_commands = { {h = {"Check Vim health", ":checkhealth"}}, {i = {"Install PLugins", ":PackerInstall"}}, {u = {"Update Plugin", ":PackerUpdate"}}, {c = {"Clean Plugin", ":PackerClean"}}, {s = {"Sync Plugin", ":PackerSync"}}, {s = {"Start Time", ":StartupTime"}}, {o = {"Open GitHub repo", ":RepoEdit"}} -- { m = {'Coc marketplace' , ':CocList marketplace' }}, } g.startify_bookmarks = { {v = "~/.config/nvim/init.lua"}, -- {k = "~/.config/kitty/kitty.conf"}, -- {f = "~/.config/fish/config.fish"}, {g = "~/.gitconfig"}, -- {a = "~/.aliases"}, {t = "~/.tmux.conf"}, -- {d = "~/dotfiles"}, -- {p = "~/CodeHub/playgrounds/playground.js"} } g.startify_session_sort = 1 g.startify_change_to_dir = 1 g.startify_session_autoload = 1 g.startify_session_delete_buffers = 0 g.startify_session_persistence = 1 g.startify_change_to_vcs_root = 1 g.startify_padding_left = 6 g.webdevicons_enable_startify = 1 g.startify_enable_special = 1 g.startify_files_number = 10 g.startify_update_oldfiles = 1 g.startify_change_to_dir = 1 -- local total_plugins = 0 -- if vim.fn.exists('*dein#get') then -- local plugins = vim.fn['dein#get']() -- for _, _ in pairs(plugins) do -- total_plugins = total_plugins + 1 -- end -- end -- g.startify_custom_footer = {'', ' neovim loaded ' .. total_plugins .. ' plugins.', ''}
local skynet = require "skynet" skynet.start(function() skynet.dispatch("lua", function(src, session, cmd, ...) local f = CMD[cmd] assert(f, "can't find dispatch handler cmd = "..cmd) if session > 0 then return skynet.ret(skynet.pack(f(...))) else f(...) end end) end)
require("reactivity/src") require("@vue/shared") describe('reactivity/computed', function() mockWarn() it('should return updated value', function() local value = reactive({}) local cValue = computed(function() value.foo end ) expect(cValue.value):toBe(undefined) value.foo = 1 expect(cValue.value):toBe(1) end ) it('should compute lazily', function() local value = reactive({}) local getter = jest:fn(function() value.foo end ) local cValue = computed(getter) expect(getter).tsvar_not:toHaveBeenCalled() expect(cValue.value):toBe(undefined) expect(getter):toHaveBeenCalledTimes(1) expect(getter):toHaveBeenCalledTimes(1) value.foo = 1 expect(getter):toHaveBeenCalledTimes(1) expect(cValue.value):toBe(1) expect(getter):toHaveBeenCalledTimes(2) expect(getter):toHaveBeenCalledTimes(2) end ) it('should trigger effect', function() local value = reactive({}) local cValue = computed(function() value.foo end ) local dummy = nil effect(function() dummy = cValue.value end ) expect(dummy):toBe(undefined) value.foo = 1 expect(dummy):toBe(1) end ) it('should work when chained', function() local value = reactive({foo=0}) local c1 = computed(function() value.foo end ) local c2 = computed(function() c1.value + 1 end ) expect(c2.value):toBe(1) expect(c1.value):toBe(0) value.foo=value.foo+1 expect(c2.value):toBe(2) expect(c1.value):toBe(1) end ) it('should trigger effect when chained', function() local value = reactive({foo=0}) local getter1 = jest:fn(function() value.foo end ) local getter2 = jest:fn(function() return c1.value + 1 end ) local c1 = computed(getter1) local c2 = computed(getter2) local dummy = nil effect(function() dummy = c2.value end ) expect(dummy):toBe(1) expect(getter1):toHaveBeenCalledTimes(1) expect(getter2):toHaveBeenCalledTimes(1) value.foo=value.foo+1 expect(dummy):toBe(2) expect(getter1):toHaveBeenCalledTimes(2) expect(getter2):toHaveBeenCalledTimes(2) end ) it('should trigger effect when chained (mixed invocations)', function() local value = reactive({foo=0}) local getter1 = jest:fn(function() value.foo end ) local getter2 = jest:fn(function() return c1.value + 1 end ) local c1 = computed(getter1) local c2 = computed(getter2) local dummy = nil effect(function() dummy = c1.value + c2.value end ) expect(dummy):toBe(1) expect(getter1):toHaveBeenCalledTimes(1) expect(getter2):toHaveBeenCalledTimes(1) value.foo=value.foo+1 expect(dummy):toBe(3) expect(getter1):toHaveBeenCalledTimes(2) expect(getter2):toHaveBeenCalledTimes(2) end ) it('should no longer update when stopped', function() local value = reactive({}) local cValue = computed(function() value.foo end ) local dummy = nil effect(function() dummy = cValue.value end ) expect(dummy):toBe(undefined) value.foo = 1 expect(dummy):toBe(1) stop(cValue.effect) value.foo = 2 expect(dummy):toBe(1) end ) it('should support setter', function() local n = ref(1) local plusOne = computed({get=function() n.value + 1 end , set=function(val) n.value = val - 1 end }) expect(plusOne.value):toBe(2) n.value=n.value+1 expect(plusOne.value):toBe(3) plusOne.value = 0 expect(n.value):toBe(-1) end ) it('should trigger effect w/ setter', function() local n = ref(1) local plusOne = computed({get=function() n.value + 1 end , set=function(val) n.value = val - 1 end }) local dummy = nil effect(function() dummy = n.value end ) expect(dummy):toBe(1) plusOne.value = 0 expect(dummy):toBe(-1) end ) it('should warn if trying to set a readonly computed', function() local n = ref(1) local plusOne = computed(function() n.value + 1 end ) plusOne.value=plusOne.value+1 expect('Write operation failed: computed value is readonly'):toHaveBeenWarnedLast() end ) end )
Talk(0, "好啊!成昆,原来你躲在这里,怎么,几个坏蛋聚在这里,是不是又在一起商量什么坏勾当?", "talkname0", 1); Talk(18, "哼!上次的事全被你坏了,我这次饶不了你.", "talkname18", 0); Talk(0, "手下败将还说大话,这次得小心一点,可别再让你跑了.", "talkname0", 1); if TryBattle(13) == true then goto label0 end; Dead(); do return end; ::label0:: ModifyEvent(-2, 0, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2); ModifyEvent(-2, 1, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2); ModifyEvent(-2, 2, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2); ModifyEvent(-2, 3, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2); ModifyEvent(-2, 4, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2); jyx2_ReplaceSceneObject("", "NPC/成昆喽喽1", "");--非当前场景时,目前代码逻辑不会立即刷新gameobject。所以显示/隐藏当前场景人物时,不需要带场景号 jyx2_ReplaceSceneObject("", "NPC/成昆喽喽2", ""); jyx2_ReplaceSceneObject("", "NPC/成昆喽喽3", ""); jyx2_ReplaceSceneObject("", "NPC/成昆", ""); LightScence(); Talk(0, "今天真是大快人心,替武林除了一个大害.", "talkname0", 1); AddItem(191, 1); AddRepute(5); do return end;
package.path = debug.getinfo(1,"S").source:match[[^@?(.*[\/])[^\/]-$]] .."?.lua;".. package.path trackFinder = require("libs.trackFinder") trackDecorator = require('libs.trackDecorator') -- setup the track color for the new track -- add a postfader send to the snare bus track function main() trackDecorator.prepareTrack('vocal-bus __vox__ __mbus__') trackDecorator.decorateBackupVocal(currentTrack) end reaper.defer(main)
local tab = {} tab.deepcopy = function(t) local ttype,d = type(t),tab.deepcopy local copy if ttype == 'table' then copy = {} for k,v in next,t,nil do copy[d(k)]=d(v) end setmetatable(copy,getmetatable(t)) else copy = t end return copy end tab.protocopy = function(t,p) local copy = t.deepcopy(t) if p then for k,v in pairs(p) do copy[k] = v end end return copy end tab.shallowcopy = function(t) local copy = {} for k,v in pairs(t) do copy[k]=v end return copy end tab.shallowcopy_n = function(t) local copy = {} for i=1,#t do local o = t[i] copy[#copy+ 1] = o end return copy end tab.condcopy = function(t,cond) local copy = {} for k,v in pairs(t) do if cond(v) then copy[k] = v end end return copy end tab.condcopy_n = function(t,cond) local copy = {} for i=1,#t do local o = t[i] if cond(o) then copy[#copy + 1] = o end end return copy end tab.merge = function(...) local copy = {} for _,t in ipairs({...}) do for k,v in pairs(t) do copy[k] = v end end return copy end tab.merge_n = function(...) local copy = {} for _,t in ipairs({...}) do for i=1,#t do copy[#copy+1] = t[i] end end return copy end tab.map = function(t,f,...) local copy = {} for k,v in pairs(t) do copy[k] = f(v,...) end return copy end tab.invert = function(t) local copy = {} for k,v in pairs(t) do nt[v] = k end return copy end tab.any = function(t,x) for k,v in pairs(t) do if x == v then return true end end end tab.contains_any = function(t,...) for _,v in ipairs({...}) do if t[v] then return true end end end tab.contains_all = function(t,...) for _,v in ipairs({...}) do if not t[v] then return end end return true end tab.slice = function(t,n,e) local s = {} for i=n,(e or #t) do s[#s+1] = t[i] end return s end tab.grid = {} tab.grid.new = function(w,h,f) local g = {} for y=1,h do g[y] = {} for x=1,w do g[y][x] = (type(f) == "function" and f(x,y) or (f or 0)) end end return setmetatable(g,tab.grid) end tab.grid.transpose = function(g) local ng = tab.grid.new(#g[1],#g) for i=1,#g do for j=1,#g[i] do ng[j][i] = g[i][j] end end return ng end tab.grid.flip_y = function(g) local ng = tab.grid.new(#g[1],#g) for i=1,#g do for j=1,#g[i] do ng[#g - i + 1][j] = g[i][j] end end return ng end tab.grid.flip_x = function(g) local ng = tab.grid.new(#g[1],#g) for i=1,#g do for j=1,#g[i] do ng[i][#g[i] - j + 1] = g[i][j] end end return ng end tab.grid.rotate_cclock = function(g) local ng = transpose(g) return tab.grid.flip_y(ng) end tab.grid.rotate_clock = function(g) local ng = tab.grid.transpose(g) return tab.grid.flip_x(ng) end setmetatable(tab.grid,{__call = tab.grid.new}) tab.queue = {} tab.queue.new = function () return setmetatable({head=0,tail=-1},{__index = tab.queue}) end tab.queue.push_left = function(q,n) q.head = q.head - 1 q[q.head] = n end tab.queue.push_right = function(q,n) q.tail = q.tail + 1 q[q.tail] = n end tab.queue.pop_left = function(q) assert(q.head <= q.tail,"attempt to pop empty queue") local n = q[q.head] q[q.head] = nil q.head = q.head + 1 return n end tab.queue.pop_right = function(q) assert(q.head <= q.tail,"attempt to pop empty queue") local n = q[q.tail] q[q.tail] = nil q.tail = q.tail - 1 return n end tab.queue.peek_left = function(q) return q[q.head+1] end tab.queue.peek_right = function(q) return q[q.tail] end tab.queue.len = function(q) return q.tail - q.head end setmetatable(tab.queue,{__call = tab.queue.new})
local ObjectManager = require("managers.object.object_manager") victorQuestpHospitalConvoHandler = conv_handler:new {} function victorQuestpHospitalConvoHandler:getInitialScreen(pPlayer, pNpc, pConvTemplate) local convoTemplate = LuaConversationTemplate(pConvTemplate) local curPhase = BestineElection:getCurrentPhase() local pInventory = CreatureObject(pPlayer):getSlottedObject("inventory") if (curPhase == BestineElection.OFFICE_PHASE) then return convoTemplate:getScreen("init_office_phase") elseif (pInventory ~= nil and getContainerObjectByTemplate(pInventory, "object/tangible/loot/quest/victor_questp_receipt.iff", true)) then return convoTemplate:getScreen("init_already_has_evidence") elseif (BestineElection:hadInvFull(pPlayer, BestineElection.VICTOR, BestineElection.VICTOR_HOSPITAL_EVIDENCE)) then return convoTemplate:getScreen("init_inv_was_full") elseif (BestineElection:hasJoinedCampaign(pPlayer, BestineElection.VICTOR)) then return convoTemplate:getScreen("init_joined_victor") else return convoTemplate:getScreen("init_election_phase") end end function victorQuestpHospitalConvoHandler:runScreenHandlers(pConvTemplate, pPlayer, pNpc, selectedOption, pConvScreen) local screen = LuaConversationScreen(pConvScreen) local screenID = screen:getScreenID() local pConvScreen = screen:cloneScreen() local clonedConversation = LuaConversationScreen(pConvScreen) local electionNum = BestineElection:getElectionNumber() local electionWinner = BestineElection:getElectionWinner(electionNum - 1) if (screenID == "init_inv_was_full") then if (BestineElection:hasFullInventory(pPlayer)) then clonedConversation:addOption("@conversation/victor_questp_hospital:s_90ec63e0", "inv_still_full") -- Yes, I do. else clonedConversation:addOption("@conversation/victor_questp_hospital:s_90ec63e0", "was_full_give_evidence") -- Yes, I do. end clonedConversation:addOption("@conversation/victor_questp_hospital:s_da9a29e9", "come_back") -- No, not yet. elseif (screenID == "perfect_thing") then if (BestineElection:hasFullInventory(pPlayer)) then clonedConversation:addOption("@conversation/victor_questp_hospital:s_67e6df55", "inv_full") -- Okay. else clonedConversation:addOption("@conversation/victor_questp_hospital:s_67e6df55", "give_evidence") -- Okay. end elseif (screenID == "inv_full") then BestineElection:setInvFull(pPlayer, BestineElection.VICTOR, BestineElection.VICTOR_HOSPITAL_EVIDENCE) elseif (screenID == "give_evidence" or screenID == "was_full_give_evidence") then BestineElection:clearInvFull(pPlayer, BestineElection.VICTOR, BestineElection.VICTOR_HOSPITAL_EVIDENCE) local pInventory = CreatureObject(pPlayer):getSlottedObject("inventory") if (pInventory ~= nil) then local pEvidence = giveItem(pInventory, "object/tangible/loot/quest/victor_questp_receipt.iff", -1) if (pEvidence == nil) then printLuaError("Error creating victor hospital evidence for player " .. CreatureObject(pPlayer):getFirstName()) end end end return pConvScreen end
--[[=========================================================================== | Copyright (c) 2018 | | ItemListItem: ========================================================================--]] local AddonName, Addon = ... local L = Addon:GetLocale() local Package = select(2, ...); local ItemListItem = {}; function ItemListItem:OnLoad() Mixin(self, ItemMixin); self:SetScript("OnClick", self.OnClick); self:SetScript("OnEnter", self.OnMouseEnter); self:SetScript("OnLeave", self.OnMouseLeave); end --[[============================================================================ | ItemListItem:SetItem | Create the frames which represent the rule parameters. ==========================================================================]] function ItemListItem:OnUpdate() if (self:IsShown()) then if (self:IsMouseOver()) then self.Hover:Show(); if (self.Delete) then self.Delete:Show(); end else self.Hover:Hide(); if (self.Delete) then self.Delete:Hide(); end end end end --[[============================================================================ | ItemListItem:SetItem | Create the frames which represent the rule parameters. ==========================================================================]] function ItemListItem:populate() local name = self:GetItemName(); local color = self:GetItemQualityColor(); if (not color) then color = GRAY_FONT_COLOR; end self.Text:SetText(name); self.Text:SetTextColor(color.r, color.g, color.b); end --[[============================================================================ | ItemListItem:SetItem | Create the frames which represent the rule parameters. ==========================================================================]] function ItemListItem:SetItem(item) self.item = item; if (type(item) == "number") then self:SetItemID(item); elseif (type(item) == "string") then self:SetItemLink(item); else self:SetItemLocation(item); end -- Test for invalid item if (self:IsItemEmpty()) then self.Text:SetText(L["ITEMLIST_INVALID_ITEM"]) self.Text:SetTextColor(RED_FONT_COLOR.r, RED_FONT_COLOR.g, RED_FONT_COLOR.b); return end -- If the data isn't cached then we want to note that and setup a callback if (not self:IsItemDataCached()) then self.Text:SetText(L.ITEMLIST_LOADING); self.Text:SetTextColor(GRAY_FONT_COLOR.r, GRAY_FONT_COLOR.g, GRAY_FONT_COLOR.b); self:ContinueOnItemLoad(function() self:populate() end); else self:populate(); end end function ItemListItem:OnModelChanged(model) self:SetItem(model); end --[[============================================================================ | Called when the "delete" button is clicked ==========================================================================]] function ItemListItem:HandleDelete() if (self.item) then Addon.Invoke(self:GetParent():GetParent(), "OnDeleteItem", self.item); end end --[[============================================================================ | Called when the user mouses over the item if our item text is truncated | then we will show a tooltip for the item. ==========================================================================]] function ItemListItem:OnMouseEnter() if (not Addon.ItemList.GetCursorItem()) then GameTooltip:SetOwner(self, "ANCHOR_BOTTOM"); GameTooltip:ClearAllPoints(); GameTooltip:SetPoint("TOPLEFT", self, "BOTTOMLEFT", 0, -4); if (not self:IsItemEmpty()) then if (self:IsItemDataCached()) then if (self:HasItemLocation()) then local location = self:GetItemLocation(); if (location:IsBagAndSlot()) then local bag, slot = location:GetBagAndSlot(); GameTooltip:SetBagItem(bag, slot); elseif (locaion:IsEquipmentSlot()) then GameTooltip:SetInventoryItem("player", location:GetEquipmentSlot()); else GameTooltip:SetHyperlink(self:GetItemLink()); end else GameTooltip:SetHyperlink(self:GetItemLink()); end else GameTooltip:SetText(L["ITEMLIST_LOADING_TOOLTIP"]); end else GameTooltip:SetText(L["ITEMLIST_INVALID_ITEM_TOOLTIP"]); end end end --[[============================================================================ | RuleItem:OnMouseLeave: | Called when the user mouses off the item ==========================================================================]] function ItemListItem:OnMouseLeave() GameTooltip:Hide(); end --[[============================================================================ | RuleItem:OnClick: | Called when the item is clicked: | LeftButton -> Remove the item from the current list | RightButton -> Swap the item from one list ot the other. | | If the cursor current has an item, this is equivlent to dropping it | on the parent - we delegate that call. ==========================================================================]] function ItemListItem:OnClick(button) if (Addon.ItemList.GetCursorItem()) then self:GetParent():GetParent():OnDrop(button); elseif (not self:IsItemEmpty()) then PickupItem(self.item); end end Addon.ItemListItem = ItemListItem;
-- x86 Assembly return { name = "Assembly x86", lexer = 34, extensions = "asm", keywords = { [0] = { name = "CPU Instructions", keywords = [[aaa aad aam aas adc add and call cbw clc cld cli cmc cmp cmps cmpsb cmpsw cwd daa das dec div esc hlt idiv imul in inc int into iret ja jae jb jbe jc jcxz je jg jge jl jle jmp jna jnae jnb jnbe jnc jne jng jnge jnl jnle jno jnp jns jnz jo jp jpe jpo js jz lahf lds lea les lods lodsb lodsw loop loope loopew loopne loopnew loopnz loopnzw loopw loopz loopzw mov movs movsb movsw mul neg nop not or out pop popf push pushf rcl rcr ret retf retn rol ror sahf sal sar sbb scas scasb scasw shl shr stc std sti stos stosb stosw sub test wait xchg xlat xlatb xor bound enter ins insb insw leave outs outsb outsw popa pusha pushw arpl lar lsl sgdt sidt sldt smsw str verr verw clts lgdt lidt lldt lmsw ltr bsf bsr bt btc btr bts cdq cmpsd cwde insd iretd iretdf iretf jecxz lfs lgs lodsd loopd looped loopned loopnzd loopzd lss movsd movsx movzx outsd popad popfd pushad pushd pushfd scasd seta setae setb setbe setc sete setg setge setl setle setna setnae setnb setnbe setnc setne setng setnge setnl setnle setno setnp setns setnz seto setp setpe setpo sets setz shld shrd stosd bswap cmpxchg invd invlpg wbinvd xadd lock rep repe repne repnz repz cflush cpuid emms femms cmovo cmovno cmovb cmovc cmovnae cmovae cmovnb cmovnc cmove cmovz cmovne cmovnz cmovbe cmovna cmova cmovnbe cmovs cmovns cmovp cmovpe cmovnp cmovpo cmovl cmovnge cmovge cmovnl cmovle cmovng cmovg cmovnle cmpxchg486 cmpxchg8b loadall loadall286 ibts icebp int1 int3 int01 int03 iretw popaw popfw pushaw pushfw rdmsr rdpmc rdshr rdtsc rsdc rsldt rsm rsts salc smi smint smintold svdc svldt svts syscall sysenter sysexit sysret ud0 ud1 ud2 umov xbts wrmsr wrshr]] }, [1] = { name = "FPU Instructions", keywords = [[f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcom fcomp fcompp fdecstp fdisi fdiv fdivp fdivr fdivrp feni ffree fiadd ficom ficomp fidiv fidivr fild fimul fincstp finit fist fistp fisub fisubr fld fld1 fldcw fldenv fldenvw fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex fndisi fneni fninit fnop fnsave fnsavew fnstcw fnstenv fnstenvw fnstsw fpatan fprem fptan frndint frstor frstorw fsave fsavew fscale fsqrt fst fstcw fstenv fstenvw fstp fstsw fsub fsubp fsubr fsubrp ftst fwait fxam fxch fxtract fyl2x fyl2xp1 fsetpm fcos fldenvd fnsaved fnstenvd fprem1 frstord fsaved fsin fsincos fstenvd fucom fucomp fucompp fcomi fcomip ffreep fcmovb fcmove fcmovbe fcmovu fcmovnb fcmovne fcmovnbe fcmovnu]] }, [2] = { name = "Registers", keywords = [[ah al ax bh bl bp bx ch cl cr0 cr2 cr3 cr4 cs cx dh di dl dr0 dr1 dr2 dr3 dr6 dr7 ds dx eax ebp ebx ecx edi edx es esi esp fs gs si sp ss st tr3 tr4 tr5 tr6 tr7 st0 st1 st2 st3 st4 st5 st6 st7 mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7]] }, [3] = { name = "Directives", keywords = [[.186 .286 .286c .286p .287 .386 .386c .386p .387 .486 .486p .8086 .8087 .alpha .break .code .const .continue .cref .data .data? .dosseg .else .elseif .endif .endw .err .err1 .err2 .errb .errdef .errdif .errdifi .erre .erridn .erridni .errnb .errndef .errnz .exit .fardata .fardata? .if .lall .lfcond .list .listall .listif .listmacro .listmacroall .model .no87 .nocref .nolist .nolistif .nolistmacro .radix .repeat .sall .seq .sfcond .stack .startup .tfcond .type .until .untilcxz .while .xall .xcref .xlist alias align assume catstr comm comment db dd df dosseg dq dt dup dw echo else elseif elseif1 elseif2 elseifb elseifdef elseifdif elseifdifi elseife elseifidn elseifidni elseifnb elseifndef end endif endm endp ends eq equ even exitm extern externdef extrn for forc ge goto group gt high highword if if1 if2 ifb ifdef ifdif ifdifi ife ifidn ifidni ifnb ifndef include includelib instr invoke irp irpc label le length lengthof local low lowword lroffset lt macro mask mod .msfloat name ne offset opattr option org %out page popcontext proc proto ptr public purge pushcontext record repeat rept seg segment short size sizeof sizestr struc struct substr subtitle subttl textequ this title type typedef union while width db dw dd dq dt resb resw resd resq rest incbin equ times %define %idefine %xdefine %xidefine %undef %assign %iassign %strlen %substr %macro %imacro %endmacro %rotate .nolist %if %elif %else %endif %ifdef %ifndef %elifdef %elifndef %ifmacro %ifnmacro %elifmacro %elifnmacro %ifctk %ifnctk %elifctk %elifnctk %ifidn %ifnidn %elifidn %elifnidn %ifidni %ifnidni %elifidni %elifnidni %ifid %ifnid %elifid %elifnid %ifstr %ifnstr %elifstr %elifnstr %ifnum %ifnnum %elifnum %elifnnum %error %rep %endrep %exitrep %include %push %pop %repl struct endstruc istruc at iend align alignb %arg %stacksize %local %line bits use16 use32 section absolute extern global common cpu org section group import export]] }, [4] = { name = "Directive Operands", keywords = [[$ ? @b @f addr basic byte c carry? dword far far16 fortran fword near near16 overflow? parity? pascal qword real4 real8 real10 sbyte sdword sign? stdcall sword syscall tbyte vararg word zero? flat near32 far32 abs all assumes at casemap common compact cpu dotname emulator epilogue error export expr16 expr32 farstack flat forceframe huge language large listing ljmp loadds m510 medium memory nearstack nodotname noemulator nokeyword noljmp nom510 none nonunique nooldmacros nooldstructs noreadonly noscoped nosignextend nothing notpublic oldmacros oldstructs os_dos para private prologue radix readonly req scoped setif2 smallstack tiny use16 use32 uses a16 a32 o16 o32 byte word dword nosplit $$ seq wrt flat large small .text .data .bss near far %0 %1 %2 %3 %4 %5 %6 %7 %8 %9]] }, [5] = { name = "Extended Instructions", keywords = [[addpd addps addsd addss andpd andps andnpd andnps cmpeqpd cmpltpd cmplepd cmpunordpd cmpnepd cmpnltpd cmpnlepd cmpordpd cmpeqps cmpltps cmpleps cmpunordps cmpneps cmpnltps cmpnleps cmpordps cmpeqsd cmpltsd cmplesd cmpunordsd cmpnesd cmpnltsd cmpnlesd cmpordsd cmpeqss cmpltss cmpless cmpunordss cmpness cmpnltss cmpnless cmpordss comisd comiss cvtdq2pd cvtdq2ps cvtpd2dq cvtpd2pi cvtpd2ps cvtpi2pd cvtpi2ps cvtps2dq cvtps2pd cvtps2pi cvtss2sd cvtss2si cvtsd2si cvtsd2ss cvtsi2sd cvtsi2ss cvttpd2dq cvttpd2pi cvttps2dq cvttps2pi cvttsd2si cvttss2si divpd divps divsd divss fxrstor fxsave ldmxscr lfence mfence maskmovdqu maskmovdq maxpd maxps paxsd maxss minpd minps minsd minss movapd movaps movdq2q movdqa movdqu movhlps movhpd movhps movd movq movlhps movlpd movlps movmskpd movmskps movntdq movnti movntpd movntps movntq movq2dq movsd movss movupd movups mulpd mulps mulsd mulss orpd orps packssdw packsswb packuswb paddb paddsb paddw paddsw paddd paddsiw paddq paddusb paddusw pand pandn pause paveb pavgb pavgw pavgusb pdistib pextrw pcmpeqb pcmpeqw pcmpeqd pcmpgtb pcmpgtw pcmpgtd pf2id pf2iw pfacc pfadd pfcmpeq pfcmpge pfcmpgt pfmax pfmin pfmul pmachriw pmaddwd pmagw pmaxsw pmaxub pminsw pminub pmovmskb pmulhrwc pmulhriw pmulhrwa pmulhuw pmulhw pmullw pmuludq pmvzb pmvnzb pmvlzb pmvgezb pfnacc pfpnacc por prefetch prefetchw prefetchnta prefetcht0 prefetcht1 prefetcht2 pfrcp pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr pi2fd pf2iw pinsrw psadbw pshufd pshufhw pshuflw pshufw psllw pslld psllq pslldq psraw psrad psrlw psrld psrlq psrldq psubb psubw psubd psubq psubsb psubsw psubusb psubusw psubsiw pswapd punpckhbw punpckhwd punpckhdq punpckhqdq punpcklbw punpcklwd punpckldq punpcklqdq pxor rcpps rcpss rsqrtps rsqrtss sfence shufpd shufps sqrtpd sqrtps sqrtsd sqrtss stmxcsr subpd subps subsd subss ucomisd ucomiss unpckhpd unpckhps unpcklpd unpcklps xorpd xorps]] } }, style = { [1] = { name = "Comment", style = "comment" }, [2] = { name = "Number", style = "number" }, [3] = { name = "String", style = "doubleQuoted String" }, [4] = { name = "Operator", style = "operator" }, [5] = { name = "Identifier", style = "identifier" }, [6] = { name = "CPU Instruction", fore = "#00007F", bold = true }, [7] = { name = "FPU Instruction", fore = "#0000FF" }, [8] = { name = "Register", fore = "#46AA03", bold = true }, [9] = { name = "Directive", style = "preprocessor" }, [10] = { name = "Directive Operand", style = "preprocessor" }, [11] = { name = "Comment Block", style = "comment" }, [12] = { name = "String", style = "doubleQuotedString" }, [13] = { name = "Unclosed String", style = "unclosedDoubleQuotedString" }, [14] = { name = "Extended Instruction", fore = "#B00040" } } }
-- -- Code by Piotr Machowski <piotr@machowski.co> -- local Growl = {} Growl.__n = 'GrowlNotifications' Growl.set = {} Growl.isAnimating = false --global config Growl.SHOW_TIME = 5000 Growl.FONT_SIZE = 8 Growl.NOTIFICATION_WIDTH = display.contentWidth*.25 --private functions function Growl:_removeNotification( _n ) for i,v in ipairs(self.set) do if _n == v then table.remove( self.set, i ) end end end function Growl:_moveNotifications( ) if self.isAnimating then -- speed move transition.cancel( Growl.__n ) for i,v in ipairs(self.set) do v.x, v.y = v.nx, v.ny end end self.isAnimating=true --remove those not in the viewport for i=#self.set,1 do if self.set[i].y > display.contentHeight then self.set[i]:removeSelf() end end --animate self.set[1].tween = transition.to( self.set[1], {tag=Growl.__n, x=self.set[1].nx, time=200, easing=easing.outExpo, onComplete=function( ) Growl.isAnimating=false end } ) if #self.set>1 then for i=2,#self.set do self.set[i].ny = self.set[i-1].ny+self.set[i-1].height+5 self.set[i].tween = transition.to( self.set[i], {tag=Growl.__n, y=self.set[i].ny, time=150, easing=easing.inExpo } ) end end end --Public methods function Growl:removeAllNotifications() for i=#self.set,1 do self.set[i]:removeSelf() end self.isAnimating=false end function Growl.new( _msg, _type, _width, _fontSize ) local w,h = _width or Growl.NOTIFICATION_WIDTH local fontSize = _fontSize or Growl.FONT_SIZE local m = display.newGroup( ) local function init( ) m.txt = display.newText( {parent=m, text=_msg, x=0,y=0,width=w-10, fontSize=fontSize, align='left'}) h = m.txt.height+10 m.bg = display.newRoundedRect(m, 0, 0, w, h, 4 ) if _type == 'error' then m.bg:setFillColor( 244/255, 122/255, 102/255, .9 ) elseif _type == 'info' then m.bg:setFillColor( 111/255, 169/255, 228/255, .9 ) else m.bg:setFillColor( 67/255, 172/255, 102/255, .9 ) end m.bg.strokeWidth=1 m.bg:setStrokeColor( 1,1,1,.2 ) m.txt:toFront( ) --config m.alpha=.8 m.anchorChildren=true m.anchorX, m.anchorY = 1,0 m.x, m.y = display.contentWidth+10+w, 10 m.nx, m.ny= display.contentWidth-10, m.y table.insert( Growl.set, 1, m ) end local function initRemove( ) function m:timer ( ) self:removeSelf() end m.removeTimer = timer.performWithDelay( Growl.SHOW_TIME, m) end m._removeSelf = m.removeSelf function m:removeSelf( ) if self.removeTimer then timer.cancel( self.removeTimer ) end self.removeTimer=nil if self.tween then transition.cancel( self.tween ) end self.tween=nil Growl:_removeNotification(self) self:_removeSelf() end init() initRemove() Growl:_moveNotifications() return m end return Growl
--深海のミンストレル --Scripted by nekrozar function c101012015.initial_effect(c) --remove local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(101012015,0)) e1:SetCategory(CATEGORY_REMOVE) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_HAND) e1:SetCountLimit(1,101012015) e1:SetCost(c101012015.rmcost) e1:SetTarget(c101012015.rmtg) e1:SetOperation(c101012015.rmop) c:RegisterEffect(e1) --to deck local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(101012015,1)) e2:SetCategory(CATEGORY_TODECK) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetCountLimit(1,101012115) e2:SetCost(c101012015.tdcost) e2:SetTarget(c101012015.tdtg) e2:SetOperation(c101012015.tdop) c:RegisterEffect(e2) end function c101012015.costfilter(c) return c:IsAttribute(ATTRIBUTE_WATER) and c:IsDiscardable() end function c101012015.rmcost(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsDiscardable() and Duel.IsExistingMatchingCard(c101012015.costfilter,tp,LOCATION_HAND,0,1,c) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DISCARD) local g=Duel.SelectMatchingCard(tp,c101012015.costfilter,tp,LOCATION_HAND,0,1,1,c) g:AddCard(c) Duel.SendtoGrave(g,REASON_COST+REASON_DISCARD) end function c101012015.rmtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,0,LOCATION_HAND,1,nil) end Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,1-tp,LOCATION_HAND) end function c101012015.rmop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_HAND,nil) if g:GetCount()==0 then return end Duel.ConfirmCards(tp,g) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local tc=g:Select(tp,1,1,nil):GetFirst() Duel.Remove(tc,POS_FACEUP,REASON_EFFECT) Duel.ShuffleHand(1-tp) local c=e:GetHandler() local fid=c:GetFieldID() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetCountLimit(1) e1:SetLabel(fid) e1:SetLabelObject(tc) e1:SetCondition(c101012015.retcon) e1:SetOperation(c101012015.retop) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) tc:RegisterFlagEffect(101012015,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,0,1,fid) end function c101012015.retcon(e,tp,eg,ep,ev,re,r,rp) local tc=e:GetLabelObject() if tc:GetFlagEffectLabel(101012015)==e:GetLabel() then return true else e:Reset() return false end end function c101012015.retop(e,tp,eg,ep,ev,re,r,rp) local tc=e:GetLabelObject() Duel.SendtoHand(tc,nil,REASON_EFFECT) end function c101012015.tdcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDiscardDeckAsCost(tp,3) end Duel.DiscardDeck(tp,3,REASON_COST) end function c101012015.tdfilter(c) return c:IsLevelBelow(4) and c:IsAttribute(ATTRIBUTE_WATER) and not c:IsCode(101012015) and c:IsAbleToDeck() end function c101012015.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c101012015.tdfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c101012015.tdfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectTarget(tp,c101012015.tdfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0) end function c101012015.tdop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then if tc:IsType(TYPE_FUSION+TYPE_SYNCHRO+TYPE_XYZ+TYPE_LINK) or Duel.SelectOption(tp,aux.Stringid(101012015,2),aux.Stringid(101012015,3))==0 then Duel.SendtoDeck(tc,nil,0,REASON_EFFECT) else Duel.SendtoDeck(tc,nil,1,REASON_EFFECT) end end end
local thisDir = __DIR__() local systemIO = require 'systemIO' local cIO = require 'cIO' local path = require 'path' local list = require 'list' local lfsu = require 'lfsu' local process = require 'process' local function mkLuaPath(dirs) local luaPath = '?.lua' if type(dirs) == 'table' then local luaPaths = {} for i,v in ipairs(dirs) do table.insert(luaPaths, v .. '/?.lua') end luaPath = table.concat(luaPaths, ';') end return luaPath end local function insertIncParams(t, xs) for _,x in ipairs(xs) do table.insert(t, '-I') table.insert(t, x) end end local function insertLibParams(t, xs) for _,x in ipairs(xs) do table.insert(t, '--open=' .. x) end end local function parseDeps(s, ignore) local t = list:new() for v in s:gmatch('[^:]+:%s*([^\r\n]+)') do -- split by spaces for v in v:gmatch('([^%s\r\n]+)') do if v ~= ignore then table.insert(t, v) end end end return t end local function dependencies(cfg, ps) assert(ps.lua, 'luaIO.dependencies: path to lua binary not provided') local sourceFile = ps.sourceFile or ps[1] local luaDeps = require 'luaDeps' if sourceFile == nil then sourceFile = cfg.buildDir .. '/interpreter.lua' lfsu.mkdir_p(cfg.buildDir) lfsu.write(sourceFile, luaDeps.interpreter) end lfsu.mkdir_p(cfg.buildDir) lfsu.write(cfg.buildDir .. '/cfromlua.lua', luaDeps.cfromlua) local args = { ps.lua, cfg.buildDir .. '/cfromlua.lua', '-MT', '-', '-MF', '-', } insertIncParams(args, ps.luaPathDirs or {}) table.insert(args, sourceFile) local err, ds, stderr = process.readProcess(args) if err then return stderr or err end return nil, parseDeps(ds, sourceFile) end local function luaCFile(cfg, ps) assert(ps.lua, 'luaIO.luaCFile: path to lua binary not provided') assert(type(ps.name) == 'string', type(ps.name)) local outdir = path.takeDirectory(ps.name) lfsu.mkdir_p(outdir) local luaDeps = require 'luaDeps' lfsu.mkdir_p(cfg.buildDir) lfsu.write(cfg.buildDir .. '/cfromlua.lua', luaDeps.cfromlua) local args = { ps.lua, cfg.buildDir .. '/cfromlua.lua', '-o', ps.name, '--minify', } insertIncParams(args, ps.luaPathDirs or {}) insertLibParams(args, ps.luaLibs or {}) for _,v in ipairs(ps.sourceFiles) do table.insert(args, v) end return systemIO.execute(cfg, {args=args, thenReturn=ps.name}) end local function program(cfg, ps) assert(ps.lua, 'luaIO.program: path to lua binary not provided') local sourceFiles = ps.sourceFiles or {ps.sourceFile or ps[1]} local luaDeps = require 'luaDeps' if sourceFiles[1] == nil then sourceFiles[1] = cfg.buildDir .. '/interpreter.lua' lfsu.mkdir_p(cfg.buildDir) lfsu.write(sourceFiles[1], luaDeps.interpreter) end local name = ps.name or cfg.outPath or (sourceFiles[1] and cfg.buildDir .. '/' .. path.takeBaseName(sourceFiles[1])) local cFileName = cfg.buildDir .. '/' .. path.takeFileName(name) .. '.c' local err, cFile = luaCFile(cfg, { name = cFileName, sourceFiles = sourceFiles, luaLibs = ps.luaLibs, luaPathDirs = ps.luaPathDirs, lua = ps.lua, }) if err then return err end local flags = {'-lm', '-ldl'} flags = ps.flags and list.append(flags, ps.flags) or flags return cIO.program(cfg, { name = name, sourceFiles = {cFile}, includeDirs = ps.includeDirs, libs = ps.libs, flags = flags, flavor = ps.flavor, cc = ps.cc, }) end local function run(cfg, ps) lfsu.mkdir_p(cfg.buildDir) local luaPath = mkLuaPath(ps.luaPathDirs) local sourceFile = ps.sourceFile or ps[1] local env = { LUA_PATH = luaPath, OUTDIR = cfg.buildDir, } for k,v in pairs(ps.env or {}) do env[k] = v end local args = {ps.host, sourceFile} for _,v in ipairs(ps.args or {}) do table.insert(args, v) end return systemIO.execute(cfg, {args=args, env=env, thenReturn=ps.validates}) end local function writeDirectory(p, x) if type(x) == 'string' then assert(lfsu.write(p, x)) return p else lfsu.mkdir_p(p) local t = {} for k,v in pairs(x) do t[k] = writeDirectory(p..'/'..k, v) end return t end end local function tools(cfg) local luaDeps = require 'luaDeps' return nil, { path = cfg.buildDir, contents = writeDirectory(cfg.buildDir, { src = { ['cfromlua.lua'] = luaDeps.cfromlua, ['interpreter.lua'] = luaDeps.interpreter, }, lib = { ['liblua.lib'] = luaDeps.liblua, }, inc = { ['lauxlib.h'] = luaDeps.inc['lauxlib.h'], ['lua.h'] = luaDeps.inc['lua.h'], ['luaconf.h'] = luaDeps.inc['luaconf.h'], ['lualib.h'] = luaDeps.inc['lualib.h'], }, }), } end return { dependencies = dependencies, dependencies__info = { outputMetatable = list, }, program = program, run = run, tools = tools, }
return { member = function (obj, mem) return function (...) obj[mem](obj, ...) end end, -- 正向追加参数 make = function (fn, obj) return function (...) fn(obj, ...) end end, -- 逆向追加参数 rmake = function (fn, obj) return function (...) local args = { ... } table.insert(args, obj) fn(unpack(args)) end end, assign = function (obj, key, value) return function () obj[key] = value end end, }
local f = Const("f") local a = Const("a") print(mk_explicit(f)(a)) assert(is_explicit(mk_explicit(f))) assert(not is_explicit(f)) assert(get_explicit_arg(mk_explicit(f)) == f) check_error(function() get_explicit_arg(f) end)
local function getRange(start, finish, lines) local start_row, start_col = lines:rowcol(start) local finish_row, finish_col = lines:rowcol(finish) return { start = { line = start_row - 1, character = start_col - 1, }, ['end'] = { line = finish_row - 1, -- 这里不用-1,因为前端期待的是匹配完成后的位置 character = finish_col, }, } end local function rgbToHsv(r, g, b, a) local max, min = math.max(r, g, b), math.min(r, g, b) local h, s, v v = max local d = max - min if max == 0 then s = 0 else s = d / max end if max == min then h = 0 -- achromatic else if max == r then h = (g - b) / d if g < b then h = h + 6 end elseif max == g then h = (b - r) / d + 2 elseif max == b then h = (r - g) / d + 4 end h = h / 6 end return h, s, v, a end --- @param lsp LSP --- @param params table --- @return table return function (lsp, params) local vm, lines = lsp:getVM(params.textDocument.uri) if not vm then return end local result = nil vm:eachSource(function(source) if result then return end if source.type ~= "call" then return end local simple = source:get 'simple' if not simple then return end if #simple >= 4 and simple[1][1] == "Color3" then if simple[3].type ~= "name" or simple[4].type ~= "call" then return end local callArgs = simple[4] if table.equal(params.range, getRange(simple[1].start, simple[1].start + 1, lines)) or table.equal(params.range, getRange(callArgs.start + 1, callArgs.finish - 1, lines)) then local funcName = simple[3][1] if funcName == "new" then for i, num in pairs(params.color) do params.color[i] = tostring(num):sub(1, 8) end elseif funcName == "fromRGB" then for i, num in pairs(params.color) do params.color[i] = tostring(math.floor(num * 255)) end elseif funcName == "fromHSV" then local hsv = {rgbToHsv(params.color.red, params.color.green, params.color.blue, 1)} hsv = { red = hsv[1], green = hsv[2], blue = hsv[3] } for i in pairs(params.color) do params.color[i] = tostring(hsv[i]):sub(1, 8) end end local rgb = string.format("%s, %s, %s", params.color.red, params.color.green, params.color.blue) result = { { label = rgb, textEdit = { range = getRange(callArgs.start + 1, callArgs.finish - 1, lines), newText = rgb } } } end end end) return result end
require("test/bustedhelper_game") local fight_state = require("fight/fight_state") require("engine/application/constants") local gamestate = require("engine/application/gamestate") local wit_fighter_app = require("application/wit_fighter_app") local dialogue_manager = require("dialogue/dialogue_manager") describe('fight_state', function () describe('static members', function () it('type is :fight', function () assert.are_equal(':fight', fight_state.type) end) end) describe('(with instance)', function () local state before_each(function () local app = wit_fighter_app() app:instantiate_and_register_managers() state = fight_state() -- no need to register gamestate properly, just add app member to pass tests state.app = app end) describe('on_enter', function () -- todo end) describe('on_exit', function () -- todo end) describe('update', function () it('should not error', function () assert.has_no_errors(function () state:update() end) end) end) describe('render', function () it('should not error', function () state:render() assert.has_no_errors(function () end) end) end) end) -- (with instance) end)
--- A double queue. -- Taken from ***Programming in Lua*** [Queues and Double Queues](http://www.lua.org/pil/11.4.html) -- and modified to not allow nil values, and returns nil if @{pop_first} or @{pop_last} is used when the queue is empty. -- @module Queue -- @usage local Queue = require('stdlib/lists/queue') local Queue = { _module = 'Queue', __index = require('stdlib/core') } setmetatable(Queue, Queue) local table = require('stdlib/utils/table') local t_size = table.size local Is = require('stdlib/utils/is') local Inspect = require('stdlib/vendor/inspect') --- Constructs a new Queue object. -- @return (<span class="types">@{Queue}</span>) a new, empty queue function Queue.new(_, ...) local queue = {first = 1, last = 0, objects = {}} setmetatable(queue, Queue._mt) for _, push in ipairs({...}) do if push ~= nil then queue(push) end end return queue end Queue.__call = Queue.new --- Load global.queue or queues during on_load, as metatables are not persisted. -- <p>This is only needed if you are using the queue as an object and storing it in global. -- @tparam table queue (<span class="types">@{Queue}</span>,...) -- @usage global.myqueue1 = Queue.new() -- script.on_load(function() Queue.load(global.myqueue)) function Queue.load(queue) if Is.Table(queue) and queue.first then return setmetatable(queue, Queue._mt) end end -- --- Gets the index which matches the stored data -- TODO future direction -- function Queue.get_index(queue, obj) -- for i, v in pairs(queue.objects) do -- if v == obj then -- return i -- end -- end -- end -- TODO pop at index, everything after index insert at -1 dec last -- function Queue.pop_at_index(queue, index) -- return queue.objects[index] -- end -- TODO push at index, everything at and after index + 1 inc last -- function Queue.push_at_index(queue, index) -- return queue -- end --- Push a new element to the front of the queue. -- @param queue (<span class="types">@{Queue}</span>) the queue to push an element to -- @tparam Mixed value the element to push function Queue.push_first(queue, value) Is.Assert(value, 'must have a value to push') local first = queue.first - 1 queue.first = first queue.objects[first] = value return queue end --- Push a new element to the back of the queue. -- @param queue (<span class="types">@{Queue}</span>) the queue to push an element to -- @tparam Mixed value the element to push function Queue.push_last(queue, value) Is.Assert(value, 'must have a value to push') local last = queue.last + 1 queue.last = last queue.objects[last] = value return queue end --- Shortcut for @{Queue.push_last} -- @function Queue.push Queue.push = Queue.push_last --- Retrieve the element at the front of the queue and remove it from the queue. -- @param queue (<span class="types">@{Queue}</span>) the queue to retrieve the element from -- @treturn Mixed value the element at the front of the queue function Queue.pop_first(queue) if Queue.is_empty(queue) then return nil end local first = queue.first local value = queue.objects[first] queue.objects[first] = nil -- to allow garbage collection queue.first = first + 1 return value end --- Shortcut for @{Queue.pop_first} -- @function Queue.pop Queue.pop = Queue.pop_first --- Return the element at the front of the queue and remove it from the queue. -- @param queue (<span class="types">@{Queue}</span>) the queue to retrieve the element from -- @treturn Mixed the element at the front of the queue function Queue.peek_first(queue) return queue.objects[queue.first] end --- Shortcut for @{Queue.peek_first} -- @function Queue.peek Queue.peek = Queue.peek_first --- Retrieve the element at the back of the queue and remove it from the queue. -- @param queue (<span class="types">@{Queue}</span>) the queue to retrieve the element from -- @treturn Mixed the element at the back of the queue function Queue.pop_last(queue) if queue.is_empty(queue) then return nil end local last = queue.last local value = queue.objects[last] queue.objects[last] = nil -- to allow garbage collection queue.last = last - 1 return value end --- Return the element at the back of the queue. -- @param queue (<span class="types">@{Queue}</span>) the queue to retrieve the element from -- @treturn Mixed the element at the back of the queue function Queue.peek_last(queue) return queue.objects[queue.last] end --- Returns true if the given queue is empty. -- @param queue (<span class="types">@{Queue}</span>) the queue to check -- @treturn boolean true if empty, false otherwise function Queue.is_empty(queue) return t_size(queue.objects) == 0 end --- Returns the number of items in the queue. -- @param queue (<span class="types">@{Queue}</span>) the queue to check -- @treturn number the number of items in the queue function Queue.count(queue) return t_size(queue.objects) end function Queue.pairs(queue, pop) local i = queue.first - 1 return function() i = i + 1 local v = pop and queue.pop(queue) or queue.objects[i] if v then return i, v end end end Queue.iter = Queue.pairs Queue.iter_first = Queue.pairs function Queue.rpairs(queue, pop) local i = queue.last + 1 return function() i = i - 1 local v = pop and queue.pop_last(queue) or queue.objects[i] if v then return i, v end end end Queue.iter_last = Queue.rpairs Queue._mt = { __pairs = Queue.pairs, __ipairs = Queue.pairs, __len = Queue.count, -- Allows queue[3] to return the item at queue.objects[3] __index = function(self, k) if Is.number(k) then return self.objects[k] else return rawget(self, k) or Queue[k] end end, -- Allows queue() to pop_first and queue(data) to push_last __call = function(self, ...) if ... then return self.push(self, ...) else return self.pop(self) end end, __tostring = function(self) return Inspect({first = self.first, last = self.last, objects = self.objects}, {arraykeys = true}) end, } return Queue
-- See LICENSE for terms if not g_AvailableDlc.picard then print("Underground Cheats: B&B DLC is missing!") return end --~ local RetMapType = ChoGGi.ComFuncs.RetMapType local function RetMapType() local UIColony = UIColony if not UIColony then return end local map_id = UICity.map_id if map_id == UIColony.underground_map_id then return "underground" elseif map_id == UIColony.surface_map_id then return "surface" else return "asteroid" end end local mod_EnableMod local mod_LightTripodRadius local mod_SupportStrutRadius local function UpdateObjs() if not mod_EnableMod or RetMapType() ~= "underground" then return end -- lights BuildingTemplates.LightTripod.reveal_range = mod_LightTripodRadius ClassTemplates.Building.LightTripod.reveal_range = mod_LightTripodRadius local UpdateRevealObject = UnitRevealDarkness.UpdateRevealObject local objs = UICity.labels.LightTripod or "" for i = 1, #objs do local obj = objs[i] obj.reveal_range = mod_LightTripodRadius UpdateRevealObject(obj) end -- struts SupportStruts.work_radius = mod_SupportStrutRadius local objs = UICity.labels.SupportStruts or "" for i = 1, #objs do objs[i].work_radius = mod_SupportStrutRadius end end local function ModOptions(id) -- id is from ApplyModOptions if id and id ~= CurrentModId then return end mod_EnableMod = CurrentModOptions:GetProperty("EnableMod") mod_LightTripodRadius = CurrentModOptions:GetProperty("LightTripodRadius") mod_SupportStrutRadius = CurrentModOptions:GetProperty("SupportStrutRadius") -- make sure we're in-game if not UICity then return end UpdateObjs() end -- load default/saved settings OnMsg.ModsReloaded = ModOptions -- fired when Mod Options>Apply button is clicked OnMsg.ApplyModOptions = ModOptions OnMsg.CityStart = UpdateObjs OnMsg.LoadGame = UpdateObjs -- switch between different maps OnMsg.ChangeMapDone = UpdateObjs
fx_version 'cerulean' game 'gta5' author 'THC' description 'Redzone Hud' ui_page 'html/index.html' files { 'html/index.html', 'html/style.css', 'html/script.js' } client_script { 'client/client.lua' }
f = f or {} f.mt = f.mt or {} f.mt.list = f.mt.list or {} f.list = function (t) t = t or {} local list = { array = {} } setmetatable (list, f.mt.list) for i = 1, #t do list [i] = t [i] end return list end f.map = function (mapF, r, ...) mapF = f.toFunction (mapF) if mapF == print then print (f.concat (f.map (tostring, r), ", ")) return end local rr = f.list () for i = 1, #r do rr [i] = mapF (r [i], ...) end return rr end f.filter = function (filterF, r, ...) filterF = f.toFunction (filterF) local rr = f.list () for i = 1, #r do if filterF (r [i], ...) then rr [#rr + 1] = r [i] end end return rr end f.foldr = function (x0, binaryF, r, ...) binaryF = f.toFunction (binaryF) for i = #r, 1, -1 do x0 = binaryF (r [i], x0, ...) end return x0 end f.foldl = function (x0, binaryF, r, ...) binaryF = f.toFunction (binaryF) for i = 1, #r do x0 = binaryF (x0, r [i], ...) end return x0 end f.range = function (x0, x1, dx) dx = dx or 1 local r = f.list () for i = x0, x1, dx do r [#r + 1] = i end return r end f.rep = function (v, n) local r = f.list () for i = 1, n do r [i] = v end return r end f.sum = function (r) return foldr (0, f.add, r) end f.prod = function (r) return foldr (1, f.mul, r) end f.keys = function (t) local r = f.list () for k, _ in pairs (t) do r [#r + 1] = k end return r end f.values = function (t) local r = f.list () for _, v in pairs (t) do r [#r + 1] = v end return r end f.mt.list.__index = {} f.mt.list.__len = function (self) return #self.array end f.mt.list.__pairs = function (self) return pairs (self.array) end f.mt.list.methods = {} f.mt.list.methods.clone = function (self) local t = {} for k, v in pairs (self.array) do t [k] = v end return f.list (t) end f.mt.list.methods.map = function (r, mapF, ...) return f.map (mapF, r, ...) end f.mt.list.methods.filter = function (r, filterF, ...) return f.filter (filterF, r, ...) end f.mt.list.methods.foldr = function (r, binaryF, x0, ...) return f.foldr (x0, binaryF, r, ...) end f.mt.list.methods.foldl = function (r, binaryF, x0, ...) return f.foldl (x0, binaryF, r, ...) end f.mt.list.methods.sum = f.sum f.mt.list.methods.prod = f.prod f.mt.list.methods.concat = f.concat f.mt.list.methods.sort = function (self, comparator) local t = self:clone () table.sort (t.array) return t end f.mt.list.methods.tostring = function (self) if #self == 0 then return "{}" end return "{ " .. self:map (f.toString):concat (", ") .. " }" end f.mt.list.__tostring = f.mt.list.methods.tostring f.mt.list.__index = function (self, k) if f.mt.list.methods [k] then return f.mt.list.methods [k] elseif type (k) == "number" then return self.array [k] elseif type (k) == "table" then return f.list (k):map (self) end end f.mt.list.__newindex = function (self, k, v) if type (k) == "number" then self.array [k] = v elseif type (k) == "table" then if type (v) == "table" then for i = 1, #k do self [k [i]] = v [i] end else for i = 1, #k do self [k [i]] = v end end end end
local g = vim.g --nord g.nord_style = "nord" g.nord_borders = false g.nord_contrast = false g.nord_cursorline_transparent = true -- Load the colorscheme local present, nord = pcall(require, "nord") if present then nord.set() end vim.cmd([[ syntax on filetype on filetype plugin indent on ]])
local _M = {} local http = require "kong.tools.http" local json = require "cjson" local log = ngx.log local ERR = ngx.ERR local WARN = ngx.WARN local INFO = ngx.INFO local ngx_time = ngx.time local ngx_timer_at = ngx.timer.at local ngx_worker_id = ngx.worker.id local ngx_worker_exiting = ngx.worker.exiting local ngx_sleep = ngx.sleep _M.ready = false _M.data = {} local function info(...) -- log(INFO, "syncer: ", ...) end local function warn(...) log(WARN, "syncer: ", ...) end local function errlog(...) log(ERR, "syncer: ", ...) end local function copyTab(st) local tab = {} for k, v in pairs(st or {}) do if type(v) ~= "table" then tab[k] = v else tab[k] = copyTab(v) end end return tab end local function indexOf(t, e) for i=1,#t do if t[i].host == e.host and t[i].port == e.port then return i end end return nil end local function basename(s) local x, y = s:match("(.*)/([^/]*)/?") return y, x end local function splitAddr(s) if not s then return "127.0.0.1", 0, "nil args" end host, port = s:match("(.*):([0-9]+)") -- verify the port local p = tonumber(port) if p == nil then return "127.0.0.1", 0, "port invalid" elseif p < 1 or p > 65535 then return "127.0.0.1", 0, "port invalid" end -- verify the ip addr local chunks = {host:match("(%d+)%.(%d+)%.(%d+)%.(%d+)")} if (#chunks == 4) then for _,v in pairs(chunks) do if (tonumber(v) < 0 or tonumber(v) > 255) then return "127.0.0.1", 0, "host invalid" end end else return "127.0.0.1", 0, "host invalid" end -- verify pass return host, port, nil end local function getLock() -- only the worker who get the lock can sync from etcd. -- the lock keeps 150 seconds. if _M.lock == true then return true end local ok, err = _M.conf.storage:add("lock", true, 12) if not ok then if err == "exists" then return nil end errlog("GET LOCK: failed to add key \"lock\": " .. err) return nil end _M.lock = true return true end local function refreshLock() local ok, err = _M.conf.storage:set("lock", true, 25) if not ok then if err == "exists" then return nil end errlog("REFRESH LOCK: failed to set \"lock\"" .. err) return nil end return true end local function releaseLock() _M.conf.storage:delete("lock") _M.lock = nil return true end local function newPeer(key, value) local name, ipport = key:match(_M.conf.etcd_path .. '([^/]+)/([^/]+)$') local h, p, err = splitAddr(ipport) if err then return {}, name, err end local ok, cfg = pcall(json.decode, value) local w, s, c, t = 1, "up", "/", 0 if type(cfg) == "table" then w = cfg.weight or 1 s = cfg.status or "up" t = cfg.slow_start or 0 if cfg.check_url ~= "" then c = cfg.check_url end end return { host = h, port = tonumber(p), weight = w, status = s, check_url = c, slow_start = t }, name, nil end local function save(name) local dict = _M.conf.storage -- when save the data, picker should not update dict:set("picker_lock", true, 0.1) -- no name means save all if not name then for name, upstream in pairs(_M.data) do if name ~= "_version" then dict:set(name .. "|version", upstream.version) dict:set(name .. "|peers", json.encode(upstream.peers)) end end else -- remove the deleted upstream if not _M.data[name] then dict:delete(name .. "|version") dict:delete(name .. "|peers") -- save the updated upstream else dict:set(name .. "|version", _M.data[name].version) dict:set(name .. "|peers", json.encode(_M.data[name].peers)) end end local allname = {} for name, _ in pairs(_M.data) do if name ~= "_version" then allname[#allname+1] = name end end dict:set("_allname", table.concat(allname, "|")) dict:set("_version", _M.data._version) -- remove the lock, picker can update now dict:delete("picker_lock") return end local function fetch(url) local client = http:new() client:set_timeout(10000) client:connect(_M.conf.etcd_host, _M.conf.etcd_port) local res, err = client:request({path=url, method="GET"}) if err then return nil, err end local body, err = res:read_body() if err then return nil, err end local ok, data = pcall(json.decode, body) if not ok then return nil, data end data.etcdIndex = res.headers["x-etcd-index"] return data, nil end local function watch(premature, index) local conf = _M.conf if premature or ngx_worker_exiting() then releaseLock() return end -- If we cannot acquire the lock, wait 1 second if not getLock() then info("Waiting 1s for pre-worker to exit...") local ok, err = ngx_timer_at(1, watch, index) if not ok then errlog("Error start watch: ", err) end return end refreshLock() local nextIndex local url = "/v2/keys" .. conf.etcd_path -- First time to fetch all the upstreams. if index == nil then local upstreamList, err = fetch(url .. "?recursive=true") if err then errlog("When fetch from etcd: " .. err) ngx_sleep(1) goto continue end if upstreamList.errorCode then errlog("When fetch from etcd: " .. upstreamList.message) ngx_sleep(1) goto continue end if not upstreamList.node.nodes then warn("Empty dir: " .. upstreamList.message) ngx_sleep(1) goto continue end for n, s in pairs(upstreamList.node.nodes) do local name = basename(s.key) _M.data[name] = {version=tonumber(upstreamList.etcdIndex), peers={}} local upstreamInfo, err = fetch(url .. name .. "?recursive=true") if err then errlog("When fetch from etcd: " .. err) ngx_sleep(1) goto continue end if upstreamList.errorCode then errlog("When fetch from etcd: " .. upstreamList.message) ngx_sleep(1) goto continue end info("full fetching: " .. json.encode(upstreamInfo)) if upstreamInfo.node.dir then if upstreamInfo.node.nodes then for i, j in pairs(upstreamInfo.node.nodes) do local peer, _, err = newPeer(j.key, j.value) if not err then _M.data[name].peers[#_M.data[name].peers+1] = peer end end end -- Keep the version is the newest response x-etcd-index _M.data[name].version = tonumber(upstreamInfo.etcdIndex) _M.data._version = _M.data[name].version end end if _M.data._version then nextIndex = _M.data._version + 1 end save() _M.conf.storage:set("ready", true) -- Watch the change and update the data. else local s_url = url .. "?wait=true&recursive=true&waitIndex=" .. index local change, err = fetch(s_url) if err == "timeout" then nextIndex = _M.data._version + 1 ngx_sleep(1) goto continue elseif err ~= nil then errlog("Error when watching etcd: ", err) ngx_sleep(1) goto continue end if change.errorCode == 401 then nextIndex = nil ngx_sleep(1) goto continue end info("recv a change: " .. json.encode(change)) local action = change.action if change.node.dir then local name = change.node.key:match(_M.conf.etcd_path .. '([^/]+)$') if name then if action == "delete" then _M.data[name] = nil elseif action == "set" or action == "update" or action == "compareAndSwap" then if not _M.data[name] then _M.data[name] = {version=tonumber(change.etcdIndex), peers={}} end end end _M.data._version = tonumber(change.node.modifiedIndex) save(name) else local peer, name, err = newPeer(change.node.key, change.node.value) if not err then if action == "delete" or action == "expire" then table.remove(_M.data[name].peers, indexOf(_M.data[name].peers, peer)) _M.data[name].version = change.etcdIndex if 0 == #_M.data[name].peers then _M.data[name] = nil end errlog("DELETE [".. name .. "]: " .. peer.host .. ":" .. peer.port) elseif action == "set" or action == "update" or action == "compareAndSwap" then if not _M.data[name] then _M.data[name] = {version=tonumber(change.etcdIndex), peers={peer}} errlog("ADD [" .. name .. "]: " .. peer.host ..":".. peer.port) else local index = indexOf(_M.data[name].peers, peer) if index == nil then errlog("ADD [" .. name .. "]: " .. peer.host ..":".. peer.port) peer.start_at = ngx_time() table.insert(_M.data[name].peers, peer) else errlog("MODIFY [" .. name .. "]: " .. peer.host ..":".. peer.port .. " " .. change.node.value) _M.data[name].peers[index] = peer end _M.data[name].version = tonumber(change.node.modifiedIndex) end end else errlog(err) end _M.data._version = tonumber(change.node.modifiedIndex) save(name) end nextIndex = _M.data._version + 1 end ::continue:: -- Start the update cycle. local ok, err = ngx_timer_at(0, watch, nextIndex) if not ok then errlog("Error start watch: ", err) end return end function _M.init(conf) -- Only one worker start the syncer, here will use worker_id == 0 if ngx_worker_id() ~= 0 then -- return end _M.conf = conf local nextIndex local dict = _M.conf.storage local allname = dict:get("_allname") local version = dict:get("_version") -- Not synced before, not reload but newly start if not allname or not version then local ok, err = ngx_timer_at(0, watch, nextIndex) if not ok then errlog("Error start watch: " .. err) end return -- Load data from shm else _M.data = {} for name in allname:gmatch("[^|]+") do upst = dict:get(name .. "|peers") vers = dict:get(name .. "|version") local ok, data = pcall(json.decode, upst) -- Any error occurs, goto full fetch if not ok then local ok, err = ngx_timer_at(0, watch, nextIndex) if not ok then errlog("Error start watch: " .. err) end return else _M.data[name] = {version = vers, peers = data} end end _M.data._version = version nextIndex = _M.data._version + 1 end -- Start the etcd watcher local ok, err = ngx_timer_at(0, watch, nextIndex) if not ok then errlog("Error start watch: " .. err) end end return _M
local ffi = require 'ffi' local ctype = require 'uv/util/ctype' local libuv = require 'uv/libuv' local libuv2 = require 'uv/libuv2' local libc = require 'uv/libc' -------------------------------------------------------------------------------- -- uv_write_t -------------------------------------------------------------------------------- local uv_write_t = ctype('uv_write_t', function() local self = ffi.cast('uv_write_t*', libc.malloc(ffi.sizeof('uv_write_t'))) return self end) function uv_write_t:free() libc.free(self) end return uv_write_t
local compose_utils = require 'utils.compose_utils' local nninit = require 'nninit' -- -- WeightedAddition composition model -- -- local WeightedAddition, parent = torch.class('torch.WeightedAddition', 'torch.CompositionModel') function WeightedAddition:__init(inputs, outputs) parent.__init(self) self.inputs = inputs self.outputs = outputs self.name = "w_addition" self.isTrainable = true self.printParameters = true end function WeightedAddition:architecture(config) parent:architecture(config) print("# WeightedAddition; vectors u and v as input; p = lambda*u + beta*v ") print("# inputs " .. self.inputs .. ", outputs " .. self.outputs) self.config = config local u = nn.Identity()(); local v = nn.Identity()(); local lambda_u = nn.Mul():init('weight', nninit.normal, 0, 1e-4)({u}):annotate{name="lambda"} local beta_v = nn.Mul():init('weight', nninit.normal, 0, 1e-4)({v}):annotate{name="beta"} local added = nn.CAddTable()({lambda_u, beta_v}) self.mlp = nn.gModule({u, v}, {added}) print("==> Network configuration") print(self.mlp) print("==> Parameters size") print(self.mlp:getParameters():size()) return self.mlp end function WeightedAddition:data(trainSet, devSet, testSet, fullSet, cmhEmbeddings) self.trainDataset = compose_utils:createCMH2TensorDataset(trainSet, cmhEmbeddings) self.testDataset = compose_utils:createCMH2TensorDataset(testSet, cmhEmbeddings) self.devDataset = compose_utils:createCMH2TensorDataset(devSet, cmhEmbeddings) self.fullDataset = compose_utils:createCMH2TensorDataset(fullSet, cmhEmbeddings) end
// ============================================================================================ // /* * Wildfire Servers - Portal RP - Base Addon * File description: Location trigger serverside script file * Copyright (C) 2022 KiwifruitDev * Licensed under the MIT License. */ // ============================================================================================ // // BASE FILE HEADER DO NOT MODIFY!! // local ent = FindMetaTable("Entity") // local ply = FindMetaTable("Player") // local vec = FindMetaTable("Vector") // // ================================ // AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetSolid(SOLID_BBOX) end function ENT:StartTouch(ent) if not IsValid(ent) then return end if ent == self then return end if not ent:IsPlayer() then if ent:GetClass() == "portalrp_core" then timer.Simple(1, function() if IsValid(ent) then ent:SetPos(self:GetDestinationPos()) ent:SetAngles(self:GetDestinationAngles()) end end) end return end if ent:GetMoveType() ~= MOVETYPE_WALK then return end if not ent:Alive() then return end ent:ScreenFade(SCREENFADE.OUT, Color(0, 0, 0), 1, 0) timer.Simple(1, function() if IsValid(ent) then ent:SetPos(self:GetDestinationPos()) ent:SetEyeAngles(self:GetDestinationAngles()) ent:ScreenFade(SCREENFADE.IN, Color(0, 0, 0), 1, 0) end end) end
local Each = { static = {} } local function clone(t) local result = {} for k,v in pairs(t) do result[k] = v end return result end local function add(klass, instance) if klass ~= Object then add(klass.super, instance) klass._instances = klass._instances or {} klass._instances[instance] = 1 end end local function remove(klass, instance) if klass ~= Object then klass._instances[instance] = nil remove(klass.super, instance) end end local function each(collection, method, ...) for instance,_ in pairs(collection) do instance[method](instance, ...) end end -- public interface function Each.static:each(method, ...) each(self._instances, method, ...) end function Each.static:safeEach(method, ...) each(clone(self._instances), method, ...) end Each.static.add = add Each.static.remove = remove return Each
local Api = require 'telegram.api' Api = Api.Init("213210238:AAEP1XgZOXjIiAqDJvUEDBzBHmLqAzO3Rug") local update_id = 0 local function script() local function updates(tab, err) for i, updates in pairs(tab.result) do local msg = updates.message if msg.text then local callback = function(a, b, var) printf("Message\t%s\nChat_id\t%s\n", var.text, var.chat.id) end Api : sendMessage({ chat_id = msg.chat.id, text = msg.text, define = msg }, callback) end update_id = updates.update_id end end Api : getUpdates({offset = update_id+1}, updates) end Api : Running (script, true)
---------------------------------------------------------------- -- KiwiHUD: Manage SavedVariables Database ---------------------------------------------------------------- local addon = KiwiHUD local rootDB = { global = {}, profiles = {}, profileChars = {} } local GetNumSpecializations = not addon.isClassic and GetNumSpecializations or function() return 1 end local GetSpecialization = not addon.isClassic and GetSpecialization or function() return 1 end local GetSpecializationInfo = not addon.isClassic and GetSpecializationInfo or function() return 1, "Default" end ---------------------------------------------------------------- -- Initialize Database ---------------------------------------------------------------- function addon:InitializeDB() local key = addon.addonName ..'DB' local db = _G[key] if not db then db = rootDB _G[key] = db end local charKey = UnitName("player") .. " - " .. GetRealmName() if not db.profiles['default'] then db.profiles['default'] = CopyTable(addon.defaults) end local profileChar = db.profileChars[charKey] if not profileChar then profileChar = {} for i=1,GetNumSpecializations() or 1 do profileChar[i] = 'default' end db.profileChars[charKey] = profileChar if not db.profiles[charKey] then db.profiles[charKey] = CopyTable(addon.defaults) end end addon.__profileChar = profileChar addon.__db = db addon:PLAYER_TALENT_UPDATE() if not addon.isClassic then addon:RegisterEvent("PLAYER_TALENT_UPDATE") end end ---------------------------------------------------------------- -- Talent change management ---------------------------------------------------------------- function addon:PLAYER_TALENT_UPDATE() local profileKey = self.__profileChar[ GetSpecialization() or 1 ] or 'default' if profileKey ~= self.__profileKey then local old_db = self.db local new_db = self.__db.profiles[profileKey] or self.__db.profiles.default self.__profileKey = profileKey self.db = new_db if old_db then self:OnProfileChanged() end end end ---------------------------------------------------------------- -- Profile management options ---------------------------------------------------------------- local values, undeletable = {}, {} local function GetProfiles() wipe(values) for key in pairs(addon.__db.profiles) do values[key] = key end return values end local function GetSpecName(i) if i<=GetNumSpecializations() then local name = select(2,GetSpecializationInfo(i)) if i==GetSpecialization() then name = name .. ' (active)' end return name else return '' end end local function GetSpecProfile(specIndex) return addon.__profileChar[specIndex] or 'default' end local function SetSpecProfile(specIndex, key) addon.__profileChar[specIndex] = key if GetSpecialization() or specIndex == 1 then addon:PLAYER_TALENT_UPDATE() end end -- profile selection per specialization local options = addon:SetupOptions( 'Profiles', 'Profiles', {} ) for i=1,6 do options['spec'..i] = { type = 'select', order = i, name = function() return GetSpecName(i) end, get = function() return GetSpecProfile(i) end, set = function(_, key) SetSpecProfile(i,key) end, hidden = function() return i>GetNumSpecializations() end, values = GetProfiles, } end -- profile database maintenance operations addon:SetupOptions( 'Profiles', 'Operations', { newDesc = { type = 'description', order = 0.5, name = "\nYou can create a new profile by entering a name in the editbox.", }, newProfile = { type = 'input', name = 'New Profile Name', order = 1, get = function() end, set = function(info,name) name = strtrim(name) addon.__db.profiles[name] = CopyTable( addon.defaults ) SetSpecProfile( GetSpecialization() or 1, name) end, validate = function(info,name) name = strtrim(name) return strlen(name)>2 and not addon.__db.profiles[name] end, }, copyDesc = { type = 'description', order = 1.5, name = "\nCopy the settings from one existing profile into the currently active profile.", }, copyProfile = { type = 'select', order = 2, name = 'Copy From', desc = "Copy the settings from one existing profile into the currently active profile.", get = function() end, set = function(_, key) local profiles = addon.__db.profiles profiles[addon.__profileKey] = CopyTable( profiles[key] ) addon.__profileKey = nil addon:PLAYER_TALENT_UPDATE() end, confirm = function() return "Selected profile will be copied into the current profile and current profile settings will be lost. Are you sure ?" end, values = function() wipe(values) for key in pairs(addon.__db.profiles) do if key ~= addon.__profileKey then values[key] = key end end return values end, }, deleteDesc = { type = 'description', order = 2.5, name = "\nYou can delete unused profiles from the database to save space.", }, deleteProfile = { type = 'select', order = 3, name = 'Delete Profile', get = function() end, set = function(_, key) addon.__db.profiles[key] = nil addon:Update() end, confirm = function() return "Are you sure you want to delete the selected profile?" end, values = function() wipe(values) wipe(undeletable) for _,keys in pairs(addon.__db.profileChars) do for _,key in pairs(keys) do undeletable[key] = true end end for key in pairs(addon.__db.profiles) do if not undeletable[key] then values[key] = key end end return values end, }, footer = { type = "description", order = 100, name = " " }, } )
local FileToString FileToString = function(path) local file = io.open(path) local s = file:read("*all") file:close() return s end return { FileToString = FileToString }
local class = require "class" local BootScreen = class:derive("BootScreen") function BootScreen:new() -- make the boot screen font bigger love.graphics.setFont(love.graphics.newFont(18)) -- github url link self.url = "https://github.com/jakubg1/opensmce" self.urlHovered = false end function BootScreen:update(dt) self.urlHovered = mousePos.x > 25 and mousePos.x < 400 and mousePos.y > 267 and mousePos.y < 292 end function BootScreen:draw() love.graphics.setColor(1, 1, 1) love.graphics.print("OpenSMCE Boot Menu", 30, 30) love.graphics.print("Version " .. VERSION, 500, 30) love.graphics.print("Notes:", 45, 75) love.graphics.print("Welcome to this brand new simple boot screen!\nA lot of things will be changed.\nThis engine is still in development!\nIf you have any bugs or suggestions, head on to Forum or Discord!\n\nOpenSMCE is a short for Open-Source Sphere Matcher Community Engine.\n\nSee our GitHub page:\n" .. self.url, 45, 100) love.graphics.print("This is the first beta release of the engine!", 30, 320) love.graphics.print("If you didn't do so yet, please read the readme!\nThank you for support!\n~jakubg1", 30, 350) love.graphics.print("Press Enter to start game \"" .. GAME_NAME .. "\".", 30, 480) love.graphics.print("Game selection screen coming soon!", 30, 510) if self.urlHovered then love.graphics.setColor(1, 1, 0) else love.graphics.setColor(0.4, 0.4, 0) end love.graphics.setLineWidth(2) love.graphics.rectangle("line", 25, 267, 375, 25) if self.urlHovered then love.graphics.print("<--- Click here to open the page!", 420, 275, 0.1) end end function BootScreen:mousepressed(x, y, button) -- STUB end function BootScreen:mousereleased(x, y, button) if self.urlHovered then love.system.openURL(self.url) end end function BootScreen:keypressed(key) if key == "return" then loadGame(GAME_NAME) end end function BootScreen:keyreleased(key) -- STUB end return BootScreen
local opts = { noremap = true, silent = true } vim.api.nvim_buf_set_keymap(0, 'n', 'j', 'gj', opts) vim.api.nvim_buf_set_keymap(0, 'n', 'k', 'gk', opts)
local reqVersion = "11.3" assert(love.isVersionCompatible(reqVersion), "Ent requires Love version " .. reqVersion .. " or greater.") local ent = {} local insert, concat = table.insert, table.concat local format = string.format local getTime = love.timer.getTime local osDate = os.date ------------------------------------------------------------------------------- -- Config ------------------------------------------------------------------------------- local config local defaultConfig = { -- log levels: identifier = {pretty string, HTML colour} -- a function will be created for each log level using the provided identifier -- e.g. log.echo("messge") logLevels = { echo = {"Echo", "#aaaaaa"}, info = {"Info", "#2288dd"}, warn = {"Warning", "#dddd22"}, error = {"Error!", "#ff44aa"}, edit = {"Editor", "#88ddbb"}, client = {"NetClient", "#aaaaaa"}, server = {"NetServer", "#aaaaaa"}, }, -- if false, log files will be plaintext useHTML = true, -- automatically delete old logs. Disables deletion if set to 0 maxOldLogs = 10, -- directory to save logs outputPath = "logs", -- custom log title title = love.filesystem.getIdentity(), -- print function print = print } ------------------------------------------------------------------------------- -- Setup ------------------------------------------------------------------------------- -- paths local srcPath = (...):gsub("%.", "/") local writerPath = srcPath .. "/logWriter.lua" local templatePath = srcPath .. "/template.html" -- thread local logWriter = love.thread.newThread(writerPath) local logWriterChannel = love.thread.getChannel "logData" local signal_shutdown = "__SHUTTING_DOWN__" -- misc local initTime = getTime() local hasInit local templateTail, bodyIndent local _print ------------------------------------------------------------------------------- -- File I/O ------------------------------------------------------------------------------- local function generateStyleCSS(indent) local output = {} local logLevelCSS = { indent .. ".%s", "{", "\tcolor: %s;", "}\n\n" } local css = concat(logLevelCSS, "\n" .. indent) for k, level in pairs(config.logLevels) do insert(output, css:format(k, level[2])) end return concat(output) end local function loadTemplate(logName, logPath) local head, tail = {}, {} local output = head local bodyIndent local sections = { {"{style}", function(indent) return generateStyleCSS(indent) end}, {"{title}", function(indent) return format("%s<title>%s</title>", indent, logName) end}, {"{header", function(indent) return format("%s<h1>Ent Log: %s</h1>", indent, logName) end}, {"{body}", function(indent) bodyIndent = indent output = tail return indent .. "<!-- Start of Log -->\n" end} } local currentSection = 1 for line in love.filesystem.lines(templatePath) do if output == head and line:match(sections[currentSection][1]) then -- for clean output, copy indentation to prepend to output local indent = line:match "(%s+){" -- generate the content insert(output, sections[currentSection][2](indent)) currentSection = currentSection + 1 else insert(output, line) end end return head, tail, bodyIndent end local function createLog(logName, logPath) -- ensure that the ouput dir exists local dirInfo = love.filesystem.getInfo(config.outputPath, "directory") if not dirInfo then assert(love.filesystem.createDirectory(config.outputPath), "Error creating log output directory") _print "Created log output directory" end if config.useHTML then local head, tail, indent = loadTemplate(logName) assert(love.filesystem.write(logPath, concat(head, "\n")), "Error creating logfile at " .. logPath) -- these values are needed later templateTail = concat(tail, "\n") bodyIndent = indent else assert(love.filesystem.write(logPath, ""), "Error creating logfile at " .. logPath) end _print("Created log file at " .. logPath) end local function getMetaPath() -- ensure log meta exists local metaPath = config.outputPath .. "/.entLogMeta" if config.maxOldLogs > 0 then local metaInfo = love.filesystem.getInfo(metaPath, "file") if not metaInfo then assert(love.filesystem.write(metaPath, ""), "Error creating .logMeta file") _print "Created .logMeta file" end end return metaPath end local function appendToMeta(logName) if config.maxOldLogs > 0 then love.filesystem.append(getMetaPath(), logName .. "\n") end end local function deleteOldLogs() if config.maxOldLogs < 1 then return end -- read meta local metaPath = getMetaPath() local names = {} for line in love.filesystem.lines(metaPath) do insert(names, line) end -- delete files for n = 1, #names - config.maxOldLogs do if love.filesystem.remove(format("%s/%s", config.outputPath, names[1])) then local outputf = ent.info or _print outputf("Removed old log file %s", names[1]) end table.remove(names, 1) end -- rewrite meta file with old logs removed love.filesystem.write(metaPath, concat(names, "\n") .. "\n") end ------------------------------------------------------------------------------- -- API ------------------------------------------------------------------------------- function ent.init(inConfig) assert(not hasInit, "Attempt to re-initialise log.") hasInit = true -- create config config = inConfig and setmetatable(inConfig, {__index = defaultConfig}) or defaultConfig -- ensure sane config assert(type(config.print) == "function", "Log config error: print must be a function") _print = config.print local numLevels = 0 for _ in pairs(config.logLevels) do numLevels = numLevels + 1 end if numLevels < 1 then _print "Log config warning: no log levels in config" end if config.title:match("[/<>:\"\\|%?%*%c]") then _print "Log config warning: log title contains characters that may be unsupported on some systems (probably Windows NTFS)" end if config.maxOldLogs == 1 then _print "Log config warning: maxOldLogs set to 1" end -- remove trailing slash from logPath config.outputPath = config.outputPath:match "^(.-)/?$" -- create log level functions for id, level in pairs(config.logLevels) do ent[id] = function(str, ...) return ent.print(id, level[1], str, ...) end end -- generate log name local time = osDate("%d-%m-%Y %H-%M-%S", os.time()) local logName = format("%s %s.%s", config.title, time, config.useHTML and "html" or "log") local logPath = format("%s/%s", config.outputPath, logName) -- boot up the thread logWriter:start(logPath) --create the file createLog(logName, logPath) appendToMeta(logName) deleteOldLogs() end function ent.print(levelid, level, str, ...) str = format(tostring(str), ...) local time = getTime() - initTime local timeStr = osDate("%H:%M:%S:", time) local nanoSecs = (time * 1000) % 1000 local logStr = string.format("[%s%03d] (%s) %s", timeStr, nanoSecs, level, str) _print(logStr) if config.useHTML then logStr = format('%s<p>\n%s\t<span class="time">[%s%03d]</span>&nbsp;<span class="%s">(%s)&nbsp;%s</span>\n%s</p>\n', bodyIndent, bodyIndent, timeStr, nanoSecs, levelid, level, str, bodyIndent) else logStr = logStr .. "\n" end logWriterChannel:push(logStr) return logStr end function ent.close() if config.useHTML then logWriterChannel:push(templateTail) -- hasInit = false end logWriterChannel:push(signal_shutdown) logWriter:wait() logWriter:release() end return ent
---------------------------------------------------- -- Walk controller based on ZMP preview control ---------------------------------------------------- local walk = {} walk._NAME = ... local Body = require'Body' local vector = require'vector' local util = require'util' local moveleg = require'moveleg' local libZMP = require'libPreviewZMP' local zmp_solver local libStep = require'libStep' local step_planner require'mcm' -- Keep track of important times local t_entry, t_update, t_last_step --Gait parameters local tStep local stepHeight = Config.walk.stepHeight -- Save gyro stabilization variables between update cycles -- They are filtered. TODO: Use dt in the filters local angleShift = vector.new{0,0,0,0} -- What foot trajectory are we using? local foot_traj_func if Config.walk.foot_traj==1 then foot_traj_func = moveleg.foot_trajectory_base else foot_traj_func = moveleg.foot_trajectory_square end local uLeft_now, uRight_now, uTorso_now, uLeft_next, uRight_next, uTorso_next local iStep, iStep_new local t, t_discrete --------------------------- -- State machine methods -- --------------------------- function walk.entry() print(walk._NAME..' Entry' ) -- Update the time of entry local t_entry_prev = t_entry -- When entry was previously called t_entry = Body.get_time() t_update = t_entry mcm.set_walk_vel({0,0,0})--reset target speed tStep = Config.walk.tStep -- Initiate the ZMP solver zmp_solver = libZMP.new_solver({ ['tStep'] = Config.walk.tStep, ['tZMP'] = Config.walk.tZMP, }) zmp_solver:precompute() step_planner = libStep.new_planner() uLeft_now, uRight_now, uTorso_now, uLeft_next, uRight_next, uTorso_next= step_planner:init_stance() zmp_solver:init_preview_queue(uLeft_now,uRight_now, uTorso_now, Body.get_time(), step_planner) mcm.set_walk_bipedal(1) mcm.set_walk_stoprequest(0) --cancel stop request flag mcm.set_walk_ismoving(1) --declare that we are moving t = Body.get_time() t_discrete = t end function walk.update() -- Get the time of update local t = Body.get_time() local t_diff = t - t_update t_update = t -- Save this at the last update time local stoprequest = mcm.get_walk_stoprequest() local discrete_updated = false local com_pos --Check if the torso stopped to move if stoprequest>0 and zmp_solver:can_stop() then return "done" end while t_discrete<t do --Get step information uLeft_now, uRight_now, uLeft_next, uRight_next, supportLeg, ph, iStep_new = zmp_solver:get_current_step_info(t_discrete) com_pos = zmp_solver:update_state() --Get the current COM position zmp_solver:update_preview_queue_velocity(step_planner,t_discrete, stoprequest) t_discrete = t_discrete + zmp_solver.preview_tStep discrete_updated = true end if discrete_updated then local uTorso = {com_pos[1],com_pos[2],0} uTorso[3] = ph*(uLeft_next[3]+uRight_next[3])/2 + (1-ph)*(uLeft_now[3]+uRight_now[3])/2 --Calculate Leg poses local phSingle = moveleg.get_ph_single(ph,Config.walk.phSingle[1],Config.walk.phSingle[2]) local uLeft, uRight, zLeft, zRight = uLeft_now, uRight_now, 0,0 if supportLeg == 0 then -- Left support uRight,zRight = foot_traj_func(phSingle,uRight_now,uRight_next,stepHeight) elseif supportLeg==1 then -- Right support uLeft,zLeft = foot_traj_func(phSingle,uLeft_now,uLeft_next,stepHeight) end step_planner:save_stance(uLeft,uRight,uTorso) -- Grab gyro feedback for these joint angles local gyro_rpy = moveleg.get_gyro_feedback( uLeft, uRight, uTorso, supportLeg ) delta_legs, angleShift = moveleg.get_leg_compensation(supportLeg,ph,gyro_rpy, angleShift) --Move legs moveleg.set_leg_positions(uTorso,uLeft,uRight,zLeft,zRight,delta_legs) --For external monitoring local uZMP = zmp_solver:get_zmp() mcm.set_status_uTorso(uTorso) mcm.set_status_uZMP(uZMP) mcm.set_status_t(t) end end -- walk.update function walk.exit() print(walk._NAME..' Exit') mcm.set_walk_ismoving(0) --We stopped moving end return walk
--- === cp.apple.finalcutpro.import.MediaImport === --- --- Media Import local require = require local axutils = require("cp.ui.axutils") local just = require("cp.just") local prop = require("cp.prop") local strings = require("cp.apple.finalcutpro.strings") local Window = require("cp.ui.Window") local cache = axutils.cache local childWith = axutils.childWith local MediaImport = {} -- _findWindowUI(windows) -> hs._asm.axuielementObject | nil -- Method -- Finds a matching window UI. -- -- Parameters: -- * windows - A table of `hs.window` objects -- -- Returns: -- * An `axuielement` or `nil` local function _findWindowUI(windows) for _,window in ipairs(windows) do if MediaImport.matches(window) then return window end end return nil end --- cp.apple.finalcutpro.import.MediaImport.matches(element) -> boolean --- Function --- Checks to see if an element matches what we think it should be. --- --- Parameters: --- * element - An `axuielementObject` to check. --- --- Returns: --- * `true` if matches otherwise `false` function MediaImport.matches(element) local importAll = strings:find("PEImportAll_NoEllipsis") return element and element:attributeValue("AXSubrole") == "AXDialog" and element:attributeValue("AXMain") and element:attributeValue("AXModal") and importAll and childWith(element, "AXTitle", importAll) ~= nil end --- cp.apple.finalcutpro.import.MediaImport.new(app) -> MediaImport --- Constructor --- Creates a new Media Import object. --- --- Parameters: --- * app - The `cp.apple.finalcutpro` object. --- --- Returns: --- * A new MediaImport object. function MediaImport.new(app) local o = prop.extend({_app = app}, MediaImport) --- cp.apple.finalcutpro.import.MediaImport:UI() -> axuielementObject --- Method --- Returns the Media Import Accessibility Object --- --- Parameters: --- * None --- --- Returns: --- * An `axuielementObject` or `nil` local UI = app.windowsUI:mutate(function(original, self) return cache(self, "_ui", function() local windowsUI = original() return windowsUI and _findWindowUI(windowsUI) end, MediaImport.matches) end) local window = Window(app.app, UI) o._window = window prop.bind(o) { UI = UI, --- cp.apple.finalcutpro.import.MediaImport.hsWindow <cp.prop: hs.window; read-only> --- Field --- The `hs.window` instance for the window, or `nil` if it can't be found. hsWindow = window.hsWindow, --- cp.apple.finalcutpro.import.MediaImport.isShowing <cp.prop: boolean> --- Field --- Is `true` if the window is visible. isShowing = window.visible, --- cp.apple.finalcutpro.import.MediaImport.isFullScreen <cp.prop: boolean> --- Field --- Is `true` if the window is full-screen. isFullScreen = window.fullScreen, --- cp.apple.finalcutpro.import.MediaImport.frame <cp.prop: frame> --- Field --- The current position (x, y, width, height) of the window. frame = window.frame, } return o end --- cp.apple.finalcutpro.import.MediaImport:app() -> App --- Method --- Returns the App instance representing Final Cut Pro. --- --- Parameters: --- * None --- --- Returns: --- * App function MediaImport:app() return self._app end function MediaImport:window() return self._window end --- cp.apple.finalcutpro.import.MediaImport:show() -> cp.apple.finalcutpro.import.MediaImport --- Method --- Shows the Media Import window. --- --- Parameters: --- * None --- --- Returns: --- * The `cp.apple.finalcutpro.import.MediaImport` object for method chaining. function MediaImport:show() if not self:isShowing() then -- open the window if self:app():menu():isEnabled({"File", "Import", "Media…"}) then self:app():menu():selectMenu({"File", "Import", "Media…"}) just.doUntil(function() return self:isShowing() end) end end return self end --- cp.apple.finalcutpro.import.MediaImport:hide() -> cp.apple.finalcutpro.import.MediaImport --- Method --- Hides the Media Import window. --- --- Parameters: --- * None --- --- Returns: --- * The `cp.apple.finalcutpro.import.MediaImport` object for method chaining. function MediaImport:hide() local ui = self:UI() if ui then local closeBtn = ui:closeButton() if closeBtn then closeBtn:doPress() end end return self end --- cp.apple.finalcutpro.import.MediaImport:show() -> cp.apple.finalcutpro.import.MediaImport --- Method --- Triggers the Import All button. --- --- Parameters: --- * None --- --- Returns: --- * The `cp.apple.finalcutpro.import.MediaImport` object for method chaining. function MediaImport:importAll() local ui = self:UI() if ui then local btn = ui:defaultButton() if btn and btn:enabled() then btn:doPress() end end return self end --- cp.apple.finalcutpro.import.MediaImport:getTitle() -> string | nil --- Method --- The title of the Media Import window or `nil`. --- --- Parameters: --- * None --- --- Returns: --- * The title of the Media Import window as a string or `nil`. function MediaImport:getTitle() local ui = self:UI() return ui and ui:title() end return MediaImport
local remotePeripherals = (...) return { width = 60, height = 100, add = function(name, window) local fillBar = advancedTiles.addSimpleFluidBar(window, 10, 80, 0, 60, 40, "water", 1) fillBar:SetRotation(270) fillBar:GetBackground():SetClickable(false) local expansionWindow = guiTiles.newBasicWindow(window:AddSubTile(60, 10, -2), 95, 80, false) expansionWindow:AddText(5, 5, "Fill history:", 0x000000) expansionWindow:SetVisible(false) expansionWindow:SetClickable(false) guiTiles.makeDraggable(window, expansionWindow:GetBackground()) local historyGraph = advancedTiles.addLineGraph(expansionWindow, 5, 15, 0, 85, 60, 0xff0000, 1) historyGraph:GetBackground():SetClickable(false) local toggleButton = window:AddButton(10, 85, 0, "More", 0x7fcc19, 0x000000, 0x57a64e, 0x000000, 40, 10) toggleButton:SetOnRelease( function() if expansionWindow:GetVisible() then expansionWindow:SetVisible(false) expansionWindow:SetClickable(false) toggleButton:SetText("More") else expansionWindow:SetVisible(true) expansionWindow:SetClickable(true) toggleButton:SetText("Less") end end ) local object = { windowID = window:GetUserdata()[2], displays = { currFuid = false, fillBar = fillBar, historyGraph = historyGraph, }, backgroundUpdate = true, } return object end, update = function(name, object) local percent = 0 local data = remotePeripherals:GetSourceData(name, "fluid_handler") if data then local tankInfo = data.getTankInfo if tankInfo and tankInfo[1] then if tankInfo[1].contents then if object.currFuid ~= tankInfo[1].contents.name then object.currFuid = tankInfo[1].contents.name object.displays.fillBar:GetBar():SetFluid(object.currFuid) end percent = tankInfo[1].contents.amount / tankInfo[1].capacity end end end object.displays.fillBar:SetPercent(percent) object.displays.historyGraph:Update(percent) end, }
Config = {} Config.OpenMenu = 51 -- Key: E Config.RequiredPermission = "police.service" Config.AntiSpamCooldown = 2 Config.Locations = { {name = "Loadout", x = 458.9700012207, y = -979.73553466797, z = 30.689664840698}, {name = "Loadout", x = 1711.6817626953, y = 2575.6123046875, z = -69.432777404785} } Config.Language = { openMenuText = "[~b~E~s~] for at tilgå våbenskabet", AccessDenied = "Adgang nægtet" }
local Codegen = require("kotaro.parser.codegen") local quotes = { lucia = "「死ね死ね変態変態、不潔不潔不潔!」", shizuru = "「むぅ」", akane = "「ツチノコは手品」", } local add_table_fields = {} function add_table_fields:new(source_field, target_field, items) return setmetatable({source_field = source_field, target_field = target_field, items = items}, {__index = add_table_fields}) end function add_table_fields:applies_to(node) if node:type() ~= "constructor_expression" then return false end -- index into the AST node as if it were a table. -- equivalent to `tbl[self.source_field]` local target = node:index(self.source_field) if not target or target:type() ~= "expression" then return false end -- convert the expression AST to an actual Lua value. local value = target:evaluate() return self.items[value] ~= nil end function add_table_fields:execute(node) local id = node:index(self.source_field):evaluate() local value = self.items[id] -- create a new AST node from scratch representing an expression -- resolving to the actual Lua value `value`. local expr = Codegen.gen_expression(value) -- equivalent to `tbl[self.target_field] = value` node:modify_index(self.target_field, value) -- mark the contents of this node as changed, which will re-run -- important AST analysis passes like parenting and line numbering. node:changed() end local rewrite = { -- these parameters are passed on the command line or from a -- compatible editor. params = { source_field = "string", target_field = "string", } } function rewrite:execute(ast, params, opts) return ast:rewrite(add_table_fields:new(params.source_field, params.target_field, quotes)) end return rewrite
-- require("/lib/stardust/playerext.lua") function init() --self.energyCost = config.getParameter("energyCost", 10) --self.initialEnergyCost = config.getParameter("initialEnergyCost", self.energyCost) --self.drainBoost = 0 self.surfaceEnergyCost = config.getParameter("surfaceEnergyCost", 1) self.zeroGEnergyCost = config.getParameter("zeroGEnergyCost", 1) sb.logInfo("rcs tech init") playerext.restoreTech() -- debug: force tech unlock end function uninit() sb.logInfo("rcs tech uninit") --playerext.overrideTech("nothing.lua") end function update(args) local newJump = args.moves["jump"] and not self.lastJump self.lastJump = args.moves["jump"] -- if mcontroller.zeroG() then -- rcs pack in space if args.moves["jump"] then local b = 25 local bf = 25*1.5 local vx = 0 local vy = 0 if args.moves["up"] then vy = vy + 1 end if args.moves["down"] then vy = vy - 1 end if args.moves["left"] then vx = vx - 1 end if args.moves["right"] then vx = vx + 1 end local sqrt2 = math.sqrt(2) if vx ~= 0 and vy ~= 0 then vx = vx / sqrt2 vy = vy / sqrt2 elseif vx == 0 and vy == 0 then bf = bf * 1.2 -- greater braking force end --mcontroller.addMomentum({vx*b, vy*b}) if status.overConsumeResource("energy", self.zeroGEnergyCost * args.dt) then mcontroller.controlApproachVelocity({vx*b, vy*b}, bf * 60 * args.dt) end end self.jetpackActive = args.moves["jump"] -- set hover state for transition into gravity well else -- rocket boots effect a la Terraria in gravity -- if mcontroller.onGround() or not args.moves["jump"] then self.jetpackActive = false elseif newJump then self.jetpackActive = true end if self.jetpackActive then if status.overConsumeResource("energy", self.surfaceEnergyCost * args.dt) then --[[playerext.setEquip("headCosmetic", { name = "clocktophathead", count = 1 }) local h = playerext.getEquip("headCosmetic") if h and h.name then playerext.message(h.name) end]] --playerext.overrideTech("startech:rcs") local bf = 300 if mcontroller.yVelocity() < -5 then bf = bf * 1.2 -- greater boost force while canceling downwards momentum elseif args.moves["down"] then bf = bf * 0.0 -- hold down for pure braking end --local xv = mcontroller.xVelocity() --mcontroller.controlApproachVelocity({xv*0, 32}, bf * 60 * args.dt) --mcontroller.setXVelocity({xv, 0}) -- restore to eliminate weirdness if mcontroller.yVelocity() < 32 then mcontroller.addMomentum({0, bf * 1 * args.dt}) end else self.jetpackActive = false end end end animator.setParticleEmitterActive("rocketParticles", self.jetpackActive or false) animator.setFlipped(mcontroller.facingDirection() < 0) end -- TODO: "heat" measure affecting surface boost cost; rebalance costs in general function applyFX(dt, onHealth) local blinkSpeed = 1.0 local color = {0x00, 0x7f, 0xff, 0xff} -- "008fffff" if onHealth then local healthPercent = status.resourcePercentage("health") color = {0xff, 0x00, 0x00, 0xff} -- "ff0000ff" if healthPercent <= 2.0/15.0 then color = {0xff, 0xff, 0xff, 0xff} end -- "ffffffff" blinkSpeed = 1.0 - healthPercent blinkSpeed = blinkSpeed * blinkSpeed * blinkSpeed blinkSpeed = 1.0 + blinkSpeed * 5 end self.blinkTimer = self.blinkTimer + dt * blinkSpeed local blink = 0.5 + math.sin(math.pi * 2.0 * self.blinkTimer) * 0.5 animator.setLightColor("hyper", colorMult(color, 0.1 + blink * 0.4)) tech.setParentDirectives("?fade=" .. colorToString(color) .. "=" .. (blink * 0.32)) end function tryActivate() if self.active then deactivate() else activate() end end function activate() -- fail if no energy if not status.overConsumeResource("energy", self.initialEnergyCost) then return end self.active = true self.blinkTimer = 0 end function deactivate() self.active = false end function colorMult(color, mult) return { color[1] * mult, color[2] * mult, color[3] * mult, color[4] * mult } end function colorToString(color) return string.format("%x", color[1] * 16777216 + color[2] * 65536 + color[3] * 256 + color[4]) end
local playsession = { {"exabyte", {29869}}, {"tykak", {552141}}, {"Krono", {437402}}, {"TheLemur", {493752}}, {"HYPPS", {923580}}, {"RainSolid", {310400}}, {"Dammpi", {919157}}, {"Kamyk", {142565}}, {"chaoticoz", {3820}}, {"adam1285", {885798}}, {"kovacspepe", {3657}}, {"yottahawk", {72556}}, {"Aero182218", {10378}}, {"Zymoran", {680355}}, {"Zorky", {700993}}, {"Jardee", {564874}}, {"dazonker", {525072}}, {"ragegear", {31286}}, {"NemesisXKL", {3387}}, {"evaldusia", {174533}}, {"DLOzTOR", {1889}}, {"Chico75", {390589}}, {"JoepieCat", {85401}}, {"thepompano", {99105}}, {"rlidwka", {11348}}, {"TXL_PLAYZ", {5179}}, {"cabb99", {695}} } return playsession
local mock = require("luassert.mock") local stub = require("luassert.stub") local lsputil = require("lspconfig.util") local scandir = require("plenary.scandir") local options = require("nvim-lsp-ts-utils.options") local utils = require("nvim-lsp-ts-utils.utils") local rename_file = require("nvim-lsp-ts-utils.rename-file") local _loop = require("nvim-lsp-ts-utils.loop") local o = mock(options, true) local u = mock(utils, true) local loop = mock(_loop, true) describe("watcher", function() stub(vim, "defer_fn") stub(scandir, "scan_dir") stub(lsputil, "find_git_ancestor") stub(lsputil.path, "is_dir") stub(lsputil.path, "exists") local watcher = require("nvim-lsp-ts-utils.watcher") local mock_root = "/my/root/dir" after_each(function() vim.defer_fn:clear() lsputil.find_git_ancestor:clear() lsputil.path.is_dir:clear() lsputil.path.exists:clear() scandir.scan_dir:clear() u.buffer.root:clear() watcher.state.reset() end) describe("state", function() it("should contain default values", function() assert.equals(watcher.state.watching, false) assert.equals(watcher.state.unwatch, nil) assert.equals(watcher.state._source, nil) end) it("should reset state on reset()", function() watcher.state.watching = true watcher.state.unwatch = function() print("unwatching") end watcher.state._source = "test-file.ts" watcher.state.reset() assert.equals(watcher.state.watching, false) assert.equals(watcher.state.unwatch, nil) assert.equals(watcher.state._source, nil) end) describe("source", function() it("should set source on set()", function() watcher.state.source.set("test-file.ts") assert.equals(watcher.state._source, "test-file.ts") end) it("should get source on get()", function() watcher.state.source.set("test-file.ts") assert.equals(watcher.state.source.get(), "test-file.ts") end) it("should reset source on reset()", function() watcher.state.source.set("test-file.ts") watcher.state.source.reset() assert.equals(watcher.state.source.get(), nil) end) end) end) describe("start", function() after_each(function() loop.watch_dir:clear() end) it("should return immediately if already watching", function() watcher.state.watching = true watcher.start() assert.stub(u.buffer.root).was_not_called() end) it("should return if root cannot be determined", function() u.buffer.root.returns(nil) watcher.start() assert.equals(watcher.state.watching, false) end) describe("git project", function() local git_root = "/git/root" before_each(function() u.buffer.root.returns(mock_root) lsputil.find_git_ancestor.returns(git_root) end) after_each(function() loop.watch_dir:clear() end) it("should call scan_dir with git root and args", function() scandir.scan_dir.returns({}) watcher.start() assert.stub(scandir.scan_dir).was_called_with( git_root, { respect_gitignore = true, depth = 1, only_dirs = true } ) end) it("should not start watching if scan_dir result is empty", function() scandir.scan_dir.returns({}) watcher.start() assert.equals(watcher.state.watching, false) end) it("should call watch_dir with file path and start watching", function() scandir.scan_dir.returns({ "dir1", "dir2" }) watcher.start() assert.equals(loop.watch_dir.calls[1].refs[1], "dir1") assert.equals(loop.watch_dir.calls[2].refs[1], "dir2") assert.equals(watcher.state.watching, true) end) it("should call callbacks on unwatch()", function() local callback = stub.new() loop.watch_dir.returns(callback) scandir.scan_dir.returns({ "dir1", "dir2", "dir3" }) watcher.start() watcher.state.unwatch() assert.stub(callback).was_called(3) end) end) describe("watch_dir fallback", function() local watch_dir = "/my/watch/dir" before_each(function() o.get.returns({ watch_dir = watch_dir }) lsputil.path.is_dir.returns(true) u.buffer.root.returns(mock_root) lsputil.find_git_ancestor.returns(false) end) after_each(function() o.get:clear() loop.watch_dir:clear() end) it("should return if watch_dir is not set", function() o.get.returns({}) watcher.start() assert.equals(watcher.state.watching, false) end) it("should return if watch_dir is not dir", function() lsputil.path.is_dir.returns(false) watcher.start() assert.stub(lsputil.path.is_dir).was_called_with(mock_root .. watch_dir) assert.equals(watcher.state.watching, false) end) it("should start watching if watch_dir is dir", function() watcher.start() assert.equals(watcher.state.watching, true) end) it("should set unwatch to watch_dir callback", function() local callback = stub.new() loop.watch_dir.returns(callback) watcher.start() assert.equals(watcher.state.unwatch, callback) end) end) describe("on_error", function() local on_error before_each(function() o.get.returns({ watch_dir = "dir" }) lsputil.path.is_dir.returns(true) watcher.start() on_error = loop.watch_dir.calls[1].refs[2].on_error end) after_each(function() u.echo_warning:clear() loop.watch_dir:clear() watcher.state.reset() end) it("should echo error message and reset state", function() watcher.state.watching = true on_error("something went wrong") assert.stub(u.echo_warning).was_called_with("error in watcher: something went wrong") assert.equals(watcher.state.watching, false) end) end) describe("on_event", function() stub(rename_file, "on_move") local watch_dir = "/my/watch/dir" local on_event before_each(function() o.get.returns({ watch_dir = watch_dir }) u.is_tsserver_file.returns(true) lsputil.path.is_dir.returns(true) watcher.start() on_event = loop.watch_dir.calls[1].refs[2].on_event end) after_each(function() u.is_tsserver_file:clear() u.file.extension:clear() loop.watch_dir:clear() rename_file.on_move:clear() watcher.state.reset() end) it("should return if path is not tsserver file and has extension", function() u.is_tsserver_file.returns(false) u.file.extension.returns(".md") on_event("file.md") assert.stub(u.is_tsserver_file).was_called() assert.stub(u.file.extension).was_called() assert.equals(watcher.state.source.get(), nil) end) it("should set source if not set", function() on_event("file.ts") assert.equals(watcher.state.source.get(), mock_root .. watch_dir .. "/" .. "file.ts") end) it("should reset source in defer callback", function() on_event("file.ts") local callback = vim.defer_fn.calls[1].refs[1] callback() assert.equals(watcher.state.source.get(), nil) end) it("should reset source if source and target are the same", function() on_event("file.ts") on_event("file.ts") assert.stub(rename_file.on_move).was_not_called() assert.equals(watcher.state.source.get(), nil) end) it("should call on_move with source and target and reset source", function() local source = lsputil.path.join(mock_root, watch_dir, "file1.ts") local target = lsputil.path.join(mock_root, watch_dir, "file2.ts") lsputil.path.exists.on_call_with(source).returns(false) lsputil.path.exists.on_call_with(target).returns(true) on_event("file1.ts") on_event("file2.ts") assert.stub(rename_file.on_move).was_called_with(source, target) assert.equals(watcher.state.source.get(), nil) end) end) end) end)
surefoot_brackaset = Creature:new { objectName = "@mob/creature_names:surefoot_brackaset", socialGroup = "brackaset", faction = "", level = 46, chanceHit = 0.44, damageMin = 340, damageMax = 390, baseXp = 4461, baseHAM = 10000, baseHAMmax = 12200, armor = 0, resists = {160,155,160,30,30,-1,-1,180,-1}, meatType = "meat_wild", meatAmount = 100, hideType = "hide_leathery", hideAmount = 91, boneType = "bone_mammal", boneAmount = 81, milk = 0, tamingChance = 0.25, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + HERD, optionsBitmask = AIENABLED, diet = CARNIVORE, templates = {"object/mobile/brackaset_hue.iff"}, hues = { 16, 17, 18, 19, 20, 21, 22, 23 }, scale = 1.2, lootGroups = { { groups = { {group = "brackaset_common", chance = 10000000} }, lootChance = 1920000 } }, weapons = {}, conversationTemplate = "", attacks = { {"stunattack",""}, {"posturedownattack",""} } } CreatureTemplates:addCreatureTemplate(surefoot_brackaset, "surefoot_brackaset")
isLoggedIn = false inJail = false jailTime = 0 currentJob = "electrician" CellsBlip = nil TimeBlip = nil ShopBlip = nil PlayerJob = {} RegisterNetEvent('QBCore:Client:OnPlayerLoaded') AddEventHandler('QBCore:Client:OnPlayerLoaded', function() isLoggedIn = true QBCore.Functions.GetPlayerData(function(PlayerData) if PlayerData.metadata["injail"] > 0 then TriggerEvent("prison:client:Enter", PlayerData.metadata["injail"]) end end) QBCore.Functions.TriggerCallback('prison:server:IsAlarmActive', function(active) if active then TriggerEvent('prison:client:JailAlarm', true) end end) PlayerJob = QBCore.Functions.GetPlayerData().job end) RegisterNetEvent('QBCore:Client:OnJobUpdate') AddEventHandler('QBCore:Client:OnJobUpdate', function(JobInfo) PlayerJob = JobInfo end) RegisterNetEvent('QBCore:Client:OnPlayerUnload') AddEventHandler('QBCore:Client:OnPlayerUnload', function() isLoggedIn = false inJail = false currentJob = nil RemoveBlip(currentBlip) end) Citizen.CreateThread(function() TriggerEvent('prison:client:JailAlarm', false) while true do Citizen.Wait(7) if jailTime > 0 and inJail then Citizen.Wait(1000 * 60) if jailTime > 0 and inJail then jailTime = jailTime - 1 if jailTime <= 0 then jailTime = 0 QBCore.Functions.Notify("Your time is up! Check yourself out at the visitors center", "success", 10000) end TriggerServerEvent("prison:server:SetJailStatus", jailTime) end else Citizen.Wait(5000) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(1) if isLoggedIn then if inJail then local pos = GetEntityCoords(PlayerPedId()) if #(pos - vector3(Config.Locations["freedom"].coords.x, Config.Locations["freedom"].coords.y, Config.Locations["freedom"].coords.z)) < 1.5 then DrawText3D(Config.Locations["freedom"].coords.x, Config.Locations["freedom"].coords.y, Config.Locations["freedom"].coords.z, "~g~E~w~ - Check time") if IsControlJustReleased(0, 38) then TriggerEvent("prison:client:Leave") end elseif #(pos - vector3(Config.Locations["freedom"].coords.x, Config.Locations["freedom"].coords.y, Config.Locations["freedom"].coords.z)) < 2.5 then DrawText3D(Config.Locations["freedom"].coords.x, Config.Locations["freedom"].coords.y, Config.Locations["freedom"].coords.z, "Check time") end if #(pos - vector3(Config.Locations["shop"].coords.x, Config.Locations["shop"].coords.y, Config.Locations["shop"].coords.z)) < 1.5 then DrawText3D(Config.Locations["shop"].coords.x, Config.Locations["shop"].coords.y, Config.Locations["shop"].coords.z, "~g~E~w~ - Canteen") if IsControlJustReleased(0, 38) then local ShopItems = {} ShopItems.label = "Prison Canteen" ShopItems.items = Config.CanteenItems ShopItems.slots = #Config.CanteenItems TriggerServerEvent("inventory:server:OpenInventory", "shop", "Kantineshop_"..math.random(1, 99), ShopItems) end DrawMarker(2, Config.Locations["shop"].coords.x, Config.Locations["shop"].coords.y, Config.Locations["shop"].coords.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.3, 0.2, 255, 55, 22, 222, false, false, false, 1, false, false, false) elseif #(pos - vector3(Config.Locations["shop"].coords.x, Config.Locations["shop"].coords.y, Config.Locations["shop"].coords.z)) < 2.5 then DrawText3D(Config.Locations["shop"].coords.x, Config.Locations["shop"].coords.y, Config.Locations["shop"].coords.z, "Canteen") DrawMarker(2, Config.Locations["shop"].coords.x, Config.Locations["shop"].coords.y, Config.Locations["shop"].coords.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.3, 0.2, 255, 55, 22, 222, false, false, false, 1, false, false, false) elseif #(pos - vector3(Config.Locations["shop"].coords.x, Config.Locations["shop"].coords.y, Config.Locations["shop"].coords.z)) < 10 then DrawMarker(2, Config.Locations["shop"].coords.x, Config.Locations["shop"].coords.y, Config.Locations["shop"].coords.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.3, 0.2, 255, 55, 22, 222, false, false, false, 1, false, false, false) end end else Citizen.Wait(5000) end end end) RegisterNetEvent('prison:client:Enter') AddEventHandler('prison:client:Enter', function(time) QBCore.Functions.Notify("You're in jail for "..time.." months..", "error") TriggerEvent("chatMessage", "SYSTEM", "warning", "Your property has been seized, you'll get everything back when your time is up..") DoScreenFadeOut(500) while not IsScreenFadedOut() do Citizen.Wait(10) end local RandomStartPosition = Config.Locations.spawns[math.random(1, #Config.Locations.spawns)] SetEntityCoords(PlayerPedId(), RandomStartPosition.coords.x, RandomStartPosition.coords.y, RandomStartPosition.coords.z - 0.9, 0, 0, 0, false) SetEntityHeading(PlayerPedId(), RandomStartPosition.coords.w) Citizen.Wait(500) TriggerEvent('animations:client:EmoteCommandStart', {RandomStartPosition.animation}) inJail = true jailTime = time currentJob = "electrician" TriggerServerEvent("prison:server:SetJailStatus", jailTime) TriggerServerEvent("prison:server:SaveJailItems", jailTime) TriggerServerEvent("InteractSound_SV:PlayOnSource", "jail", 0.5) CreateCellsBlip() Citizen.Wait(2000) DoScreenFadeIn(1000) QBCore.Functions.Notify("Do some work for sentence reduction, instant job: "..Config.Jobs[currentJob]) end) RegisterNetEvent('prison:client:Leave') AddEventHandler('prison:client:Leave', function() if jailTime > 0 then QBCore.Functions.Notify("You still have to... "..jailTime.." months..") else jailTime = 0 TriggerServerEvent("prison:server:SetJailStatus", 0) TriggerServerEvent("prison:server:GiveJailItems") TriggerEvent("chatMessage", "SYSTEM", "warning", "you've received your property back..") inJail = false RemoveBlip(currentBlip) RemoveBlip(CellsBlip) CellsBlip = nil RemoveBlip(TimeBlip) TimeBlip = nil RemoveBlip(ShopBlip) ShopBlip = nil QBCore.Functions.Notify("You're free! Enjoy it! :)") DoScreenFadeOut(500) while not IsScreenFadedOut() do Citizen.Wait(10) end SetEntityCoords(PlayerPedId(), Config.Locations["outside"].coords.x, Config.Locations["outside"].coords.y, Config.Locations["outside"].coords.z, 0, 0, 0, false) SetEntityHeading(PlayerPedId(), Config.Locations["outside"].coords.w) Citizen.Wait(500) DoScreenFadeIn(1000) end end) RegisterNetEvent('prison:client:UnjailPerson') AddEventHandler('prison:client:UnjailPerson', function() if jailTime > 0 then TriggerServerEvent("prison:server:SetJailStatus", 0) TriggerServerEvent("prison:server:GiveJailItems") TriggerEvent("chatMessage", "SYSTEM", "warning", "You got your property back..") inJail = false RemoveBlip(currentBlip) RemoveBlip(CellsBlip) CellsBlip = nil RemoveBlip(TimeBlip) TimeBlip = nil RemoveBlip(ShopBlip) ShopBlip = nil QBCore.Functions.Notify("You're free! Enjoy it! :)") DoScreenFadeOut(500) while not IsScreenFadedOut() do Citizen.Wait(10) end SetEntityCoords(PlayerPedId(), Config.Locations["outside"].coords.x, Config.Locations["outside"].coords.y, Config.Locations["outside"].coords.z, 0, 0, 0, false) SetEntityHeading(PlayerPedId(), Config.Locations["outside"].coords.w) Citizen.Wait(500) DoScreenFadeIn(1000) end end) function CreateCellsBlip() if CellsBlip ~= nil then RemoveBlip(CellsBlip) end CellsBlip = AddBlipForCoord(Config.Locations["yard"].coords.x, Config.Locations["yard"].coords.y, Config.Locations["yard"].coords.z) SetBlipSprite (CellsBlip, 238) SetBlipDisplay(CellsBlip, 4) SetBlipScale (CellsBlip, 0.8) SetBlipAsShortRange(CellsBlip, true) SetBlipColour(CellsBlip, 4) BeginTextCommandSetBlipName("STRING") AddTextComponentSubstringPlayerName("Cellen") EndTextCommandSetBlipName(CellsBlip) if TimeBlip ~= nil then RemoveBlip(TimeBlip) end TimeBlip = AddBlipForCoord(Config.Locations["freedom"].coords.x, Config.Locations["freedom"].coords.y, Config.Locations["freedom"].coords.z) SetBlipSprite (TimeBlip, 466) SetBlipDisplay(TimeBlip, 4) SetBlipScale (TimeBlip, 0.8) SetBlipAsShortRange(TimeBlip, true) SetBlipColour(TimeBlip, 4) BeginTextCommandSetBlipName("STRING") AddTextComponentSubstringPlayerName("Time check") EndTextCommandSetBlipName(TimeBlip) if ShopBlip ~= nil then RemoveBlip(ShopBlip) end ShopBlip = AddBlipForCoord(Config.Locations["shop"].coords.x, Config.Locations["shop"].coords.y, Config.Locations["shop"].coords.z) SetBlipSprite (ShopBlip, 52) SetBlipDisplay(ShopBlip, 4) SetBlipScale (ShopBlip, 0.5) SetBlipAsShortRange(ShopBlip, true) SetBlipColour(ShopBlip, 0) BeginTextCommandSetBlipName("STRING") AddTextComponentSubstringPlayerName("Canteen") EndTextCommandSetBlipName(ShopBlip) end function DrawText3D(x, y, z, text) SetTextScale(0.35, 0.35) SetTextFont(4) SetTextProportional(1) SetTextColour(255, 255, 255, 215) SetTextEntry("STRING") SetTextCentre(true) AddTextComponentString(text) SetDrawOrigin(x,y,z, 0) DrawText(0.0, 0.0) local factor = (string.len(text)) / 370 DrawRect(0.0, 0.0+0.0125, 0.017+ factor, 0.03, 0, 0, 0, 75) ClearDrawOrigin() end
local config = require 'config' local u = require 'utilities' local api = require 'methods' local HTTP = require('socket.http') local URL = require('socket.url') local plugin = {} function plugin.onTextMessage(msg, blocks) if blocks[1] == 'cat' or blocks[1] == 'cats' then api.sendChatAction(msg.chat.id, "upload_photo") local url = "http://barreeeiroo.ga/BarrePolice/cats/" local output, res = HTTP.request(url) if not output or res ~= 200 or output:len() == 0 then output, res = HTTP.request(url) end api.sendMediaId(msg.chat.id, output, "photo", msg.message_id, "Cat's are our Gods!") end end plugin.triggers = { onTextMessage = { config.cmd..'(cat)s?$' } } return plugin
data.raw["gui-style"]["default"]["cc-scroll-pane"] = { type = "scroll_pane_style", maximal_height = 300, maximal_width = 400 }
local gears = require('gears') local beautiful = require('beautiful') local filesystem = gears.filesystem local dpi = beautiful.xresources.apply_dpi local gtk_variable = beautiful.gtk.get_theme_variables local theme_dir = filesystem.get_configuration_dir() .. '/theme' local titlebar_theme = 'stoplight' local titlebar_icon_path = theme_dir .. '/icons/titlebar/' .. titlebar_theme .. '/' local tip = titlebar_icon_path -- Create theme table local theme = {} -- Font theme.font = 'Inter Regular 10' theme.font_bold = 'Inter Bold 10' -- Menu icon theme theme.icon_theme = 'Tela-blue-dark' local awesome_overrides = function(theme) theme.dir = theme_dir theme.icons = theme_dir .. '/icons/' -- Default wallpaper path theme.wallpaper = theme.dir .. '/wallpapers/morning-wallpaper.jpg' -- Default font theme.font = 'Inter Regular 10' -- Foreground theme.fg_normal = '#ffffffde' theme.fg_focus = '#e4e4e4' theme.fg_urgent = '#CC9393' theme.bg_normal = theme.background theme.bg_focus = '#5a5a5a' theme.bg_urgent = '#3F3F3F' -- System tray theme.bg_systray = theme.background theme.systray_icon_spacing = dpi(16) -- Titlebar theme.titlebar_size = dpi(34) theme.titlebar_bg_focus = gtk_variable().bg_color:sub(1,7)-- .. '66' theme.titlebar_bg_normal = gtk_variable().base_color:sub(1,7)-- .. '66' theme.titlebar_fg_focus = gtk_variable().fg_color theme.titlebar_fg_normal = gtk_variable().fg_color -- Close Button theme.titlebar_close_button_normal = tip .. 'close_normal.svg' theme.titlebar_close_button_focus = tip .. 'close_focus.svg' -- Minimize Button theme.titlebar_minimize_button_normal = tip .. 'minimize_normal.svg' theme.titlebar_minimize_button_focus = tip .. 'minimize_focus.svg' -- Ontop Button theme.titlebar_ontop_button_normal_inactive = tip .. 'ontop_normal_inactive.svg' theme.titlebar_ontop_button_focus_inactive = tip .. 'ontop_focus_inactive.svg' theme.titlebar_ontop_button_normal_active = tip .. 'ontop_normal_active.svg' theme.titlebar_ontop_button_focus_active = tip .. 'ontop_focus_active.svg' -- Sticky Button theme.titlebar_sticky_button_normal_inactive = tip .. 'sticky_normal_inactive.svg' theme.titlebar_sticky_button_focus_inactive = tip .. 'sticky_focus_inactive.svg' theme.titlebar_sticky_button_normal_active = tip .. 'sticky_normal_active.svg' theme.titlebar_sticky_button_focus_active = tip .. 'sticky_focus_active.svg' -- Floating Button theme.titlebar_floating_button_normal_inactive = tip .. 'floating_normal_inactive.svg' theme.titlebar_floating_button_focus_inactive = tip .. 'floating_focus_inactive.svg' theme.titlebar_floating_button_normal_active = tip .. 'floating_normal_active.svg' theme.titlebar_floating_button_focus_active = tip .. 'floating_focus_active.svg' -- Maximized Button theme.titlebar_maximized_button_normal_inactive = tip .. 'maximized_normal_inactive.svg' theme.titlebar_maximized_button_focus_inactive = tip .. 'maximized_focus_inactive.svg' theme.titlebar_maximized_button_normal_active = tip .. 'maximized_normal_active.svg' theme.titlebar_maximized_button_focus_active = tip .. 'maximized_focus_active.svg' -- Hovered Close Button theme.titlebar_close_button_normal_hover = tip .. 'close_normal_hover.svg' theme.titlebar_close_button_focus_hover = tip .. 'close_focus_hover.svg' -- Hovered Minimize Buttin theme.titlebar_minimize_button_normal_hover = tip .. 'minimize_normal_hover.svg' theme.titlebar_minimize_button_focus_hover = tip .. 'minimize_focus_hover.svg' -- Hovered Ontop Button theme.titlebar_ontop_button_normal_inactive_hover = tip .. 'ontop_normal_inactive_hover.svg' theme.titlebar_ontop_button_focus_inactive_hover = tip .. 'ontop_focus_inactive_hover.svg' theme.titlebar_ontop_button_normal_active_hover = tip .. 'ontop_normal_active_hover.svg' theme.titlebar_ontop_button_focus_active_hover = tip .. 'ontop_focus_active_hover.svg' -- Hovered Sticky Button theme.titlebar_sticky_button_normal_inactive_hover = tip .. 'sticky_normal_inactive_hover.svg' theme.titlebar_sticky_button_focus_inactive_hover = tip .. 'sticky_focus_inactive_hover.svg' theme.titlebar_sticky_button_normal_active_hover = tip .. 'sticky_normal_active_hover.svg' theme.titlebar_sticky_button_focus_active_hover = tip .. 'sticky_focus_active_hover.svg' -- Hovered Floating Button theme.titlebar_floating_button_normal_inactive_hover = tip .. 'floating_normal_inactive_hover.svg' theme.titlebar_floating_button_focus_inactive_hover = tip .. 'floating_focus_inactive_hover.svg' theme.titlebar_floating_button_normal_active_hover = tip .. 'floating_normal_active_hover.svg' theme.titlebar_floating_button_focus_active_hover = tip .. 'floating_focus_active_hover.svg' -- Hovered Maximized Button theme.titlebar_maximized_button_normal_inactive_hover = tip .. 'maximized_normal_inactive_hover.svg' theme.titlebar_maximized_button_focus_inactive_hover = tip .. 'maximized_focus_inactive_hover.svg' theme.titlebar_maximized_button_normal_active_hover = tip .. 'maximized_normal_active_hover.svg' theme.titlebar_maximized_button_focus_active_hover = tip .. 'maximized_focus_active_hover.svg' -- UI Groups theme.groups_title_bg = '#ffffff' .. '15' theme.groups_bg = '#ffffff' .. '10' theme.groups_radius = dpi(9) -- UI events theme.leave_event = transparent theme.enter_event = '#ffffff' .. '10' theme.press_event = '#ffffff' .. '15' theme.release_event = '#ffffff' .. '10' -- Client Decorations -- Borders theme.border_focus = '#003f6b' --gtk_variable().bg_color theme.border_normal = gtk_variable().base_color theme.border_marked = '#CC9393' theme.border_width = dpi(1) theme.border_radius = dpi(9) -- Decorations theme.useless_gap = dpi(4) theme.client_shape_rectangle = gears.shape.rectangle theme.client_shape_rounded = function(cr, width, height) gears.shape.rounded_rect(cr, width, height, dpi(6)) end -- Menu theme.menu_font = 'Inter Regular 11' theme.menu_submenu = '' -- ➤ theme.menu_height = dpi(34) theme.menu_width = dpi(200) theme.menu_border_width = dpi(2) theme.menu_bg_focus = theme.accent .. 'CC' theme.menu_bg_normal = theme.background:sub(1,7) .. '33' theme.menu_fg_normal = '#ffffff' theme.menu_fg_focus = '#ffffff' theme.menu_border_color = theme.background:sub(1,7) .. '5C' -- Tooltips theme.tooltip_bg = theme.background theme.tooltip_border_color = theme.transparent theme.tooltip_border_width = 0 theme.tooltip_gaps = dpi(5) theme.tooltip_shape = function(cr, w, h) gears.shape.rounded_rect(cr, w, h, dpi(6)) end -- Separators theme.separator_color = '#f2f2f244' -- Layoutbox icons theme.layout_max = theme.icons .. 'layouts/max.svg' theme.layout_tile = theme.icons .. 'layouts/tile.svg' theme.layout_dwindle = theme.icons .. 'layouts/dwindle.svg' theme.layout_floating = theme.icons .. 'layouts/floating.svg' -- Taglist theme.taglist_bg_empty = theme.background .. '99' theme.taglist_bg_occupied = theme.background -- '#ffffff' .. '1A' theme.taglist_bg_urgent = '#E91E63' .. '99' theme.taglist_bg_focus = '#ffffff' .. '1A' --theme.background theme.taglist_spacing = dpi(0) -- Tasklist theme.tasklist_font = 'Roboto medium 11' theme.tasklist_bg_normal = theme.background .. '99' theme.tasklist_bg_focus = '#ffffff' .. '1A' theme.tasklist_bg_urgent = '#E91E63' .. '99' theme.tasklist_fg_focus = '#DDDDDD' theme.tasklist_fg_urgent = '#ffffff' theme.tasklist_fg_normal = '#AAAAAA' -- Notification theme.notification_position = 'top_right' theme.notification_bg = theme.transparent theme.notification_margin = dpi(5) theme.notification_border_width = dpi(0) theme.notification_border_color = theme.transparent theme.notification_spacing = dpi(5) theme.notification_icon_resize_strategy = 'center' theme.notification_icon_size = dpi(32) -- Client Snap Theme theme.snap_bg = theme.background theme.snap_shape = gears.shape.rectangle theme.snap_border_width = dpi(15) -- Hotkey popup theme.hotkeys_font = 'Inter Bold' theme.hotkeys_description_font = 'Inter Regular Regular' theme.hotkeys_bg = theme.background theme.hotkeys_group_margin = dpi(20) end return { theme = theme, awesome_overrides = awesome_overrides }
local wezterm = require "wezterm" -- Link for checking mapping keys: -- https://wezfurlong.org/wezterm/config/keys.html -- Example configuration for wezterm.lua: -- https://github.com/bew/dotfiles/blob/main/gui/wezterm/wezterm.lua -- Example wezterm lua configurations: -- https://github.com/wez/wezterm/discussions/628 local myfunc = function(params) local handle = io.popen(params) local result = handle:read "*a" handle:close() return result:gsub("\n", "") end return { -- [1.0] alpha channel value with floating point numbers in the range 0.0 -- (meaning completely translucent/transparent) through to 1.0 (meaning -- completely opaque)- Base window_background_opacity = 0.9, window_close_confirmation = "NeverPrompt", exit_behavior = "Close", window_padding = { left = 2, right = 2, top = 2, bottom = 2, }, -- Fonts font = wezterm.font_with_fallback { -- "LiterationMono Nerd Font", -- "TerminessTTF Nerd Font", -- "SauceCodePro Nerd Font", -- "Iosevka Nerd Font", "JetBrainsMono Nerd Font", -- "Hack Nerd Font", -- "Cascadia Mono", -- "LastResort", }, adjust_window_size_when_changing_font_size = false, warn_about_missing_glyphs = false, font_antialias = "Subpixel", -- None, Greyscale, Subpixel font_hinting = "None", -- None, Vertical, VerticalSubpixel, Full font_size = 7.5, disable_default_key_bindings = true, disable_default_mouse_bindings = false, -- font_hinting = "Full", -- font_shaper = "Harfbuzz", -- allow_square_glyphs_to_overflow_width = "Always", -- Mappings leader = { key = "a", mods = "CTRL" }, keys = { -- Send "CTRL-A" to the terminal when pressing CTRL-A, CTRL-A { key = "a", mods = "LEADER|CTRL", action = wezterm.action { SendString = "\x01" }, }, { key = "f", mods = "LEADER", action = "QuickSelect" }, { key = "l", mods = "LEADER", action = wezterm.action { SplitHorizontal = { domain = "CurrentPaneDomain" }, }, }, { key = "j", mods = "LEADER", action = wezterm.action { SplitVertical = { domain = "CurrentPaneDomain" }, }, }, { key = "n", mods = "LEADER", action = wezterm.action { SpawnTab = "CurrentPaneDomain" }, }, { key = "c", mods = "CTRL|SHIFT", action = wezterm.action { CopyTo = "Clipboard" }, }, { key = "v", mods = "CTRL|SHIFT", action = wezterm.action { PasteFrom = "Clipboard" }, }, { key = "N", mods = "LEADER", action = "ShowLauncher" }, { key = "R", mods = "LEADER", action = "ReloadConfiguration" }, { key = "m", mods = "LEADER", action = "TogglePaneZoomState" }, -- toggle maximize { key = "j", mods = "CTRL|SHIFT", action = "IncreaseFontSize" }, { key = "k", mods = "CTRL|SHIFT", action = "DecreaseFontSize" }, { key = "Home", mods = "CTRL|SHIFT", action = "ResetFontSize" }, { key = "h", mods = "ALT|CTRL", action = wezterm.action { MoveTabRelative = -1 }, }, { key = "l", mods = "ALT|CTRL", action = wezterm.action { MoveTabRelative = 1 }, }, { key = "h", mods = "ALT", action = wezterm.action { ActivateTabRelative = -1 }, }, { key = "l", mods = "ALT", action = wezterm.action { ActivateTabRelative = 1 }, }, { key = "q", mods = "LEADER", action = wezterm.action { CloseCurrentPane = { confirm = true } }, }, { key = "LeftArrow", mods = "CTRL|SHIFT", action = wezterm.action { ActivatePaneDirection = "Left" }, }, { key = "DownArrow", mods = "CTRL|SHIFT", action = wezterm.action { ActivatePaneDirection = "Down" }, }, { key = "UpArrow", mods = "CTRL|SHIFT", action = wezterm.action { ActivatePaneDirection = "Up" }, }, { key = "RightArrow", mods = "CTRL|SHIFT", action = wezterm.action { ActivatePaneDirection = "Right" }, }, { key = "1", mods = "LEADER", action = wezterm.action { ActivateTab = 0 }, }, { key = "2", mods = "LEADER", action = wezterm.action { ActivateTab = 1 }, }, { key = "3", mods = "LEADER", action = wezterm.action { ActivateTab = 2 }, }, { key = "4", mods = "LEADER", action = wezterm.action { ActivateTab = 3 }, }, { key = "5", mods = "LEADER", action = wezterm.action { ActivateTab = 4 }, }, { key = "6", mods = "LEADER", action = wezterm.action { ActivateTab = 5 }, }, { key = "7", mods = "LEADER", action = wezterm.action { ActivateTab = 6 }, }, { key = "8", mods = "LEADER", action = wezterm.action { ActivateTab = 7 }, }, { key = "9", mods = "LEADER", action = wezterm.action { ActivateTab = 8 }, }, { key = "K", mods = "LEADER", action = wezterm.action { ClearScrollback = "ScrollbackOnly" }, }, { key = "k", mods = "LEADER", action = wezterm.action { ScrollToPrompt = 1 }, }, { key = "j", mods = "LEADER", action = wezterm.action { ScrollToPrompt = -1 }, }, { key = "PageUp", mods = "NONE", action = wezterm.action { ScrollByPage = -1 }, }, { key = "PageDown", mods = "NONE", action = wezterm.action { ScrollByPage = 1 }, }, }, colors = { -- The default text color foreground = myfunc "xrdb -query | grep -i foreground| cut -d':' -f2 | xargs", -- The default background color background = myfunc "xrdb -query | grep -i background| cut -d':' -f2 | xargs", }, }
ENT.Base = "base_anim" ENT.PrintName = "Cassette Player" ENT.Author = "Thermadyle" ENT.data = { insert_delay = 1, click_delay = 0.5, buttons = { { text = "PREV", GetPos = function(self, width, height, display) return display.btn_padding, display.height - display.btn_padding - height end, OnClick = function(self, ent) ent:AdvanceSongKey(true) end }, { text = "NEXT", GetPos = function(self, width, height, display) return display.width - width - display.btn_padding, display.height - display.btn_padding - height end, OnClick = function(self, ent) ent:AdvanceSongKey() end }, { GetText = function(self, ent) local song, key = ent.active_song, ent:GetSongKey() return (ent:GetCassetteKey() == 0 and "----") or ((ent:GetPlaying() and song and song.key == key) and "STOP") or "PLAY" end, GetPos = function(self, width, height, display) return (display.width / 2) - (width / 2), display.height - display.btn_padding - height end, OnClick = function(self, ent) local song, key = ent.active_song, ent:GetSongKey() if ent:GetPlaying() and (not song or song.key == key) then ent:Play(false) else ent:Play(true) end end }, { GetText = function(self, ent) local data = ent:GetData() return string.format("EJECT> %s", (data and data.name) or "----") end, GetPos = function(self, width, height, display) return display.btn_padding, display.btn_padding end, OnClick = function(self, ent) ent:EjectCassette() end } } } function ENT:SetupDataTables() self:NetworkVar("Int", 0, "CassetteKey") self:NetworkVar("Int", 1, "SongKey") self:NetworkVar("Bool", 0, "Playing") end function ENT:GetData() local key = self:GetCassetteKey() return t_cassette.cassettes[key] end function ENT:GetSongData() local data = self:GetData() if data then local key = self:GetSongKey() return data.playlist[key] end end function ENT:GetCassettePos(bEject) local ang = self:GetAngles() local pos = self:GetPos() + (ang:Right() * -6.5) + (ang:Up() * 3.55) + (ang:Forward() * ((bEject and -3.25) or -1.5)) return pos, ang end function ENT:CanClick() return not self.next_click or self.next_click < SysTime() end
--[[ A basic ternary function! Usage: local ternary = require 'me.strangepan.libs.util.v1.ternary' function foo(bar) print(ternary(bar == nil, 'unset', bar)) end ]] return function(condition, if_true, if_false) if condition then return if_true else return if_false end end
-- -- Please see the license.txt file included with this distribution for -- attribution and copyright information. -- -- A Trigger consists of one or more Events and one or more Actions. -- When any of the events fire all of the Actions will be executed. -- An Event consists of zero or more Conditions. -- All of an event's Conditions must be met in order for the event to fire. local tEventDefinitions = {}; local tConditionDefinitions = {}; local tActionDefinitions = {}; local tRegisteredTriggers = {}; local tRegisteredEventTriggers = {}; local tInterruptedEvents = {}; local nInterruptedEvents = 0; function onInit() if Session.IsHost then DB.createNode("activetrigger").setPublic(true); end DB.addHandler("activetrigger.*", "onChildUpdate", onActiveTriggerUpdated); DB.addHandler("activetrigger.*", "onDelete", onActiveTriggerDeleted); for _,nodeTrigger in pairs(DB.getChildren("activetrigger")) do registerTrigger(nodeTrigger); end end function onActiveTriggerUpdated(nodeParent, bListchanged) registerTrigger(nodeParent); end function onActiveTriggerDeleted(nodeToBeDeleted) unregisterTrigger(nodeToBeDeleted); end function defineEvent(rEvent) tEventDefinitions[rEvent.sName] = rEvent; end function getEventDefinition(sEventName) return tEventDefinitions[sEventName]; end function getEventDefinitions() return tEventDefinitions; end function getParametersForEvent(vEvent) local rEvent = vEvent; if type(vEvent) == "string" then rEvent = tEventDefinitions[vEvent]; end return rEvent.aParameters; end function getCommonParametersForEvents(aEvents) local tParameterCounts = {}; local nEventCount = 0; for _,vEvent in ipairs(aEvents) do nEventCount = nEventCount + 1; local aParameters = getParametersForEvent(vEvent); for _,sParameter in ipairs(aParameters) do tParameterCounts[sParameter] = (tParameterCounts[sParameter] or 0) + 1; end end local aParameters = {} for sParameter,nCount in pairs(tParameterCounts) do if nCount == nEventCount then table.insert(aParameters, sParameter); end end return aParameters; end function defineCondition(rCondition) tConditionDefinitions[rCondition.sName] = rCondition; end function getConditionDefinition(sConditionName) return tConditionDefinitions[sConditionName]; end function getConditionDefinitions() return tConditionDefinitions; end function getConditionDefinitionsForEvent(vEvent) return getConditionDefinitionsForEventParameters(getParametersForEvent(vEvent)); end function getConditionDefinitionsForEventParameters(aEventParameters) local aConditions = {} for _,rConditionDefinition in pairs(tConditionDefinitions) do if hasRequiredParameters(rConditionDefinition.aRequiredParameters, aEventParameters) then table.insert(aConditions, rConditionDefinition); end end return aConditions; end function defineAction(rAction) tActionDefinitions[rAction.sName] = rAction; end function getActionDefinition(sActionName) return tActionDefinitions[sActionName]; end function getActionDefinitions() return tActionDefinitions; end function getActionDefinitionsForEvents(aEvents) return getActionDefinitionsForCommonEventParameters(getCommonParametersForEvents(aEvents)); end function getActionDefinitionsForEvent(vEvent) return getActionDefinitionsForCommonEventParameters(getParametersForEvent(vEvent)); end function getActionDefinitionsForCommonEventParameters(aEventParameters) local aActions = {} for _,rActionDefinition in pairs(tActionDefinitions) do if hasRequiredParameters(rActionDefinition.aRequiredParameters, aEventParameters) then table.insert(aActions, rActionDefinition); end end return aActions; end function hasRequiredParameters(aRequiredParameters, aEventParameters) local bHasRequirements = true; for _,sParameterName in ipairs(aRequiredParameters or {}) do if not StringManager.contains(aEventParameters, sParameterName) then bHasRequirements = false; break; end end return bHasRequirements; end function registerTrigger(nodeTrigger) local rTrigger = loadTriggerFromNode(nodeTrigger); tRegisteredTriggers[nodeTrigger] = rTrigger; for sEventName,_ in pairs(rTrigger.tEventLists) do local tEventTriggers = tRegisteredEventTriggers[sEventName]; if not tEventTriggers then tEventTriggers = {}; tRegisteredEventTriggers[sEventName] = tEventTriggers; end tEventTriggers[nodeTrigger] = rTrigger; end end function unregisterTrigger(nodeTrigger) local rTrigger = tRegisteredTriggers[nodeTrigger]; if not rTrigger then return; end for sEventName,_ in pairs(rTrigger.tEventLists) do local tEventTriggers = tRegisteredEventTriggers[sEventName]; if tEventTriggers then tEventTriggers[nodeTrigger] = nil; end end tRegisteredTriggers[nodeTrigger] = nil; end function loadTriggerFromNode(nodeTrigger) local rTrigger = { tEventLists = {}, aActions = {} }; for _,nodeEvent in pairs(DB.getChildren(nodeTrigger, "events")) do local rEvent = loadTriggerEventFromNode(nodeEvent); local aEvents = rTrigger.tEventLists[rEvent.sName]; if not aEvents then aEvents = {}; rTrigger.tEventLists[rEvent.sName] = aEvents; end table.insert(aEvents, rEvent); end for _,nodeAction in pairs(DB.getChildren(nodeTrigger, "actions")) do local rAction = loadTriggerActionFromNode(nodeAction); table.insert(rTrigger.aActions, rAction); end return rTrigger; end function loadTriggerEventFromNode(nodeEvent) local rEvent = { sName = DB.getValue(nodeEvent, "eventname", ""); aConditions = {} }; for _,nodeCondition in pairs(DB.getChildren(nodeEvent, "conditions")) do local rCondition = loadTriggerConditionFromNode(nodeCondition); table.insert(rEvent.aConditions, rCondition); end return rEvent; end function loadTriggerConditionFromNode(nodeCondition) local rCondition = { sName = DB.getValue(nodeCondition, "conditionname", ""); rData = loadParametersFromNode(nodeCondition), bInverted = DB.getValue(nodeCondition, "inverted", 0) ~= 0, }; return rCondition; end function loadTriggerActionFromNode(nodeAction) local rAction = { sName = DB.getValue(nodeAction, "actionname", ""); rData = loadParametersFromNode(nodeAction) }; return rAction; end function loadParametersFromNode(nodeContainer) local tParameters = {}; for _,nodeParameter in pairs(DB.getChildren(nodeContainer, "parameters")) do local sName = DB.getValue(nodeParameter, "name", ""); local vValue = DB.getValue(nodeParameter, "value"); if DB.getValue(nodeParameter, "type") == "bool" then vValue = vValue ~= 0; end tParameters[sName] = vValue; end return tParameters; end -- TODO if supporting interruptions how does it work across triggers? -- Other triggers are unaffected? -- ensure other triggers are avoided when resuming -- subsequent actions of the current trigger are skipped -- upon resume remember which action for this trigger -- previous in-sequence events are unaffected -- be sure not to double dip when resuming -- next in-sequence events are interrupted -- make sure other triggers get to fire function fireEvent(sEventName, rEventData) local tEventTriggers = tRegisteredEventTriggers[sEventName]; local aInterruptions = {}; for _,rTrigger in pairs(tEventTriggers or {}) do for _,rEvent in ipairs(rTrigger.tEventLists[sEventName]) do local bConditionsMet = checkConditions(rEvent, rEventData); if bConditionsMet then local rInterruption = invokeActions(rTrigger, rEventData); if rInterruption then table.insert(aInterruptions, rInterruption); end end end end return aInterruptions; end function checkConditions(rEvent, rEventData) local bConditionsMet = true; for _,rCondition in ipairs(rEvent.aConditions) do local rConditionDefinition = tConditionDefinitions[rCondition.sName]; if not (rConditionDefinition and (rCondition.bInverted ~= rConditionDefinition.fCondition(rCondition.rData, rEventData))) then bConditionsMet = false; break; end end return bConditionsMet; end function invokeActions(rTrigger, rEventData) for nIndex,rAction in ipairs(rTrigger.aActions or {}) do local rActionDefinition = tActionDefinitions[rAction.sName]; if rActionDefinition then local rInterruption = rActionDefinition.fAction(rAction.rData, rEventData); if rInterruption then -- TODO multiple triggers can interrupt the same event, and some interruptions may actually block -- interruption actions should actually fire in their own loop -- the event itself should be responsible for defining how to resume from interruption -- the above info concerning sequence handling applies the same return {rInterruption = rInterruption, rTrigger = rTrigger, nActionIndex = nIndex}; end end end end function fireInterruptions(sEventName, rEventData, aInterruptions) if #aInterruptions == 0 then return; end local rEventDefinition = getEventDefinition(sEventName) local sInterruptionKey = ""; -- TODO generate unique key from event local rInterruptedEvent = beginTrackingInterruptedEvent(sInterruptionKey, rEventDefinition, rEventData) for _,rInterruptionData in ipairs(aInterruptions) do table.insert(rInterruptedEvent.aInterruptedTriggers, { rTrigger = rInterruptionData.rTrigger, nActionIndex = rInterruptionData.nActionIndex }); rInterruptedEvent.nTriggerCount = rInterruptedEvent.nTriggerCount + 1; end for _,rInterruptionData in ipairs(aInterruptions) do rInterruptionData.rInterruption.fAction(sInterruptionKey, rInterruptionData.rInterruption.rData); end end function beginTrackingInterruptedEvent(sInterruptionKey, rEventDefinition, rEventData) local rInterruptedEvent = { rEventDefinition = rEventDefinition, rEventData = rEventData, nTriggerCount = 0, aInterruptedTriggers = {} }; tInterruptedEvents[sInterruptionKey] = rInterruptedEvent; nInterruptedEvents = nInterruptedEvents + 1; if nInterruptedEvents > 100 then -- TODO configurable count? dropOldestEvent(); end return rInterruptedEvent; end -- TODO maybe this logic can be consolidated for use with flags as well? function dropOldestEvent() local nEarliest = math.huge; local sEarliest; for sInterruptionKey, rInterruptionData in pairs(tInterruptedEvents) do if rInterruptionData.nCreated < nEarliest then nEarliest = rInterruptionData.nCreated; sEarliest = sInterruptionKey; end end if sEarliest then tInterruptedEvents[sEarliest] = nil; nInterruptedEvents = nInterruptedEvents - 1; end end function endTriggerInterruption(sInterruptionKey) local rInterruptedEvent = tInterruptedEvents[sInterruptionKey]; if not rInterruptedEvent then return; end rInterruptedEvent.nTriggerCount = rInterruptedEvent.nTriggerCount - 1; if rInterruptedEvent.nTriggerCount == 0 then resumeEvent(sInterruptionKey, rInterruptedEvent); end end function resumeEvent(sInterruptionKey, rInterruptedEvent) tInterruptedEvents[sInterruptionKey] = nil; nInterruptedEvents = nInterruptedEvents - 1; rInterruptedEvent.rEventDefinition.fResume(rInterruptedEvent.rEventData); --TODO how to deal with trigger and index data? -- best to avoid stateful globals where possible and maintain an execution chain. -- perhaps optional variables that get passed on through to fireEvent? end
--地葬星カイザ -- --Script by Trishula9 function c101107022.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_HAND) e1:SetCountLimit(1,101107022+EFFECT_COUNT_CODE_OATH) e1:SetCondition(c101107022.spcon) e1:SetOperation(c101107022.spop) c:RegisterEffect(e1) --to grave local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(101107022,0)) e2:SetCategory(CATEGORY_TOGRAVE) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1,101107022+100) e2:SetCost(c101107022.tgcost) e2:SetTarget(c101107022.tgtg) e2:SetOperation(c101107022.tgop) c:RegisterEffect(e2) end function c101107022.spfilter(c,tp) return c:IsRace(RACE_WARRIOR) and c:IsAttribute(ATTRIBUTE_LIGHT|ATTRIBUTE_EARTH) and c:IsFaceup() and Duel.GetMZoneCount(tp,c)>0 end function c101107022.spcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.CheckReleaseGroup(tp,c101107022.spfilter,1,nil) end function c101107022.spop(e,tp,eg,ep,ev,re,r,rp,c) local g=Duel.SelectReleaseGroup(tp,c101107022.spfilter,1,1,nil) Duel.Release(g,REASON_COST) c:RegisterFlagEffect(0,RESET_EVENT+0x4fc0000,EFFECT_FLAG_CLIENT_HINT,1,0,aux.Stringid(101107022,1)) local atk=g:GetFirst():GetBaseAttack() if atk<0 then return end local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(atk) e1:SetReset(RESET_EVENT+0xff0000) c:RegisterEffect(e1) end function c101107022.rmfilter(c) return c:IsRace(RACE_WARRIOR) and c:IsAbleToRemoveAsCost() end function c101107022.tgcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c101107022.rmfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c101107022.rmfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c101107022.tgfilter(c) return c:IsRace(RACE_WARRIOR) and c:IsAttribute(ATTRIBUTE_LIGHT|ATTRIBUTE_EARTH) and c:IsAbleToGrave() end function c101107022.tgtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c101107022.tgfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK) end function c101107022.tgop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c101107022.tgfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoGrave(g,REASON_EFFECT) end end
local scene = storyboard.newScene() local app = require('lib.app') local api = app.api local vec3 = require('lib.vec3') local s = 250 local function position3d(v) return s * v.x / v.z + _CX, s * v.y / v.z + _CY end local function dot(group, pos, color) local c = display.newCircle(group, 0, 0, 3) if color then c:setFillColor(unpack(color)) else c:setFillColor(1, 0, 0) end c.pos = pos c.rot = {0, 0, 0} c.isDot = true return c end local function newPlane(group) local plane = display.newSprite(group, graphics.newImageSheet('images/plane.png', {width = 100, height = 100, numFrames = 9, sheetContentWidth = 300, sheetContentHeight = 300}),{ name = 'normal', start = 1, count = 9 }) plane.horizont, plane.vertical = 0, 0 function plane:setOrientation() self:setFrame(5 + self.horizont + 3 * self.vertical) end plane:setFrame(5) return plane end local function newSlicedImage(filename, params) local n = params.numSlices or 2 local rp = params.rp local sw = math.floor(params.w / n) local sh = math.floor(params.h / n) local sheet = graphics.newImageSheet(filename, {width = sw, height = sh, numFrames = n * n, sheetContentWidth = params.w, sheetContentHeight = params.h}) local slicedImage = {numSlices = n, map = {}, pos = vec3(0, 0, 0)} local slices = {} local ind, s for y = 1, n do for x = 1, n do ind = x + (y - 1) * n s = display.newImage(params.g, sheet, ind) if rp then app.setRP(s, rp) end s.mX, s.mY = x - 1, y - 1 s.pivot = slicedImage slices[ind] = s end end function slicedImage:toFront() for i = 1, #slices do slices[i]:toFront() end end function slicedImage.__newindex(t, key, value) if key == 'isVisible' then for i = 1, #slices do slices[i].isVisible = value end elseif key == 'faceSize' then for i = 1, #slices do slices[i].faceSize = value / n end end end setmetatable(slicedImage, slicedImage) return slicedImage end local function newCube(group) local cube = {} local back, front, left, right, up, down local n = 4 local s = 1024 local box = 'images/box2/' back = newSlicedImage(box .. 'back-z.png', {g = group, w = s, h = s, numSlices = n, rp = 'TopLeft'}) left = newSlicedImage(box .. 'left-x.png', {g = group, w = s, h = s, numSlices = n, rp = 'TopLeft'}) right = newSlicedImage(box .. 'right+x.png', {g = group, w = s, h = s, numSlices = n, rp = 'TopLeft'}) up = newSlicedImage(box .. 'up-y.png', {g = group, w = s, h = s, numSlices = n, rp = 'TopLeft'}) down = newSlicedImage(box .. 'down+y.png', {g = group, w = s, h = s, numSlices = n, rp = 'TopLeft'}) front = newSlicedImage(box .. 'front+z.png', {g = group, w = s, h = s, numSlices = n, rp = 'TopLeft'}) local faces = {back, front, left, right, up, down} cube.back, cube.front, cube.left, cube.right, cube.up, cube.down = back, front, left, right, up, down front.isVisible = false back.faceSize = s front.faceSize = s left.faceSize = s right.faceSize = s down.faceSize = s up.faceSize = s local dots = {} local d = 1/n for x = 0, n do for y = 0, n do back.map[x + y * (n + 1)] = vec3((x * d - 0.5) * 2, (y * d - 0.5) * 2, 1) dots[#dots + 1] = dot(group, back.map[x + y * (n + 1)], {0, 1, 0}) end end for x = 0, n do for y = 0, n do front.map[x + y * (n + 1)] = vec3(((n - x) * d - 0.5) * 2, (y * d - 0.5) * 2, -1) end end for z = 0, n do for y = 0, n do left.map[z + y * (n + 1)] = vec3(-1, (y * d - 0.5) * 2, (z * d - 0.5) * 2) end end for z = 0, n do for y = 0, n do right.map[z + y * (n + 1)] = vec3(1, (y * d - 0.5) * 2, ((n - z) * d - 0.5) * 2) end end for x = 0, n do for z = 0, n do down.map[x + z * (n + 1)] = vec3((x * d - 0.5) * 2, 1, ((n - z) * d - 0.5) * 2) end end for x = 0, n do for z = 0, n do up.map[x + z * (n + 1)] = vec3((x * d - 0.5) * 2, -1, (z * d - 0.5) * 2) end end dots[#dots + 1] = dot(group, vec3(-1, -1, -1)) dots[#dots + 1] = dot(group, vec3(1, -1, -1)) dots[#dots + 1] = dot(group, vec3(-1, -1, 1)) dots[#dots + 1] = dot(group, vec3(1, -1, 1)) dots[#dots + 1] = dot(group, vec3(-1, 1, -1)) dots[#dots + 1] = dot(group, vec3(1, 1, -1)) dots[#dots + 1] = dot(group, vec3(-1, 1, 1)) dots[#dots + 1] = dot(group, vec3(1, 1, 1)) function cube:rotate(axis, angle) local f, map for i = 1, #faces do f = faces[i] map = f.map for j = 0, #f.map do f.map[j] = f.map[j]:rot_around(axis, angle) end f.pos = f.pos:rot_around(axis, angle) end self:zOrder() local d for i = 1, #dots do d = dots[i] d.pos = d.pos:rot_around(axis, angle) d:toFront() end end local tSort = table.sort function cube:zOrder() tSort(faces, function(a, b) return a.pos.z < b.pos.z end) for i = #faces, 1, -1 do faces[i]:toFront() end end return cube end function scene:render() local group = self.view local obj for i = 1, group.numChildren do obj = group[i] if obj.isDot then if obj.pos.z < 0 or not self.showDots then obj.isVisible = false else obj.isVisible = true obj.x, obj.y = position3d(obj.pos) end elseif obj.mX then local map = obj.pivot.map local mX, mY = obj.mX, obj.mY local n = obj.pivot.numSlices + 1 local topLeft = map[mX + mY * n] local bottomLeft = map[mX + (mY + 1) * n] local bottomRight = map[mX + 1 + (mY + 1) * n] local topRight = map[mX + 1 + mY * n] if topLeft.z < 0 or bottomLeft.z < 0 or bottomRight.z < 0 or topRight.z < 0 then obj.isVisible = false else local path = obj.path local s = obj.faceSize obj.isVisible = true local x, y x, y = position3d(topLeft) path.x1, path.y1 = x, y x, y = position3d(bottomLeft) path.x2, path.y2 = x, y - s x, y = position3d(bottomRight) path.x3, path.y3 = x - s, y - s x, y = position3d(topRight) path.x4, path.y4 = x - s, y end elseif obj.isBullet then if obj.pos.z < 0 then obj.isVisible = false else obj.isVisible = true obj.x, obj.y = position3d(obj.pos) obj.xScale = 1 / obj.pos.z obj.yScale = obj.xScale end end end for i = 1, #self.bullets do self.bullets[i]:toFront() end self.plane:toFront() end local gun_sound = audio.loadSound('sounds/gun.wav') function scene:fire() local group = self.view local bullet = app.newImage('images/bullet.png', {g = group, w = 32, h = 32}) bullet.pos = vec3(0, 0.05, 0.3) bullet.x, bullet.y = position3d(bullet.pos) bullet.isBullet = true bullet.blendMode = 'add' bullet:rotate(math.random(0, 360)) table.insert(self.bullets, bullet) audio.play(gun_sound) timer.performWithDelay(1, function() bullet.pos = bullet.pos + bullet.pos:unit() * 0.04 + vec3(0, -0.002, 0) end, 300) timer.performWithDelay(5000, function() table.remove(self.bullets, table.indexOf(self.bullets, bullet)) bullet:removeSelf() end) -- Having so many timers is not advices, better to have single enterFrame function which does all the stuff end function scene:rotate(axis, angle) self.cube:rotate(axis, angle) for i = 1, #self.bullets do self.bullets[i].pos = self.bullets[i].pos:rot_around(axis, angle) end end function scene:createScene (event) local group = self.view local stage = display.getCurrentStage() local r = display.newRect(group, _L, _T, _R - _L, _B - _T) r.x, r.y = _CX, _CY self.cube = newCube(group) self.plane = newPlane(group) self.plane.x, self.plane.y = _CX, _H - 100 self.bullets = {} local function navigationControl() if self.kW then self:rotate(vec3(1, 0, 0), -0.01) end if self.kA then self:rotate(vec3(0, 1, 0), 0.01) end if self.kS then self:rotate(vec3(1, 0, 0), 0.01) end if self.kD then self:rotate(vec3(0, 1, 0), -0.01) end self:render() end self.t = timer.performWithDelay(1, navigationControl, 0) local function keyListener(event) local key = event.keyName local down = event.phase == 'down' if key == 'w' then self.kW = down if down then self.plane.vertical = 1 else self.plane.vertical = 0 end elseif key == 'a' then self.kA = down if down then self.plane.horizont = -1 else self.plane.horizont = 0 end elseif key == 's' then self.kS = down if down then self.plane.vertical = -1 else self.plane.vertical = 0 end elseif key == 'd' then self.kD = down if down then self.plane.horizont = 1 else self.plane.horizont = 0 end elseif key == ' ' or key == 'space' then if down then if not self.fireTimer then self.fireTimer = timer.performWithDelay(100, function() self:fire() end, 0) end else timer.cancel(self.fireTimer) self.fireTimer = nil end elseif key == 't' and down then self.showDots = not self.showDots end self.plane:setOrientation() end Runtime:addEventListener('key', keyListener) -- remove listener on scene exit end function scene:didExitScene() timer.cancel(self.t) storyboard.removeScene('scenes.demo') end scene:addEventListener('didExitScene', scene) scene:addEventListener('createScene', scene) return scene
-- Definition of the Graph class. local Object = require "lib/classic" local GraphNode = require "engine/pathfinding/graphnode" local GraphEdge = require "engine/pathfinding/graphedge" local Graph = Object:extend() -------------------------------------------------------------------------------- -- Instantiate a new Graph object. -------------------------------------------------------------------------------- function Graph:new() self.nodes = {} self.edges = {} end -------------------------------------------------------------------------------- -- Create a copy the the Graph. -- @returns The copy. -------------------------------------------------------------------------------- function Graph:clone() local new_graph = Graph() for i, v in ipairs(self.nodes) do table.insert(new_graph.nodes, v:clone()) end for i, v in ipairs(self.edges) do table.insert(new_graph.edges, {}) for _, v2 in ipairs(v) do table.insert(new_graph.edges[i], v2:clone()) end end return new_graph end -------------------------------------------------------------------------------- -- Retrieve the edge between two nodes. -- @param from Index of the node from which the edge starts. -- @param to Index of the node to which the edge goes. -- @returns The edge if it exists, nil otherwise. -------------------------------------------------------------------------------- function Graph:getEdge(from, to) local from_edges = self.edges[from] for _, edge in ipairs(from_edges) do if edge.to == to then return edge end end return nil end -------------------------------------------------------------------------------- -- Add a node to the graph. -- @param node The node to add to the graph. -------------------------------------------------------------------------------- function Graph:addNode(node) table.insert(self.nodes, node) table.insert(self.edges, {}) end -------------------------------------------------------------------------------- -- Add an edge to the graph. -- @param edge The edge to add to the graph. -------------------------------------------------------------------------------- function Graph:addEdge(edge) if self:getEdge(edge.from, edge.to) == nil then table.insert(self.edges[edge.from], edge) end if self:getEdge(edge.to, edge.from) == nil then table.insert(self.edges[edge.to], GraphEdge(edge.to, edge.from, edge.cost)) end end return Graph
local utils = {} -- Check http://www.lua.org/pil/12.1.1.html -- for more information function utils.serialize(o) -- TODO: We should make an optimistic tostring call -- and check if it errors, instead of just giving -- an error anyways if type(o) == "number" then return string.format("%d", o), nil elseif type(o) == "string" then return string.format("%q", o), nil elseif type(o) == "table" then s = "{\n" for k, v in pairs(o) do c, err = utils.serialize(v) if err then return nil, err end s = s .. string.format(" %s = %s,\n", k, c) end s = s .. "}" return s, nil elseif type(o) == "boolean" then return tostring(o), nil else return nil, "cannot serialize a " .. type(o) end end return utils
loot_crates = {} loot_crates.ent = {} -- Inventory -- minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "loot_crates:loot_crate_common" then local name = player:get_player_name() local ent = loot_crates.ent[name] if ent and ent:get_luaentity() then ent = ent:get_luaentity() local inv = minetest.get_inventory({type = "detached", name = "loot_crate_common"}) local table = {} local inv_size = inv:get_size("loot_crate_common_inv") if inv_size > 0 then for i = 1, inv_size do table[i] = inv:get_stack("loot_crate_common_inv", i):to_table() end ent.loot_table = mobkit.remember(ent, "loot_table", table) end end return true elseif formname == "loot_crates:loot_crate_uncommon" then local name = player:get_player_name() local ent = loot_crates.ent[name] if ent and ent:get_luaentity() then ent = ent:get_luaentity() local inv = minetest.get_inventory({type = "detached", name = "loot_crate_uncommon"}) local table = {} local inv_size = inv:get_size("loot_crate_uncommon_inv") if inv_size > 0 then for i = 1, inv_size do table[i] = inv:get_stack("loot_crate_uncommon_inv", i):to_table() end ent.loot_table = mobkit.remember(ent, "loot_table", table) end end return true elseif formname == "loot_crates:loot_crate_rare" then local name = player:get_player_name() local ent = loot_crates.ent[name] if ent and ent:get_luaentity() then ent = ent:get_luaentity() local inv = minetest.get_inventory({type = "detached", name = "loot_crate_rare"}) local table = {} local inv_size = inv:get_size("loot_crate_rare_inv") if inv_size > 0 then for i = 1, inv_size do table[i] = inv:get_stack("loot_crate_rare_inv", i):to_table() end ent.loot_table = mobkit.remember(ent, "loot_table", table) end end return true else return false end end) local function create_detached_inv(name) local inv = minetest.create_detached_inventory(name, { allow_move = function(inv, from_list, from_index, _, _, _, player) local stack = inv:get_stack(from_list, from_index) return 0 end, allow_put = function(_, _, _, stack) return 0 end, allow_take = function(_, _, _, stack) return stack:get_count() end, }) inv:set_size(name .. "_inv", 3) inv:set_width(name .. "_inv", 3) end create_detached_inv("loot_crate_common") create_detached_inv("loot_crate_uncommon") create_detached_inv("loot_crate_rare") -- Loot registration -- loot_crates.common_loot = {} loot_crates.uncommon_loot = {} loot_crates.rare_loot = {} local function is_valid_rarity(str) local valid = { "common", "uncommon", "rare" } for i = 1, 3 do if str == valid[i] then return true end end return false end function loot_crates.register_loot(rarity, loot) if not is_valid_rarity(rarity) then return end if loot.name and type(loot.name) == "string" and loot.max_count and type(loot.max_count) == "number" then table.insert(loot_crates[rarity .. "_loot"], {name = loot.name, max_count = loot.max_count}) end end if minetest.get_modpath("default") then loot_crates.register_loot("common", {name = "default:stick", max_count = 14}) loot_crates.register_loot("common", {name = "default:torch", max_count = 99}) loot_crates.register_loot("common", {name = "default:cobble", max_count = 48}) loot_crates.register_loot("uncommon", {name = "default:steel_ingot", max_count = 12}) loot_crates.register_loot("uncommon", {name = "default:gold_ingot", max_count = 8}) loot_crates.register_loot("uncommon", {name = "default:copper_ingot", max_count = 8}) loot_crates.register_loot("uncommon", {name = "binoculars:binoculars", max_count = 1}) loot_crates.register_loot("rare", {name = "default:diamond", max_count = 4}) loot_crates.register_loot("rare", {name = "default:mese_crystal", max_count = 4}) end local function update_emission(self, texture, overlay) local pos = self.object:get_pos() local level = minetest.get_node_light(pos, minetest.get_timeofday()) if not level then return end local color = math.ceil(level / minetest.LIGHT_MAX * 255) if color > 255 then color = 255 end local modifier = ("^[multiply:#%02X%02X%02X"):format(color, color, color) self.object:set_properties({ textures = {"(" .. texture .. modifier .. ")^" .. overlay} }) end minetest.register_entity("loot_crates:common", { hp_max = 1, physical = true, collisionbox = {-0.25, 0, -0.25, 0.25, 0.5, 0.25}, visual = "mesh", visual_size = {x = 6.5, y = 6.5}, mesh = "loot_crates_mesh.b3d", textures = {"loot_crates_bg.png"}, glow = 16, makes_footstep_sound = false, get_staticdata = mobkit.statfunc, logic = function(self) if mobkit.timer(self, 1) then minetest.add_particle({ pos = self.object:get_pos(), velocity = {x = 0, y = 10, z = 0}, acceleration = {x = 0, y = 20, z = 0}, expirationtime = 6, size = 6, collisiondetection = false, vertical = false, glow = 16, texture = "loot_crates_green_beacon.png" }) end end, physics = function(self) end, on_step = function(self, dtime, moveresult) mobkit.stepfunc(self, dtime, moveresult) update_emission(self, "loot_crates_bg.png", "loot_crates_green.png") local remove = true if #self.loot_table < 1 then minetest.add_particlespawner({ amount = math.random(4, 6), time = 0.25, minpos = self.object:get_pos(), maxpos = self.object:get_pos(), minvel = vector.new(-1, 1, -1), maxvel = vector.new(1, 2, 1), minacc = vector.new(0, -9.81, 0), maxacc = vector.new(0, -9.81, 0), minsize = 1, maxsize = 1.5, collisiondetection = true, glow = 16, texture = "loot_crates_green_beacon.png" }) self.object:remove() end end, on_activate = function(self, dtime, staticdata) mobkit.actfunc(self, dtime, staticdata) self.object:set_animation({x = 0, y = 60}, 10, 0, true) self.loot_table = mobkit.recall(self, "loot_table") or {} self.loot_init = mobkit.recall(self, "loot_init") or false if not self.loot_init then for i = 1, 3 do local random = math.random(#loot_crates.common_loot) local loot = loot_crates.common_loot[random] self.loot_table[i] = {name = loot.name, count = math.random(loot.max_count), wear=0, metadata=""} end self.loot_table = mobkit.remember(self, "loot_table", self.loot_table) self.loot_init = mobkit.remember(self, "loot_init", true) end end, on_rightclick = function(self, clicker) loot_crates.ent[clicker:get_player_name()] = self.object local inv = minetest.get_inventory({type = "detached", name = "loot_crate_common"}) inv:set_list("loot_crate_common_inv", {}) for k, v in pairs(self.loot_table) do inv:set_stack("loot_crate_common_inv", k, v) end local formspec = { "size[8, 8;]", "label[3,0;Common Loot Crate]", "list[detached:loot_crate_common;loot_crate_common_inv;2.5,1;3,2;]", "list[current_player;main;0,4;8,4;]" } minetest.show_formspec(clicker:get_player_name(), "loot_crates:loot_crate_common", table.concat(formspec)) end }) minetest.register_entity("loot_crates:uncommon", { hp_max = 1, physical = true, collisionbox = {-0.25, 0, -0.25, 0.25, 0.5, 0.25}, visual = "mesh", visual_size = {x = 6.5, y = 6.5}, mesh = "loot_crates_mesh.b3d", textures = {"loot_crates_bg.png"}, glow = 16, makes_footstep_sound = false, get_staticdata = mobkit.statfunc, logic = function(self) end, physics = function(self) end, on_step = function(self, dtime, moveresult) mobkit.stepfunc(self, dtime, moveresult) update_emission(self, "loot_crates_bg.png", "loot_crates_blue.png") if mobkit.timer(self, 3) then minetest.add_particle({ pos = self.object:get_pos(), velocity = {x = 0, y = 10, z = 0}, acceleration = {x = 0, y = 20, z = 0}, expirationtime = 6, size = 4, collisiondetection = false, vertical = false, glow = 16, texture = "loot_crates_blue_beacon.png" }) end local remove = true if #self.loot_table < 1 then minetest.add_particlespawner({ amount = math.random(4, 6), time = 0.25, minpos = self.object:get_pos(), maxpos = self.object:get_pos(), minvel = vector.new(-1, 1, -1), maxvel = vector.new(1, 2, 1), minacc = vector.new(0, -9.81, 0), maxacc = vector.new(0, -9.81, 0), minsize = 1, maxsize = 1.5, collisiondetection = true, glow = 16, texture = "loot_crates_blue_beacon.png" }) self.object:remove() end end, on_activate = function(self, dtime, staticdata) mobkit.actfunc(self, dtime, staticdata) self.object:set_animation({x = 1, y = 59}, 10, 0, true) self.loot_table = mobkit.recall(self, "loot_table") or {} self.loot_init = mobkit.recall(self, "loot_init") or false if not self.loot_init then for i = 1, 3 do local random = math.random(#loot_crates.uncommon_loot) local loot = loot_crates.uncommon_loot[random] self.loot_table[i] = {name = loot.name, count = math.random(loot.max_count), wear=0, metadata=""} end self.loot_table = mobkit.remember(self, "loot_table", self.loot_table) self.loot_init = mobkit.remember(self, "loot_init", true) end end, on_rightclick = function(self, clicker) loot_crates.ent[clicker:get_player_name()] = self.object local inv = minetest.get_inventory({type = "detached", name = "loot_crate_uncommon"}) inv:set_list("loot_crate_uncommon_inv", {}) for k, v in pairs(self.loot_table) do inv:set_stack("loot_crate_uncommon_inv", k, v) end local formspec = { "size[8, 8;]", "label[3,0;Uncommon Loot Crate]", "list[detached:loot_crate_uncommon;loot_crate_uncommon_inv;2.5,1;3,2;]", "list[current_player;main;0,4;8,4;]" } minetest.show_formspec(clicker:get_player_name(), "loot_crates:loot_crate_uncommon", table.concat(formspec)) end }) minetest.register_entity("loot_crates:rare", { hp_max = 1, physical = true, collisionbox = {-0.25, 0, -0.25, 0.25, 0.5, 0.25}, visual = "mesh", visual_size = {x = 6.5, y = 6.5}, mesh = "loot_crates_mesh.b3d", textures = {"loot_crates_bg.png"}, glow = 16, makes_footstep_sound = false, get_staticdata = mobkit.statfunc, logic = function(self) end, physics = function(self) end, on_step = function(self, dtime, moveresult) mobkit.stepfunc(self, dtime, moveresult) update_emission(self, "loot_crates_bg.png", "loot_crates_red.png") if mobkit.timer(self, 6) then minetest.add_particle({ pos = self.object:get_pos(), velocity = {x = 0, y = 10, z = 0}, acceleration = {x = 0, y = 20, z = 0}, expirationtime = 6, size = 2, collisiondetection = false, vertical = false, glow = 16, texture = "loot_crates_red_beacon.png" }) end local remove = true if #self.loot_table < 1 then minetest.add_particlespawner({ amount = math.random(4, 6), time = 0.25, minpos = self.object:get_pos(), maxpos = self.object:get_pos(), minvel = vector.new(-1, 1, -1), maxvel = vector.new(1, 2, 1), minacc = vector.new(0, -9.81, 0), maxacc = vector.new(0, -9.81, 0), minsize = 1, maxsize = 1.5, collisiondetection = true, glow = 16, texture = "loot_crates_red_beacon.png" }) self.object:remove() end end, on_activate = function(self, dtime, staticdata) mobkit.actfunc(self, dtime, staticdata) self.object:set_animation({x = 1, y = 59}, 10, 0, true) self.loot_table = mobkit.recall(self, "loot_table") or {} self.loot_init = mobkit.recall(self, "loot_init") or false if not self.loot_init then for i = 1, 3 do local random = math.random(#loot_crates.rare_loot) local loot = loot_crates.rare_loot[random] self.loot_table[i] = {name = loot.name, count = math.random(loot.max_count), wear=0, metadata=""} end self.loot_table = mobkit.remember(self, "loot_table", self.loot_table) self.loot_init = mobkit.remember(self, "loot_init", true) end end, on_rightclick = function(self, clicker) loot_crates.ent[clicker:get_player_name()] = self.object local inv = minetest.get_inventory({type = "detached", name = "loot_crate_rare"}) inv:set_list("loot_crate_rare_inv", {}) for k, v in pairs(self.loot_table) do inv:set_stack("loot_crate_rare_inv", k, v) end local formspec = { "size[8, 8;]", "label[3,0;Rare Loot Crate]", "list[detached:loot_crate_rare;loot_crate_rare_inv;2.5,1;3,2;]", "list[current_player;main;0,4;8,4;]" } minetest.show_formspec(clicker:get_player_name(), "loot_crates:loot_crate_rare", table.concat(formspec)) end }) mob_core.register_spawn({ name = "loot_crates:common", nodes = {}, min_light = 0, max_light = 15, min_height = 1, max_height = 1024, min_rad = 24, max_rad = 256, group = 0, }, 300, 15) mob_core.register_spawn({ name = "loot_crates:uncommon", nodes = {}, min_light = 0, max_light = 15, min_height = -1024, max_height = 1, min_rad = 24, max_rad = 256, group = 0, }, 300, 20) mob_core.register_spawn({ name = "loot_crates:rare", nodes = {}, min_light = 0, max_light = 15, min_height = -31000, max_height = -1024, min_rad = 24, max_rad = 256, group = 0, }, 300, 25)
local packer local function init() if packer == nil then packer = require('packer') packer.init({ compile_path = vim.fn.stdpath('config') .. '/lua/packer_compiled.lua', disable_commands = true, display = { open_fn = require('packer.util').float, keybindings = { quit = '<Esc>', }, } }) end packer.reset() for _, name in pairs { 'all', } do packer.use(require('plugin.'..name)) end end return setmetatable({}, { __index = function(_, key) init() return packer[key] end, })
-- rocket.lua require "rocket/tank" require "rocket/engine" local anim8 = require "liberies/anim8" -- Properties -- Static -- image => the rocket image -- dynamic -- x,y => cords -- xyvel = 0 Rocket = {} Rocket.__index = Rocket local ANGACCEL = 4 setmetatable(Rocket, { __call = function (cls, ...) local self = setmetatable({}, cls) self:_init(...) return self end, }) -- -- image = love.image type == default is nil -- x,y of top left == default is 0 -- function Rocket:_init(image, x, y, world, firePNG) self.image = image self.firePNG =firePNG self.body = love.physics.newBody( world, x, y, "dynamic" ) self.shape = love.physics.newRectangleShape( self.image:getWidth(), self.image:getHeight() ) self.fixture = love.physics.newFixture( self.body, self.shape, 1 ) self.tank = Tank() self.engine = Engine() local g16 = anim8.newGrid(16, 16, firePNG:getWidth(), firePNG:getHeight()) self.fireAnimation = anim8.newAnimation(g16('1-5',1), 0.1) end function Rocket:update(dt) velx, vely = self.body:getLinearVelocity( ) if vely <= 25 then accs = self.engine:use(self.tank) local angle = self.body:getAngle() local xf = math.cos(angle) * accs local yf = math.sin(angle) * accs self.body:applyForce(yf, -xf) end if self.tank then self.tank:update() end if self.needToTurnLeft then self:left(dt) end if self.needToTurnRight then self:right(dt) end self.fireAnimation:update(dt) end function Rocket:right(dt) -- rotate clockwise self.body:applyTorque(10000) end function Rocket:left(dt) -- rotate unclockwise self.body:applyTorque(-10000) end function Rocket:touchpressed(id, x) width = love.graphics.getWidth() if x <= width/2 then self.needToTurnLeft = true else self.needToTurnRight = true end end function Rocket:touchreleased(id) self.needToTurnLeft = false self.needToTurnRight = false end function Rocket:draw() love.graphics.setColor(255, 255, 255, 255) add1,add2 = self.body:getWorldCenter() love.graphics.draw(self.image,add1,add2,self.body:getAngle(),1,1,self.image:getWidth()/2,self.image:getHeight()/2) self.fireAnimation:draw(self.firePNG,add1,add2,self.body:getAngle(),2,2,self.image:getWidth()/8-2,-(self.image:getHeight()/4-4)) if self.tank then self.tank:draw() end end
-- -- Copyright (c) 2017 Milos Tosic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- function projectDependencies_rqt() return { "rdebug", "rbase" } end function projectAdd_rqt() addProject_qt("rqt", true) end
-- Simple script for testing porpuses of "librs232-luajit" -- read from the port local rs232 = require("mod_librs232") port = rs232.new() -- Arguments: -- Device name, Baud rate, Timeout in micro-seconds port:open("/dev/ttyUSB0", 115200, 10000) count, data = port:read() print(data) port:close() -- write to port local rs232 = require("./librs232-luajit-master/mod_librs232") port = rs232.new() -- Arguments: -- Device name, Baud rate, Timeout in micro-seconds port:open("/dev/ttyS0", 115200, 10000) print("/n open succ") data="Please or your string" port:write(data:byte(1,data:len(str)),data:len(str)) port:close() print("/n close succ")
--radio.lua local Widget = require("euler.widget") local Radio = class(Widget) local prop = property(Radio) prop:accessor("group", nil) prop:accessor("value", nil) prop:accessor("checked", true, true) function Radio:__init(id, checked) self.checked = checked self.root = gui.get_node(id .. "/radio") self.label = gui.get_node(id .. "/label") self.capture = gui.get_node(id .. "/radio") self:add_child("checked", gui.get_node(id .. "/checked")) self:add_child("unchecked", gui.get_node(id .. "/unchecked")) self:on_prop_changed(checked) end function Radio:setup(euler) local size = gui.get_size(self.root) for _, child in pairs(self.childrens) do gui.set_size(child, size) end local pos = gui.get_position(self.label) pos.x = size.x + 5 gui.set_position(self.label, pos) end function Radio:on_prop_changed(checked) self:show_child(checked and "checked" or "unchecked") if checked and self.group then self.group:changed(self) end end function Radio:on_lbutton_up(action) self:set_checked(true) return false end return Radio
local charWidth = 40 local alphabet_character_mt = { __index = { create_actors = function(self, name) self.name=name local af = Def.ActorFrame{ Name=name, InitCommand=function(subself) self.container = subself subself:diffusealpha(0) subself:MaskDest() end, OnCommand=function(self) self:linear(0.25):diffusealpha(1) end, HideCommand=function(self) self:linear(0.25):diffusealpha(0) end, Def.BitmapText{ Font="_roboto Bold 80px", InitCommand=function(subself) self.bmt = subself subself:zoom(0.5) subself:diffuse(0.75,0.75,0.75,1) end, OnCommand=function(self) self:sleep(0.2):linear(0.25) end, } } return af end, transform = function(self, item_index, num_items, has_focus) self.container:finishtweening() if item_index <= 0 or item_index >= num_items-1 then self.container:diffusealpha(0) else self.container:diffusealpha(1) end if has_focus then self.bmt:diffuse(1,1,1,1) else self.bmt:diffuse(0.75,0.75,0.75,1) end self.container:linear(0.075) self.container:x(charWidth * (item_index - math.ceil(num_items/2))) end, set = function(self, character) if not character then return end self.bmt:settext( character ) end } } return alphabet_character_mt
local sexfeel_cds = {} gpay.boosters = { ["HP250"] = function(ply) ply:SetHealth(250) end, ["AR228"] = function(ply) ply:SetArmor(250) end, ["DJUMP"] = function(ply) ply:SetJumpPower(ply:GetJumpPower()*2) end, ["FEEL"] = function(ply) if sexfeel_cds[ply:SteamID()] and CurTime() < sexfeel_cds[ply:SteamID()] then gpay.Notify(ply,Color(255,255,255),"Шестое чувство можно активировать раз в час") return end ply:SendLua"ad_sexfeel()" sexfeel_cds[ply:SteamID()] = CurTime() + 3600 ply.sexfeel = true end, ["PROPS"] = function(ply) if ply.addproplimit then return end ply.addproplimit = 40 end, ["HUNGRY"] = function(ply) if ply.antihungry then return end ply:HFM_SetHunger(100) ply.antihungry = true end, } povish = { -- ["user"] = "vip", ["vip"] = "vip+", ["vip+"] = "moderator", ["moderator"] = "admin", ["admin"] = "adminl1", ["adminl1"] = "adminl2", ["adminl2"] = "adminl3", ["adminl3"] = "adminl4", ["adminl4"] = "premadmin", ["premadmin"] = "owner" } function groupup(ply) ply:AdvancedSetUserGroup(povish[string.lower(ply:GetUserGroup())]) ply:SetNetVar("DonateUserGroupExpires",0) gpay.mysql.WriteVarServers(ply:SteamID64(),"mpdonate_groups","usergroup",sql.SQLStr(ply:GetUserGroup())) gpay.mysql.WriteVarServers(ply:SteamID64(),"mpdonate_groups","expires",0) end local function stop() hook.Remove("EntityTakeDamage", "Jopa v govne1") timer.Destroy("Mamka Johnny Sdohla1") for k,v in pairs(ents.GetAll()) do if v.pidorasObossaniy then v:Remove() end end BroadcastLua([[ zbremove1() ]]) concommand.Remove("stop_combine_sas") end function zbstart1() local zombs, pos, cops = 5, nil, {} for k,v in pairs(player.GetAll()) do if v:IsCP() then table.insert(cops, v) end end if #cops == 0 then pos = table.Random{ Vector(3420, 1241, 94), Vector(1121, 1779, 92), Vector(1104, 155, 117), Vector(-173, -1181, 111), Vector(1935, -1317, 107), Vector(3418, 169, 100) } else pos = table.Random(cops):GetPos() end timer.Create("ZombieSas", 10, 5, function() local comb = ents.Create( 'npc_combine_s' ) comb:SetPos( util.FindEmptyPos(pos) ) comb:Spawn() comb:Activate() comb:SetHealth(7000) comb:Give'weapon_ar2' comb.pidorasObossaniy = true end) BroadcastLua"zbstart1()" local function win(pl, zb) pl:AddMoney(50000) pl:Notify(0, "Ты победил Бери 50 00$") zombs = zombs - 1 zb:Remove() if zombs == 0 then stop() end end hook.Add("EntityTakeDamage", "Jopa v govne1", function(ent, dmg) local att = dmg:GetAttacker() if att.pidorasObossaniy then dmg:SetDamage(45) return end if !IsValid(att) or !att:IsPlayer() or !ent.pidorasObossaniy then return end if att:GetActiveWeapon():GetClass() == "swb_357_a" and !att:IsRoot() or att:GetBVar'adminmode' and !att:IsRoot() then att:Kill() dmg:SetDamage(0) return end if ent:Health() - dmg:GetDamage() < 1 then win(att, ent) end end) timer.Create("Mamka Johnny Sdohla1", 10, 0, function() local sas = math.random(0, 1) local zb for k,v in pairs(ents.GetAll()) do if v.pidorasObossaniy then zb = v end end if !zb then return end if sas == 0 then zb:SetColor(Color(255, 255, 255, math.random(50, 255))) zb:SetRenderMode( RENDERMODE_TRANSALPHA ) return end if sas == 1 then zb:SetModelScale(math.random(0.5, 2), 2) end end) concommand.Add("stop_combine_sas", function(p) if !p:IsRoot() then return end stop() end) end
--[[ MIT License Copyright (c) 2019-2021 Marco Lizza 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. ]]-- -- http://developer.classpath.org/doc/java/util/Collections-source.html -- FIXME: adopt build pattern and remove copies? local function map(array, callback) -- mapper(value, index, length, array) local result = {} local length = #array for index = 1, length do local value = array[index] result[index] = callback(value, index, length, array) end return result end local function filter(array, callback) -- filter(value, index, length, array) local result = {} local length = #array local n = 0 for index = 1, length do local value = array[index] if callback(value, index, length, array) then n = n + 1 result[n] = value end end return result end local function reduce(array, callback, initial_value) -- reducer(accumulator, value, index, length, array) local accumulator = initial_value local length = #array for index = 1, length do local value = array[index] if accumulator == nil then accumulator = value else accumulator = callback(accumulator, value, index, length, array) end end return accumulator end local function for_each(array, callback) -- callback(value, index, length, array) local length = #array for index = 1, length do local value = array[index] callback(value, index, length, array) end end local function every(array, callback) -- callback(value, index, length, array) local length = #array for index = 1, length do local value = array[index] if not callback(value, index, length, array) then return false, index end end return true, nil end local function some(array, callback) -- callback(value, index, length, array) local length = #array for index = 1, length do local value = array[index] if callback(value, index, length, array) then return true, index end end return false, nil end local function find(array, callback) -- callback(value, index, length, array) local length = #array for index = 1, length do local value = array[index] if callback(value, index, length, array) then return value, index end end return nil, nil end local function erase_if(array, callback) -- callback(value, index, length, array) local erased = 0 local length = #array for index = length, 1, -1 do local value = array[index] local erase, stop = callback(value, index, length, array) if erase then table.remove(array, index) erased = erased + 1 end if stop then break end end return erased end local function displace(array, callback) -- shuffle (?), rotate, reverse local result = {} local length = #array for index = 1, length do local value = array[index] result[callback(value, index, length, array)] = value end return result end local function generate(callback) local result = {} local index = 1 while true do local value = callback(index) if value == nil then break end result[index] = value index = index + 1 end return result end local function index_of(array, search, from) local length = #array for index = from or 1, length do local value = array[index] if value == search then return index end end return 0 end local function reversed(array) local result = {} local length = #array for index = 1, length do result[length - index + 1] = array[index] end return result end local function reverse(array) local length = #array for index = 1, math.floor(length / 2) do array[length - index + 1], array[index] = array[index], array[length - index + 1] end end local function rotated(array, amount) local result = {} local length = #array amount = amount % length -- Don't bail out for zero amount, since we need to copy the array! if amount < 0 then -- fix the amount if negative amount = amount + length end for index = 1, length do local value = array[index] local j = index + amount if j > length then j = j - length end result[j] = value end return result end local function rotate(array, amount) local length = #array amount = amount % length if amount == 0 then return end if amount < 0 then -- fix the amount if negative amount = amount + length end -- compute the least-common-multiple local a = length local lcm = amount local b = a % lcm while b ~= 0 do a = lcm lcm = b b = a % lcm end for i = 1, lcm do local aux = array[i] local j = i + amount while j ~= i do array[j], aux = aux, array[j] j = j + amount if j > length then j = j - length end end array[i] = aux end end local function shuffled(array) -- inside-out algorithm local result = {} for i = 1, #array do local j = math.random(i) if i ~= j then result[i] = result[j] end result[j] = array[i] end return result end local function shuffle(array) for i = #array, 2, -1 do local j = math.random(i) array[j], array[i] = array[i], array[j] end end local function uniqued(array) local result = {} local n = 0 local length = #array local previous = nil for index = 1, length do local current = array[index] if not previous or previous ~= current then n = n + 1 result[n] = current; end previous = current end return result end local function unique(array) local previous = nil for index = #array, 1, -1 do local current = array[index] if previous and previous == current then table.remove(array, index) end previous = current end end local function new(length, value) local result = {} for index = 1, length do result[index] = value or index - 1 end return result end local function equals(a, b) if a == b then return true end if not a or not b then return false end if #a ~= #b then return false end for index = 1, #a do if a[index] ~= b[index] then return false end end return true end local function copy(array, from, to) local result = {} local n = 0 for index = from or 1, to or #array do n = n + 1 result[n] = array[index] end return result end local function merge(a, b) local n = #a for index = 1, #b do n = n + 1 a[n] = b[index] end end local function merged(a, b) local result = {} local n = 0 for index = 1, #a do n = n + 1 a[n] = a[index] end for index = 1, #b do n = n + 1 a[n] = b[index] end return result end -- Naive implementation of insertion-sort which is stable and uber-efficient when the table is incrementally grown -- and re-sorted every time (that is, only the last item is_pressed eventually moved to the correct place). -- It's even faster than `table.sort()`. -- -- Note that's not Cormen-Leiserson-Rivest's optimized version, since it won't work with Lua's `for ...`. local function _lower_than(a, b) return a < b end local function sort(array, comparator) local lower_than = comparator or _lower_than local length = #array for i = 2, length do for j = i, 2, -1 do if not lower_than(array[j], array[j - 1]) then -- Preserve stability! Swap only if strictly lower-than! break end array[j - 1], array[j] = array[j], array[j - 1] -- Swap adjacent slots. end end end -- Add the element `item` to `array`, preserving the current ordering. Designed to be incrementally called to -- obtain an ever-ordered array of elements. local function add(array, item, comparator) local lower_than = comparator or _lower_than for index, other in ipairs(array) do if lower_than(item, other) then table.insert(array, index, item) return end end table.insert(array, item) end return { map = map, filter = filter, reduce = reduce, for_each = for_each, every = every, some = some, find = find, erase_if = erase_if, displace = displace, generate = generate, index_of = index_of, reversed = reversed, reverse = reverse, rotated = rotated, rotate = rotate, shuffled = shuffled, shuffle = shuffle, uniqued = uniqued, unique = unique, new = new, equals = equals, copy = copy, merge = merge, merged = merged, sort = sort, add = add }
object_tangible_tcg_series1_consumable_nuna_ball_advertisement = object_tangible_tcg_series1_shared_consumable_nuna_ball_advertisement:new { } ObjectTemplates:addTemplate(object_tangible_tcg_series1_consumable_nuna_ball_advertisement, "object/tangible/tcg/series1/consumable_nuna_ball_advertisement.iff")
local Event = require 'utils.event' local table = require 'utils.table' local Gui = require 'utils.gui' local Model = require 'utils.debug.model' local format = string.format local insert = table.insert local events = defines.events -- Constants local events_to_keep = 10 -- Local vars local Public = { name = 'Events' } local name_lookup = {} -- GUI names local checkbox_name = Gui.uid_name() -- global tables local enabled = {} local last_events = {} global.debug_event_view = { enabled = enabled, last_events = last_events } function Public.on_open_debug() local tbl = global.debug_event_view if tbl then enabled = tbl.enabled last_events = tbl.last_events else enabled = {} last_events = {} global.debug_event_view = { enabled = enabled, last_events = last_events } end Public.on_open_debug = nil end -- Local functions local function event_callback(event) local id = event.name if not enabled[id] then return end local name = name_lookup[id] if not last_events[name] then last_events[name] = {} end insert(last_events[name], 1, event) last_events[name][events_to_keep + 1] = nil event.name = nil local str = format('%s (id = %s): %s', name, id, Model.dump(event)) game.print(str) log(str) end local function on_gui_checked_state_changed(event) local element = event.element local name = element.caption local id = events[name] local state = element.state and true or false element.state = state if state then enabled[id] = true else enabled[id] = false end end -- GUI -- Create a table with events sorted by their names local grid_builder = {} for name, id in pairs(events) do grid_builder[id] = name end grid_builder[#grid_builder + 1] = grid_builder[0] grid_builder[0] = nil table.sort(grid_builder) function Public.show(container) local main_frame_flow = container.add({type = 'flow', direction = 'vertical'}) local scroll_pane = main_frame_flow.add({type = 'scroll-pane'}) local gui_table = scroll_pane.add({type = 'table', column_count = 3, draw_horizontal_lines = true}) for _, event_name in pairs(grid_builder) do local index = events[event_name] gui_table.add({type = 'flow'}).add { name = checkbox_name, type = 'checkbox', state = enabled[index] or false, caption = event_name } end end Gui.on_checked_state_changed(checkbox_name, on_gui_checked_state_changed) -- Event registers (TODO: turn to removable hooks.. maybe) for name, id in pairs(events) do name_lookup[id] = name Event.add(id, event_callback) end return Public
local curl = require "lcurl.safe" local json = require "cjson.safe" script_info = { ["title"] = "怡萱动漫", ["description"] = "http://www.yxdm.tv/", ["version"] = "0.0.1", } function request(url) local r = "" local c = curl.easy{ url = url, httpheader = { "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36", "Referer: http://www.yxdm.tv/", }, ssl_verifyhost = 0, ssl_verifypeer = 0, followlocation = 1, timeout = 15, proxy = pd.getProxy(), writefunction = function(buffer) r = r .. buffer return #buffer end, } local _, e = c:perform() c:close() return r end function onInitAnime() local data = request("http://www.yxdm.tv/") local anime_week = {} local week = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"} local sep = {"weektbc_01", "weektbc_02", "weektbc_03", "weektbc_04", "weektbc_05", "weektbc_06", "weektbc_07", "</ul>"} for i = 1, 7 do local _, _, tmp = string.find(data, sep[i].."(.-)"..sep[i+1]) local begin = 1 local anime_day = {["title"] = week[i]} while tmp do local _, b, name, id = string.find(tmp, '<A title="(.-)" href="/resource/(%d+).html"', begin) if id == nil then break end table.insert(anime_day, {["url"] = "http://www.yxdm.tv/getdlist.php?id="..id, ["name"] = name}) begin = b + 1 end table.insert(anime_week, anime_day) end return anime_week end function onSearch(keyword, page) local data = request("http://www.yxdm.tv/search.html?keyword="..pd.urlEncode(keyword).."&searchtype=titlekeyword&channeltype=0&orderby=&kwtype=0&pagesize=18&typeid=0&PageNo="..page) local result = {} local start = 1 while true do local _, b, title, id, img, desc, time = string.find(data, '<p><a title="([^"]+)" href="/resource/(%d+).html" target="_blank"><img src="(.-)">.-更新至:.->([^<>]+)</a>.-日期:.->([^<]+)</', start) if id == nil then break end if #img > 0 and string.byte(img) == 47 then img = "http://www.yxdm.tv"..img end table.insert(result, {["url"] = "http://www.yxdm.tv/getdlist.php?id="..id, ["title"] = pd.htmlUnescape(title), ["image"] = img, ["icon_size"] = "50,67", ["time"] = time, ["description"] = "更新至:"..desc}) start = b + 1 end return result end function onItemClick(item) local j = json.decode(request(item.url)) if j == nil or j.data == nil or #j.data == 0 or j.data[1].list == nil or #j.data[1].list == 0 or j.data[1].list[1].url == nil or #j.data[1].list[1].url == 0 then return ACT_ERROR, "获取资源失败" end return ACT_SHARELINK, pd.base64Decode(j.data[1].list[1].url) end
---------------------------------------- -- ioc.lua -- -- desc : io control -- -- rev : 1.0 -- -- date : 04/25/2021 -- -- author : tuan nguyen (pdxtigre) -- -- email : info@codesmiths.org -- -- website: https://codesmiths.org -- ---------------------------------------- local ioc = {MOD_NAME="ioc"} function ioc:init(cfg) log_debug("Initializing IO board..") for k,v in pairs(cfg.io.digital.outputs) do log_debug("Setting digital output "..v.pin) gpio.mode(v.pin, gpio.OUTPUT) gpio.write(v.pin, gpio.LOW) end for k,v in pairs(cfg.io.digital.inputs) do log_debug("Setting digital input "..v.pin) gpio.mode(v.pin, gpio.INPUT) end log_debug("IO board initialization complete") end function ioc:pin_on(cfg, name) local dig = cfg.io.digital.outputs[name] local pin = dig.pin dig.state=1 log_debug("Pin: "..tostring(pin).." HIGH") gpio.write(pin, gpio.HIGH) end function ioc:pin_off(cfg, name) local dig = cfg.io.digital.outputs[name] local pin = dig.pin dig.state=0 log_debug("Pin: "..tostring(pin).." LOW") gpio.write(pin, gpio.LOW) end flashMod(ioc)
local _2afile_2a = "fnl/conjure/mapping.fnl" local _2amodule_name_2a = "conjure.mapping" local _2amodule_2a do package.loaded[_2amodule_name_2a] = {} _2amodule_2a = package.loaded[_2amodule_name_2a] end local _2amodule_locals_2a do _2amodule_2a["aniseed/locals"] = {} _2amodule_locals_2a = (_2amodule_2a)["aniseed/locals"] end local autoload = (require("conjure.aniseed.autoload")).autoload local a, bridge, client, config, eval, extract, log, nvim, str, _ = autoload("conjure.aniseed.core"), autoload("conjure.bridge"), autoload("conjure.client"), autoload("conjure.config"), autoload("conjure.eval"), autoload("conjure.extract"), autoload("conjure.log"), autoload("conjure.aniseed.nvim"), autoload("conjure.aniseed.string"), nil _2amodule_locals_2a["a"] = a _2amodule_locals_2a["bridge"] = bridge _2amodule_locals_2a["client"] = client _2amodule_locals_2a["config"] = config _2amodule_locals_2a["eval"] = eval _2amodule_locals_2a["extract"] = extract _2amodule_locals_2a["log"] = log _2amodule_locals_2a["nvim"] = nvim _2amodule_locals_2a["str"] = str _2amodule_locals_2a["_"] = _ local function cfg(k) return config["get-in"]({"mapping", k}) end _2amodule_locals_2a["cfg"] = cfg local function vim_repeat(mapping) return ("repeat#set(\"" .. nvim.fn.escape(mapping, "\"") .. "\", 1)") end _2amodule_locals_2a["vim-repeat"] = vim_repeat local function buf(mode_or_opts, cmd_suffix, keys, ...) if keys then local function _2_(...) if ("table" == type(mode_or_opts)) then return {a.get(mode_or_opts, "mode"), mode_or_opts} else return {mode_or_opts, {}} end end local _let_1_ = _2_(...) local mode = _let_1_[1] local opts = _let_1_[2] local args = {...} local mapping if a["string?"](keys) then mapping = (cfg("prefix") .. keys) else mapping = a.first(keys) end local cmd = (cmd_suffix and ("Conjure" .. cmd_suffix)) if cmd then nvim.ex.command_(("-range " .. cmd), bridge["viml->lua"](unpack(args))) else end local _5_ if cmd then local function _6_(...) if (false ~= a.get(opts, "repeat?")) then return (":silent! call " .. vim_repeat(mapping) .. "<cr>") else return "" end end _5_ = (":" .. cmd .. "<cr>" .. _6_(...)) else _5_ = unpack(args) end return nvim.buf_set_keymap(0, mode, mapping, _5_, {silent = true, noremap = true}) else return nil end end _2amodule_2a["buf"] = buf local function eval_marked_form() local mark = eval["marked-form"]() local mapping local function _9_(m) return ((":ConjureEvalMarkedForm<CR>" == m.rhs) and m.lhs) end mapping = a.some(_9_, nvim.buf_get_keymap(0, "n")) if (mark and mapping) then return nvim.ex.silent_("call", vim_repeat((mapping .. mark))) else return nil end end _2amodule_2a["eval-marked-form"] = eval_marked_form local function on_filetype() buf("n", "LogSplit", cfg("log_split"), "conjure.log", "split") buf("n", "LogVSplit", cfg("log_vsplit"), "conjure.log", "vsplit") buf("n", "LogTab", cfg("log_tab"), "conjure.log", "tab") buf("n", "LogCloseVisible", cfg("log_close_visible"), "conjure.log", "close-visible") buf("n", "LogResetSoft", cfg("log_reset_soft"), "conjure.log", "reset-soft") buf("n", "LogResetHard", cfg("log_reset_hard"), "conjure.log", "reset-hard") buf("n", nil, cfg("eval_motion"), ":set opfunc=ConjureEvalMotion<cr>g@") buf("n", "EvalCurrentForm", cfg("eval_current_form"), "conjure.eval", "current-form") buf("n", "EvalCommentCurrentForm", cfg("eval_comment_current_form"), "conjure.eval", "comment-current-form") buf("n", "EvalRootForm", cfg("eval_root_form"), "conjure.eval", "root-form") buf("n", "EvalCommentRootForm", cfg("eval_comment_root_form"), "conjure.eval", "comment-root-form") buf("n", "EvalWord", cfg("eval_word"), "conjure.eval", "word") buf("n", "EvalCommentWord", cfg("eval_comment_word"), "conjure.eval", "comment-word") buf("n", "EvalReplaceForm", cfg("eval_replace_form"), "conjure.eval", "replace-form") buf({mode = "n", ["repeat?"] = false}, "EvalMarkedForm", cfg("eval_marked_form"), "conjure.mapping", "eval-marked-form") buf("n", "EvalFile", cfg("eval_file"), "conjure.eval", "file") buf("n", "EvalBuf", cfg("eval_buf"), "conjure.eval", "buf") buf("v", "EvalVisual", cfg("eval_visual"), "conjure.eval", "selection") buf("n", "DocWord", cfg("doc_word"), "conjure.eval", "doc-word") buf("n", "DefWord", cfg("def_word"), "conjure.eval", "def-word") do local fn_name = config["get-in"]({"completion", "omnifunc"}) if fn_name then nvim.ex.setlocal(("omnifunc=" .. fn_name)) else end end return client["optional-call"]("on-filetype") end _2amodule_2a["on-filetype"] = on_filetype local function on_exit() local function _12_() return client["optional-call"]("on-exit") end return client["each-loaded-client"](_12_) end _2amodule_2a["on-exit"] = on_exit local function on_quit() return log["close-hud"]() end _2amodule_2a["on-quit"] = on_quit local function init(filetypes) nvim.ex.augroup("conjure_init_filetypes") nvim.ex.autocmd_() nvim.ex.autocmd("FileType", str.join(",", filetypes), bridge["viml->lua"]("conjure.mapping", "on-filetype", {})) nvim.ex.autocmd("CursorMoved", "*", bridge["viml->lua"]("conjure.log", "close-hud-passive", {})) nvim.ex.autocmd("CursorMovedI", "*", bridge["viml->lua"]("conjure.log", "close-hud-passive", {})) nvim.ex.autocmd("CursorMoved", "*", bridge["viml->lua"]("conjure.inline", "clear", {})) nvim.ex.autocmd("CursorMovedI", "*", bridge["viml->lua"]("conjure.inline", "clear", {})) nvim.ex.autocmd("VimLeavePre", "*", bridge["viml->lua"]("conjure.log", "clear-close-hud-passive-timer", {})) nvim.ex.autocmd("ExitPre", "*", ("lua require('" .. _2amodule_name_2a .. "')['" .. "on-exit" .. "']()")) nvim.ex.autocmd("QuitPre", "*", ("lua require('" .. _2amodule_name_2a .. "')['" .. "on-quit" .. "']()")) return nvim.ex.augroup("END") end _2amodule_2a["init"] = init local function eval_ranged_command(start, _end, code) if ("" == code) then return eval.range(a.dec(start), _end) else return eval.command(code) end end _2amodule_2a["eval-ranged-command"] = eval_ranged_command local function connect_command(...) local args = {...} local function _15_(...) if (1 == a.count(args)) then local host, port = string.match(a.first(args), "([a-zA-Z%d\\.-]+):(%d+)$") if (host and port) then return {host = host, port = port} else return {port = a.first(args)} end else return {host = a.first(args), port = a.second(args)} end end return client.call("connect", _15_(...)) end _2amodule_2a["connect-command"] = connect_command local function client_state_command(state_key) if state_key then return client["set-state-key!"](state_key) else return a.println(client["state-key"]()) end end _2amodule_2a["client-state-command"] = client_state_command local function omnifunc(find_start_3f, base) if find_start_3f then local _let_17_ = nvim.win_get_cursor(0) local row = _let_17_[1] local col = _let_17_[2] local _let_18_ = nvim.buf_get_lines(0, a.dec(row), row, false) local line = _let_18_[1] return (col - a.count(nvim.fn.matchstr(string.sub(line, 1, col), "\\k\\+$"))) else return eval["completions-sync"](base) end end _2amodule_2a["omnifunc"] = omnifunc nvim.ex.function_(str.join("\n", {"ConjureEvalMotion(kind)", "call luaeval(\"require('conjure.eval')['selection'](_A)\", a:kind)", "endfunction"})) nvim.ex.function_(str.join("\n", {"ConjureOmnifunc(findstart, base)", "return luaeval(\"require('conjure.mapping')['omnifunc'](_A[1] == 1, _A[2])\", [a:findstart, a:base])", "endfunction"})) nvim.ex.command_("-nargs=? -range ConjureEval", bridge["viml->lua"]("conjure.mapping", "eval-ranged-command", {args = "<line1>, <line2>, <q-args>"})) nvim.ex.command_("-nargs=* -range -complete=file ConjureConnect", bridge["viml->lua"]("conjure.mapping", "connect-command", {args = "<f-args>"})) nvim.ex.command_("-nargs=* ConjureClientState", bridge["viml->lua"]("conjure.mapping", "client-state-command", {args = "<f-args>"})) return nvim.ex.command_("ConjureSchool", bridge["viml->lua"]("conjure.school", "start", {}))
local NumColumns = GAMESTATE:GetCurrentStyle():ColumnsPerPlayer() local player = ... local pn = ToEnumShortString(player) local mods = SL[pn].ActiveModifiers local columns = {} local style = GAMESTATE:GetCurrentStyle(player) local width = style:GetWidth(player) if mods.ColumnFlashOnMiss then local y_offset = SL.Global.GameMode == "StomperZ" and 40 or 80 local af = Def.ActorFrame{ InitCommand=function(self) self:xy( GetNotefieldX(player), y_offset) -- Via empirical observation/testing, it seems that 200% mini is the effective cap. -- At 200% mini, arrows are effectively invisible; they reach a zoom_factor of 0. -- So, keeping that cap in mind, the spectrum of possible mini values in this theme -- becomes 0 to 2, and it becomes necessary to transform... -- a mini value like 35% to a zoom factor like 0.825, or -- a mini value like 150% to a zoom factor like 0.25 local zoom_factor = 1 - scale( mods.Mini:gsub("%%","")/100, 0, 2, 0, 1) self:zoomx( zoom_factor ) end, JudgmentMessageCommand=function(self, params) if params.Player == player and (params.Notes or params.Holds) then for i,col in pairs(params.Notes or params.Holds) do local tns = ToEnumShortString(params.TapNoteScore or params.HoldNoteScore) if tns == "Miss" or tns == "MissedHold" then columns[i]:playcommand("Flash") end end end end } for ColumnIndex=1,NumColumns do af[#af+1] = Def.Quad{ InitCommand=function(self) columns[ColumnIndex] = self self:diffuse(0,0,0,0) :x((ColumnIndex - (NumColumns/2 + 0.5)) * (width/NumColumns)) :vertalign(top) :setsize(width/NumColumns, _screen.h - y_offset) :fadebottom(0.333) end, FlashCommand=function(self) self:diffuse(1,0,0,0.66) :accelerate(0.165):diffuse(0,0,0,0) end } end return af end
local present1, autopairs = pcall(require, 'nvim-autopairs') if not (present1 or present2) then return end autopairs.setup({ check_ts = true }) -- autopairs_completion.setup({ -- map_cr = true, -- map <CR> on insert mode -- map_complete = true, -- it will auto insert `(` after select function or method item -- auto_select = true, -- automatically select the first item -- insert = false, -- use insert confirm behavior instead of replace -- map_char = { -- modifies the function or method delimiter by filetypes -- all = '(', -- tex = '{', -- }, -- })
local widget = require("widget") local selectBox = {} selectBox.__index = selectBox setmetatable(selectBox, widget) function selectBox.new(app, x, y, content, drop) local self = {} setmetatable(self, selectBox) selectBox.init(self, app, x, y, content, drop) return self end function selectBox.init(self, app, x, y, content, drop) self.width = 150 self.height = 30 self.x = x self.y = y self.text = content[1] self.drop = "down" -- use "down" or "up" self.open = false self.dropWidth = 200 self.dropHeight = 200 if drop == nil then self.drop = "down" else self.drop = drop end if self.drop == "down" then self.dropY = self.y + self.height self.dropX = self.x else self.dropY = self.y - self.dropHeight self.dropX = self.x end widget.init(self, app) return self end function selectBox.draw(self) local currentColor = self:getColor() local bw = 30 -- the width of the button on the right of the combo. love.graphics.setColor(currentColor.fill) love.graphics.rectangle("fill", self.x, self.y, self.width, self.height, self.radius.x, self.radius.y) love.graphics.setColor(currentColor.stroke) love.graphics.rectangle("line", self.x, self.y, self.width, self.height, self.radius.x, self.radius.y) love.graphics.setColor(currentColor.stroke) love.graphics.rectangle("line", self.x + self.width - bw, self.y, bw, self.height, self.radius.x, self.radius.y) if self.drop == "down" then love.graphics.polygon( "fill", self.x + self.width - bw/2, self.y + self.height/3*2, self.x + self.width - bw/3*2, self.y + self.height/3, self.x + self.width - bw/3, self.y + self.height/3 ) else love.graphics.polygon( "fill", self.x + self.width - bw/2, self.y + self.height/3, self.x + self.width - bw/3*2, self.y + self.height/3*2, self.x + self.width - bw/3, self.y + self.height/3*2 ) end love.graphics.setColor(currentColor.text) love.graphics.printf(self.text, self.x, self.y, self.width - self.padding.x * 2 - bw, "center", 0, self.height / 30, self.height / 30, self.padding.x *-1, self.padding.y * -1) end function selectBox.drawAfter(self) local currentColor = self:getColor() if self.open then love.graphics.setColor(currentColor.fill) love.graphics.rectangle("fill", self.dropX, self.dropY, self.dropWidth, self.dropHeight, self.radius.x, self.radius.y) love.graphics.setColor(currentColor.stroke) love.graphics.rectangle("line", self.dropX, self.dropY, self.dropWidth, self.dropHeight, self.radius.x, self.radius.y) end end function selectBox.keyPressed(self, handled, key) if self.focused then self.text = self.text .. key end end function selectBox.mousePressed(self, handled, x, y, button, isTouch) if self:hit(x,y) then self.color = self.colors.pressed self.pressed = true end end function selectBox.mouseReleased(self, handled, x, y, button, isTouch) if self:hit(x,y) and self.pressed then self.focused = true self.open = not self.open self.color = self.colors.focused else self.focused = false self.color = self.colors.released self.open = false end end return selectBox
-- SilentsReplacement -- init -- August 12, 2021 local RunService = game:GetService("RunService") if RunService:IsClient() then return require(script.Client) else return require(script.Server) end
items= { [1] = { ["item_name"] = "红宝石", ["item_detail"] = "攻击力加3", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["attack"] = hero_propertys["attack"] + 3 set_hero_property(hero_propertys) end }, [2] = { ["item_name"] = "蓝宝石", ["item_detail"] = "防御力加3", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["defense"] = hero_propertys["defense"] + 3 set_hero_property(hero_propertys) end }, [3] = { ["item_name"] = "黄钥匙", ["item_detail"] = "黄钥匙加1", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["yellow_key"] = hero_propertys["yellow_key"] + 1 set_hero_property(hero_propertys) end }, [4] = { ["item_name"] = "黄钥匙", ["item_detail"] = "蓝钥匙加1", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["blue_key"] = hero_propertys["blue_key"] + 1 set_hero_property(hero_propertys) end }, [5] = { ["item_name"] = "红钥匙", ["item_detail"] = "红钥匙加1", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["red_key"] = hero_propertys["red_key"] + 1 set_hero_property(hero_propertys) end }, [6] = { ["item_name"] = "小血瓶", ["item_detail"] = "生命值加200", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["life"] = hero_propertys["life"] + 200 set_hero_property(hero_propertys) end }, [7] = { ["item_name"] = "大血瓶", ["item_detail"] = "生命值加500", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["life"] = hero_propertys["life"] + 500 set_hero_property(hero_propertys) end }, [8] = { ["item_name"] = "铁剑", ["item_detail"] = "攻击力增加10", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["attack"] = hero_propertys["attack"] + 10 set_hero_property(hero_propertys) end }, [9] = { ["item_name"] = "铁盾", ["item_detail"] = "防御力增加10", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["defense"] = hero_propertys["defense"] + 10 set_hero_property(hero_propertys) end }, [10] = { ["item_name"] = "钥匙盒", ["item_detail"] = "所有钥匙各加1", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["yellow_key"] = hero_propertys["yellow_key"] + 1 hero_propertys["blue_key"] = hero_propertys["blue_key"] + 1 hero_propertys["red_key"] = hero_propertys["red_key"] + 1 set_hero_property(hero_propertys) end }, [11] = { ["item_name"] = "小金币", ["item_detail"] = "金币加100", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["gold"] = hero_propertys["gold"] + 100 set_hero_property(hero_propertys) end }, [12] = { ["item_name"] = "经验书", ["item_detail"] = "等级加1", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["level"] = hero_propertys["level"] + 1 hero_propertys["life"] = hero_propertys["life"] + 1000 hero_propertys["attack"] = hero_propertys["attack"] + 7 hero_propertys["defense"] = hero_propertys["defense"] + 7 set_hero_property(hero_propertys) end }, [13] = { ["item_name"] = "钢剑", ["item_detail"] = "攻击力加70", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["attack"] = hero_propertys["attack"] + 70 set_hero_property(hero_propertys) end }, [14] = { ["item_name"] = "钢盾", ["item_detail"] = "防御力加70", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["defense"] = hero_propertys["defense"] + 70 set_hero_property(hero_propertys) end }, [15] = { ["item_name"] = "十字架", ["item_detail"] = "三围各加1/3", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["life"] = math.floor(hero_propertys["life"] + hero_propertys["life"]/3) hero_propertys["attack"] = math.floor(hero_propertys["attack"] + hero_propertys["attack"]/3) hero_propertys["defense"] = math.floor(hero_propertys["defense"] + hero_propertys["defense"]/3) set_hero_property(hero_propertys) end }, [16] = { ["item_name"] = "大经验书", ["item_detail"] = "等级加3", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["level"] = hero_propertys["level"] + 3 hero_propertys["life"] = hero_propertys["life"] + 3000 hero_propertys["attack"] = hero_propertys["attack"] + 21 hero_propertys["defense"] = hero_propertys["defense"] + 21 set_hero_property(hero_propertys) end }, [17] = { ["item_name"] = "圣水", ["item_detail"] = "生命值加30000", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["life"] = hero_propertys["life"] + 30000 set_hero_property(hero_propertys) end }, [18] = { ["item_name"] = "圣剑", ["item_detail"] = "攻击力加150", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["attack"] = hero_propertys["attack"] + 150 set_hero_property(hero_propertys) end }, [19] = { ["item_name"] = "圣盾", ["item_detail"] = "防御力加150", ["item_func"] = function() local hero_propertys = get_hero_property() hero_propertys["defense"] = hero_propertys["defense"] + 150 set_hero_property(hero_propertys) end } }