content
stringlengths
5
1.05M
require("../logger") require("../diff/diff_export") require("../events") require("../tick") require("../utils/deepcopy") Track = {} Track.__index = Track setmetatable(Track, { __call = function(cls, ...) return cls.init(...) end }) function Track.init() local self = setmetatable({}, Track) self.type = "Track" self.logger = Logger(self.type) self:reset() return self end function Track:reset() if self._id then EventHandler.instance:del(self._id) EventHandler.instance:del(self._frameid) end self.track = {} self:clear() self._id = EventHandler.instance:on(Events.TRACK, self.onTrack, self) self._frameid = EventHandler.instance:on(Events.FRAME, self.onFrame, self) return false end function Track:clear() self.size = 0 self._track = {[0] = { type = "Node", maxAir = 0, jumpAirTime = 0, AjumpAirTime = 0, pos = { x = 0, y = 0, z = 0 }, rot = { x = 0, y = 0, z = 0, pan = 0, tilt = 0, roll = 0 }, funkyrot = false, color = { r = 255, g = 255, b = 255, a = 0 }, intensity = 0, trafficStrength = 0, AtrafficStrength = 0, time = -5 }} self._maxAir = {} self._jumpAirTime = {} self._AjumpAirTime = {} self._pos = {} -- x-y-z self._rot = {} -- x-y-z, aka pan-tilt-roll self._funkyRot = {} self._color = {} -- r-g-b-a self._intensity = {} self._trafficStrength = {} self._AtrafficStrength = {} self._time = {} self.current = 0 self.currentNode = deepcopy(self._track[0]) self.minTilt = 0 self.maxTilt = 0 return false end function Track:generateLogJumps() if self.size <= 0 then return true end self._logJumps = {} for i = 1, self.size do local j = 1 local k = 1 self._logJumps[i] = {} while i + k <= self.size do self._logJumps[i][j] = {i+k, self._time[i+k]} j = j + 1 k = k * 2 end end return false end function Track:process() self:clear() local lastTime = -5 for k, v in ipairs(self.track) do self._track[k] = deepcopy(self._track[0]) self.size = self.size + 1 if v.maxair ~= nil then self._maxAir[k] = v.maxair self._track[k].maxAir = v.maxair else self._maxAir[k] = 0 self._track[k].maxAir = 0 end if v.jumpairtime ~= nil then self._jumpAirTime[k] = v.jumpairtime self._track[k].jumpAirTime = v.jumpairtime else self._jumpAirTime[k] = 0 self._track[k].jumpAirTime = 0 end if v.antiairtime ~= nil then self._AjumpAirTime[k] = v.antiairtime self._track[k].AjumpAirTime = v.antiairtime else self._AjumpAirTime[k] = 0 self._track[k].AjumpAirTime = 0 end if v.pos ~= nil then self._pos[k] = v.pos self._track[k].pos = v.pos else self._pos[k] = {x = 0, y = 0, z = 0} self._track[k].pos = {x = 0, y = 0, z = 0} end if v.rot ~= nil then self._rot[k] = {x = v.rot.x, roll = v.rot.x, y = v.rot.y, tilt = v.rot.y, z = v.rot.z, pan = v.rot.z} self._track[k].rot = {x = v.rot.x, roll = v.rot.x, y = v.rot.y, tilt = v.rot.y, z = v.rot.z, pan = v.rot.z} else self._rot[k] = {x = 0, y = 0, z = 0, pan = 0, tilt = 0, roll = 0} self._track[k].rot = {x = 0, y = 0, z = 0, pan = 0, tilt = 0, roll = 0} end if v.funkyrot ~= nil then self._funkyRot[k] = v.funkyrot self._track[k].funkyRot = v.funkyrot else self._funkyRot[k] = false self._track[k].funkyRot = false end if v.color ~= nil then self._color[k] = v.color self._track[k].color = v.color else self._color[k] = {r = 255, g = 255, b = 255, a = 0} self._track[k].color = {r = 255, g = 255, b = 255, a = 0} end if v.intensity ~= nil then self._intensity[k] = v.intensity self._track[k].intensity = v.intensity else self._intensity[k] = 0 self._track[k].intensity = 0 end if v.trafficstrength ~= nil then self._trafficStrength[k] = v.trafficstrength self._track[k].trafficStrength = v.trafficstrength else self._trafficStrength[k] = 0 self._track[k].trafficStrength = 0 end if v.antitrafficstrength ~= nil then self._AtrafficStrength[k] = v.antitrafficstrength self._track[k].AtrafficStrength = v.antitrafficstrength else self._AtrafficStrength[k] = 0 self._track[k].AtrafficStrength = 0 end if v.seconds ~= nil then self._time[k] = v.seconds self._track[k].time = v.seconds lastTime = v.seconds else self._time[k] = lastTime self._track[k].time = lastTime end self._track[k].id = k end local min = math.min local max = math.max for i=1,self.size do self.minTilt = min(self.minTilt, self._rot[i].tilt) self.maxTilt = max(self.maxTilt, self._rot[i].tilt) end self:generateLogJumps() return false end function Track:load(tr) if type(tr) == "table" then self.track = tr elseif GameStates.current == PRE_TRACK then return true else self.track = GetTrack() end self:process() return false end function Track:timeToNode(sec) if self.size <= 0 then return true end local min = math.min local current = 1 local jumpCounter = #self._logJumps[current] while jumpCounter > 0 do if self._logJumps[current][jumpCounter][2] <= sec then current = self._logJumps[current][jumpCounter][1] jumpCounter = min(jumpCounter - 1, #self._logJumps[current]) else jumpCounter = jumpCounter - 1 end end return deepcopy(self._track[current]) end function Track:nodeToTime(num) if num <= 0 then return self._time[1] elseif num <= self.size then return self._time[num] else return self._time[self.size] end end function Track:getNode(num) if num > 0 and num <= self.size then return self._track[num] else return self._track[0] end end function Track:get(varname) if varname == nil then return deepcopy(self._track) elseif self["_" .. varname] then return deepcopy(self["_" .. varname]) else return true end end function Track:onTrack(ev) self.track = ev.data self:process() return false end function Track:onFrame(ev) self.currentNode = self:timeToNode(Tick.instance:getRelativeTime()) self.currentID = self.currentNode.id return false end
Note = {} Note.__index = Note setmetatable(Note, { __call = function(cls, ...) return cls.init(...) end, __lt = function(a, b) return a:lt(b) end }) Note.Objects = { AUTO = 0, DEFAULT = "Meteor", DEFAULT_TAIL = "Meteor_Tail" } Note.HandTypes = { AUTO = 0, LEFT = 1, RIGHT = 2, PURPLE = 4 } function Note.init(obj) local self = setmetatable({}, Note) self.type = "Note" self.logger = Logger(self.type) self:reset() self:set(obj) return self end function Note.defaultOffset(id, pos, span, handType) return { pos = {x = pos.x, y = pos.y}, span = {x = span.x, y = span.y} } end function Note:reset() self.enabled = true self.startTime = -5 self.startNode = 1 self.lengthTime = 0 self.lengthNode = 1 self.endTime = -5 self.endNode = 1 self.handType = Note.HandTypes.AUTO self.stack = 1 -- meteors in the same position self.pos = {x = 0, y = 0} -- assign manual positions here self.span = {x = 0, y = 0} self.endPos = {x = 0, y = 0} self.endSpan = {x = 0, y = 0} self.offsetFunc = Note.defaultOffset self.assigned = false self.curve = {roll = 0, tilt = 0, pan = -1} -- The next one should be pan-tilt-roll? More testing is needed -- I only have "The game does this for us" as the official documentation LUL self.autoCurve = true self.objects = {note = Note.Objects.DEFAULT, tail = Note.Objects.DEFAULT_TAIL} -- alternatively, you can give a note length-size array of object names self.scales = {note = Diff.instance.noteScale, tail = Diff.instance.tailScale} -- same as above self.speeds = {Diff.instance.meteorSpeed} -- || -- self.colors = {{53, 141, 255}, {255, 52, 0}, {103, 53, 176}} self.emissives = self.colors self.generator = "none" end function Note:modify(obj) return self:set(obj) end function Note:load(obj) return self:set(obj) end function Note:set(obj) if type(obj) ~= "table" then return true end if obj.type == "Note" then self.id = obj.id or 0 self.enabled = obj.enabled self.startTime = obj.startTime self.startNode = obj.startNode self.endTime = obj.endTime self.endNode = obj.endNode self.lengthTime = obj.lengthTime self.lengthNode = obj.lengthNode self.handType = obj.handType self.stack = obj.stack self.pos = deepcopy(obj.pos) self.span = deepcopy(obj.span) self.endPos = deepcopy(obj.endPos) self.endSpan = deepcopy(obj.endSpan) self.offsetFunc = obj.offsetFunc self.assigned = obj.assigned self.curve = deepcopy(obj.curve) self.autoCurve = obj.autoCurve self.objects = deepcopy(obj.objects) self.scales = deepcopy(obj.scales) self.speeds = deepcopy(obj.speeds) self.colors = deepcopy(obj.colors) self.emissives = (obj.colors == obj.emissives) and self.colors or deepcopy(obj.emissives) self.generator = obj.generator return false end if obj.node ~= nil or obj.startNode ~= nil then self.startNode = obj.startNode or obj.node self.startTime = obj.startTime or obj.time or Track.instance:nodeToTime(self.startNode) elseif obj.time ~= nil or obj.startTime ~= nil then self.startTime = obj.startTime or obj.time self.startNode = Track.instance:timeToNode(self.start) end if obj.endNode ~= nil then self.endNode = obj.endNode self.endTime = obj.endTime or Track.instance:nodeToTime(self.endNode) else self.endTime = obj.endTime or self.startTime self.endNode = Track.instance:timeToNode(self.endTime) end self.lengthTime = self.endTime - self.startTime self.lengthNode = self.endNode - self.startNode + 1 self.offsetFunc = obj.offsetFunc or self.offsetFunc self.stack = obj.stack or self.stack if obj.pos then self.assigned = true self.pos.x = obj.pos.x or self.pos.x self.pos.y = obj.pos.y or self.pos.y end if obj.span then self.assigned = true self.span.x = obj.span.x or self.span.x self.span.y = obj.span.y or self.span.y end if obj.curve then self.curve = deepcopy(obj.curve) self.autoCurve = false end if obj.objects then self.objects = deepcopy(obj.objects) end if obj.scales then self.scales = deepcopy(obj.scales) end if obj.speeds then self.speeds = deepcopy(obj.speeds) end if obj.colors then self.colors = deepcopy(obj.colors) if obj.emissives then if obj.emissives == obj.colors then self.emissives = self.colors else self.emissives = deepcopy(obj.emissives) end end elseif obj.emissives then self.emissives = deepcopy(obj.emissives) end if obj.generator then self.generator = obj.generator end return false end function Note:enable() self.enabled = true end function Note:disable() self.enabled = false end function Note:toggle() self.enabled = not self.enabled end function Note:get() local ret = {} for k, v in pairs(self) do if k ~= "PosTypes" and k ~= "RenderTypes" and type(v) ~= "function" then ret[k] = v end end return ret end function Note:setHand(hand) if hand == 0 then return true end if self.assigned and self.handType >= 3 and hand < 3 then if hand == 2 then self.pos.x = self.pos.x + self.span.x / 2 self.pos.y = self.pos.y + self.span.y / 2 self.span.x = 0 self.span.y = 0 else self.pos.x = self.pos.x - self.span.x / 2 self.pos.y = self.pos.y - self.span.y / 2 self.span.x = 0 self.span.y = 0 end end self.handType = hand return false end --[[ Returns true if - there's the hand OR - there's a purple Exclusive mode: Returns true ONLY if - there's exactly the hand --]] function Note:hasHands(hands, excHands) local floor = math.floor return ( (hands%2 == self.handType%2 or (not excHands and self.handType%2 == 1)) or (not excHands and floor(self.handType/4)%2 == 1) ) and ( (floor(hands/2)%2 == floor(self.handType/2)%2 or (not excHands and floor(self.handType/2)%2 == 1)) or (not excHands and floor(self.handType/4)%2 == 1) ) and ( floor(hands/4)%2 == floor(self.handType/4)%2 or (not excHands and floor(self.handType/4)%2 == 1) ) end function Note:finishAssign() return self:finalize() end function Note:markAssigned() return self:finalize() end function Note:finalize() local endVals = self.offsetFunc(self.lengthNode, self.pos, self.span, self.handType) self.endPos = endVals.pos self.endSpan = endVals.span self.assigned = true end function Note:calcCurves(realPos) return { z = math.max(Diff.instance.spanZ - Diff.instance.spanZ_factor, math.sqrt(Diff.instance.spanZ*Diff.instance.spanZ - realPos.x*realPos.x - (realPos.y - Diff.instance.chestHeight)*(realPos.y - Diff.instance.chestHeight))), roll = self.autoCurve and 0 or self.curve.roll, tilt = self.autoCurve and 0 or self.curve.tilt, pan = self.autoCurve and -1 or self.curve.pan, peakX = realPos.x * Diff.instance.curveFactorX, peakY = math.min(math.max(realPos.y * Diff.instance.curveFactorY, Diff.instance.curveY_min), Diff.instance.curveY_max), peakZ = 0 } end function Note:clone() return Note:copy() end function Note:copy() return Note(self) end function Note:toBREF() if not self.enabled or not self.assigned then return {} end local floor = math.floor local ret = {} for i=1,(self.lengthNode) do local preSpanPos = self.offsetFunc(i - 1, self.pos, self.span, Note.HandTypes.PURPLE) if floor(self.handType/4)%2==1 then local postSpanPos = { x = preSpanPos.pos.x, y = preSpanPos.pos.y } local curves = self:calcCurves(postSpanPos) local outPos = {postSpanPos.x, postSpanPos.y + Diff.instance.chestHeight, curves.z} local outDir = {curves.roll, curves.tilt, curves.pan} local obj = self.objects[i] or (i ~= 1 and self.objects.tail) or self.objects.note or self.objects[1] local tailedObj = (i==1 and "h_" or "t_") .. obj local peaks = {curves.peakX, curves.peakY, curves.peakZ} local purp = { tailedObject = tailedObj, object = obj, node = self.startNode + i, pos = outPos, handType = 2, emissive = self.emissives[3], color = self.colors[3], scale = self.scales[i] or (i ~= 1 and self.scales.tail) or self.scales.note or self.scales[1], speed = self.speeds[i] or (i ~= 1 and self.speeds.tail) or self.speeds.note or self.speeds[1], direction = outDir, curvePeak = peaks } ret[#ret+1] = purp end if floor(self.handType/2)%2==1 then local postSpanPos = { x = preSpanPos.pos.x + preSpanPos.span.x / 2, y = preSpanPos.pos.y + preSpanPos.span.y / 2 } local curves = self:calcCurves(postSpanPos) local outPos = {postSpanPos.x, postSpanPos.y + Diff.instance.chestHeight, curves.z} local outDir = {curves.roll, curves.tilt, curves.pan} local obj = self.objects[i] or (i ~= 1 and self.objects.tail) or self.objects.note or self.objects[1] local tailedObj = (i == 1 and "h_" or "t_") .. obj local peaks = {curves.peakX, curves.peakY, curves.peakZ} local rig = { tailedObject = tailedObj, object = obj, node = self.startNode + i, pos = outPos, handType = 1, emissive = self.emissives[2], color = self.colors[2], scale = self.scales[i] or (i ~= 1 and self.scales.tail) or self.scales.note or self.scales[1], speed = self.speeds[i] or (i ~= 1 and self.speeds.tail) or self.speeds.note or self.speeds[1], direction = outDir, curvePeak = peaks } ret[#ret+1] = rig end if self.handType%2==1 then local postSpanPos = { x = preSpanPos.pos.x - preSpanPos.span.x / 2, y = preSpanPos.pos.y - preSpanPos.span.y / 2 } local curves = self:calcCurves(postSpanPos) local outPos = {postSpanPos.x, postSpanPos.y + Diff.instance.chestHeight, curves.z} local outDir = {curves.roll, curves.tilt, curves.pan} local obj = self.objects[i] or (i ~= 1 and self.objects.tail) or self.objects.note or self.objects[1] local tailedObj = (i == 1 and "h_" or "t_") .. obj local peaks = {curves.peakX, curves.peakY, curves.peakZ} local lef = { tailedObject = tailedObj, object = obj, node = self.startNode + i, pos = outPos, handType = 0, emissive = self.emissives[1], color = self.colors[1], scale = self.scales[i] or (i ~= 1 and self.scales.tail) or self.scales.note or self.scales[1], speed = self.speeds[i] or (i ~= 1 and self.speeds.tail) or self.speeds.note or self.speeds[1], direction = outDir, curvePeak = peaks } ret[#ret+1] = lef end end return ret end
-- Vis Sleuth Plugin -- Detect and set indentation. require("vis") local tab_width = 2 local defaults = { expandtab = "on" , softtabstop = tab_width , tabwidth = tab_width } local function vis_sleuth(win) local function map(fn, list) local mapped = {} for key, value in pairs(list) do mapped[key] = fn(key, value) end return mapped end local function command(option, value) vis:command("set " .. option .. " " .. value) return true end local function commands(options) local merged = options for key, value in pairs(defaults) do if not merged[key] then merged[key] = value end end return map(command, merged) end local new_file = { elixir = function() commands(defaults) end , elm = function() commands({ ["elm-format-indent"] = tab_width }) end , python = function() local tab_width = 4 commands ( { softtabstop = tab_width , tabwidth = tab_width } ) end } if type(new_file[win.syntax]) == "function" then new_file[win.syntax]() else commands(defaults) end end vis.events.subscribe(vis.events.WIN_OPEN, vis_sleuth)
redis_host = os.getenv("REDIS_HOST") dark_canary_threshold = tonumber(os.getenv("DARK_CANARY_THRESHOLD"))
Plane = class.sub(Mob) function Plane:init(pDelay) Mob.init(self, pDelay, -100, love.math.random(150) + 50) self.speed = 1.7 + self.level/10 if self.speed >= 5 then self.speed = 5 end self.score = 5 self.targetX = config.gameWidth + 100 self.targetY = love.math.random(150) + 50 self.scale = 2 self.image = images.plane self.colliderX = self.image:getWidth()/2 * self.scale self.colliderY = self.image:getHeight()/2 * self.scale self.stage2 = false self.stage2trigX = love.math.random(150)+70 self.stage2trigBomb = 0 self.stage2posX = 0 end function Plane:update() Mob.update(self) if (self.x >= self.stage2trigX) and not self.stage2 then self.stage2 = true self.stage2posX = self.x end if self.stage2 and ((self.x - self.stage2posX) > self.stage2trigBomb) and (self.x <= 730) then mobs:add(class.new(Bomb, self.x, self.y+30, 0)) self.stage2trigBomb = 20 + love.math.random(10) self.stage2posX = self.x end if self.x > config.gameWidth + 50 then self.destroyed = true end end function Plane:setTarget() self.direction = math.atan2(self.targetY-self.startY, self.targetX-self.startX) self.vX = math.cos(self.direction) * self.speed self.vY = math.sin(self.direction) * self.speed end function Plane:destroy() Mob.destroy(self) if self.hit and not self.stage2 then game.scenes.stages.score = game.scenes.stages.score + 15 end end
pistol_intimidator = { minimumLevel = 0, maximumLevel = -1, customObjectName = "Intimidator pistol", directObjectTemplate = "object/weapon/ranged/pistol/pistol_intimidator.iff", craftingValues = { {"mindamage",150,200,0}, {"maxdamage",200,250,0}, {"attackspeed",5.3,3.7,1}, {"woundchance",8,16,0}, {"roundsused",30,65,0}, {"hitpoints",1500,1500,1500}, {"zerorangemod",-35,-35,0}, {"maxrangemod",-50,-50,0}, {"midrange",40,40,0}, {"midrangemod",5,15,0}, {"attackhealthcost",15,5,0}, {"attackactioncost",15,5,0}, {"attackmindcost",15,5,0}, }, customizationStringNames = {}, customizationValues = {}, -- randomDotChance: The chance of this weapon object dropping with a random dot on it. Higher number means less chance. Set to 0 to always have a random dot. randomDotChance = -1, junkDealerTypeNeeded = JUNKWEAPONS, junkMinValue = 20, junkMaxValue = 40 } -- this is the intimidator_pistol addLootItemTemplate("pistol_intimidator", pistol_intimidator)
local P = {} local debug_level = tonumber(os.getenv('jagen_debug')) or -1 function P.message(...) io.write('(I) ', string.format(...), '\n') io.flush() end function P.warning(...) io.stderr:write('(W) ', string.format(...), '\n') io.stderr:flush() end function P.error(...) io.stderr:write('(E) ', string.format(...), '\n') io.stderr:flush() end function P.debug(...) if debug_level >= 0 then io.write('(D0) ', string.format(...), '\n') io.flush() end end function P.debug1(...) if debug_level >= 1 then io.write('(D1) ', string.format(...), '\n') io.flush() end end function P.debug2(...) if debug_level >= 2 then io.write('(D2) ', string.format(...), '\n') io.flush() end end return P
--[[ Netherstorm -- Nether Ray.lua This script was written and is protected by the GPL v2. This script was released by BlackHer0 of the BLUA Scripting Project. Please give proper accredidations when re-releasing or sharing this script with others in the emulation community. ~~End of License Agreement -- BlackHer0, July, 29th, 2008. ]] function Ray_OnEnterCombat(Unit,Event) Unit:RegisterEvent("Ray_Drain",1000,0) Unit:RegisterEvent("Ray_Shock",1000,0) Unit:RegisterEvent("Ray_Sting",1000,0) end function Ray_Drain(Unit,Event) Unit:FullCastSpellOnTarget(17008,Unit:GetClosestPlayer()) end function Ray_Shock(Unit,Event) Unit:FullCastSpellOnTarget(35334,Unit:GetClosestPlayer()) end function Ray_Sting(Unit,Event) Unit:FullCastSpellOnTarget(36659,Unit:GetClosestPlayer()) end function Ray_OnLeaveCombat(Unit,Event) Unit:RemoveEvents() end function Ray_OnDied(Unit,Event) Unit:RemoveEvents() end RegisterUnitEvent (18880, 1, "Ray_OnEnterCombat") RegisterUnitEvent (18880, 2, "Ray_OnLeaveCombat") RegisterUnitEvent (18880, 4, "Ray_OnDied")
local Spawn = require("coro-spawn") return { GetWifi = function () local Commands = { Windows = "Powershell.exe -Command \"(get-netconnectionProfile).Name\"", Mac = "/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport -I | awk -F: '/ SSID/{print $2}'" } local Handle = io.popen(Commands[RuntimeOS], "r") local Name for Line in Handle:lines() do Name = Line --Logger.Info(Line) end Handle:close() return Name end }
-- -- config -- local P = {} setfenv(1, P) -- Redis P.redis = {} P.redis.host = "127.0.0.1" P.redis.port = "6379" -- 短链服务序列号[0|1|2|3] P.worker_id = 0 return P
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You under the Apache License, Version 2.0 -- (the "License"); you may not use this file except in compliance with -- the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- local core = require("apisix.core") local log_util = require("apisix.utils.log-util") local bp_manager_mod = require("apisix.utils.batch-processor-manager") local plugin_name = "sls-logger" local ngx = ngx local rf5424 = require("apisix.plugins.slslog.rfc5424") local tcp = ngx.socket.tcp local tostring = tostring local ipairs = ipairs local table = table local batch_processor_manager = bp_manager_mod.new(plugin_name) local schema = { type = "object", properties = { include_req_body = {type = "boolean", default = false}, timeout = {type = "integer", minimum = 1, default= 5000}, host = {type = "string"}, port = {type = "integer"}, project = {type = "string"}, logstore = {type = "string"}, access_key_id = {type = "string"}, access_key_secret = {type ="string"} }, required = {"host", "port", "project", "logstore", "access_key_id", "access_key_secret"} } local _M = { version = 0.1, priority = 406, name = plugin_name, schema = batch_processor_manager:wrap_schema(schema), } function _M.check_schema(conf) return core.schema.check(schema, conf) end local function send_tcp_data(route_conf, log_message) local err_msg local res = true local sock, soc_err = tcp() local can_close if not sock then return false, "failed to init the socket" .. soc_err end sock:settimeout(route_conf.timeout) local ok, err = sock:connect(route_conf.host, route_conf.port) if not ok then return false, "failed to connect to TCP server: host[" .. route_conf.host .. "] port[" .. tostring(route_conf.port) .. "] err: " .. err end ok, err = sock:sslhandshake(true, nil, false) if not ok then return false, "failed to perform TLS handshake to TCP server: host[" .. route_conf.host .. "] port[" .. tostring(route_conf.port) .. "] err: " .. err end core.log.debug("sls logger send data ", log_message) ok, err = sock:send(log_message) if not ok then res = false can_close = true err_msg = "failed to send data to TCP server: host[" .. route_conf.host .. "] port[" .. tostring(route_conf.port) .. "] err: " .. err else ok, err = sock:setkeepalive(120 * 1000, 20) if not ok then can_close = true core.log.warn("failed to set socket keepalive: host[", route_conf.host, "] port[", tostring(route_conf.port), "] err: ", err) end end if can_close then ok, err = sock:close() if not ok then core.log.warn("failed to close the TCP connection, host[", route_conf.host, "] port[", route_conf.port, "] ", err) end end return res, err_msg end local function combine_syslog(entries) local items = {} for _, entry in ipairs(entries) do table.insert(items, entry.data) core.log.info("buffered logs:", entry.data) end return table.concat(items) end _M.combine_syslog = combine_syslog local function handle_log(entries) local data = combine_syslog(entries) if not data then return true end return send_tcp_data(entries[1].route_conf, data) end -- log phase in APISIX function _M.log(conf, ctx) local entry = log_util.get_full_log(ngx, conf) if not entry.route_id then core.log.error("failed to obtain the route id for sys logger") return end local json_str, err = core.json.encode(entry) if not json_str then core.log.error('error occurred while encoding the data: ', err) return end local rf5424_data = rf5424.encode("SYSLOG", "INFO", ctx.var.host,"apisix", ctx.var.pid, conf.project, conf.logstore, conf.access_key_id, conf.access_key_secret, json_str) local process_context = { data = rf5424_data, route_conf = conf } if batch_processor_manager:add_entry(conf, process_context) then return end batch_processor_manager:add_entry_to_new_processor(conf, process_context, ctx, handle_log) end return _M
pg = pg or {} pg.item_data_frame = { [0] = { time_limit_type = 0, name = "默认装扮", gain_by = "", id = 0, time_second = 0, desc = "<color=#ffffff>不设置任何头像框</color>\n该状态下将誓约角色设置为秘书舰,可显示誓约头像框", scene = {} }, [101] = { time_limit_type = 0, name = "一周年纪念", gain_by = "", id = 101, time_second = 0, desc = "<color=#ffffff>献给所有一年间持续奋斗在港区的指挥官们</color>\n开启「再诞·曙光」纪念币获取", scene = {} }, [102] = { time_limit_type = 0, name = "二周年纪念", gain_by = "", id = 102, time_second = 0, desc = "<color=#ffffff>献给所有两年间持续奋斗在港区的指挥官们</color>\n通过参与二周年限定活动获取", scene = {} }, [103] = { time_limit_type = 0, name = "千日的纪念", gain_by = "", id = 103, time_second = 0, desc = "<color=#ffffff>愿能一起走过下一个、再下一个,再下无数个的千日~啾!</color>\n碧蓝航线港区开设1000天奖励", scene = {} }, [104] = { time_limit_type = 0, name = "三周年纪念", gain_by = "", id = 104, time_second = 0, desc = "<color=#ffffff>献给所有三年间持续奋斗在港区的指挥官们</color>\n通过参与三周年限定活动获取", scene = {} }, [105] = { time_limit_type = 0, name = "四周年纪念", gain_by = "", id = 105, time_second = 0, desc = "<color=#ffffff>献给所有四年间持续奋斗在港区的指挥官们</color>\n通过参与四周年限定活动获取", scene = {} }, [201] = { time_limit_type = 0, name = "限界的挑战者", gain_by = "", id = 201, time_second = 0, desc = "<color=#ffffff>献给所有勇于挑战极限的指挥官们</color>\n通过参与「限界挑战」获取 (19.06.06-19.07.28)", scene = {} }, [202] = { time_limit_type = 0, name = "限界的挑战者II", gain_by = "", id = 202, time_second = 0, desc = "<color=#ffffff>献给所有勇于挑战极限的指挥官们</color>\n通过参与「限界挑战」获取 (19.08.07-19.09.29)", scene = {} }, [203] = { time_limit_type = 0, name = "限界的挑战者III", gain_by = "", id = 203, time_second = 0, desc = "<color=#ffffff>献给所有勇于挑战极限的指挥官们</color>\n通过参与「限界挑战」获取 (19.10.10-19.12.08)", scene = {} }, [204] = { time_limit_type = 0, name = "限界的挑战者IV", gain_by = "", id = 204, time_second = 0, desc = "<color=#ffffff>献给所有勇于挑战极限的指挥官们</color>\n通过参与「限界挑战」获取 (19.12.19-20.03.29)", scene = {} }, [205] = { time_limit_type = 0, name = "限界的挑战者V", gain_by = "", id = 205, time_second = 0, desc = "<color=#ffffff>献给所有勇于挑战极限的指挥官们</color>\n通过参与「限界挑战」获取 (20.04.09-20.07.05)", scene = {} }, [206] = { time_limit_type = 0, name = "限界的挑战者VI", gain_by = "", id = 206, time_second = 0, desc = "<color=#ffffff>献给所有勇于挑战极限的指挥官们</color>\n通过参与「限界挑战」获取 (20.07.09-20.10.04)", scene = {} }, [207] = { time_limit_type = 0, name = "限界的挑战者VII", gain_by = "", id = 207, time_second = 0, desc = "<color=#ffffff>献给所有勇于挑战极限的指挥官们</color>\n通过参与「限界挑战」获取 (20.10.12-21.01.17)", scene = {} }, [208] = { time_limit_type = 0, name = "限界的挑战者VIII", gain_by = "", id = 208, time_second = 0, desc = "<color=#ffffff>献给所有勇于挑战极限的指挥官们</color>\n通过参与「限界挑战」获取 (21.01.21-21.04.18)", scene = {} }, [209] = { time_limit_type = 0, name = "限界的挑战者IX", gain_by = "", id = 209, time_second = 0, desc = "<color=#ffffff>献给所有勇于挑战极限的指挥官们</color>\n通过参与「限界挑战」获取 (21.04.22-21.07.18)", scene = {} }, [210] = { time_limit_type = 0, name = "限界的挑战者X", gain_by = "", id = 210, time_second = 0, desc = "<color=#ffffff>献给所有勇于挑战极限的指挥官们</color>\n通过参与「限界挑战」获取 (21.07.22-21.10.17)", scene = {} }, [300] = { time_limit_type = 1, name = "召集者", gain_by = "", id = 300, time_second = 2592000, desc = "<color=#ffffff>感谢您对于动员指令的响应,指挥官</color>\n有效期30天", scene = {} }, [301] = { time_limit_type = 1, name = "回归者", gain_by = "", id = 301, time_second = 2592000, desc = "<color=#ffffff>指挥部欢迎您的归来,期待您今后的活跃</color>\n有效期30天", scene = {} }, [302] = { time_limit_type = 0, name = "铁血之誓", gain_by = "铁血、音符与誓言", id = 302, time_second = 0, desc = "<color=#ffffff>以赤红的血、和冷彻的铁,铸就坚定的意志</color>\n「铁血、音符与誓言」活动获取", scene = {} }, [303] = { time_limit_type = 0, name = "自由之翼", gain_by = "箱庭疗法", id = 303, time_second = 0, desc = "<color=#ffffff>「——为了碧蓝色的自由意志,天佑白鹰」</color>\n「箱庭疗法」活动获取", scene = {} }, [304] = { time_limit_type = 0, name = "荣光之徽", gain_by = "神圣的悲喜剧", id = 304, time_second = 0, desc = "<color=#ffffff>「让世界知晓撒丁帝国的荣耀与尊严吧!」</color>\n「神圣的悲喜剧」活动获取", scene = {} }, [305] = { time_limit_type = 0, name = "重樱之仪", gain_by = "浮樱影华", id = 305, time_second = 0, desc = "<color=#ffffff>「奉纳信仰,为重樱之未来祈愿光明」</color>\n「浮樱影华」活动获取", scene = {} }, [306] = { time_limit_type = 0, name = "团结之证", gain_by = "北境序曲", id = 306, time_second = 0, desc = "<color=#ffffff>「同志们,团结起来吧!世界将在我们手中改变!」</color>\n「北境序曲」活动获取", scene = {} }, [307] = { time_limit_type = 0, name = "闪耀之翼", gain_by = "微层混合", id = 307, time_second = 0, desc = "<color=#ffffff>「无畏的闪电划破黑暗,照亮我们前进的方向」</color>\n「微层混合」活动获取", scene = {} }, [308] = { time_limit_type = 0, name = "鸢尾之颂", gain_by = "穹顶下的圣咏曲", id = 308, time_second = 0, desc = "<color=#ffffff>「愿昔日的颂歌再次响彻天空,Vive la Iris!」</color>\n「穹顶下的圣咏曲」活动获取", scene = {} }, [309] = { time_limit_type = 0, name = "皇家之冠", gain_by = "永夜幻光", id = 309, time_second = 0, desc = "<color=#ffffff>为皇家的荣耀而战,天佑女王</color>\n「永夜幻光」活动获取", scene = {} }, [311] = { time_limit_type = 0, name = "浮光蝶影", gain_by = "蝶海梦花", id = 311, time_second = 0, desc = "<color=#ffffff>「无论现世亦或梦境,皆愿希望之光长存。」</color>\n「蝶海梦花」活动获取", scene = {} }, [312] = { time_limit_type = 0, name = "铁血之器", gain_by = "负象限作战", id = 312, time_second = 0, desc = "<color=#ffffff>「以冷彻之器,重铸赤红的铁血意志。」</color>\n「负象限作战」活动获取", scene = {} }, [313] = { time_limit_type = 0, name = "冰华之证", gain_by = "破晓冰华", id = 313, time_second = 0, desc = "<color=#ffffff>「让我们一同探寻隐藏在“密室”之中的秘密吧!」</color>\n「破晓冰华」活动获取", scene = {} }, [314] = { time_limit_type = 0, name = "帝国之柱", gain_by = "复兴的赞美诗", id = 314, time_second = 0, desc = "<color=#ffffff>「坚固的立柱撑起了崭新的帝国,一起为光荣而战吧!」</color>\n「复兴的赞美诗」活动获取", scene = {} }, [315] = { time_limit_type = 0, name = "掣电光翼", gain_by = "镜位螺旋", id = 315, time_second = 0, desc = "<color=#ffffff>「白鹰最大最强的Black Dragon登场!一起去撼动世界吧!」</color>\n「镜位螺旋」活动获取", scene = {} }, [316] = { time_limit_type = 0, name = "龙宫之证", gain_by = "碧海光粼", id = 316, time_second = 0, desc = "<color=#ffffff>「愿汝等揭开龙宫城中谜题,寻获真正的宝藏」</color>\n「碧海光粼」活动获取", scene = {} }, [401] = { time_limit_type = 0, name = "殿堂纪念:企业", gain_by = "", id = 401, time_second = 0, desc = "<color=#ffffff>为企业特别制作的角色专属头像框</color>\n「Azurlane人气投票2019」活动获取", scene = {} }, [402] = { time_limit_type = 0, name = "殿堂纪念:贝尔法斯特", gain_by = "", id = 402, time_second = 0, desc = "<color=#ffffff>为贝尔法斯特特别制作的角色专属头像框</color>\n「Azurlane人气投票2019」活动获取", scene = {} }, [404] = { time_limit_type = 0, name = "殿堂纪念:椿", gain_by = "", id = 404, time_second = 0, desc = "<color=#ffffff>为椿特别制作的角色专属头像框</color>\n「Azurlane人气投票2019」活动获取", scene = {} }, [501] = { time_limit_type = 0, name = "美味的纪念 ", gain_by = "", id = 501, time_second = 0, desc = "<color=#ffffff>献给所有对美味比萨有爱的指挥官们</color>\n通过参与「啾啾欢乐餐厅」活动获取", scene = {} }, all = { 0, 101, 102, 103, 104, 105, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 311, 312, 313, 314, 315, 316, 401, 402, 404, 501 } } return
RegisterClientScript() RegisterClientAssets("placeholder/socle.png") ENTITY.IsNetworked = true ENTITY.Properties = { { Name = "respawntime", Type = PropertyType.Integer, Default = 30 }, { Name = "powerup_type", Type = PropertyType.String, Default = "" } } ENTITY.CanSpawn = true function ENTITY:Initialize() if (CLIENT) then self:AddSprite({ Scale = Vec2(0.5, 0.5), TexturePath = "placeholder/socle.png" }) end end if (SERVER) then ENTITY.NextRespawn = os.time() function ENTITY:OnPowerupConsumed() self.CanSpawn = true self.NextRespawn = os.time() + self:GetProperty("respawntime") end function ENTITY:OnTick() local now = os.time() if (now >= self.NextRespawn) then if (self.CanSpawn) then local powerup = match.CreateEntity({ Type = self:GetProperty("powerup_type"), LayerIndex = self:GetLayerIndex(), Parent = self, Position = Vec2(0, -10) }) powerup.Parent = self self.CanSpawn = false end self.NextRespawn = os.time() + self:GetProperty("respawntime") end end end
--Copyright (C) 2009 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. object_tangible_wearables_armor_padded_shared_armor_padded_s01_belt = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_belt.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/armor_padded_s01_belt_f.sat", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/belt.iff", certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 259, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@wearables_detail:armor_padded_s01_belt", gameObjectType = 259, locationReservationRadius = 0, lookAtText = "@wearables_lookat:armor_padded_s01_belt", noBuildRadius = 0, objectName = "@wearables_name:armor_padded_s01_belt", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 4150080953, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/wearables/base/shared_wearables_base.iff", "object/tangible/wearables/base/shared_base_belt.iff"} ]] } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_padded_shared_armor_padded_s01_belt, "object/tangible/wearables/armor/padded/shared_armor_padded_s01_belt.iff") object_tangible_wearables_armor_padded_shared_armor_padded_s01_bicep_l = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_bicep_l.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/armor_padded_s01_bicep_l_f.sat", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/bicep_l.iff", certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 261, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@wearables_detail:armor_padded_s01_bicep_l", gameObjectType = 261, locationReservationRadius = 0, lookAtText = "@wearables_lookat:armor_padded_s01_bicep_l", noBuildRadius = 0, objectName = "@wearables_name:armor_padded_s01_bicep_l", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 3710375326, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/wearables/base/shared_wearables_base.iff", "object/tangible/wearables/base/shared_armor_base.iff", "object/tangible/wearables/base/shared_base_bicep_l.iff"} ]] } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_padded_shared_armor_padded_s01_bicep_l, "object/tangible/wearables/armor/padded/shared_armor_padded_s01_bicep_l.iff") object_tangible_wearables_armor_padded_shared_armor_padded_s01_bicep_r = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_bicep_r.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/armor_padded_s01_bicep_r_f.sat", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/bicep_r.iff", certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 261, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@wearables_detail:armor_padded_s01_bicep_r", gameObjectType = 261, locationReservationRadius = 0, lookAtText = "@wearables_lookat:armor_padded_s01_bicep_r", noBuildRadius = 0, objectName = "@wearables_name:armor_padded_s01_bicep_r", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 2918354957, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/wearables/base/shared_wearables_base.iff", "object/tangible/wearables/base/shared_armor_base.iff", "object/tangible/wearables/base/shared_base_bicep_r.iff"} ]] } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_padded_shared_armor_padded_s01_bicep_r, "object/tangible/wearables/armor/padded/shared_armor_padded_s01_bicep_r.iff") object_tangible_wearables_armor_padded_shared_armor_padded_s01_boots = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_boots.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/armor_padded_s01_boots_f.sat", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/shoe.iff", certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 263, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@wearables_detail:armor_padded_s01_boots", gameObjectType = 263, locationReservationRadius = 0, lookAtText = "@wearables_lookat:armor_padded_s01_boots", noBuildRadius = 0, objectName = "@wearables_name:armor_padded_s01_boots", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 343908402, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/wearables/base/shared_wearables_base.iff", "object/tangible/wearables/base/shared_base_shoes.iff"} ]] } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_padded_shared_armor_padded_s01_boots, "object/tangible/wearables/armor/padded/shared_armor_padded_s01_boots.iff") object_tangible_wearables_armor_padded_shared_armor_padded_s01_bracer_l = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_bracer_l.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/armor_padded_s01_bracer_l_f.sat", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/bracer_l.iff", certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 261, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@wearables_detail:armor_padded_s01_bracer_l", gameObjectType = 261, locationReservationRadius = 0, lookAtText = "@wearables_lookat:armor_padded_s01_bracer_l", noBuildRadius = 0, objectName = "@wearables_name:armor_padded_s01_bracer_l", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 2948310718, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/wearables/base/shared_wearables_base.iff", "object/tangible/wearables/base/shared_armor_base.iff", "object/tangible/wearables/base/shared_base_bracer_l.iff"} ]] } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_padded_shared_armor_padded_s01_bracer_l, "object/tangible/wearables/armor/padded/shared_armor_padded_s01_bracer_l.iff") object_tangible_wearables_armor_padded_shared_armor_padded_s01_bracer_r = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_bracer_r.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/armor_padded_s01_bracer_r_f.sat", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/bracer_r.iff", certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 261, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@wearables_detail:armor_padded_s01_bracer_r", gameObjectType = 261, locationReservationRadius = 0, lookAtText = "@wearables_lookat:armor_padded_s01_bracer_r", noBuildRadius = 0, objectName = "@wearables_name:armor_padded_s01_bracer_r", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 3748586285, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/wearables/base/shared_wearables_base.iff", "object/tangible/wearables/base/shared_armor_base.iff", "object/tangible/wearables/base/shared_base_bracer_r.iff"} ]] } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_padded_shared_armor_padded_s01_bracer_r, "object/tangible/wearables/armor/padded/shared_armor_padded_s01_bracer_r.iff") object_tangible_wearables_armor_padded_shared_armor_padded_s01_chest_plate = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_chest_plate.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/armor_padded_s01_chest_plate_f.sat", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/vest.iff", certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 257, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@wearables_detail:armor_padded_s01_chest_plate", gameObjectType = 257, locationReservationRadius = 0, lookAtText = "@wearables_lookat:armor_padded_s01_chest_plate", noBuildRadius = 0, objectName = "@wearables_name:armor_padded_s01_chest_plate", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 927787210, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/wearables/base/shared_wearables_base.iff", "object/tangible/wearables/base/shared_base_vest.iff"} ]] } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_padded_shared_armor_padded_s01_chest_plate, "object/tangible/wearables/armor/padded/shared_armor_padded_s01_chest_plate.iff") object_tangible_wearables_armor_padded_shared_armor_padded_s01_gloves = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_gloves.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/armor_padded_s01_gloves_f.sat", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/gauntlets.iff", certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 262, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@wearables_detail:armor_padded_s01_gloves", gameObjectType = 262, locationReservationRadius = 0, lookAtText = "@wearables_lookat:armor_padded_s01_gloves", noBuildRadius = 0, objectName = "@wearables_name:armor_padded_s01_gloves", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 2813934470, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/wearables/base/shared_wearables_base.iff", "object/tangible/wearables/base/shared_armor_base.iff", "object/tangible/wearables/base/shared_base_gauntlets.iff"} ]] } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_padded_shared_armor_padded_s01_gloves, "object/tangible/wearables/armor/padded/shared_armor_padded_s01_gloves.iff") object_tangible_wearables_armor_padded_shared_armor_padded_s01_helmet = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_helmet.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/armor_padded_s01_helmet_f.sat", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/helmet_closed_full.iff", certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 258, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@wearables_detail:armor_padded_s01_helmet", gameObjectType = 258, locationReservationRadius = 0, lookAtText = "@wearables_lookat:armor_padded_s01_helmet", noBuildRadius = 0, objectName = "@wearables_name:armor_padded_s01_helmet", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 293198478, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/wearables/base/shared_wearables_base.iff", "object/tangible/wearables/base/shared_armor_base.iff", "object/tangible/wearables/base/shared_base_helmet_closed_full.iff"} ]] } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_padded_shared_armor_padded_s01_helmet, "object/tangible/wearables/armor/padded/shared_armor_padded_s01_helmet.iff") object_tangible_wearables_armor_padded_shared_armor_padded_s01_leggings = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_leggings.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/armor_padded_s01_leggings_f.sat", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/skirt.iff", certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 260, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@wearables_detail:armor_padded_s01_leggings", gameObjectType = 260, locationReservationRadius = 0, lookAtText = "@wearables_lookat:armor_padded_s01_leggings", noBuildRadius = 0, objectName = "@wearables_name:armor_padded_s01_leggings", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 547322785, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/wearables/base/shared_wearables_base.iff", "object/tangible/wearables/base/shared_base_skirt.iff"} ]] } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_padded_shared_armor_padded_s01_leggings, "object/tangible/wearables/armor/padded/shared_armor_padded_s01_leggings.iff")
--[[ Event system (aka pub/sub) mixin for any object or class. Written by Cosmin Apreutesei. Public Domain. Events are a way to associate an action with one or more callback functions to be called on that action, with the distinct ability to remove one or more callbacks later on, based on a criteria. This module is only a mixin (a plain table with methods). It must be added to your particular object system by copying the methods over to your base class. EVENT FACTS * events fire in the order in which they were added. * extra args passed to `fire()` are passed to each event handler. * if the method `obj:on_EVENT(args...)` is found, it is called first. * returning a non-nil value from a handler interrupts the event handling call chain and the value is returned back by `fire()`. * the meta-event called `'event'` is fired on all events (the name of the event that was fired is received as arg#1). * events can be tagged with multiple tags/namespaces `'event.ns1.ns2...'` or `{event, ns1, ns2, ...}`: tags/namespaces are useful for easy bulk event removal with `obj:off'.ns1'` or `obj:off({nil, ns1})`. * multiple handlers can be added for the same event and/or namespace. * handlers are stored in `self.__observers`. * tags/namespaces can be of any type, which allows objects to register event handlers on other objects using `self` as tag so they can later remove them with `obj:off({nil, self})`. * `obj:off()` can be safely called inside any event handler, even to remove itself. LIMITATIONS * no bubbling or trickling/capturing as there is no awareness of a hierarchy. Add them yourself as needed by walking up or down the tree and firing them for each node (don't forget to inject the target object in the arg list). EXAMPLES * `apple:on('falling.ns1.ns2', function(self, args...) ... end)` - register an event handler and associate it with the `ns1` and `ns2` tags/namespaces. * `apple:on({'falling', ns1, ns2}, function ... end)` - same but the tags can be any type. * `apple:once('falling', function ... end)` - fires only once. * `Apple:falling(args...)` - default event handler for the `falling` event. * `apple:fire('falling', args...)` - call all `falling` event handlers. * `apple:off'falling'` - remove all `falling` event handlers. * `apple:off'.ns1'` - remove all event handlers on the `ns1` tag. * `apple:off{nil, ns1}` - remove all event handlers on the `ns1` tag. * `apple:off() - remove all event handlers registered on `apple`. API obj:on('event[.ns1...]', function(self, args...) ... end) obj:on({event_name, ns1, ...}, function(self, args...) ... end) obj:once(event, function(self, args...) ... end) obj:fire(event, args...) -> ret obj:off('[event][.ns1...]') obj:off({[event], [ns1, ...]}) obj:off() ]] local glue = require'glue' local add = table.insert local remove = table.remove local indexof = glue.indexof local attr = glue.attr local events = {} --default values to speed up look-up in class systems with dynamic dispatch. events.event = false events.__observers = false local function parse_event(s) local ev, t if type(s) == 'table' then -- {ev|false, ns1, ...} local ev = s[1] or nil t = {} for i=2,#s do t[i-1] = s[i] end elseif s:find('.', 1, true) then -- `[ev].ns1.ns2` t = {} for s in s:gmatch'[^%.]*' do if not ev then ev = s elseif s ~= '' then add(t, s) end end else --`ev` ev = s end if ev == '' then ev = nil end return ev, t end --register a function to be called for a specific event type. function events:on(s, fn, on) if not fn then return end if on == false then return self:off(s, fn) end local ev, nss = parse_event(s) assert(ev, 'event name missing') local t = self.__observers if not t then t = {} self.__observers = t end local t = attr(t, ev) add(t, fn) if nss then for _,ns in ipairs(nss) do attr(t, ns)[fn] = true end end end --remove a handler or all handlers of an event and/or namespace. function events:off(s, fn) local t = self.__observers if not t then return end local ev, nss = parse_event(s) if fn then local t = t[ev] local i = t and indexof(fn, t) elseif ev and nss then local t = t[ev] if t then for _,ns in ipairs(nss) do local fns = t[ns] if fns then for fn in pairs(fns) do local i = indexof(fn, t) if i then remove(t, i) end fns[fn] = nil end end end end elseif ev then t[ev] = nil elseif nss then for _,ns in ipairs(nss) do for _,t in pairs(t) do local fns = t[ns] if fns then for fn in pairs(fns) do local i = indexof(fn, t) if i then remove(t, i) end fns[fn] = nil end end end end end end function events:once(ev, func) local ev, nss = parse_event(ev) local id = {} local ev if nss then add(nss, 1, ev) add(nss, id) else ev = {ev, id} end self:on(ev, function(...) self:off(ev) return func(...) end) end --fire an event, i.e. call its handler method and all observers. function events:fire(ev, ...) local fn = self['on_'..ev] if fn then local ret = fn(self, ...) if ret ~= nil then return ret end end local t = self.__observers local t = t and t[ev] if t then local i = 1 while true do local handler = t[i] if not handler then break end --list end or handler removed local ret = handler(self, ...) if ret ~= nil then return ret end if t[i] ~= handler then --handler was removed from inside itself, stay at i else i = i + 1 end end end if ev ~= 'event' then return self:fire('event', ev, ...) end end --tests ---------------------------------------------------------------------- if not ... then local obj = {} for k,v in pairs(events) do obj[k] = v end local n = 0 local t = {} local function handler_func(order) return function(self, a, b, c) assert(a == 3) assert(b == 5) assert(c == nil) n = n + 1 table.insert(t, order) end end obj:on('testing.ns1', handler_func(2)) obj:on('testing.ns2', handler_func(3)) obj:on('testing.ns3', handler_func(4)) obj.on_testing = handler_func(1) obj:fire('testing', 3, 5) assert(#t == 4) assert(t[1] == 1) assert(t[2] == 2) assert(t[3] == 3) assert(t[4] == 4) t = {} obj:off'.ns2' obj:fire('testing', 3, 5) assert(#t == 3) assert(t[1] == 1) assert(t[2] == 2) assert(t[3] == 4) t = {} obj:off'testing' obj:fire('testing', 3, 5) assert(#t == 1) assert(t[1] == 1) end return events
local EMPTY_VALUE = "NULL" local currentGame local lastGestationData = {} local function initCurrentGameObject() currentGame = {} currentGame["classKillCounts"] = {} currentGame["classBuildCounts"] = {} currentGame["classBuildCompleteCounts"] = {} currentGame["clients"] = {} currentGame["WeldHealth"] = {} currentGame["HealSpray"] = {} currentGame["ClassDurations"] = {} currentGame["HarvestersKilled"] = {} currentGame["ExtractorsKilled"] = {} currentGame["ParasitesInjested"] = {} currentGame["ParasitesLanded"] = {} end local trackedClassData = { {PlayerDataPropertyName="GorgeSeconds", TechId=kTechId.Gorge}, {PlayerDataPropertyName="LerkSeconds", TechId=kTechId.Lerk}, {PlayerDataPropertyName="FadeSeconds", TechId=kTechId.Fade}, {PlayerDataPropertyName="OnosSeconds", TechId=kTechId.Onos} } local function addClientClassDuration(client) if client and Shine:IsValidClient(client) and not TGNS.GetIsClientVirtual(client) then local lastGestation = lastGestationData[client] if lastGestation and lastGestation.what and lastGestation.when and currentGame then local classDuration = Shared.GetTime() - lastGestation.when currentGame["ClassDurations"][client] = currentGame["ClassDurations"][client] or {} local currentGameClassSeconds = currentGame["ClassDurations"][client][lastGestation.what.TechId] or 0 currentGame["ClassDurations"][client][lastGestation.what.TechId] = currentGameClassSeconds + classDuration lastGestationData[client] = nil -- TGNS.DebugPrint(string.format("addClientClassDuration[%s]: id=%s; techid=%s (%s); addingDuration=%s; totalDuration=%s", currentGame["startTimeSeconds"], TGNS.GetClientSteamId(client), lastGestation.what.PlayerDataPropertyName, lastGestation.what.TechId, classDuration, currentGame["ClassDurations"][client][lastGestation.what.TechId])) end end end local function audit(statementId, data, callback) local updateUrl = string.format("%s&v=%s&g=%s&s=%s&n=%s", TGNS.Config.AuditEndpointBaseUrl, TGNS.UrlEncode(json.encode(data)), TGNS.UrlEncode(Shine.GetGamemode()), statementId, TGNS.UrlEncode(TGNS.GetSimpleServerName())) -- TGNS.DebugPrint(string.format("Auditing URL: %s", updateUrl)) TGNS.GetHttpAsync(updateUrl, callback) end local function incrementCurrentGameClassKillCounts(killedPlayer) local className = TGNS.GetPlayerClassName(killedPlayer) currentGame["classKillCounts"][className] = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"][className]) + 1 end local Plugin = {} function Plugin:ClientConfirmConnect(client) end function Plugin:OnConstructInit(building) local className = building:GetClassName() if className:lower() ~= "cyst" then currentGame["classBuildCounts"][className] = TGNS.GetNumericValueOrZero(currentGame["classBuildCounts"][className]) + 1 -- Shared.Message("OnConstructInit - className: " .. tostring(className)) local originalSetConstructionComplete = building.SetConstructionComplete building.SetConstructionComplete = function(buildingSelf, builder) originalSetConstructionComplete(buildingSelf, builder) local builderClient = TGNS.GetClient(builder) if builderClient then local className = buildingSelf:GetClassName() -- Shared.Message("SetConstructionComplete - className: " .. tostring(className)) currentGame["classBuildCompleteCounts"][builderClient] = currentGame["classBuildCompleteCounts"][builderClient] or {} currentGame["classBuildCompleteCounts"][builderClient][className] = TGNS.GetNumericValueOrZero(currentGame["classBuildCompleteCounts"][builderClient][className]) + 1 end end end end function Plugin:OnEntityKilled(gamerules, victim, attacker, inflictor, point, dir) if attacker and inflictor and victim then local victimClassName = victim:GetClassName() if victimClassName == "Marine" then local primaryWeapon = victim.GetWeaponInHUDSlot and victim:GetWeaponInHUDSlot(1) if primaryWeapon then if primaryWeapon:isa("Shotgun") then victimClassName = "ShotgunMarine" elseif primaryWeapon:isa("Flamethrower") then victimClassName = "FlamethrowerMarine" elseif primaryWeapon:isa("GrenadeLauncher") then victimClassName = "GranadeLauncherMarine" end end elseif victimClassName == "Exo" then victimClassName = victim.layout end currentGame["classKillCounts"][victimClassName] = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"][victimClassName]) + 1 local attackerClient = TGNS.GetClient(attacker) if attackerClient then local currentGamePersonalCounterToIncrement if victim:isa("Harvester") then currentGamePersonalCounterToIncrement = "HarvestersKilled" elseif victim:isa("Extractor") then currentGamePersonalCounterToIncrement = "ExtractorsKilled" end if currentGamePersonalCounterToIncrement then currentGame[currentGamePersonalCounterToIncrement][attackerClient] = currentGame[currentGamePersonalCounterToIncrement][attackerClient] or 0 currentGame[currentGamePersonalCounterToIncrement][attackerClient] = currentGame[currentGamePersonalCounterToIncrement][attackerClient] + 1 end end end end function Plugin:PostJoinTeam(gamerules, player, oldTeamNumber, newTeamNumber, force, shineForce) local client = TGNS.GetClient(player) if TGNS.IsGameplayTeamNumber(newTeamNumber) then if TGNS.GetIsClientVirtual(client) then currentGame["includedBots"] = true else table.insertunique(currentGame["clients"], client) end end addClientClassDuration(client) end function Plugin:ClientDisconnect(client) addClientClassDuration(client) end function Plugin:Initialise() self.Enabled = true initCurrentGameObject() TGNS.RegisterEventHook("GameStarted", function(secondsSinceEpoch) initCurrentGameObject() currentGame["startTimeSeconds"] = secondsSinceEpoch currentGame["isCaptainsMode"] = Shine.Plugins.captains and Shine.Plugins.captains.IsCaptainsModeEnabled and Shine.Plugins.captains:IsCaptainsModeEnabled() currentGame["includedBots"] = TGNS.Any(TGNS.GetClientList(), TGNS.GetIsClientVirtual) TGNS.DoFor(TGNS.GetPlayingClients(TGNS.GetPlayerList()), function(c) table.insertunique(currentGame["clients"], c) end) lastGestationData = {} end) TGNS.RegisterEventHook("WinOrLoseCalled", function(teamNumber) currentGame["surrenderTeamNumber"] = teamNumber end) TGNS.RegisterEventHook("WinOrLoseCountdownChanged", function(countdownValue) currentGame["winOrLoseEndGameCountdownValue"] = countdownValue end) TGNS.RegisterEventHook("FullGamePlayed", function(clients, winningTeam, gameDurationInSeconds) TGNS.DoFor(clients, addClientClassDuration) local gamerules = GetGamerules() local gameData = {} gameData.StartTimeSeconds = currentGame["startTimeSeconds"] gameData.DurationInSeconds = gameDurationInSeconds gameData.WinningTeamNumber = winningTeam and winningTeam:GetTeamNumber() or 0 gameData.TotalPlayerCount = #currentGame["clients"] gameData.FullGameSupportingMemberCount = #TGNS.Where(clients, TGNS.IsClientSM) gameData.FullGamePrimerWithGamesCount = #TGNS.Where(clients, TGNS.HasClientSignedPrimerWithGames) gameData.FullGameStrangerCount = #TGNS.Where(clients, TGNS.IsClientStranger) gameData.SkulksKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["Skulk"]) gameData.GorgesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["Gorge"]) gameData.LerksKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["Lerk"]) gameData.FadesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["Fade"]) gameData.OnosKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["Onos"]) gameData.RifleMarinesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["Marine"]) gameData.JetpackMarinesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["JetpackMarine"]) gameData.ClawMinigunMarinesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["ClawMinigun"]) gameData.ClawRailgunMarinesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["ClawRailgun"]) gameData.MinigunMinigunMarinesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["MinigunMinigun"]) gameData.RailgunRailgunMarinesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["RailgunRailgun"]) gameData.ShotgunMarinesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["ShotgunMarine"]) gameData.FlamethrowerMarinesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["FlamethrowerMarine"]) gameData.GrenadeLauncherMarinesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["GranadeLauncherMarine"]) gameData.HivesKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["Hive"]) gameData.ChairsKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["CommandStation"]) gameData.HarvestersKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["Harvester"]) gameData.ExtractorsKilled = TGNS.GetNumericValueOrZero(currentGame["classKillCounts"]["Extractor"]) gameData.CaptainsMode = currentGame["isCaptainsMode"] == true gameData.SurrenderTeamNumber = currentGame["surrenderTeamNumber"] or EMPTY_VALUE gameData.WinOrLoseEndGameCountdownValue = currentGame["winOrLoseEndGameCountdownValue"] or EMPTY_VALUE gameData.MarineTeamResourcesTotal = gamerules.team1:GetTotalTeamResources() gameData.AlienTeamResourcesTotal = gamerules.team2:GetTotalTeamResources() gameData.MarineStartLocationName = gamerules.startingLocationNameTeam1 or EMPTY_VALUE gameData.AlienStartLocationName = gamerules.startingLocationNameTeam2 or EMPTY_VALUE gameData.StartingLocationsPathDistance = gamerules.startingLocationsPathDistance or EMPTY_VALUE gameData.MarineBonusResourcesAwarded = (Shine.Plugins.tf_comeback and Shine.Plugins.tf_comeback.Enabled and Shine.Plugins.tf_comeback.GetBonusResourcesAwardedSoFar) and Shine.Plugins.tf_comeback:GetBonusResourcesAwardedSoFar(1) or 0 gameData.AlienBonusResourcesAwarded = (Shine.Plugins.tf_comeback and Shine.Plugins.tf_comeback.Enabled and Shine.Plugins.tf_comeback.GetBonusResourcesAwardedSoFar) and Shine.Plugins.tf_comeback:GetBonusResourcesAwardedSoFar(2) or 0 gameData.StartingLocationsPathDistance = gamerules.startingLocationsPathDistance or EMPTY_VALUE gameData.BuildNumber = Shared.GetBuildNumber() gameData.MapName = TGNS.GetCurrentMapName() gameData.IncludedBots = currentGame["includedBots"] audit(382, gameData, function(gameDataAuditResponseJson) local gameDataAuditResponse = json.decode(gameDataAuditResponseJson) or {} if gameDataAuditResponse.success then TGNS.DoFor(clients, function(c) if Shine:IsValidClient(c) and not TGNS.GetIsClientVirtual(c) then TGNS.ScheduleAction(0, function() if Shine:IsValidClient(c) then local p = TGNS.GetPlayer(c) local playerData = {} playerData.StartTimeSeconds = gameData.StartTimeSeconds playerData.PlayerId = TGNS.GetClientSteamId(c) playerData.MarineSeconds = p:GetMarinePlayTime() playerData.AlienSeconds = p:GetAlienPlayTime() playerData.CommanderSeconds = p:GetCommanderTime() playerData.EndGameCommander = Shine.Plugins.communityslots.IsClientRecentCommander and Shine.Plugins.communityslots:IsClientRecentCommander(c) playerData.Captain = Shine.Plugins.captains.IsClientCaptain and Shine.Plugins.captains:IsClientCaptain(c) playerData.Score = TGNS.GetPlayerScore(p) playerData.Kills = TGNS.GetPlayerKills(p) playerData.Assists = TGNS.GetPlayerAssists(p) playerData.Deaths = TGNS.GetPlayerDeaths(p) playerData.SupportingMember = TGNS.IsClientSM(c) playerData.PrimerSignerWithGames = TGNS.HasClientSignedPrimerWithGames(c) playerData.Stranger = TGNS.IsClientStranger(c) playerData.WeldGave = TGNS.GetNumericValueOrZero(currentGame["WeldHealth"][c]) playerData.HealSprayGave = TGNS.GetNumericValueOrZero(currentGame["HealSpray"][c]) playerData.HarvestersKilled = TGNS.GetNumericValueOrZero(currentGame["HarvestersKilled"][c]) playerData.ExtractorsKilled = TGNS.GetNumericValueOrZero(currentGame["ExtractorsKilled"][c]) playerData.ParasitesInjested = TGNS.GetNumericValueOrZero(currentGame["ParasitesInjested"][c]) playerData.ParasitesLanded = TGNS.GetNumericValueOrZero(currentGame["ParasitesLanded"][c]) currentGame["ClassDurations"][c] = currentGame["ClassDurations"][c] or {} TGNS.DoFor(trackedClassData, function(d) playerData[d.PlayerDataPropertyName] = currentGame["ClassDurations"][c][d.TechId] or 0 end) playerData.GorgeSeconds = currentGame["ClassDurations"][c][kTechId.Gorge] or 0 playerData.LerkSeconds = currentGame["ClassDurations"][c][kTechId.Lerk] or 0 playerData.FadeSeconds = currentGame["ClassDurations"][c][kTechId.Fade] or 0 playerData.OnosSeconds = currentGame["ClassDurations"][c][kTechId.Onos] or 0 playerData.StructuresBuilt = 0 playerData.HarvestersBuilt = 0 playerData.ExtractorsBuilt = 0 TGNS.DoForPairs(currentGame["classBuildCompleteCounts"][c], function(className, count) playerData.StructuresBuilt = playerData.StructuresBuilt + 1 if className == "Harvester" then playerData.HarvestersBuilt = playerData.HarvestersBuilt + 1 elseif className == "Extractor" then playerData.ExtractorsBuilt = playerData.ExtractorsBuilt + 1 end end) playerData.IPV4 = IPAddressToString(Server.GetClientAddress(c)) audit(718, playerData, function(playerDataAuditResponseJson) local playerDataAuditResponse = json.decode(playerDataAuditResponseJson) or {} if playerDataAuditResponse.success then if gameData.TotalPlayerCount >= 8 then if playerData.CommanderSeconds > (gameData.DurationInSeconds / 2) and not gameData.IncludedBots then TGNS.Karma(playerData.PlayerId, "Commanding") end if playerData.Captain then TGNS.Karma(playerData.PlayerId, "BeingCaptain") end end else TGNS.DebugPrint(string.format("audit ERROR: Unable to audit playerData. msg: %s | stacktrace: %s", playerDataAuditResponse.msg, playerDataAuditResponse.stacktrace)) TGNS.PrintTable(playerData, "playerData", function(x) TGNS.DebugPrint(x) end) end end) end end) end end) else TGNS.DebugPrint(string.format("audit ERROR: Unable to audit gameData. msg: %s | stacktrace: %s", gameDataAuditResponse.msg, gameDataAuditResponse.stacktrace), false, "audit") TGNS.PrintTable(gameData, "gameData", function(x) TGNS.DebugPrint(x) end) end end) end, TGNS.HIGHEST_EVENT_HANDLER_PRIORITY) local originalAddContinuousScore originalAddContinuousScore = TGNS.ReplaceClassMethod("ScoringMixin", "AddContinuousScore", function(self, name, addAmount, amountNeededToScore, pointsGivenOnScore) originalAddContinuousScore(self, name, addAmount, amountNeededToScore, pointsGivenOnScore) local client = TGNS.GetClient(self) if client then currentGame[name][client] = TGNS.GetNumericValueOrZero(currentGame[name][client]) + addAmount end end) local originalParasiteMixinSetParasited = ParasiteMixin.SetParasited ParasiteMixin.SetParasited = function(parasiteMixinSelf, fromPlayer, durationOverride) local wasParasited = parasiteMixinSelf.parasited originalParasiteMixinSetParasited(parasiteMixinSelf, fromPlayer, durationOverride) if (durationOverride or kParasiteDuration) == kParasiteDuration and not wasParasited then local victimClient = TGNS.GetClient(parasiteMixinSelf) if victimClient then currentGame["ParasitesInjested"][victimClient] = currentGame["ParasitesInjested"][victimClient] or 0 currentGame["ParasitesInjested"][victimClient] = currentGame["ParasitesInjested"][victimClient] + 1 end local fromClient = TGNS.GetClient(fromPlayer) if fromClient then currentGame["ParasitesLanded"][fromClient] = currentGame["ParasitesLanded"][fromClient] or 0 currentGame["ParasitesLanded"][fromClient] = currentGame["ParasitesLanded"][fromClient] + 1 end end end local originalEmbryoSetGestationData = Embryo.SetGestationData Embryo.SetGestationData = function(embryoSelf, techIds, previousTechId, healthScalar, armorScalar) originalEmbryoSetGestationData(embryoSelf, techIds, previousTechId, healthScalar, armorScalar) local client = TGNS.GetClient(embryoSelf) addClientClassDuration(client) local trackedClass = TGNS.FirstOrNil(trackedClassData, function(d) return TGNS.Has(techIds, d.TechId) end) if trackedClass then lastGestationData[client] = {when=Shared.GetTime(),what=trackedClass} end end local originalPlayerOnKill = Player.OnKill Player.OnKill = function(playerSelf, killer, doer, point, direction) originalPlayerOnKill(playerSelf, killer, doer, point, direction) local client = TGNS.GetClient(playerSelf) addClientClassDuration(client) end return true end function Plugin:Cleanup() --Cleanup your extra stuff like timers, data etc. self.BaseClass.Cleanup( self ) end Shine:RegisterExtension("audit", Plugin )
RegisterServerEvent('npc-vehicleshop.requestInfo') AddEventHandler('npc-vehicleshop.requestInfo', function() local src = source local user = exports["npc-core"]:getModule("Player"):GetUser(src) local firstname = user:getCurrentCharacter().first_name local rows TriggerClientEvent('npc-vehicleshop.receiveInfo', src, user:getBalance(), firstname) TriggerClientEvent("npc-vehicleshop.notify", src, 'error', 'Use A and D To Rotate') end) RegisterServerEvent('npc-vehicleshop.isPlateTaken') AddEventHandler('npc-vehicleshop.isPlateTaken', function (plate) local src = source exports.ghmattimysql:execute("SELECT * FROM `player_vehicles` WHERE `plate` = @plate", {["plate"] = plate}, function(result) TriggerClientEvent('npc-vehicleshop.isPlateTaken', src, (result[1] ~= nil)) end) end) RegisterServerEvent('npc-vehicleshop.CheckMoneyForVeh') AddEventHandler('npc-vehicleshop.CheckMoneyForVeh', function(veh, price, name, vehicleProps) local src = source local user = exports["npc-core"]:getModule("Player"):GetUser(src) local chrctr = user:getCurrentCharacter() local bankbal = user:getBalance() if bankbal >= tonumber(price) then user:removeBank(tonumber(price)) local vehiclePropsjson = json.encode(vehicleProps) if Cfg.SpawnVehicle then stateVehicle = 0 else stateVehicle = 1 end local q = [[INSERT INTO player_vehicles (steam, cid, vehicle, hash, mods, plate, state) VALUES(@steam, @cid, @vehicle, @hash, @mods, @plate, @state);]] local v = { ["steam"] = chrctr.owner, ["cid"] = chrctr.id, ["vehicle"] = veh, ["hash"] = GetHashKey(veh), ["mods"] = vehiclePropsjson, ["plate"] = vehicleProps.plate, ["state"] = stateVehicle } exports.ghmattimysql:execute(q, v) TriggerClientEvent("npc-vehicleshop.successfulbuy", source, name, vehicleProps.plate, price) TriggerClientEvent('npc-vehicleshop.receiveInfo', src, user:getBalance()) TriggerClientEvent('npc-vehicleshop.spawnVehicle', src, veh, vehicleProps.plate) else TriggerClientEvent("npc-vehicleshop.notify", source, 'error', 'Not Enough Money') end end) RegisterServerEvent('npc-vehicleshop:npcCreate') AddEventHandler('npc-vehicleshop:npcCreate', function() TriggerClientEvent('npc-vehicleshop:npcCreate', -1) end)
-- Buildat: extension/sandbox_test/init.lua -- http://www.apache.org/licenses/LICENSE-2.0 -- Copyright 2014 Perttu Ahola <celeron55@gmail.com> local log = buildat.Logger("sandbox_test") local dump = buildat.dump local try_exploit = dofile(buildat.extension_path("sandbox_test").."/try_exploit.lua") local M = {} local function get_file_content(path) local f = io.open(path, "rb") if not f then log:error("Could not open file "..dump(path)) return nil end local content = f:read("*all") f:close() return content end local function run_in_sandbox(content, chunkname) local sandbox_status = nil local f = function() sandbox_status = __buildat_run_code_in_sandbox(content, chunkname) end local status, err = __buildat_pcall(f) if err then log:verbose(err) end return sandbox_status end function M.run() log:info("sandbox_test(): Begin") local ext_path = buildat.extension_path("sandbox_test") local tmp_path = buildat.extension_path("sandbox_test") -- Check that running safe code works log:info("sandbox_test(): Testing safe code") local safe_content = get_file_content(ext_path.."/tests/safe.lua") assert(safe_content) local success = run_in_sandbox(safe_content, "=safe.lua") assert(success) -- Check that running the safe code as bytecode doesn't work log:info("sandbox_test(): Testing bytecode") local f, err = loadstring(safe_content) if f == nil then error("Could not load bytecode source: "..err) end local bytecode = string.dump(f) local success = run_in_sandbox(bytecode) assert(success == false) -- Run the exploit search log:info("sandbox_test(): Trying to find an exploit") try_exploit.run() log:info("sandbox_test(): Finished") end -- Enabled when this module is loaded. -- Normally that happens when KEY_F10 is pressed on the client. local value_checker_enabled = true function M.check_value(value) if not value_checker_enabled then return end log:debug("sandbox_test.check_value()") try_exploit.search_single_value(value) end __buildat_sandbox_debug_check_value_sub(M.check_value) local is_active = false function M.toggle() -- Called by client/app if not is_active then M.run() value_checker_enabled = true is_active = true else value_checker_enabled = false is_active = false end end return M -- vim: set noet ts=4 sw=4:
------------------------------------------------- -- AE2 auto craft 'fluix crystal' 自動生成用プログラム -- 要求最大128個ver -- -- creater 'wusagi24' ------------------------------------------------- local material_1_slot = 1 local material_2_slot = 2 local material_3_slot = 3 local product_slot = 16 while true do -- インベントリにアイテムが入るのを待つ local evt = os.pullEvent("turtle_inventory") -- インベントリにアイテムが入る print("change inventory") print() -- インベントリに素材がある程度搬入されるまで待つ -- sleep(3) repeat -- 素材スロットのアイテムを32セット真下にドロップする [*] turtle.select(material_1_slot) turtle.dropDown(1) turtle.select(material_2_slot) turtle.dropDown(1) turtle.select(material_3_slot) turtle.dropDown(1) -- 一定時間待機する sleep(4) -- 完成品スロットに移動 turtle.select(product_slot) -- 真下のアイテムを完成品スロットに拾う while turtle.suckDown() do -- 完成品スロットのアイテムを正面に送り出す turtle.drop() end -- 素材スロットにまだアイテムセットがあれば[*] に戻る until turtle.getItemCount(material_1_slot) <= 0 -- 待機状態に戻る end
-- Toggle dynamic lighting on blaster bolts if !ConVarExists("cl_dynamic_tracer") then CreateClientConVar("cl_dynamic_tracer", 1, true, false, "Enable/Disable dynamic lighting on Star Wars weapons") end
-- Licensed to the public under the Apache License 2.0. local m = Map("radicale2", translate("Radicale 2.x"), translate("A lightweight CalDAV/CardDAV server")) local s = m:section(NamedSection, "logging", "section", translate("Logging")) s.addremove = true s.anonymous = false local logging_file = nil logging_file = s:option(FileUpload, "config", translate("Logging File"), translate("Log configuration file (no file means default procd which ends up in syslog")) logging_file.rmempty = true logging_file.default = "" o = s:option(Button, "remove_conf", translate("Remove configuration for logging"), translate("This permanently deletes configuration for logging")) o.inputstyle = "remove" function o.write(self, section) if logging_file:cfgvalue(section) and fs.access(logging_file:cfgvalue(section)) then fs.unlink(loggin_file:cfgvalue(section)) end self.map:del(section, "config") luci.http.redirect(luci.dispatcher.build_url("admin", "services", "radicale2", "logging")) end o = s:option(Flag, "debug", translate("Debug"), translate("Send debug information to logs")) o.rmempty = true o.default = o.disabled o = s:option(Flag, "full_environment", translate("Dump Environment"), translate("Include full environment in logs")) o.rmempty = true o.default = o.disabled o = s:option(Flag, "mask_passwords", translate("Mask Passwords"), translate("Redact passwords in logs")) o.rmempty = true o.default = o.enabled -- TODO: Allow configuration logging file from this page return m
project "VortexAnimatSim" language "C++" kind "SharedLib" files { "../*.h", "../*.cpp"} configuration { "Debug or Debug_Double", "windows" } includedirs { "../../../include", "../../../../3rdParty/Vortex_5_1/include", "../../../../3rdParty/Vortex_5_1/3rdparty/osg-2.8.3/include", "../../../../3rdParty/Vortex_5_1/3rdparty/sdl-1.2.14/include", "../../StdUtils", "../../AnimatSim", "../../../../3rdParty/boost_1_54_0"} libdirs { "../../../lib", "$(OutDir)", "../../../../3rdParty/Vortex_5_1/3rdparty/osg-2.8.3/lib", "../../../../3rdParty/Vortex_5_1/lib", "../../../../3rdParty/Vortex_5_1/3rdparty/boost-1.45.0/lib", "../../../../3rdParty/Vortex_5_1/3rdparty/sdl-1.2.14/lib", "../../../../3rdParty/boost_1_54_0/lib" } defines { "WIN32", "_DEBUG", "_WINDOWS", "_USRDLL", "VORTEXANIMATLIBRARY_EXPORTS", "_CRT_SECURE_NO_WARNINGS" } flags { "Symbols", "SEH" } targetdir ("Debug") targetname ("VortexAnimatSim_vc10D") links { "libVx51d", "libVxController51d", "libVxControllerPersistence51d", "libVxGraphics51d", "libVxPersistence51d", "libVxPs51d", "libVxPsExtraOSG51d", "libVxVehicle51d", "libVxVehiclePersistence51d", "libVxExtra51d", "libVxExtraOSG51d", "libVxVehicleExtra51d", "libVxVehicleExtraOSG51d", "libVxOSG51d-2.8.3", "libboostVx_filesystem-vc100-mt-gd", "libboostVx_regex-vc100-mt-gd", "libboostVx_serialization-vc100-mt-gd", "libboostVx_system-vc100-mt-gd", "OpenThreadsd", "osgAnimationd", "osgd", "osgDBd", "osgFXd", "osgGAd", "osgManipulatord", "osgParticled", "osgShadowd", "osgSimd", "osgTerraind", "osgTextd", "osgUtild", "osgViewerd", "osgVolumed", "osgWidgetd", "SDL", "opengl32", "wsock32", "netapi32", "comctl32", "wbemuuid" } postbuildcommands { "Copy $(OutDir)VortexAnimatSim_vc10D.lib ..\\..\\..\\lib\\VortexAnimatSim_vc10D.lib", "Copy $(TargetPath) ..\\..\\..\\bin" } configuration { "Release or Release_Double", "windows" } includedirs { "../../../include", "../../../../3rdParty/Vortex_5_1/include", "../../../../3rdParty/Vortex_5_1/3rdparty/osg-2.8.3/include", "../../../../3rdParty/Vortex_5_1/3rdparty/sdl-1.2.14/include", "../../StdUtils", "../../AnimatSim", "../../../../3rdParty/boost_1_54_0"} libdirs { "../../../lib", "$(OutDir)", "../../../../3rdParty/Vortex_5_1/3rdparty/osg-2.8.3/lib", "../../../../3rdParty/Vortex_5_1/lib", "../../../../3rdParty/Vortex_5_1/3rdparty/boost-1.45.0/lib", "../../../../3rdParty/Vortex_5_1/3rdparty/sdl-1.2.14/lib", "../../../../3rdParty/boost_1_54_0/lib" } defines { "WIN32", "NDEBUG", "_WINDOWS", "_USRDLL", "VORTEXANIMATLIBRARY_EXPORTS" } flags { "Optimize", "SEH" } targetdir ("Release") targetname ("VortexAnimatSim_vc10") links { "libVx51", "libVxController51", "libVxControllerPersistence51", "libVxGraphics51", "libVxPersistence51", "libVxPs51", "libVxPsExtraOSG51", "libVxVehicle51", "libVxVehiclePersistence51", "libVxExtra51", "libVxExtraOSG51", "libVxVehicleExtra51", "libVxVehicleExtraOSG51", "libVxOSG51-2.8.3", "libboostVx_filesystem-vc100-mt", "libboostVx_regex-vc100-mt", "libboostVx_serialization-vc100-mt", "libboostVx_system-vc100-mt", "OpenThreads", "osgAnimation", "osg", "osgDB", "osgFX", "osgGA", "osgManipulator", "osgParticle", "osgShadow", "osgSim", "osgTerrain", "osgText", "osgUtil", "osgViewer", "osgVolume", "osgWidget", "SDL", "opengl32", "wsock32", "netapi32", "comctl32", "wbemuuid" } postbuildcommands { "Copy $(OutDir)VortexAnimatSim_vc10.lib ..\\..\\..\\lib\\VortexAnimatSim_vc10.lib", "Copy $(TargetPath) ..\\..\\..\\bin" }
ENT.Base = "base_ai" ENT.Type = "ai" ENT.PrintName = "Black Helicopter" ENT.Author = "Shark_vil by. Xystus234" ENT.Contact = "https://steamcommunity.com/groups/fgserv" ENT.Purpose = "Helicopter for battles." ENT.Instructions = "You can spawn it through the Sandbox menu, in the NPC tab, in the SCP:CB category." ENT.Information = "Security helicopter of the fund." ENT.Category = "SCP:CB" ENT.AutomaticFrameAdvance = true ENT.Spawnable = false ENT.AdminSpawnable = false function ENT:SetAutomaticFrameAdvance( bUsingAnim ) self.AutomaticFrameAdvance = bUsingAnim end
function WallMovementMixin:TraceWallNormal(startPoint, endPoint, result, feelerSize) local theTrace = Shared.TraceCapsule(startPoint, endPoint, feelerSize, 0, CollisionRep.Move, PhysicsMask.AllButPCs, EntityFilterOneAndIsaActual(self, "Babbler")) --[[ double-comment to see wall-walk traces if Client then DebugLine(startPoint, theTrace.endPoint, 5, 0,1,0,1) end --]] if self:ValidWallTrace(theTrace) then table.insert(result, theTrace.normal) return true end return false end
addCommandHandler("rapor", function(cmd, ...) if getElementData(localPlayer, "loggedin") == 1 then if not (...) then outputChatBox(exports.mrp_pool:getServerSyntax(false, "e").."/rapor <bilgi>", 255, 255, 255, true) return end local message = table.concat({...}, " ") triggerServerEvent("clientSendReport", localPlayer, localPlayer, message, 1) end end ) addCommandHandler("sorusor", function(cmd, ...) if getElementData(localPlayer, "loggedin") == 1 then if not (...) then outputChatBox(exports.mrp_pool:getServerSyntax(false, "w").."/sorusor <soru içeriği>", 255, 255, 255, true) return end local message = table.concat({...}, " ") triggerServerEvent("clientSendReport", localPlayer, localPlayer, message, 2) end end )
local server = require "nvim-lsp-installer.server" local installers = require "nvim-lsp-installer.installers" local path = require "nvim-lsp-installer.path" local zx = require "nvim-lsp-installer.installers.zx" local root_dir = server.get_server_root_path "ruby" return server.Server:new { name = "solargraph", root_dir = root_dir, installer = installers.when { unix = zx.file "./install.mjs", }, pre_install_check = function() if vim.fn.executable "bundle" ~= 1 then error "bundle not installed" end end, default_options = { cmd = { path.concat { root_dir, "solargraph", "solargraph" }, "stdio" }, }, }
/* * @package : rlib * @module : promises * @author : Richard [http://steamcommunity.com/profiles/76561198135875727] * @copyright : (C) 2020 - 2020 * @since : 1.0.0 * @website : https://rlib.io * @docs : https://docs.rlib.io * * MIT License * * 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. */ /* * @package : promises * @author : Lex Robinson * @copyright : (C) 2013 * * MIT License * * 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. */ /* * standard tables and localization */ rlib = rlib or { } local base = rlib local mf = base.manifest local pf = mf.prefix /* * lib includes */ local access = base.a local helper = base.h /* * localizations */ local smt = setmetatable local table = table local pairs = pairs local ipairs = ipairs local error = error local istable = istable local sf = string.format /* * simplifiy funcs */ local function con( ... ) base:console( ... ) end local function log( ... ) base:log( ... ) end /* * prefix :: create id */ local function pref( id, suffix ) local affix = istable( suffix ) and suffix.id or isstring( suffix ) and suffix or prefix affix = affix:sub( -1 ) ~= '.' and sf( '%s.', affix ) or affix id = isstring( id ) and id or 'noname' id = id:gsub( '[%c%s]', '.' ) return sf( '%s%s', affix, id ) end /* * prefix :: handle */ local function pid( str, suffix ) local state = ( isstring( suffix ) and suffix ) or ( base and mf.prefix ) or false return pref( str, state ) end /* * declarations */ local M = { } local deferred = { } deferred.__index = deferred /* * declare :: status */ local PENDING = 0 local RESOLVING = 1 local REJECTING = 2 local RESOLVED = 3 local REJECTED = 4 /* * finish */ local function finish( deferred, state ) state = state or REJECTED for i, f in ipairs( deferred.queue ) do if state == RESOLVED then f:resolve( deferred.value ) else f:reject( deferred.value ) end end deferred.state = state end /* * isfunc */ local function isfunc( f ) if type( f ) == 'table' then local mt = getmetatable( f ) return mt ~= nil and type( mt.__call ) == 'function' end return type( f ) == 'function' end /* * promise */ local function promise( deferred, next, success, failure, nonpromisecb ) if istable( deferred ) and istable( deferred.value ) and isfunc( next ) then local called = false local ok, err = pcall( next, deferred.value, function( v ) if called then return end called = true deferred.value = v success( ) end, function( v ) if called then return end called = true deferred.value = v failure( ) end ) if not ok and not called then deferred.value = err failure( ) end else nonpromisecb( ) end end /* * fire */ local function fire( deferred ) local next if type( deferred.value ) == 'table' then next = deferred.value.next end promise( deferred, next, function( ) deferred.state = RESOLVING fire( deferred ) end, function( ) deferred.state = REJECTING fire( deferred ) end, function( ) local ok local v if deferred.state == RESOLVING and isfunc( deferred.success ) then ok, v = pcall( deferred.success, deferred.value ) elseif deferred.state == REJECTING and isfunc( deferred.failure ) then ok, v = pcall( deferred.failure, deferred.value ) if ok then deferred.state = RESOLVING end end if ok ~= nil then if ok then deferred.value = v else deferred.value = v return finish( deferred ) end end if deferred.value == deferred then deferred.value = pcall( error, 'resolving promise with itself' ) return finish( deferred ) else promise( deferred, next, function( ) finish( deferred, RESOLVED ) end, function( state ) finish( deferred, state ) end, function( ) finish( deferred, deferred.state == RESOLVING and RESOLVED ) end ) end end ) end /* * resolve */ local function resolve( deferred, state, value ) if deferred.state == 0 then deferred.value = value deferred.state = state fire( deferred ) end return deferred end /* * PUBLIC */ /* * deferred :: resolve */ function deferred:resolve( val ) return resolve( self, RESOLVING, val ) end /* * deferred :: reject */ function deferred:reject( val ) return resolve( self, REJECTING, val ) end /* * new * * returns a new promise object * * @ex : local deferred = require( 'deferred' ) */ function M.new( options ) if isfunc( options ) then local d = M.new( ) local ok, err = pcall( options, d ) if not ok then d:reject( err ) end return d end options = options or { } local d d = { next = function( self, success, failure ) local next = M.new( { success = success, failure = failure, extend = options.extend } ) if d.state == RESOLVED then next:resolve( d.value ) elseif d.state == REJECTED then next:reject( d.value ) else table.insert( d.queue, next ) end return next end, state = 0, queue = { }, success = options.success, failure = options.failure, } d = smt( d, deferred ) if isfunc( options.extend ) then options.extend( d ) end return d end /* * all * * returns a new promise object that is resolved when all promises are resolved/rejected. */ function M.all( args ) local d = M.new( ) if #args == 0 then return d:resolve( { } ) end local method = 'resolve' local pending = #args local results = { } local function synchronizer( i, resolved ) return function( value ) results[ i ] = value if not resolved then method = 'reject' end pending = pending - 1 if pending == 0 then d[ method ]( d, results ) end return value end end for i = 1, pending do args[ i ]:next( synchronizer( i, true ), synchronizer( i, false ) ) end return d end /* * new * * returns a new promise object that is resolved with the values * of sequential application of function fn to each element in the * list. fn is expected to return promise object. */ function M.map( args, fn ) local d = M.new( ) local results = { } local function donext( i ) if i > #args then d:resolve( results ) else fn( args[ i ] ):next( function( res ) table.insert( results, res ) donext( i + 1 ) end, function( err ) d:reject( err ) end ) end end donext( 1 ) return d end /* * first * * returns a new promise object that is resolved as soon as * the first of the promises gets resolved/rejected. */ function M.first( args ) local d = M.new( ) for _, v in ipairs( args ) do v:next( function( res ) d:resolve(res) end, function( err ) d:reject( err ) end ) end return d end return M
-- test case:__index is a table print("----------test case 1----------") local mt = { [1] = 2020 } local tbl = setmetatable({}, { __index = mt }) print(tbl[1]) print(tbl[2]) -- test case2 print("----------test case 2----------") local c2_mt0 = { world = "hello" } local c2_mt1 = { hello = "world" } setmetatable(c2_mt1, { __index = c2_mt0 }) local c2_tbl = setmetatable({}, { __index = c2_mt1 }) print(c2_tbl.world) print(c2_tbl.hello) print(c2_tbl.xxx) print(c2_mt1.hello) print(c2_mt1.world) print(c2_mt0.hello) print(c2_mt0.world) -- test case3 print("----------test case 3----------") local c3_mt0 = setmetatable({}, { __index = function(t, k) print(t, k) end }) local c3_mt1 = setmetatable({}, { __index = c3_mt0 }) local c3_tbl = setmetatable({}, { __index = c3_mt1 }) print(c3_mt1.hello) print(c3_tbl.hello) -- test case4 print("----------test case 4----------") local c4_mt0 = setmetatable({}, { __index = function(t, k) print("c4_mt0") end }) local c4_mt1 = setmetatable({}, { __index = function(t, k) print("c4_mt1"); return "hello world" end }) local c4_tbl = setmetatable({}, { __index = c4_mt1 }) print(c4_mt1.hello) print(c4_tbl.hello) -- test case5 print("----------test case 5----------") local c5_mt0 = setmetatable({}, { __newindex = function(t, k, v) print("c5_mt0"); print(t, k, v) end }) local c5_mt1 = setmetatable({}, { __newindex = function(t, k, v) print("c5_mt1"); print(t, k, v) end }) local c5_tbl = setmetatable({}, { __newindex = c5_mt1}) c5_tbl.key = "key" print(c5_tbl.key) c5_mt1.key = "key_c5_mt1" print(c5_tbl.key) -- test case6 print("----------test case 6----------") local c6_mt0 = {} local c6_mt1 = setmetatable({}, { __newindex = c6_mt0 }) local c6_mt2 = setmetatable({}, { __newindex = c6_mt1 }) c6_mt2.key = "key1" print(c6_mt2.key) print(c6_mt1.key) print(c6_mt0.key) c6_mt1.key = "key2" print(c6_mt0.key) -- test case7 print("----------test case 7----------") local t1, t2 = {}, {} setmetatable(t1, { __add = function(lhs, rhs) print(lhs, rhs); return 0 end }) local t3 = t1 + t2 print(t3) -- ignore more binary arith test cases -- test case8 print("----------test case 8----------") local c8_t1 = { value = 1 } local c8_t2 = { value = 2 } setmetatable(c8_t1, { __eq = function(lhs, rhs) print("__eq"); return lhs.value == rhs.value end, __lt = function(lhs, rhs) print("__lt"); return lhs.value < rhs.value end, __le = function(lhs, rhs) print("__le"); return lhs.value <= rhs.value end, __concat = function(lhs, rhs) return tostring(lhs.value) .. tostring(rhs.value) end, }) print(c8_t1 == c8_t2) print(c8_t1 < c8_t2) print(c8_t1 <= c8_t2) print(c8_t1 .. c8_t2)
local insert,getn,remove = table.insert,table.getn,table.remove local p = require('pretty-print').prettyPrint local Events = { name = "Events", magicalCharacters = {'+','-','*','.','?','^','@',"#"}, registeredEvents = { Emoji = {} }, pendent = { guildLoad = {} }, redirections = {}, whitelistedCommands = {} } local function EndsWith(str1, str2) return str == "" or str1:sub(-#str2) == str2 end function Events.onMessage(msg) --Check if its a command, if it is then attempt to run it if msg.author.bot then return end local words = {} for w in msg.content:gmatch("%g+") do insert(words, w) end words.msg = msg if #Events.redirections > 0 then for _, redirector in ipairs(Events.redirections) do local result = {redirector.inspector(words)} if result and result[1] then redirector.consumer(table.unpack(result)) return true end end end local prefix = Events.prefix local st = msg.content:find(Events.prefix) if st ~= 1 then return else for _,v in ipairs(Events.magicalCharacters) do if EndsWith(prefix,v) then prefix = prefix:gsub("%"..v,"%%"..v) -- Ugly stuff here, we check if it ends with a magical character and break end end local command = remove(words, 1):gsub(prefix,"") if not msg.guild then if not Events.whitelistedCommands[command] then msg:reply("Excuse me sir, but I'm not employed to do private affairs!") return false end local s,e = Commands:Run(command, words, msg) else local s,e = Commands:Run(command, words, msg) end end end function Events.onReady() print("Ready!") end function Events.onReact(...) local args = {...} if args[3] then Events:callBack("Emoji",args[3],{hash=args[3],msgId=args[2],userId = args[4]}) else Events:callBack("Emoji",args[1].emojiName,{hash=args[1].emojiName,msgId=args[1].message.id,userId=args[2]}) end end function Events:registerEvent(eventType,eventKey,callback) if not self.registeredEvents[eventType] then return false end if not self.registeredEvents[eventType][eventKey] then self.registeredEvents[eventType][eventKey] = {} end insert(self.registeredEvents[eventType][eventKey],callback) end function Events:callBack(eventType,eventKey,args) for k,v in pairs(self.registeredEvents) do if k == eventType then if not v[eventKey] then print("Key is not registered!") return false end for _,z in ipairs(v[eventKey]) do z(args) end break end end end function Events:registerRedirect(inspector, consumer) table.insert(self.redirections, { inspector = inspector, consumer = consumer }) end function Events:whitelistPrivateCommand(name) self.whitelistedCommands[name] = true end function Events:__init() if not _G.dev then self.prefix = self.Deps.Config.Defaults.Prefix else self.prefix = self.Deps.Config.Defaults.DevPrefix end return Events end return Events
-- Created by Elfansoer --[[ Ability checklist (erase if done/checked): - Scepter Upgrade - Break behavior - Linken/Reflect behavior - Spell Immune/Invulnerable/Invisible behavior - Illusion behavior - Stolen behavior ]] -------------------------------------------------------------------------------- modifier_hoodwink_scurry_lua = class({}) -------------------------------------------------------------------------------- -- Classifications function modifier_hoodwink_scurry_lua:IsHidden() return self:GetStackCount()~=0 end function modifier_hoodwink_scurry_lua:IsDebuff() return false end function modifier_hoodwink_scurry_lua:IsStunDebuff() return false end function modifier_hoodwink_scurry_lua:IsPurgable() return false end -------------------------------------------------------------------------------- -- Initializations function modifier_hoodwink_scurry_lua:OnCreated( kv ) self.parent = self:GetParent() -- references self.evasion = self:GetAbility():GetSpecialValueFor( "evasion" ) self.radius = self:GetAbility():GetSpecialValueFor( "radius" ) self.interval = 0.5 if not IsServer() then return end -- Start interval self:StartIntervalThink( self.interval ) self:OnIntervalThink() end function modifier_hoodwink_scurry_lua:OnRefresh( kv ) -- references self.evasion = self:GetAbility():GetSpecialValueFor( "evasion" ) self.radius = self:GetAbility():GetSpecialValueFor( "radius" ) end function modifier_hoodwink_scurry_lua:OnRemoved() end function modifier_hoodwink_scurry_lua:OnDestroy() end -------------------------------------------------------------------------------- -- Modifier Effects function modifier_hoodwink_scurry_lua:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_EVASION_CONSTANT, } return funcs end function modifier_hoodwink_scurry_lua:GetModifierEvasion_Constant() if self:GetStackCount()==1 then return 0 end return self.evasion end -------------------------------------------------------------------------------- -- Interval Effects function modifier_hoodwink_scurry_lua:OnIntervalThink() -- check trees local trees = GridNav:GetAllTreesAroundPoint( self.parent:GetOrigin(), self.radius, false ) local stack = 1 if #trees>0 then stack = 0 end -- stack: 0 is active, 1 is inactive (no tree) if self:GetStackCount()~=stack then self:SetStackCount( stack ) -- set effects if stack==0 then self:PlayEffects() else self:StopEffects() end end end -------------------------------------------------------------------------------- -- Graphics & Animations function modifier_hoodwink_scurry_lua:PlayEffects() -- Get Resources local particle_cast = "particles/units/heroes/hero_hoodwink/hoodwink_scurry_passive.vpcf" -- Create Particle local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, self.parent ) ParticleManager:SetParticleControl( effect_cast, 2, Vector( self.radius, 0, 0 ) ) self.effect_cast = effect_cast end function modifier_hoodwink_scurry_lua:StopEffects() if not self.effect_cast then return end ParticleManager:DestroyParticle( self.effect_cast, false ) ParticleManager:ReleaseParticleIndex( self.effect_cast ) end
local utSwitchCam = false function onCreate() makeLuaSprite('hall', 'stages/sans/hall', 0, 0); addLuaSprite('hall', false); end function onMoveCamera(focus) if not utSwitchCam then if focus == 'dad' then setProperty('camFollow.y', getProperty('camFollow.y') ); setProperty('camFollow.x', getProperty('camFollow.x') +50); elseif focus == 'boyfriend' then setProperty('camFollow.y', getProperty('camFollow.y') -50); setProperty('camFollow.x', getProperty('camFollow.x') -300); end else if focus == 'dad' then setProperty('camFollow.y', getProperty('camFollow.y')); setProperty('camFollow.x', getProperty('camFollow.x') -150); elseif focus == 'boyfriend' then setProperty('camFollow.y', getProperty('camFollow.y') +100); setProperty('camFollow.x', getProperty('camFollow.x') +100); end end end function onStepHit() if curStep == 800 then removeLuaSprite('hall', false) makeLuaSprite('battle', 'stages/sans/battle', 0, 0); addLuaSprite('battle', false); setProperty('dad.x', 750); setProperty('dad.y', 720); setProperty('boyfriend.x', 750); setProperty('boyfriend.y', 1500); utSwitchCam = true; end end
return function() local Root = script.Parent.Parent local MarketplaceService = game:GetService("MarketplaceService") local CorePackages = game:GetService("CorePackages") local PurchasePromptDeps = require(CorePackages.PurchasePromptDeps) local Rodux = PurchasePromptDeps.Rodux local RequestType = require(Root.Enums.RequestType) local PromptState = require(Root.Enums.PromptState) local Reducer = require(Root.Reducers.Reducer) local createSpy = require(Root.Test.createSpy) local Thunk = require(Root.Thunk) local completeRequest = require(script.Parent.completeRequest) describe("should signal prompt finished when purchase was not made", function() it("should signal product purchase finished", function() local store = Rodux.Store.new(Reducer, { promptState = PromptState.PromptPurchase, promptRequest = { id = 123, requestType = RequestType.Product, infoType = Enum.InfoType.Product }, }) local thunk = completeRequest() local finishedSignalSpy = createSpy() local connection = MarketplaceService.PromptProductPurchaseFinished:Connect(finishedSignalSpy.value) Thunk.test(thunk, store) local state = store:getState() expect(state.promptState).to.equal(PromptState.None) expect(finishedSignalSpy.callCount).to.equal(1) local values = finishedSignalSpy:captureValues("userId", "productId", "didPurchase") expect(values.productId).to.equal(123) expect(values.didPurchase).to.equal(false) connection:Disconnect() end) it("should signal game pass purchase finished", function() local store = Rodux.Store.new(Reducer, { promptState = PromptState.Error, promptRequest = { id = 456, requestType = RequestType.GamePass, infoType = Enum.InfoType.GamePass }, }) local thunk = completeRequest() local finishedSignalSpy = createSpy() local connection = MarketplaceService.PromptGamePassPurchaseFinished:Connect(finishedSignalSpy.value) Thunk.test(thunk, store) local state = store:getState() expect(state.promptState).to.equal(PromptState.None) expect(finishedSignalSpy.callCount).to.equal(1) local values = finishedSignalSpy:captureValues("player", "gamePassId", "didPurchase") expect(values.gamePassId).to.equal(456) expect(values.didPurchase).to.equal(false) connection:Disconnect() end) it("should signal asset purchase finished", function() local store = Rodux.Store.new(Reducer, { promptState = PromptState.Error, promptRequest = { id = 789, requestType = RequestType.Asset, infoType = Enum.InfoType.Asset }, }) local thunk = completeRequest() local finishedSignalSpy = createSpy() local connection = MarketplaceService.PromptPurchaseFinished:Connect(finishedSignalSpy.value) Thunk.test(thunk, store) local state = store:getState() expect(state.promptState).to.equal(PromptState.None) expect(finishedSignalSpy.callCount).to.equal(1) local values = finishedSignalSpy:captureValues("player", "assetId", "didPurchase") expect(values.assetId).to.equal(789) expect(values.didPurchase).to.equal(false) connection:Disconnect() end) end) describe("should signal prompt finished when purchase was completed", function() it("should signal product purchase finished", function() local store = Rodux.Store.new(Reducer, { promptState = PromptState.PurchaseComplete, promptRequest = { id = 123, requestType = RequestType.Product, infoType = Enum.InfoType.Product }, hasCompletedPurchase = true, }) local thunk = completeRequest() local finishedSignalSpy = createSpy() local connection = MarketplaceService.PromptProductPurchaseFinished:Connect(finishedSignalSpy.value) Thunk.test(thunk, store) local state = store:getState() expect(state.promptState).to.equal(PromptState.None) expect(finishedSignalSpy.callCount).to.equal(1) local values = finishedSignalSpy:captureValues("userId", "productId", "didPurchase") expect(values.productId).to.equal(123) expect(values.didPurchase).to.equal(true) connection:Disconnect() end) it("should signal game pass purchase finished", function() local store = Rodux.Store.new(Reducer, { promptState = PromptState.PurchaseComplete, promptRequest = { id = 456, requestType = RequestType.GamePass, infoType = Enum.InfoType.GamePass }, hasCompletedPurchase = true, }) local thunk = completeRequest() local finishedSignalSpy = createSpy() local connection = MarketplaceService.PromptGamePassPurchaseFinished:Connect(finishedSignalSpy.value) Thunk.test(thunk, store) local state = store:getState() expect(state.promptState).to.equal(PromptState.None) expect(finishedSignalSpy.callCount).to.equal(1) local values = finishedSignalSpy:captureValues("player", "gamePassId", "didPurchase") expect(values.gamePassId).to.equal(456) expect(values.didPurchase).to.equal(true) connection:Disconnect() end) it("should signal asset purchase finished", function() local store = Rodux.Store.new(Reducer, { promptState = PromptState.PurchaseComplete, promptRequest = { id = 789, requestType = RequestType.Asset, infoType = Enum.InfoType.Asset }, hasCompletedPurchase = true, }) local thunk = completeRequest() local finishedSignalSpy = createSpy() local connection = MarketplaceService.PromptPurchaseFinished:Connect(finishedSignalSpy.value) Thunk.test(thunk, store) local state = store:getState() expect(state.promptState).to.equal(PromptState.None) expect(finishedSignalSpy.callCount).to.equal(1) local values = finishedSignalSpy:captureValues("player", "assetId", "didPurchase") expect(values.assetId).to.equal(789) expect(values.didPurchase).to.equal(true) connection:Disconnect() end) end) end
local play = require 'play' local title = require 'title' function normalise(vx, vy, speed) local length = math.sqrt(vx * vx + vy * vy) local speed_len = speed / length return vx * speed_len, vy * speed_len end function switch_scene(c_scene) scene = c_scene c_scene.load() for i, v in pairs(c_scene) do if i ~= "load" then love[i] = v end end end function love.load() font = love.graphics.newFont("font/PressStart2P.ttf", 42) small_font = love.graphics.newFont("font/PressStart2P.ttf", 21) switch_scene(title) end
-- Class definition of a servient -- Autor: Sebastian Kaebisch (sebastiankb@git) -- servient class servient={} servient.name = "" -- which protocols does the servient support (e.g., CoAP, HTTP, ...) servient.coap=false servient.http=false servient.properties={} -- servient's properties servient.actions={} -- servient's actions servient.events={} -- servient's events --property class property={} property.name="" property.writable=false property.bpr = "" -- binds Lua parameter (=property value) to resource --action class action={} action.name="" action.inputData={} -- multiple data can be transmitted action.outputData="" -- only one return type action.bpr = "" -- binds Lua parameter (=action function) to resource function servient:new() local res = {} setmetatable(res,self) self.__index = self return res end function property:new() local res = {} setmetatable(res,self) self.__index = self return res end function action:new() local res = {} setmetatable(res,self) self.__index = self return res end function servient:addProperty(prop) table.insert(self.properties, prop) end function servient:addAction(act) table.insert(self.actions, act) end json_msg="{\"value\":" -- starts the servient and provides the services online function startServient(s) if(s.coap==true) then cs=coap.Server() cs:listen(5683) -- for each property a coap resource is added for i=1,#s.properties,1 do if s.properties[i].writable == true then cs:var(coap.GET, coap.PUT, s.properties[i].bpr, 0, 0) else cs:var(coap.GET, s.properties[i].bpr, 0, 0) end end end if(s.http==true) then startHTTPServer(s) end end function startHTTPServer(s) print("Start HTTP Server") srv = net.createServer(net.TCP) srv:listen(80, function(conn) conn:on("receive", function(conn, payload) -- get requested resource name i_s, j = string.find(payload, "/") i_e, j = string.find(payload, " ",j) meth = string.sub(payload,1,i_s-2); res = string.sub(payload,i_s+1,i_e-1); -- print(meth) if meth=="GET" then ret = (_G[res]) if ret~=nil then if type(ret) == "number" then ret = json_msg .. ret .."}" else ret = json_msg .. "\"".. ret .."\"}" end conn:send(ret) end elseif meth=="PUT" then if (_G[res])~=nil then -- _G[res] = 123 -- get payload data i, j_s = string.find(payload, ":", i_e) i_e, j = string.find(payload, "}", j_s) a = string.sub(payload,j_s+1, i_e-1) a=a:gsub("^%s*", "") if type(_G[res])== "number" then _G[res] = tonumber(a) else _G[res] = a end conn:send() end elseif meth=="POST" then if (_G[res])~=nil then -- todo, read input data ret = _G[res]() if type(ret) == "number" then ret = json_msg .. ret .."}" else ret = json_msg .. "\"".. ret .."\"}" end conn:send(ret) end end end) conn:on("sent", function(conn) conn:close() end) end) end
--------------------------------------------- -- Amber Scutum -- Family: Wamouracampa -- Description: Increases defense. -- Type: Enhancing -- Utsusemi/Blink absorb: N/A -- Range: Self --------------------------------------------- require("scripts/globals/monstertpmoves") require("scripts/globals/status") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local status = mob:getStatusEffect(tpz.effect.DEFENSE_BOOST) local power = 100 if status ~= nil then -- This is as accurate as we get until effects applied by mob moves can use subpower.. power = status:getPower() * 2 end skill:setMsg(MobBuffMove(mob, tpz.effect.DEFENSE_BOOST, power, 0, 60)) return tpz.effect.DEFENSE_BOOST end
fx_version 'bodacious' game 'gta5' developer 'kim111#2795' client_scripts { 'config.lua', 'client/*.lua', 'locale.lua', 'Locales/*.lua' } server_scripts { '@mysql-async/lib/MySQL.lua', 'server/*.lua', 'config.lua', 'locale.lua', 'Locales/*.lua' }
local m = {}; function m.print() print("module03 print()."); end return m;
function morebombs.nuke(pos, radius) tnt.boom(pos, { radius = radius, }) local corium = minetest.find_node_near(pos, 3, {"air"}) or pos minetest.set_node(corium, {name = "morebombs:falling_corium"}) minetest.check_for_falling(corium) end minetest.register_node("morebombs:falling_corium", { drawtype = "airlike", paramtype = "light", groups = {falling_node = 1, not_in_creative_inventory = 1}, }) minetest.register_abm{ label = "Falling Corium Transformation", nodenames = {"morebombs:falling_corium"}, interval = 1, chance = 1, action = function(pos) minetest.set_node(pos, {name = "technic:corium_source"}) end, } morebombs.register("morebombs:nuclear_bomb", { description = "Nuclear Bomb", tiles = {"morebombs_nuke.png"}, sounds = default.node_sound_metal_defaults(), groups = {cracky = 2}, action = function(pos) morebombs.nuke(pos, 14) end, }) minetest.register_craft{ output = "morebombs:nuclear_bomb 2", recipe = { {"default:mese_crystal", "tnt:tnt", "default:mese_crystal"}, {"technic:stainless_steel_block", "technic:uranium_fuel", "technic:stainless_steel_block"}, {"default:mese_crystal", "tnt:tnt", "default:mese_crystal"}, }, } morebombs.register("morebombs:infused_nuclear_bomb", { description = "Infused Nuclear Bomb", tiles = {"morebombs_infused.png"}, sounds = default.node_sound_metal_defaults(), groups = {cracky = 2}, action = function(pos) morebombs.nuke(pos, 22) end, }) minetest.register_craft{ output = "morebombs:infused_nuclear_bomb", recipe = { {"morebombs:nuclear_bomb", "morebombs:nuclear_bomb", "morebombs:nuclear_bomb"}, {"technic:stainless_steel_block", "morebombs:nuclear_bomb", "technic:stainless_steel_block"}, {"technic:stainless_steel_block", "default:diamondblock", "technic:stainless_steel_block"}, }, } morebombs.register("morebombs:armageddon", { description = "Armageddon", tiles = {"morebombs_armageddon.png"}, sounds = default.node_sound_metal_defaults(), groups = {cracky = 2}, action = function(pos) morebombs.nuke(pos, 30) end, }) minetest.register_craft{ output = "morebombs:armageddon", recipe = { {"morebombs:infused_nuclear_bomb", "morebombs:thunderfist", "morebombs:infused_nuclear_bomb"}, {"technic:stainless_steel_block", "morebombs:infused_nuclear_bomb", "technic:stainless_steel_block"}, {"technic:stainless_steel_block", "default:diamondblock", "technic:stainless_steel_block"}, }, }
---@class IsoSpriteManager : zombie.iso.sprite.IsoSpriteManager ---@field public instance IsoSpriteManager ---@field public NamedMap HashMap|String|IsoSprite ---@field public IntMap TIntObjectHashMap|Unknown ---@field private emptySprite IsoSprite IsoSpriteManager = {} ---@public ---@param gid String ---@return IsoSprite ---@overload fun(gid:int) function IsoSpriteManager:getSprite(gid) end ---@public ---@param gid int ---@return IsoSprite function IsoSpriteManager:getSprite(gid) end ---@public ---@param tex String ---@return IsoSprite ---@overload fun(tex:String, col:Color) function IsoSpriteManager:getOrAddSpriteCache(tex) end ---@public ---@param tex String ---@param col Color ---@return IsoSprite function IsoSpriteManager:getOrAddSpriteCache(tex, col) end ---@public ---@param tex String ---@return IsoSprite ---@overload fun(tex:String, ID:int) function IsoSpriteManager:AddSprite(tex) end ---@public ---@param tex String ---@param ID int ---@return IsoSprite function IsoSpriteManager:AddSprite(tex, ID) end ---@public ---@return void function IsoSpriteManager:Dispose() end
AddCSLuaFile(); SWEP.PrintName = "Base"; SWEP.Slot = 1; SWEP.SlotPos = 1; SWEP.ViewModelFlip = false; SWEP.ViewModelFOV = 54; SWEP.ViewModel = ""; SWEP.WorldModel = ""; SWEP.SwayScale = 0; SWEP.Primary.ClipSize = -1; SWEP.Primary.DefaultClip = -1; SWEP.Primary.Ammo = ""; SWEP.Primary.Automatic = false; SWEP.Secondary.ClipSize = 1; SWEP.Secondary.DefaultClip = 1; SWEP.Secondary.Ammo = "none"; SWEP.Secondary.Automatic = false; SWEP.CanReload = false; SWEP.Holsterable = true; local ActIndex = { [ "pistol" ] = ACT_HL2MP_IDLE_PISTOL, [ "revolver" ] = ACT_HL2MP_IDLE_REVOLVER, [ "smg" ] = ACT_HL2MP_IDLE_SMG1, [ "grenade" ] = ACT_HL2MP_IDLE_GRENADE, [ "ar2" ] = ACT_HL2MP_IDLE_AR2, [ "shotgun" ] = ACT_HL2MP_IDLE_SHOTGUN, [ "rpg" ] = ACT_HL2MP_IDLE_RPG, [ "physgun" ] = ACT_HL2MP_IDLE_PHYSGUN, [ "crossbow" ] = ACT_HL2MP_IDLE_CROSSBOW, [ "melee" ] = ACT_HL2MP_IDLE_MELEE, [ "slam" ] = ACT_HL2MP_IDLE_SLAM, [ "normal" ] = ACT_HL2MP_IDLE, [ "" ] = ACT_HL2MP_IDLE, [ "fist" ] = ACT_HL2MP_IDLE_FIST, [ "melee2" ] = ACT_HL2MP_IDLE_MELEE2, [ "passive" ] = ACT_HL2MP_IDLE_PASSIVE, [ "knife" ] = ACT_HL2MP_IDLE_KNIFE, [ "camera" ] = ACT_HL2MP_IDLE_CAMERA, [ "duel" ] = ACT_HL2MP_IDLE_DUEL, [ "magic" ] = ACT_HL2MP_IDLE_MAGIC, [ "zombie" ] = ACT_HL2MP_IDLE_ZOMBIE, [ "suitcase" ] = ACT_HL2MP_IDLE_SUITCASE } function SWEP:SetWeaponHoldType( t ) local index = ActIndex[ t ] self.ActivityTranslate = { } self.ActivityTranslate [ ACT_MP_STAND_IDLE ] = index self.ActivityTranslate [ ACT_MP_WALK ] = index+1 self.ActivityTranslate [ ACT_MP_RUN ] = index+2 self.ActivityTranslate [ ACT_MP_CROUCH_IDLE ] = index+3 self.ActivityTranslate [ ACT_MP_CROUCHWALK ] = index+4 self.ActivityTranslate [ ACT_MP_ATTACK_STAND_PRIMARYFIRE ] = index+5 self.ActivityTranslate [ ACT_MP_ATTACK_CROUCH_PRIMARYFIRE ] = index+5 self.ActivityTranslate [ ACT_MP_RELOAD_STAND ] = index+6 self.ActivityTranslate [ ACT_MP_RELOAD_CROUCH ] = index+6 self.ActivityTranslate [ ACT_MP_JUMP ] = index+7 self.ActivityTranslate [ ACT_RANGE_ATTACK1 ] = index+8 if t == "normal" then self.ActivityTranslate [ ACT_MP_JUMP ] = ACT_HL2MP_JUMP_SLAM end if t == "revolver" then self.ActivityTranslate [ ACT_RANGE_ATTACK1 ] = ACT_HL2MP_GESTURE_RANGE_ATTACK_PISTOL; end if t == "passive" then self.ActivityTranslate [ ACT_MP_CROUCH_IDLE ] = ACT_HL2MP_IDLE_CROUCH; end if( t == "suitcase" ) then self.ActivityTranslate [ ACT_MP_STAND_IDLE ] = ACT_HL2MP_IDLE_SUITCASE self.ActivityTranslate [ ACT_MP_WALK ] = ACT_HL2MP_WALK_SUITCASE self.ActivityTranslate [ ACT_MP_RUN ] = ACT_HL2MP_IDLE+2 self.ActivityTranslate [ ACT_MP_CROUCH_IDLE ] = ACT_HL2MP_IDLE+3 self.ActivityTranslate [ ACT_MP_CROUCHWALK ] = ACT_HL2MP_IDLE+4 self.ActivityTranslate [ ACT_MP_ATTACK_STAND_PRIMARYFIRE ] = ACT_HL2MP_IDLE+5 self.ActivityTranslate [ ACT_MP_ATTACK_CROUCH_PRIMARYFIRE ] = ACT_HL2MP_IDLE+5 self.ActivityTranslate [ ACT_MP_RELOAD_STAND ] = ACT_HL2MP_IDLE+6 self.ActivityTranslate [ ACT_MP_RELOAD_CROUCH ] = ACT_HL2MP_IDLE+6 self.ActivityTranslate [ ACT_MP_JUMP ] = ACT_HL2MP_IDLE+7 self.ActivityTranslate [ ACT_RANGE_ATTACK1 ] = ACT_HL2MP_IDLE+8 end end function SWEP:SetWeaponHoldTypeHolster( t ) local index = ActIndex[ t ] self.ActivityTranslateHolster = { } self.ActivityTranslateHolster [ ACT_MP_STAND_IDLE ] = index self.ActivityTranslateHolster [ ACT_MP_WALK ] = index+1 self.ActivityTranslateHolster [ ACT_MP_RUN ] = index+2 self.ActivityTranslateHolster [ ACT_MP_CROUCH_IDLE ] = index+3 self.ActivityTranslateHolster [ ACT_MP_CROUCHWALK ] = index+4 self.ActivityTranslateHolster [ ACT_MP_ATTACK_STAND_PRIMARYFIRE ] = index+5 self.ActivityTranslateHolster [ ACT_MP_ATTACK_CROUCH_PRIMARYFIRE ] = index+5 self.ActivityTranslateHolster [ ACT_MP_RELOAD_STAND ] = index+6 self.ActivityTranslateHolster [ ACT_MP_RELOAD_CROUCH ] = index+6 self.ActivityTranslateHolster [ ACT_MP_JUMP ] = index+7 self.ActivityTranslateHolster [ ACT_RANGE_ATTACK1 ] = index+8 if t == "normal" then self.ActivityTranslateHolster [ ACT_MP_JUMP ] = ACT_HL2MP_JUMP_SLAM end if t == "revolver" then self.ActivityTranslateHolster [ ACT_RANGE_ATTACK1 ] = ACT_HL2MP_GESTURE_RANGE_ATTACK_PISTOL; end if t == "passive" then self.ActivityTranslateHolster [ ACT_MP_CROUCH_IDLE ] = ACT_HL2MP_IDLE_CROUCH; end if( t == "suitcase" ) then self.ActivityTranslateHolster [ ACT_MP_STAND_IDLE ] = ACT_HL2MP_IDLE_SUITCASE self.ActivityTranslateHolster [ ACT_MP_WALK ] = ACT_HL2MP_WALK_SUITCASE self.ActivityTranslateHolster [ ACT_MP_RUN ] = ACT_HL2MP_IDLE+2 self.ActivityTranslateHolster [ ACT_MP_CROUCH_IDLE ] = ACT_HL2MP_IDLE+3 self.ActivityTranslateHolster [ ACT_MP_CROUCHWALK ] = ACT_HL2MP_IDLE+4 self.ActivityTranslateHolster [ ACT_MP_ATTACK_STAND_PRIMARYFIRE ] = ACT_HL2MP_IDLE+5 self.ActivityTranslateHolster [ ACT_MP_ATTACK_CROUCH_PRIMARYFIRE ] = ACT_HL2MP_IDLE+5 self.ActivityTranslateHolster [ ACT_MP_RELOAD_STAND ] = ACT_HL2MP_IDLE+6 self.ActivityTranslateHolster [ ACT_MP_RELOAD_CROUCH ] = ACT_HL2MP_IDLE+6 self.ActivityTranslateHolster [ ACT_MP_JUMP ] = ACT_HL2MP_IDLE+7 self.ActivityTranslateHolster [ ACT_RANGE_ATTACK1 ] = ACT_HL2MP_IDLE+8 end end function SWEP:TranslateActivity( act ) local val = -1; if( self.Owner:Holstered() ) then if( self.ActivityTranslateHolster[ act ] ) then val = self.ActivityTranslateHolster[ act ] end else if( self.ActivityTranslate[ act ] ) then val = self.ActivityTranslate[ act ] end end local len2d = self.Owner:GetVelocity():Length2D(); if( val == ACT_HL2MP_RUN and len2d >= 200 ) then val = ACT_HL2MP_RUN_FAST; end return val; end function SWEP:Initialize() self:SetWeaponHoldType( self.HoldType ); self:SetWeaponHoldTypeHolster( self.HoldTypeHolster ); end function SWEP:Precache() if( self.Firearm ) then if( type( self.Primary.Sound ) == "table" ) then for _, v in pairs( self.Primary.Sound ) do util.PrecacheSound( v ); end else util.PrecacheSound( self.Primary.Sound ); end util.PrecacheSound( self.Primary.ReloadSound ); end end function SWEP:DoDrawAnim() if( self.DrawAnim ) then if( type( self.DrawAnim ) == "string" ) then local vm = self.Owner:GetViewModel(); vm:SendViewModelMatchingSequence( vm:LookupSequence( self.DrawAnim ) ); else self:SendWeaponAnimShared( self.DrawAnim ); end else self:SendWeaponAnimShared( ACT_VM_DRAW ); end self:Idle(); end function SWEP:DoHolsterAnim() if( self.HolsterAnim ) then if( type( self.HolsterAnim ) == "string" ) then local vm = self.Owner:GetViewModel(); vm:SendViewModelMatchingSequence( vm:LookupSequence( self.HolsterAnim ) ); else self:SendWeaponAnimShared( self.HolsterAnim ); end else self:SendWeaponAnimShared( ACT_VM_HOLSTER ); end timer.Stop( "cc_weapon_idle" .. self:EntIndex() ); end function SWEP:IdleNow() self:SendWeaponAnimShared( ACT_VM_IDLE ); end function SWEP:Idle() if( self.DevMode ) then return end -- No pesky animations getting in MY way. local vm = self.Owner:GetViewModel(); timer.Create( "cc_weapon_idle" .. self:EntIndex(), vm:SequenceDuration(), 1, function() if( !self or !self:IsValid() or !self.Owner or !self.Owner:IsValid() ) then return end self:IdleNow(); end ) end function SWEP:Deploy() if( self.Owner:Holstered() and self.HolsterUseAnim ) then self:DoHolsterAnim(); elseif( !self.Owner:Holstered() and self.HolsterUseAnim ) then self:DoDrawAnim(); else if( self.Owner:Holstered() ) then self.IronMode = IRON_HOLSTERED; self.IronMul = 1; else self.IronMode = IRON_IDLE; self.IronMul = 0; end end if( self:DeployChild() ) then return false end return true; end function SWEP:DeployChild() end function SWEP:OnRemove() end function SWEP:HolsterChild() end function SWEP:Holster() timer.Stop( "cc_weapon_idle" .. self:EntIndex() ); if( self:HolsterChild() ) then return false end return true; end function SWEP:Think() if( self.ApplyReload and CurTime() >= self.ApplyReload ) then self.ApplyReload = nil; self:SetClip1( self:Clip1() + self.ApplyReloadAmount ); if( !self.Primary.InfiniteAmmo ) then self.Owner:RemoveAmmo( self.ApplyReloadAmount, self.Primary.Ammo ); end end if( !IsFirstTimePredicted() ) then return end if( self.ThinkChild ) then self:ThinkChild() end if( !self.Owner or !self.Owner:IsValid() ) then return end if( self.Owner:Holstered() and self.IronMode > IRON_HOLSTERED ) then -- Going down. if( self.IronMode > IRON_IDLE ) then self.IronMul = 0; end if( self.HolsterUseAnim ) then self:DoHolsterAnim(); self.IronMode = IRON_HOLSTERED; else self.IronMode = IRON_HOLSTERED2IDLE; self.IronDir = 1; self:Idle(); end elseif( !self.Owner:Holstered() and self.IronMode < IRON_IDLE ) then -- Raising up. if( self.HolsterUseAnim ) then self:DoDrawAnim(); self.IronMode = IRON_IDLE; self.IronMul = 0; else self.IronMode = IRON_HOLSTERED2IDLE; self.IronDir = -1; timer.Stop( "cc_weapon_idle" .. self:EntIndex() ); end end if( self.Owner:KeyDown( IN_ATTACK2 ) ) then if( self.IronMode == IRON_IDLE or self.IronMode == IRON_IDLE2AIM ) then self.IronMode = IRON_IDLE2AIM; self.IronDir = 1; end elseif( self.IronMode > IRON_IDLE ) then self.IronMode = IRON_IDLE2AIM; self.IronDir = -1; end end function SWEP:PlaySound( snd, vol, pit ) if( SERVER ) then if( type( snd ) == "table" ) then self.Owner:EmitSound( table.Random( snd ), vol, pit ); else self.Owner:EmitSound( snd, vol, pit ); end end end function SWEP:StopSound( snd ) if( SERVER ) then self.Owner:StopSound( snd ); end end function SWEP:CanPrimaryAttack( noreload ) if( self:Clip1() <= 0 ) then self:EmitSound( self.EmptySound or "Weapon_Pistol.Empty" ); self:SetNextPrimaryFire( CurTime() + 0.2 ); if( !noreload ) then self:Reload(); end return false; end return true; end function SWEP:CanSecondaryAttack() if( self:Clip2() <= 0 ) then self:EmitSound( self.EmptyAltSound or "Weapon_Pistol.Empty" ); self:SetNextSecondaryFire( CurTime() + 0.2 ); return false; end return true; end function SWEP:BulletAccuracyModifier( m ) local m = m or 0.8; local mulstat = 1 - ( self.Owner:Aim() / 100 ) * m; local muliron = self.Owner:KeyDown( IN_ATTACK2 ) and 0.7 or 1; return mulstat * muliron; end function SWEP:PrimaryHolstered() end function SWEP:ShootEffects() self:SendWeaponAnimShared( ACT_VM_PRIMARYATTACK ); self.Owner:MuzzleFlash(); self.Owner:SetAnimation( PLAYER_ATTACK1 ); end function SWEP:PrimaryUnholstered() if( self.Firearm ) then if( self:CanPrimaryAttack() ) then self:SetNextPrimaryFire( CurTime() + self.Primary.Delay ); self:ShootEffects(); self:TakePrimaryAmmo( 1 ); self:Idle(); if( self.AddViewKick ) then self:AddViewKick(); else if( type( self.Primary.ViewPunch ) == "Angle" ) then self.Owner:ViewPunch( Angle( self.Primary.ViewPunch.p, math.random( -self.Primary.ViewPunch.y, self.Primary.ViewPunch.y ), math.random( -self.Primary.ViewPunch.r, self.Primary.ViewPunch.r ) ) ); else self:DoMachineGunKick( self.Primary.ViewPunch.x, self.Primary.ViewPunch.y, self.Primary.Delay, self.Primary.ViewPunch.z ); end end self.CanReload = true; if( type( self.Primary.Sound ) == "table" ) then for _, v in pairs( self.Primary.Sound ) do self:PlaySound( v, 80, 100 ); end else self:PlaySound( self.Primary.Sound, 80, 100 ); end if( !IsFirstTimePredicted() ) then return end self:ShootBullet( self.Primary.Damage, self.Primary.Force, self.Primary.NumBullets, self.Primary.Accuracy * self:BulletAccuracyModifier() ); end elseif( self.Melee ) then if( self.Owner:KeyDown( IN_ATTACK2 ) ) then return end self:SetNextPrimaryFire( CurTime() + self.MissDelay ); self:SetNextSecondaryFire( CurTime() + self.MissDelay ); self.Owner:LagCompensation( true ); self.Owner:SetAnimation( PLAYER_ATTACK1 ); self:PlaySound( self.SwingSound ); local trace = { }; trace.start = self.Owner:GetShootPos(); trace.endpos = trace.start + self.Owner:GetAimVector() * self.Length; trace.filter = self.Owner; trace.mins = Vector( -8, -8, -8 ); trace.maxs = Vector( 8, 8, 8 ); local tr = util.TraceHull( trace ); if( tr.Hit ) then self.Weapon:SendWeaponAnimShared( self.HitAnim or ACT_VM_PRIMARYATTACK ); self:SetNextPrimaryFire( CurTime() + self.HitDelay ); self:SetNextSecondaryFire( CurTime() + self.HitDelay ); local ltr = util.TraceLine( trace ); if( tr.Entity and tr.Entity:IsValid() and ( tr.Entity:IsPlayer() or tr.Entity:IsNPC() ) ) then self:PlaySound( self.HitFleshSound ); else if( type( self.HitWallSound ) == "boolean" ) then if( self.HitWallSound ) then self:PlaySound( GAMEMODE:GetImpactSound( tr ) ); end else self:PlaySound( self.HitWallSound ); end end if( type( self.BulletDecal ) == "boolean" and self.BulletDecal ) then util.Decal( GAMEMODE:GetTraceDecal( tr ), ltr.HitPos + ltr.HitNormal, ltr.HitPos - ltr.HitNormal ); elseif( self.BulletDecal ) then util.Decal( self.BulletDecal, ltr.HitPos + ltr.HitNormal, ltr.HitPos - ltr.HitNormal ); end if( SERVER ) then if( !self.Owner.NextStrength ) then self.Owner.NextStrength = 0 end if( CurTime() >= self.Owner.NextStrength ) then self.Owner:SetStrength( math.Clamp( self.Owner:Strength() + GAMEMODE:ScaledStatIncrease( self.Owner, self.Owner:Strength() ) * 0.02, 0, 100 ) ); self.Owner:UpdateCharacterField( "StatStrength", tostring( self.Owner:Strength() ), true ); self.Owner.NextStrength = CurTime() + 10; end local blockmul = 1; if( tr.Entity:IsPlayer() ) then if( tr.Entity:GetActiveWeapon() and tr.Entity:GetActiveWeapon():IsValid() ) then if( tr.Entity:GetActiveWeapon().IsBlocking and tr.Entity:GetActiveWeapon():IsBlocking() ) then blockmul = tr.Entity:GetActiveWeapon().BlockMul; end end end if( tr.Entity:IsPlayer() ) then net.Start( "nFlashRed" ); net.Send( tr.Entity ); end local dmg = DamageInfo(); dmg:SetAttacker( self.Owner ); dmg:SetDamage( math.Round( ( ( self.Owner:Strength() + 20 ) / 50 ) * ( self.DamageMul or 10 ) * blockmul ) ); dmg:SetDamageForce( tr.Normal * 50 ); dmg:SetDamagePosition( tr.HitPos ); dmg:SetDamageType( self.DamageType or DMG_SLASH ); dmg:SetInflictor( self ); if( tr.Entity.DispatchTraceAttack ) then tr.Entity:DispatchTraceAttack( dmg, tr ); end end else self.Weapon:SendWeaponAnimShared( self.MissAnim or ACT_VM_MISSCENTER ); end if( self.AddViewKick ) then self:AddViewKick(); else if( type( self.Primary.ViewPunch ) == "Angle" ) then self.Owner:ViewPunch( Angle( self.Primary.ViewPunch.p, math.random( -self.Primary.ViewPunch.y, self.Primary.ViewPunch.y ), math.random( -self.Primary.ViewPunch.r, self.Primary.ViewPunch.r ) ) ); else self:DoMachineGunKick( self.Primary.ViewPunch.x, self.Primary.ViewPunch.y, self.Primary.Delay, self.Primary.ViewPunch.z ); end end self.Owner:LagCompensation( false ); self:Idle(); end end function SWEP:SecondaryHolstered() end function SWEP:SecondaryUnholstered() end function SWEP:ShootBullet( damage, force, n, aimcone ) local bullet = { }; bullet.Num = n or 1; bullet.Src = self.Owner:GetShootPos(); bullet.Dir = self.Owner:GetAimVector(); bullet.Spread = Vector( aimcone, aimcone, 0 ); bullet.Tracer = 1; bullet.Force = force; bullet.Damage = damage; bullet.AmmoType = "Pistol"; bullet.TracerName = self.Primary.TracerName or "Tracer"; self.Owner:FireBullets( bullet ); end function SWEP:PrimaryAttack() if( self.Owner:Holstered() ) then self:PrimaryHolstered(); else self:PrimaryUnholstered(); end end function SWEP:SecondaryAttack() if( self.Owner:Holstered() ) then self:SecondaryHolstered(); else self:SecondaryUnholstered(); end end function SWEP:IsBlocking() if( self.SecondaryBlock ) then if( !self.Owner:Holstered() and self.Owner:KeyDown( IN_ATTACK2 ) ) then return true; end end return false; end function SWEP:Reload() if( self.Owner:Holstered() ) then return end if( !self.Firearm ) then return end if( !self.CanReload ) then return end local delta = self.Primary.ClipSize - self:Clip1(); if( !self.Primary.InfiniteAmmo ) then delta = math.min( self.Primary.ClipSize - self:Clip1(), self:Ammo1() ); end if( delta > 0 ) then if( self.ReloadAnim ) then self:SendWeaponAnimShared( self.ReloadAnim ); elseif( self:SelectWeightedSequence( ACT_VM_RELOAD ) != -1 ) then self:SendWeaponAnimShared( ACT_VM_RELOAD ); else self:SendWeaponAnimShared( ACT_VM_RELOAD_EMPTY ); end self:PlaySound( self.Primary.ReloadSound ); self.Owner:SetAnimation( PLAYER_RELOAD ); self:SetNextPrimaryFire( CurTime() + self:SequenceDuration() ); self:SetNextSecondaryFire( CurTime() + self:SequenceDuration() ); self.CanReload = false; self:Idle(); self.ApplyReload = CurTime() + self:SequenceDuration(); self.ApplyReloadAmount = delta; end end SWEP.Holstered = false; SWEP.IronMode = IRON_HOLSTERED; SWEP.IronDir = 1; SWEP.IronMul = 1; SWEP.IronNetPos = Vector(); SWEP.IronNetAng = Vector(); function SWEP:CalcIron() if( !self.Holsterable and self.IronMode < IRON_IDLE ) then self.IronMode = IRON_IDLE; end if( self.HolsterPos and self.AimPos and self.HolsterAng and self.AimAng ) then if( self.IronMode == IRON_HOLSTERED ) then self.IronNetPos = self.HolsterPos; self.IronNetAng = self.HolsterAng; elseif( self.IronMode == IRON_HOLSTERED2IDLE ) then if( self.IronMul == 1 and self.IronDir == 1 ) then -- Going up... and hit idle self.IronMode = IRON_HOLSTERED; elseif( self.IronMul == 0 and self.IronDir == -1 ) then -- Going down... and hit holstered self.IronMode = IRON_IDLE; else self.IronMul = math.Clamp( self.IronMul + self.IronDir * GAMEMODE:IronsightsMul(), 0, 1 ); self.IronNetPos = self.IronMul * self.HolsterPos; self.IronNetAng = self.IronMul * self.HolsterAng; end elseif( self.IronMode == IRON_IDLE ) then self.IronNetPos = Vector(); self.IronNetAng = Vector(); elseif( self.IronMode == IRON_IDLE2AIM ) then if( self.IronMul == 1 and self.IronDir == 1 ) then self.IronMode = IRON_AIM; elseif( self.IronMul == 0 and self.IronDir == -1 ) then self.IronMode = IRON_IDLE; else self.IronMul = math.Clamp( self.IronMul + self.IronDir * GAMEMODE:IronsightsMul(), 0, 1 ); self.IronNetPos = self.IronMul * self.AimPos; self.IronNetAng = self.IronMul * self.AimAng; end elseif( self.IronMode == IRON_AIM ) then self.IronNetPos = self.AimPos; self.IronNetAng = self.AimAng; end end end function SWEP:GetViewModelPosition( pos, ang ) if( CCP.IronDev ) then ang:RotateAroundAxis( ang:Up(), GAMEMODE.IronDevAng.y ); ang:RotateAroundAxis( ang:Right(), GAMEMODE.IronDevAng.x ); ang:RotateAroundAxis( ang:Forward(), GAMEMODE.IronDevAng.z ); pos = pos + GAMEMODE.IronDevPos.x * ang:Right(); pos = pos + GAMEMODE.IronDevPos.y * ang:Up(); pos = pos + GAMEMODE.IronDevPos.z * ang:Forward(); return pos, ang; end local vOriginalOrigin = pos; local vOriginalAngles = ang; self:CalcIron(); ang:RotateAroundAxis( ang:Right(), self.IronNetAng.x ); ang:RotateAroundAxis( ang:Up(), self.IronNetAng.y ); ang:RotateAroundAxis( ang:Forward(), self.IronNetAng.z ); pos = pos + self.IronNetPos.x * ang:Right(); pos = pos + self.IronNetPos.y * ang:Up(); pos = pos + self.IronNetPos.z * ang:Forward(); if( !self.m_vecLastFacing ) then self.m_vecLastFacing = vOriginalOrigin; end local forward = vOriginalAngles:Forward(); local right = vOriginalAngles:Right(); local up = vOriginalAngles:Up(); local vDifference = self.m_vecLastFacing - forward; local flSpeed = 7; local flDiff = vDifference:Length(); if( flDiff > 1.5 ) then flSpeed = flSpeed * ( flDiff / 1.5 ); end vDifference:Normalize(); self.m_vecLastFacing = self.m_vecLastFacing + vDifference * flSpeed * FrameTime(); self.m_vecLastFacing:Normalize(); pos = pos + ( vDifference * -1 ) * 5; return pos - forward * 5, ang; end function SWEP:FreezeMovement() if( self.Owner.FreezeTime and CurTime() < self.Owner.FreezeTime ) then return true; end return false; end SWEP.DevMode = false; SWEP.ScopeTexture = "gmod/scope-refract"; SWEP.ScopeTextureTop = "gmod/scope"; function SWEP:PreDrawViewModel( vm, wep, ply ) if( self.Scoped ) then if( self.IronMode == IRON_AIM ) then vm:SetMaterial( "engine/occlusionproxy" ); else vm:SetMaterial( "" ); end else vm:SetMaterial( "" ); end end function SWEP:InScope() if( self.Scoped and LocalPlayer():GetViewEntity() == LocalPlayer() and self.IronMode == IRON_AIM ) then return true; end return false; end function SWEP:DrawHUD() if( self:InScope() ) then local h = ScrH(); local w = ( 4 / 3 ) * h; local dw = ( ScrW() - w ) / 2; surface.SetDrawColor( 0, 0, 0, 255 ); surface.DrawRect( 0, 0, dw, h ); surface.DrawRect( w + dw, 0, dw, h ); if( render.GetDXLevel() >= 90 ) then render.UpdateRefractTexture(); surface.SetTexture( surface.GetTextureID( self.ScopeTexture ) ); surface.SetDrawColor( 255, 255, 255, 255 ); surface.DrawTexturedRect( dw, 0, w, h ); end surface.SetTexture( surface.GetTextureID( self.ScopeTextureTop ) ); surface.SetDrawColor( 0, 0, 0, 255 ); surface.DrawTexturedRect( dw, 0, w, h ); surface.SetDrawColor( 0, 0, 0, 255 ); surface.DrawLine( 0, ScrH() / 2, ScrW(), ScrH() / 2 ); surface.DrawLine( ScrW() / 2, 0, ScrW() / 2, ScrH() ); end if( CCP.IronDev ) then surface.SetDrawColor( 255, 255, 255, 255 ); surface.DrawLine( 0, ScrH() / 2, ScrW(), ScrH() / 2 ); surface.DrawLine( ScrW() / 2, 0, ScrW() / 2, ScrH() ); end if( self.DevMode ) then draw.DrawTextShadow( self.IronMode, "CombineControl.LabelGiant", ScrW(), 0, Color( 255, 255, 255, 255 ), Color( 0, 0, 0, 255 ), 2 ); draw.DrawTextShadow( self.IronMul, "CombineControl.LabelGiant", ScrW(), 20, Color( 255, 255, 255, 255 ), Color( 0, 0, 0, 255 ), 2 ); end end function SWEP:TranslateFOV( fov ) if( self:InScope() ) then return 20; end return fov; end function SWEP:AdjustMouseSensitivity() if( self:InScope() ) then return ( 20 / GetConVarNumber( "fov_desired" ) ); end return 1; end function SWEP:DrawWorldModel() if( self.CSFallback ) then local hasCS = false; for _, v in pairs( engine.GetGames() ) do if( v.depot == 240 and v.mounted ) then hasCS = true; end end if( !hasCS ) then local hand = self.Owner:GetAttachment( self.Owner:LookupAttachment( "anim_attachment_rh" ) ); if( hand ) then self:SetRenderOrigin( hand.Pos ); self:SetRenderAngles( hand.Ang ); end end elseif( self.RepositionToHand ) then local hand = self.Owner:GetAttachment( self.Owner:LookupAttachment( "anim_attachment_rh" ) ); if( hand ) then self:SetRenderOrigin( hand.Pos ); self:SetRenderAngles( hand.Ang ); end end self:DrawModel(); end function SWEP:ClipPunchAngleOffset( inang, punch, clip ) local final = inang + punch; for _, v in pairs( { "p", "y", "r" } ) do inang[v] = math.Clamp( final[v], -clip[v], clip[v] ) - punch[v]; end return inang; end function SWEP:DoMachineGunKick( dampEasy, maxVerticalKickAngle, fireDurationTime, slideLimitTime ) local KICK_MIN_X = 0.2; local KICK_MIN_Y = 0.2; local KICK_MIN_Z = 0.1; local duration = math.min( fireDurationTime, slideLimitTime ); local kickPerc = duration / slideLimitTime; self.Owner:ViewPunchReset( 10 ); local vecScratch = Angle(); vecScratch.p = -( KICK_MIN_X + ( maxVerticalKickAngle * kickPerc ) ); vecScratch.y = -( KICK_MIN_Y + ( maxVerticalKickAngle * kickPerc ) ) / 3; vecScratch.r = KICK_MIN_Z + ( maxVerticalKickAngle * kickPerc ) / 8; if( math.random( -1, 1 ) >= 0 ) then vecScratch.y = vecScratch.y * -1; end if( math.random( -1, 1 ) >= 0 ) then vecScratch.r = vecScratch.r * -1; end vecScratch = self:ClipPunchAngleOffset( vecScratch, self.Owner:GetViewPunchAngles(), Angle( 24, 3, 1 ) ); self.Owner:ViewPunch( vecScratch * 2 ); end function SWEP:SendWeaponAnimShared( act ) --[[ local vm = self.Owner:GetViewModel(); vm:SendViewModelMatchingSequence( vm:SelectWeightedSequence( ACT_VM_IDLE ) ); timer.Simple( 0, function() if ( !IsValid( self ) || !IsValid( self.Owner ) || !self.Owner:GetActiveWeapon() || self.Owner:GetActiveWeapon() != self ) then return end local vm = self.Owner:GetViewModel(); vm:SendViewModelMatchingSequence( vm:SelectWeightedSequence( act ) ); end ); --]] --if( SERVER ) then self:SendWeaponAnim( act ); --end end
return {'cortes','cordiaal','cordiet','corduroy','corebusiness','coreferent','coregisseur','corgi','cornedbeef','corner','cornerbal','cornerspecialist','cornervlag','cornet','cornflakes','corona','coronaal','coronair','corporale','corporalen','corporatie','corporatief','corporatisme','corporatistisch','corporeel','corps','corpsbal','corpslid','corpsstudent','corpulent','corpulentie','corpus','corpusculair','correct','correctheid','correctheidsbewijs','correctheidsbewijzen','correctie','correctieafdeling','correctief','correctiefactor','correctiefase','correctielak','correctielint','correctiemechanisme','correctiemodel','correctieronde','correctiesleutel','correctieteken','correctietoets','correctievloeistof','correctiewerk','correctionaliseren','correctioneel','corrector','correctrice','correlaat','correlatie','correlatiecoefficient','correlatief','correlatierekening','correleren','correspondent','correspondente','correspondentennet','correspondentie','correspondentieadres','correspondentiekaart','correspondentieonderwijs','correspondentievriend','correspondentievriendin','correspondentschap','corresponderen','corridor','corrigeerbaar','corrigenda','corrigendum','corrigeren','corroderen','corrosie','corrosief','corrumperen','corrumpering','corrupt','corruptheid','corruptie','corruptieaffaire','corruptiebestrijder','corruptiebestrijding','corruptief','corruptieonderzoek','corruptiepraktijk','corruptieproces','corruptieschandaal','corruptiezaak','corsage','corselet','corso','cortex','corticosteron','corticosteroiden','corticoide','cortison','cortisone','cortege','corvee','corveedienst','corveelijst','corveeer','corveeers','coryfee','coryfeeen','corveeen','cornisch','coronie','corniche','corbillard','coroniaan','coroniaans','corporatiesector','corpusonderzoek','correctievoorschrift','corsowagen','corporatiebezit','correspondentietheorie','correctieverzoek','correctiekaart','cor','corantijn','corfu','cornelia','cornelis','corne','corrie','corry','corsica','corsicaan','corsicaans','cornelissen','cornelisse','cora','corien','corina','corine','corinna','corinne','corneel','cornel','cornelius','cordes','corten','corsten','cornet','corstjens','coremans','cornielje','corte','corbijn','corba','corporaal','corver','cortenbach','cortenraad','coret','corstanje','correia','corbeau','corijn','corbeij','corbet','cornips','cordia','corts','corsius','corneille','correa','cordiale','corners','coronas','coronaire','corpora','corporaties','corporatieve','corporatiewoningen','corporele','corpsen','corpsleden','corpulente','corpulenter','corpulentere','corpusculaire','corpussen','correcte','correcter','correctere','correctielinten','correctiemechanismen','correcties','correctiestrookje','correctietekens','correctieve','correctieven','correctionele','correctoren','correctors','correctrices','correctst','correctste','correlatiecoefficienten','correlaties','correlatieve','correleer','correleerde','correleerden','correleert','correspondeer','correspondeerde','correspondeerden','correspondeert','correspondenten','correspondentieadressen','correspondenties','corresponderend','corresponderende','corridors','corrigeer','corrigeerbare','corrigeerde','corrigeerden','corrigeert','corrigerend','corrigerende','corrodeerde','corrodeerden','corrodeert','corrosieve','corrumpeer','corrumpeerde','corrumpeerden','corrumpeert','corrumperende','corrupte','corrupter','corruptere','corruptiegevallen','corrupties','corruptiezaken','corruptste','corsages','corsos','corticoiden','cortisonen','corveediensten','corvees','cornervlaggen','corporatistische','corpsballen','corpsstudenten','correctiesleutels','correctietoetsen','correctionaliseerde','correspondentes','correspondentiekaarten','correspondentievrienden','corrumperend','corruptieaffaires','corruptiepraktijken','corruptieschandalen','corruptieve','corselets','coronianen','corsicaanse','corveetje','corteges','corsootje','coronale','correlaten','coroniaanse','corniches','coreferenten','cornets','corbillards','coregisseurs','corgis','corseletten','corveede','corveet','cors','coras','coriens','corinas','corines','corinnas','corinnes','corneels','cornels','cornelias','cornelis','cornelius','cornes','corries','corrys','correctiefactoren','correctievoorschriften','corsowagens','cornerballen','correctiemodellen','correctierondes','correspondentiekaartjes','correspondentievriendje'}
-- =========================================================================== -- Cui Great Person Tooltip -- eudaimonia, 2/26/2019 -- =========================================================================== include("InstanceManager") include("SupportFunctions") include("CivilizationIcon") local CuiGreatPersonTT = {} TTManager:GetTypeControlTable("CuiGreatPersonTT", CuiGreatPersonTT) -- =========================================================================== function UpdateGreatPersonTooltip(tControl, tData_Player, tData_GP) local classData = GameInfo.GreatPersonClasses[tData_GP.ClassID] -- Prep Instance Managers if CuiGreatPersonTT["PlayerIM"] ~= nil then CuiGreatPersonTT["PlayerIM"]:ResetInstances() else CuiGreatPersonTT["PlayerIM"] = InstanceManager:new("CuiRecruitInstance", "Top", CuiGreatPersonTT.ProgressStack) end local classText = Locale.Lookup(classData.Name) CuiGreatPersonTT.Label:SetText(classText) CuiGreatPersonTT.Divider:SetSizeX(CuiGreatPersonTT.Label:GetSizeX() + 60) for i, kPlayerPoints in ipairs(tData_Player) do local canEarnAnotherOfThisClass = true if (kPlayerPoints.MaxPlayerInstances ~= nil and kPlayerPoints.NumInstancesEarned ~= nil) then canEarnAnotherOfThisClass = kPlayerPoints.MaxPlayerInstances > kPlayerPoints.NumInstancesEarned end if (canEarnAnotherOfThisClass) then local tProgressInstance = CuiGreatPersonTT["PlayerIM"]:GetInstance() local sProgress = "" local sTurns = "" local pointTotal = tData_GP.RecruitCost local pointPlayer = Round(kPlayerPoints.PointsTotal, 0) local percent = Clamp(pointPlayer / pointTotal, 0, 1) if percent < 1 then local pointRemaining = Round(pointTotal - pointPlayer, 0) local pointPerturn = Round(kPlayerPoints.PointsPerTurn, 1) local turnsRemaining = pointPerturn == 0 and 999 or math.ceil(pointRemaining / pointPerturn) if pointPerturn == 0 then sProgress = "-" else sProgress = "[COLOR_ModStatusGreen]+" .. pointPerturn .. "[ENDCOLOR]" end sTurns = turnsRemaining .. "[ICON_TURN]" end tProgressInstance.Country:SetText(kPlayerPoints.PlayerName) tProgressInstance.Point:SetText(sProgress) tProgressInstance.TurnsRemaining:SetText(sTurns) tProgressInstance.ProgressBar:SetPercent(percent) tProgressInstance.YouIndicator:SetHide(not (kPlayerPoints.PlayerID == Game.GetLocalPlayer())) tProgressInstance.YouBacking:SetHide(not (kPlayerPoints.PlayerID == Game.GetLocalPlayer())) tProgressInstance.CivilizationIcon = tProgressInstance.CivilizationIcon or CivilizationIcon:new(tProgressInstance) tProgressInstance.CivilizationIcon:UpdateIconFromPlayerID(kPlayerPoints.PlayerID) end end end -- =========================================================================== function SetGreatPersonToolTip(tControl, tData_Player, tData_GP) tControl:SetToolTipType("CuiGreatPersonTT") tControl:ClearToolTipCallback() tControl:SetToolTipCallback(function() UpdateGreatPersonTooltip(tControl, tData_Player, tData_GP) end) end -- =========================================================================== LuaEvents.CuiGreatPersonToolTip.Add(SetGreatPersonToolTip)
class 'EventManager' function EventManager:__init( ... ) self.active_events = {} self.timer = Timer() self.event_post_tick = Events:Subscribe( 'PostTick', self, self.Tick ) self.event_module_load = Events:Subscribe( 'MapsLoaded', self, self.LoadDebug ) end function EventManager:LoadDebug() -- military base test event -- local t = { -- event_type = 'Populate', -- centerPoint = Vector3( -7747.413574, 203.999985, -6959.811523 ), -- activateDistance = 500, -- actors = { -- { type = 'CombatGrunt', position = Vector3( -7723.378418, 209.999985, -7012.460449 ), angle = Angle(), goal = AiGoal.Guard, faction = Faction.PanauMilitary }, -- { type = 'CombatGrunt', position = Vector3( -7704.593262, 208.884323, -7051.159180 ), angle = Angle(), goal = AiGoal.Guard, faction = Faction.PanauMilitary }, -- { type = 'CombatGrunt', position = Vector3( -7686.826172, 208.880722, -7050.500000 ), angle = Angle(), goal = AiGoal.Guard, faction = Faction.PanauMilitary }, -- { type = 'CombatGrunt', position = Vector3( -7651.135742, 210.219849, -7034.099121 ), angle = Angle(), goal = AiGoal.Guard, faction = Faction.PanauMilitary }, -- { type = 'CombatGrunt', position = Vector3( -7651.875000, 210.196991, -7016.163086 ), angle = Angle(), goal = AiGoal.Guard, faction = Faction.PanauMilitary }, -- { type = 'CombatGrunt', position = Vector3( -7741.729004, 218.979019, -7039.564941 ), angle = Angle(), goal = AiGoal.Guard, faction = Faction.PanauMilitary }, -- { type = 'CombatGrunt', position = Vector3( -7633.865234, 238.945633, -6916.647461 ), angle = Angle(), goal = AiGoal.Guard, faction = Faction.PanauMilitary }, -- { type = 'CombatGrunt', position = Vector3( -7666.199219, 214.699982, -6829.084961 ), angle = Angle(), goal = AiGoal.Guard, faction = Faction.PanauMilitary }, -- { type = 'CombatGrunt', position = Vector3( -7681.496094, 210.000015, -6770.031250 ), angle = Angle(), goal = AiGoal.Guard, faction = Faction.PanauMilitary }, -- { type = 'CombatGrunt', position = Vector3( -7841.692871, 203.999557, -6916.616699 ), angle = Angle(), goal = AiGoal.Guard, faction = Faction.PanauMilitary }, -- { type = 'MilitaryAPC_Cannon', position = Vector3( -7749.505859, 204.006073, -6962.047363 ), angle = Angle( -0.803231, 0.000000, 0.000000 ), goal = AiGoal.Guard, faction = Faction.PanauMilitary } -- } -- } -- self:AddEvent( t ) end function EventManager:AddEvent( args ) local event = nil if args.event_type == 'Populate' then event = PopulateEvent( args ) elseif args.event_type == 'Heat' then event = HeatEvent( args ) end if event then table.insert( self.active_events, event ) else error('Error loading event of type :', args.event_type) end return event end function EventManager:RemoveEvent( event ) local t = self.active_events for i=1,#t do local e = t[i] if e == event then e:Remove() table.remove( self.active_events, i ) return end end end function EventManager:Tick( ... ) local t = self.timer if t:GetMilliseconds() < 250 then return end t:Restart() -- event logic currently runs every 250ms local t = self.active_events for i=1,#t do local event = t[i] event:Tick() end end EM = EventManager()
require "weapon" WeaponsManager = {} -- this manager give the ability of who inherat to use weapons function WeaponsManager.new() local self = {} self.weapons = {} function self.change_delay_of_all_weapons(new_delay) for _, weapon in ipairs(self.weapons) do weapon.change_delay_to(new_delay) end end function self.change_ammo_of_all_weapons(new_ammo) for _, weapon in ipairs(self.weapons) do weapon.change_ammo_to(new_ammo) end end function self.change_delay_of_weapon(weapon_id, new_delay) if self.weapons[weapon_id] ~= nil then self.weapons[weapon_id].change_delay_to(new_ammo) end end function self.change_ammo_of_weapon(weapon_id, new_ammo) if self.weapons[weapon_id] ~= nil then self.weapons[weapon_id].change_ammo_to(new_ammo) end end -- create a "weapon" with position relative the body of ship function self.add_weapon(ammo_name, x_pos_relative, y_pos_relative, delay) local new_weapon = Weapon.new(ammo_name, x_pos_relative, y_pos_relative, delay) new_weapon.active() self.weapons[#self.weapons+1] = new_weapon end -- shoot all weapons at the same time (if it possible) -- note that here we use : because body "doesn't belong to this class" function self:shoot_every_weapon() for _, weapon in ipairs(self.weapons) do if weapon.actived and weapon.can_shoot() then weapon.shoot(self.body.x, self.body.y, self.owner, self.title) end end end return self end
package = "blunty666.nodes" interface = "INodeController" methods = { "_CheckCoordDrawn", "_CheckCoordVisible", "_CheckCoordClickable", "GetOrder", "SetOrder", "_CheckActiveSubNode", "GetActiveSubNode", "SetActiveSubNode", }
local a = 1 local b = 1 log(a) log(b) log(mathex.add(a, b))
----------------------------------- -- Area: Bastok Mines -- NPC: Davyad -- Involved in Mission: Bastok 3-2 -- !pos 83 0 30 234 ----------------------------------- require("scripts/globals/missions") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if (player:getCurrentMission(BASTOK) == tpz.mission.id.bastok.TO_THE_FORSAKEN_MINES) then player:startEvent(54) else player:startEvent(53) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
--- currently contains useful lua functions for vrep only --- to use: --- 1) symlink or copy grl.lua into the same folder as the vrep executable --- 2) add the following line to your script before you want to use the library: --- require "grl" --- 3) call your function! ex: grl.isModuleLoaded('') grl = {} grl.isModuleLoaded=function(moduleName) -- Check if the required plugin is there: local loadedModuleName=0 local moduleVersion=0 local index=0 local isModuleFound=false while loadedModuleName do loadedModuleName,moduleVersion=simGetModuleName(index) if (loadedModuleName==moduleName) then isModuleFound=true end index=index+1 end return isModuleFound end grl.getQuaternionFromEulerAngle=function(position,eulerAngle) local m=simBuildMatrix(position,eulerAngle) local q=simGetQuaternionFromMatrix(m) return q end --- Get the pose of one object relative to another --- --- @param objectpositionHandle The Object you want to get the position of --- @param relativeToBaseFrameHandle The object or frame the position should be defined in, nil for world --- @return position,orientation a 3 vector and quaternion value pair grl.getTransformBetweenHandles=function(objectPositionHandle, relativeToBaseFrameHandle) local p=simGetObjectPosition(objectPositionHandle,relativeToBaseFrameHandle) local o=simGetObjectQuaternion(objectPositionHandle,relativeToBaseFrameHandle) return p,o end --- Get the pose of a point on a path in the world frame --- --- @param pathHandle handle representing the path object you are referring to --- @param relative distance along a path from the start at 0 to the end at 1 (percentage*100) --- @return position,orientation a 3 vector and quaternion value pair grl.getPathPointInWorldFrame=function(pathHandle,relativeDistance) local p=simGetPositionOnPath(pathHandle,relativeDistance) local euler_o=simGetOrientationOnPath(pathHandle,relativeDistance) local o=grl.getQuaternionFromEulerAngle(p,euler_o) return p,o end --- @brief Load a vrep path from a file --- --- @note if the objectName parameter already exists, it will default to the first of path,path0,path1 which doesn't exist. --- --- @todo can be 11 or 16 elements, read the file and determine it as you go --- --- @param fileName path and name of file to load, for example 'pathFile.csv' --- @param objectName vrep object name you can use to get the handle later, for example 'MyPath', see simSetObjectName --- @param pathProperties http://www.coppeliarobotics.com/helpFiles/en/apiConstants.htm#pathObjectProperties --- --- @return handle to the path --- --- @see path overview http://www.coppeliarobotics.com/helpFiles/en/paths.htm --- @see path import/export http://www.coppeliarobotics.com/helpFiles/en/pathImportExport.htm grl.loadPathFile=function(fileName, objectName, pathProperties) if(pathProperties == nil) then pathProperties = sim_pathproperty_show_line or sim_pathproperty_show_orientation or sim_pathproperty_infinite_acceleration or sim_pathproperty_show_position end local file = io.open(fileName, "r") local ctrlPointsBufferTable = {} --define buffer table local lineCount = 0; --csv line counter local lineElementCount=11; for line in io.lines(fileName) do if(lineCount==0) then lineCopy=line -- string.gsub returns the number of replacements -- each line will have 1 less comma then values -- @see https://stackoverflow.com/questions/11152220/counting-number-of-string-occurrences local _,lineElementCount = string.gsub(lineCopy,",",",") lineElementCount = lineElementCount+1 -- 1 more value than commas end lineCount = lineCount + 1 end --Number of data in csv file(each line contains 11 data, or 16 data with aux values) local fileTotalElementCount = lineCount * lineElementCount for n =1,fileTotalElementCount do ctrlPointsBufferTable[n] =file:read('*n'); file:read(1) end --- @see http://www.coppeliarobotics.com/helpFiles/en/apiFunctions.htm#simInsertPathCtrlPoints --- set the flag indicating if there are 11 or 16 elements in each row of the csv file local pathCtrlPointsOptions = 0 if(lineElementCount == 16) then pathCtrlPointsOptions = 2 -- see LuaScriptFunctions.cpp end --point1 = {0.324854,-0.825006,0.215077,-0,0,math.pi,1.000000,0,15,0.500000,0.500000} --Orientation should be in radian --point2 = {0.424805,-0.750010,0.215113,-0.000000,0.000000,math.pi,1.000000,0,15,0.5,0.5} --BallJointPath=simGetObjectHandle('RemoveBallJoint') --pathPosition=simGetObjectPosition(BallJointPath,-1) --pathOrientation=simGetObjectOrientation(BallJointPath,-1) local MyPathHandle = simCreatePath(pathProperties,nil,nil,nil) --simSetObjectPosition(MyPathHandle,-1,pathPosition) --simSetObjectOrientation(MyPathHandle,-1,pathOrientation) simInsertPathCtrlPoints(MyPathHandle, pathCtrlPointsOptions, 0, lineCount, ctrlPointsBufferTable) local initialName=simGetObjectName(MyPathHandle) local initialHandle=simGetObjectHandle(initialName) simSetObjectName(initialHandle,objectName) --simGetObjectPosition() io.close(file) return MyPathHandle end grl.setPoseRelativeToParent=function(objectHandle,parentHandle,objectPositionXYZ,objectOrientationRPY) simSetObjectPosition(objectHandle,parentHandle,objectPositionXYZ) simSetObjectOrientation(objectHandle,parentHandle,objectOrientationRPY) simSetObjectParent(objectHandle,parentHandle,true) end return grl
--[[FDOC @id AiRtEvChkIsPlayingVoice @category Ai RouteNodeEvent @brief ルートイベント条件スクリプト * 汎用。ChVoicePluginの再生完了待ちを行うスクリプト ]]-- AiRtEvChkIsPlayingVoice = { ---------------------------------------- --開始条件判定 EnableCheck() -- RouteNodeEventのアクション実行前に呼ばれます。 -- boolを返してください。 -- true: アクションを開始します。 -- false: アクションを開始せずに、次のアクションを実行します。 ---------------------------------------- EnableCheck = function( chara ) --VoicePluginが見つからない場合終了 local plgVoice = chara:FindPlugin( "ChVoicePlugin" ) if Entity.IsNull( plgVoice ) then plgVoice = chara:FindPlugin( "ChVoicePlugin2" ) if Entity.IsNull( plgVoice ) then return false end end return true end, ---------------------------------------- --終了条件判定 EndCheck() -- RouteNodeEventのアクション実行後に呼ばれます。 -- boolを返してください。 -- true: アクションを終了します。 -- false: アクションを終了せずに、もう一度同じアクションを繰り返し実行します。 ---------------------------------------- EndCheck = function( chara ) --VoicePluginが見つからない場合終了 local plgVoice = chara:FindPlugin( "ChVoicePlugin" ) if Entity.IsNull( plgVoice ) then plgVoice = chara:FindPlugin( "ChVoicePlugin2" ) if Entity.IsNull( plgVoice ) then return true end end -- 音声再生終了で終了 if not plgVoice:IsPlaying() then return true end return false end, }
if settings.startup["enable-morebobsaddon"] and settings.startup["enable-morebobsaddon"].value then require("lib/tu_market") script.on_event(defines.events.on_entity_died, function(event) -- get shops market_spawning(event) end) local tuonela = require("lib/tuonela") end
-- this module define some Mono tools (ex: non global assembly loader) (experimental, doesn't fully work) local Mono = {} local function splitString(str, sep) if sep == nil then sep = "%s" end local t={} local i=1 for str in string.gmatch(str, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end local function __call_type(self,...) print("call "..tostring(self._type)) return clr.System.Activator.CreateInstance(self._type, arg) end -- build assembly namespace local function add_assembly_type(namespace,atype) local path = splitString(tostring(atype),".") local t = namespace for i=1,#path do local name = path[i] if i == #path then -- last iteration, add type -- proxy type definition, can call the activator instance creation local def = setmetatable({}, { __call = __call_type }) def._type = atype def.GetType = function() return def._type end t[name] = def else local nt = t[name] if nt == nil then -- create subspace if not exists nt = {} t[name] = nt end t = nt end end end function Mono.loadAssembly(path) local bytes = clr.System.IO.File.ReadAllBytes(path) local assembly = clr.System.Reflection.Assembly.Load(bytes) local r = {} if assembly ~= nil then -- build assembly namespace local count = 0 foreach atype in assembly.GetTypes() do add_assembly_type(r,atype) count = count+1 end print("[vRP Mono] loaded assembly "..path.." ("..count.." types)") else print("[vRP Mono] ERROR: failed to load assembly "..path) end return r end return Mono
local skynet = require "skynet" local Room = require "Room" local constant = require "constant" local log = require "skynet.log" local cluster = require "skynet.cluster" local utils = require "utils" local ALL_CARDS = constant.ALL_CARDS local RECOVER_GAME_TYPE = constant.RECOVER_GAME_TYPE local GAME_CMD = constant.GAME_CMD local NET_RESULT = constant.NET_RESULT local ZJ_MODE = constant.ZJ_MODE local PUSH_EVENT = constant.PUSH_EVENT local PAY_TYPE = constant.PAY_TYPE local ROUND_COST = constant.ROUND_COST local cjson = require "cjson" local judgecard = require "hzmj.judgecard" local GANG_TYPE = { AN_GANG = 1, MING_GANG = 2, PENG_GANG = 3, } local GAME_OVER_TYPE = { ["NORMAL"] = 1, --正常胡牌 ["FLOW"] = 2, --流局 ["DISTROY_ROOM"] = 3, --房间解散推送结算积分 } local TYPE = { PENG = 1, GANG = 2, CHI = 3, } local game = {} local game_meta = {} setmetatable(game,game_meta) game.__index = game_meta game.__newindex = game_meta function game:clear() local players = self.room:get("players") local over_round = self.room:get("over_round") local round = self.room:get("round") -- 大赢家金币结算 if over_round >= 1 then local pay_type = self.room:get("pay_type") --赢家出资 积分高的掏钱 if pay_type == PAY_TYPE.WINNER_COST then -- 积分从高到低排序 table.sort(players,function(a,b) return a.score > b.score end) local max_score = players[1].score --大赢家列表 local winners = {} for i,obj in ipairs(players) do if obj.score >= max_score then table.insert(winners,obj) end end local gold_list = { } local per_cost = math.floor(cost/#winners) for _,obj in ipairs(winners) do local gold_num = self:safeClusterCall(obj.node_name,".agent_manager","updateResource",obj.user_id,"gold_num",-1*per_cost) obj.gold_num = gold_num local info = {user_id=obj.user_id,user_pos=obj.user_pos,gold_num=gold_num} table.insert(gold_list,info) end self:broadcastAllPlayers("update_cost_gold",{gold_list=gold_list}) end end --如果在1局跟最后一局之间解散的,则需要发送结算通知 if over_round >= 1 and over_round < round then self:gameOver(player,GAME_OVER_TYPE.DISTROY_ROOM) end --清空数据 local game_meta = {} setmetatable(game,game_meta) game.__index = game_meta game.__newindex = game_meta end --洗牌 FisherYates洗牌算法 --算法的思想是每次从未选中的数字中随机挑选一个加入排列,时间复杂度为O(n) function game:fisherYates() for i = #self.card_list,1,-1 do --在剩余的牌中随机取一张 local j = math.random(i) --交换i和j位置的牌 local temp = self.card_list[i] self.card_list[i] = self.card_list[j] self.card_list[j] = temp end end function game:safeClusterCall(node_name,service_name,func,...) local result,rsp = xpcall(cluster.call,debug.traceback,node_name,service_name,func,...) if not result then log.warning("cluster call faild") end return rsp end --更新玩家的积分 function game:updatePlayerScore(player,over_type,operate,tempResult) local players = self.room:get("players") local seat_num = self.room:get("seat_num") local award_list = {} if over_type == GAME_OVER_TYPE.NORMAL then local count = seat_num - 1 --如果是自摸胡 赢每个玩家2*底分 if operate == "WAIT_PLAY_CARD" then player.cur_score = player.cur_score + self.base_score * 2 * count for _,obj in ipairs(players) do if player.user_id ~= obj.user_id then obj.cur_score = obj.cur_score - self.base_score * 2 end end end --摸到四张红中胡牌,赢每个玩家2*底分; if tempResult.iHuiNum == 4 then player.cur_score = player.cur_score + self.base_score * 2 * count for _,obj in ipairs(players) do if player.user_id ~= obj.user_id then obj.cur_score = obj.cur_score - self.base_score * 2 end end end --胡七对 赢每个玩家2*底分 if tempResult.iChiNum + tempResult.iPengNum == 0 then player.cur_score = player.cur_score + self.base_score * 2 * count for _,obj in ipairs(players) do if player.user_id ~= obj.user_id then obj.cur_score = obj.cur_score - self.base_score * 2 end end end local award_num = self.award_num --每一张码 赢每个玩家2*底分 if tempResult.iHuiNum == 0 then --如果没有红中,则额外奖励两张码 award_num = award_num + 2 end --奖码列表 for i=1,award_num do local card = self.card_list[i] if card then table.insert(award_list,card) end end local num = 0 for _,card in ipairs(award_list) do local card_value = card % 10 --红中的值是35,所以这里就不单独写了 if card_value == 1 or card_value == 5 or card_value == 9 then num = num + 1 end end if num > 0 then player.cur_score = player.cur_score + self.base_score * 2 * 2 * num * count for _,obj in ipairs(players) do if player.user_id ~= obj.user_id then obj.cur_score = obj.cur_score - self.base_score * 2 * 2 * num end end end --更新玩家的总积分 for i,obj in ipairs(players) do obj.score = obj.score + obj.cur_score end else for _,player in ipairs(players) do player.cur_score = 0 end end if over_type == GAME_OVER_TYPE.NORMAL then player.hu_num = player.hu_num + 1 for _,player in ipairs(players) do for i,obj in ipairs(player.card_stack) do if obj.type == TYPE.GANG then if obj.gang_type == GANG_TYPE.AN_GANG then player.an_gang_num = player.an_gang_num + 1 else player.ming_gang_num = player.ming_gang_num + 1 end end end player.reward_num = player.reward_num + 1 player.card_stack = {} end end local info = self.room:getPlayerInfo("user_id","score","card_list","user_pos","cur_score") local data = {over_type = over_type,players = info,award_list=award_list} if over_type == GAME_OVER_TYPE.NORMAL then data.winner_pos = player.user_pos if operate == "WAIT_PLAY_CARD" then data.winner_type = constant["WINNER_TYPE"].ZIMO elseif operate == "WAIT_HU" then data.winner_type = constant["WINNER_TYPE"].QIANG_GANG end end local cur_round = self.room:get("cur_round") local round = self.room:get("round") data.last_round = cur_round == round self.room:broadcastAllPlayers("notice_game_over",data) end --更新玩家的金币 function game:updatePlayerGold(over_type) if over_type == GAME_OVER_TYPE.DISTROY_ROOM then return end local room = self.room local players = room:get("players") local cur_round = room:get("cur_round") local round = room:get("round") local seat_num = room:get("seat_num") --花费 local cost = round * ROUND_COST --出资类型 local pay_type = room:get("pay_type") --第一局结束 结算(房主出资/平摊出资)的金币 if cur_round == 1 then --房主出资 if pay_type == PAY_TYPE.ROOM_OWNER_COST then local owner_id = room:get("owner_id") local owner = room:getPlayerByUserId(owner_id) --更新玩家的金币数量 local gold_num = self:safeClusterCall(owner.node_name,".agent_manager","updateResource",owner_id,"gold_num",-1*cost) --如果owner不存在 有可能不在游戏中(比如:有人开房给别人玩,自己不玩) if owner then owner.gold_num = gold_num local gold_list = {{user_id = owner_id,user_pos = owner.user_pos,gold_num=gold_num}} --通知房间中的所有人,有人的金币发生了变化 room:broadcastAllPlayers("update_cost_gold",{gold_list=gold_list}) end --平摊 elseif pay_type == PAY_TYPE.AMORTIZED_COST then --每个人的花费 local per_cost = math.floor(cost / seat_num) local gold_list = {} for i,obj in ipairs(players) do local gold_num = self:safeClusterCall(obj.node_name,".agent_manager","updateResource",obj.user_id,"gold_num",-1*per_cost) obj.gold_num = gold_num local info = {user_id = obj.user_id,user_pos = obj.user_pos,gold_num = gold_num} table.insert(gold_list,info) end room:broadcastAllPlayers("update_cost_gold",{gold_list=gold_list}) end end end --游戏结束 function game:gameOver(player,over_type,operate,tempResult) local room = self.room local players = room:get("players") local cur_round = room:get("cur_round") local round = room:get("round") local seat_num = room:get("seat_num") local room_id = room:get("room_id") --计算金币并通知玩家更新 self:updatePlayerGold(over_type) --计算积分并通知玩家 self:updatePlayerScore(player,over_type,operate,tempResult) --FYD1 --更新当前已经完成的局数 local over_round = self.room:get("over_round") self.room:set("over_round",over_round + 1) local players = self.room:get("players") for i,player in ipairs(players) do player.is_sit = false end room:set("sit_down_num",0) local room_info = self.room:getAllInfo() skynet.call(".room_manager","lua","gameOver",room_id,room_info) end --检测流局 function game:flowBureau() local num = #self.card_list if num == self.award_num + 1 then return true end return false end --游戏初始化 function game:init(room_id,gtype) self.room = Room.recover("room:"..room_id) --填充牌库 self.card_list = {} for _,value in ipairs(ALL_CARDS[gtype]) do table.insert(self.card_list,value) end --洗牌 self:fisherYates() self.other_setting = self.room:get("other_setting") --底分 self.base_score = self.other_setting[1] --奖码数 self.award_num = self.other_setting[2] --七对 self.seven_pairs = self.other_setting[3] --喜分 self.hi_point = self.other_setting[4] --一码不中当全中 self.convert = self.other_setting[5] --等待玩家操作的列表 self.waite_operators = {} --当前出牌人 self.cur_play_user = nil --当前出的牌 self.cur_play_card = nil local players = self.room:get("players") for _,player in ipairs(players) do --玩家当前局积分清零 player.cur_score = 0 end end --更新庄家的位置 function game:updateZpos() local zpos = nil local zj_mode = self.room:get("zj_mode") local sit_down_num = self.room:get("sit_down_num") if not self.zpos then zpos = math.random(1,sit_down_num) else zpos = self.zpos end self.zpos = zpos end function game:start() --1、更新庄家的位置 self:updateZpos() if constant["DEBUG"] then local conf = require("hzmj/conf") self.zpos = conf.zpos utils:mergeToTable(self.card_list,conf.card_list) end local players = self.room:get("players") local random_nums = {} for i = 1,2 do local num = math.random(1,6) table.insert(random_nums,num) end --2、发牌 local deal_num = 13 --红中麻将发13张牌 for index=1,self.room:get("sit_down_num") do local cards = {} for j=1,deal_num do --从最后一个开始移除,避免大量的元素位置重排 local card = table.remove(self.card_list) table.insert(cards,card) end local player = self.room:getPlayerByPos(index) player.card_list = cards local rsp_msg = {} rsp_msg.zpos = self.zpos rsp_msg.cards = cards rsp_msg.user_id = user_id rsp_msg.user_pos = player.user_pos rsp_msg.random_nums = random_nums rsp_msg.cur_round = self.room:get("cur_round") self.room:sendMsgToPlyaer(player, "deal_card", rsp_msg) end --3、将card按类别和数字存储 for _,player in ipairs(players) do local card_list = player.card_list local handle_cards = { } for i= 1,4 do handle_cards[i] = {} for j= 1,10 do handle_cards[i][j] = 0 end end for _,value in ipairs(card_list) do local card_type = math.floor(value / 10) + 1 local card_value = value % 10 handle_cards[card_type][10] = handle_cards[card_type][10] + 1 handle_cards[card_type][card_value] = handle_cards[card_type][card_value] + 1 end player.handle_cards = handle_cards end for i,player in ipairs(players) do self.waite_operators[player.user_pos] = "WAIT_DEAL_FINISH" end end --增加手牌 function game:addHandleCard(player,card) table.insert(player.card_list,card) local card_type = math.floor(card / 10) + 1 local card_value = card % 10 local handle_cards = player.handle_cards handle_cards[card_type][10] = handle_cards[card_type][10] + 1 handle_cards[card_type][card_value] = handle_cards[card_type][card_value] + 1 end --减去手牌 function game:removeHandleCard(player,card,num) num = num or 1 local indexs = {} for i=#player.card_list,1,-1 do local value = player.card_list[i] if value == card then table.insert(indexs,i) end end if #indexs < num then return false end for i,idx in ipairs(indexs) do if i <= num then table.remove(player.card_list,idx) local card_type = math.floor(card / 10) + 1 local card_value = card % 10 local handle_cards = player.handle_cards handle_cards[card_type][10] = handle_cards[card_type][10] - 1 handle_cards[card_type][card_value] = handle_cards[card_type][card_value] - 1 else break end end return true end --通知玩家出牌 function game:noticePushPlayCard(splayer,operator) local players = self.room:get("players") for i,player in ipairs(players) do local rsp_msg = {user_id=splayer.user_id,user_pos=splayer.user_pos} if player.user_id == splayer.user_id then rsp_msg.card_list = player.card_list rsp_msg.card_stack = player.card_stack end rsp_msg.operator = operator self.room:sendMsgToPlyaer(player,"push_play_card",rsp_msg) end end --向A发一张牌 摸牌 function game:drawCard(player) --检查是否流局 local is_flow = self:flowBureau() if is_flow then self:gameOver(player,GAME_OVER_TYPE.FLOW) return end local card = table.remove(self.card_list) self:addHandleCard(player,card) local user_id = player.user_id --通知摸牌 for _,obj in ipairs(self.room:get("players")) do local data = {user_id = user_id,user_pos = player.user_pos} if obj.user_id == user_id then data.card = card end self.room:sendMsgToPlyaer(obj,"push_draw_card",data) end --通知玩家出牌了 local operator = 1 self:noticePushPlayCard(player,operator) self.waite_operators[player.user_pos] = "WAIT_PLAY_CARD" end --发牌完毕 game["DEAL_FINISH"] = function(self, player) local user_pos = player.user_pos if self.waite_operators[user_pos] ~= "WAIT_DEAL_FINISH" then return "invaild_operator" end self.waite_operators[user_pos] = nil --计算剩余的数量 local num = 0 for k, v in pairs(self.waite_operators) do num = num + 1 end if num == 0 then --庄家出牌 local zplayer = self.room:getPlayerByPos(self.zpos) self:drawCard(zplayer) end return "success" end --出牌 game["PLAY_CARD"] = function(self,player,data) if self.waite_operators[player.user_pos] ~= "WAIT_PLAY_CARD" then return "invaild_operator" end if not data.card then return "paramater_error" end --减少A玩家的手牌 local result = self:removeHandleCard(player,data.card) if not result then return "invaild_operator" end self.waite_operators[player.user_pos] = nil local user_id = player.user_id local data = {user_id = user_id,card = data.card,user_pos = player.user_pos} --通知所有人 A 已经出牌 self.room:broadcastAllPlayers("notice_play_card",data) --记录下当前出牌人和当前出的牌 self.cur_play_user = player self.cur_play_card = data.card local card_type = math.floor(data.card / 10) + 1 local card_value = data.card % 10 --因为红中麻将只能 抢杠胡(碰杠,先碰,然后自摸一个)和自摸胡,所以这里不用判断胡牌 --只需要判断是否碰、杠 并且有且最多只有一个人会碰、杠 local num = 0 local check_player = nil local user_pos = player.user_pos for pos = user_pos+1,user_pos + self.room:get("seat_num")-1 do if pos > self.room:get("seat_num") then pos = 1 end check_player = self.room:getPlayerByPos(pos) local handle_cards = check_player.handle_cards num = handle_cards[card_type][card_value] if num == 2 then break elseif num == 3 then break end end local operator_list = {} if num == 2 then --碰 table.insert(operator_list,"PENG") self.room:sendMsgToPlyaer(check_player,"push_player_operator_state",{operator_list=operator_list,user_pos=check_player.user_pos,card=data.card}) self.waite_operators[check_player.user_pos] = "WAIT_PENG" elseif num == 3 then --杠 table.insert(operator_list,"PENG") table.insert(operator_list,"GANG") self.room:sendMsgToPlyaer(check_player,"push_player_operator_state",{operator_list=operator_list,user_pos=check_player.user_pos,card=data.card}) self.waite_operators[check_player.user_pos] = "WAIT_GANG_WAIT_PENG" else next_pos = user_pos + 1 if next_pos > self.room:get("seat_num") then next_pos = 1 end local next_player = self.room:getPlayerByPos(next_pos) self:drawCard(next_player) end return "success" end function game:checkPeng(player,card) local card_type = math.floor(card / 10) + 1 local card_value = card % 10 local handle_cards = player.handle_cards return handle_cards[card_type][card_value] >= 2 end --碰 game["PENG"] = function(self,player,data) if not string.find(self.waite_operators[player.user_pos],"WAIT_PENG") then return "invaild_operator" end self.waite_operators[player.user_pos] = nil local card = self.cur_play_card if not self:checkPeng(player,card) then return "invaild_operator" end local obj = {value = card,from = self.cur_play_user.user_pos,type=TYPE.PENG} --记录下已经碰的牌 table.insert(player.card_stack,obj) --移除手牌 local result = self:removeHandleCard(player,card,2) if not result then return "server_error" end --通知所有人,有人碰了 local data = {user_id=player.user_id,user_pos=player.user_pos,item=obj} self.room:broadcastAllPlayers("notice_peng_card",data) --通知玩家出牌 local operator = 2 self:noticePushPlayCard(player,operator) self.waite_operators[player.user_pos] = "WAIT_PLAY_CARD" return "success" end function game:checkGang(player,card) --1、暗杠 手牌拥有四张牌 =>暗杠 --2、明杠 手牌拥有三张,加上别人出的一张 =>别人放的杠 --3、碰杠 手牌拥有1张 =>自己摸的明杠 local result local card_type = math.floor(card / 10) + 1 local card_value = card % 10 local handle_cards = player.handle_cards local num = handle_cards[card_type][card_value] if num >= 4 then result = GANG_TYPE.AN_GANG elseif num >= 3 then result = GANG_TYPE.MING_GANG elseif num == 1 then for _,obj in ipairs(player.card_stack) do if obj.value == card and obj.type == TYPE.PENG then result = GANG_TYPE.PENG_GANG break end end end return result end --检查是否可以胡牌 function game:checkHu(player) local tempResult = { iChiNum = 0; iPengNum = 0; iHuiNum = 0; bJiangOK = false; iHuiType = 0; chiType = { [1] = {iType = 0,iFirstValue = 0,iFromPost = 0}, [2] = {iType = 0,iFirstValue = 0,iFromPost = 0}, [3] = {iType = 0,iFirstValue = 0,iFromPost = 0}, [4] = {iType = 0,iFirstValue = 0,iFromPost = 0}, }; pengType = { [1] = {iType = 0,iValue = 0,iFromPost = 0}, [2] = {iType = 0,iValue = 0,iFromPost = 0}, [3] = {iType = 0,iValue = 0,iFromPost = 0}, [4] = {iType = 0,iValue = 0,iFromPost = 0}, }; jiangType = { [1] = {iType = 0,iValue = 0}, [2] = {iType = 0,iValue = 0}, [3] = {iType = 0,iValue = 0}, [4] = {iType = 0,iValue = 0}, } } tempResult.iHuiCard = 35 return judgecard:JudgeIfHu2(player.handle_cards, tempResult, self.seven_pairs),tempResult end --杠 game["GANG"] = function(self,player,data) local card = data.card local gang_type = self:checkGang(player,card) if not gang_type then return "invaild_operator" end local operate = self.waite_operators[player.user_pos] --如果操作是等待出牌,并且可以进行暗杠,则可以进去 if operate == "WAIT_PLAY_CARD" and (gang_type == GANG_TYPE.AN_GANG or gang_type == GANG_TYPE.PENG_GANG ) then elseif not string.find(self.waite_operators[player.user_pos],"WAIT_GANG") then return "invaild_operator" end self.waite_operators[player.user_pos] = nil local obj = {value = card,gang_type = gang_type,type=TYPE.GANG} local num = 0 if gang_type == GANG_TYPE.AN_GANG then obj.from = player.user_pos num = 4 --记录下已经杠的牌 table.insert(player.card_stack,obj) elseif gang_type == GANG_TYPE.MING_GANG then obj.from = self.cur_play_user.user_pos num = 3 --记录下已经杠的牌 table.insert(player.card_stack,obj) elseif gang_type == GANG_TYPE.PENG_GANG then num = 1 --如果是碰杠,则更改碰变成杠 for _,item in ipairs(player.card_stack) do if item.value == card and item.type == TYPE.PENG then item.type = TYPE.GANG item.gang_type = GANG_TYPE.PENG_GANG obj = item break end end end --移除手牌 local result = self:removeHandleCard(player,card,num) if not result then return "server_error" end --通知所有人,有人杠了 local data = {user_id = player.user_id,user_pos = player.user_pos,item = obj} self.room:broadcastAllPlayers("notice_gang_card",data) local players = self.room:get("players") local count = self.room:get("seat_num") - 1 local origin_data = self.room:getPlayerInfo("user_id","cur_score") --计算杠的积分 for _,obj in ipairs(player.card_stack) do if obj.gang_type == GANG_TYPE.AN_GANG then --暗杠,赢每个玩家2*底分; player.cur_score = player.cur_score + self.base_score * 2 * count for _,obj in ipairs(players) do if player.user_id ~= obj.user_id then obj.cur_score = obj.cur_score - self.base_score * 2 end end elseif obj.gang_type == GANG_TYPE.MING_GANG then --明杠 赢放杠者3*底分 player.cur_score = player.cur_score + self.base_score * 3 for _,obj in ipairs(players) do if obj.from == obj.user_pos then obj.cur_score = obj.cur_score - self.base_score * 3 end end elseif obj.gang_type == GANG_TYPE.PENG_GANG then --自己摸的明杠(公杠) 三家出,赢每个玩家1*底分; player.cur_score = player.cur_score + self.base_score * 1 * count for _,obj in ipairs(players) do if player.user_id ~= obj.user_id then obj.cur_score = obj.cur_score - self.base_score * 1 end end end end local data = self.room:getPlayerInfo("user_id","user_pos","cur_score") for _,origin_info in ipairs(origin_data) do for _,info in ipairs(data) do if origin_info.user_id == info.user_id then info.delt_score = info.cur_score - origin_info.cur_score info.cur_score = nil end end end self.room:broadcastAllPlayers("refresh_player_cur_score",{cur_score_list=data}) if gang_type ~= GANG_TYPE.PENG_GANG then --杠了之后再摸一张牌 self:drawCard(player) return "success" end --如果是碰杠,则需要检查是否有人胡这张牌 local hu_list = {} local players = self.room:get("players") for _,temp_player in ipairs(players) do if temp_player.user_id ~= player.user_id then --胡牌前,先将这张杠牌加入玩家手牌 self:addHandleCard(temp_player,card) local is_hu = self:checkHu(player) --检查完之后,去掉这张牌 self:removeHandleCard(temp_player,card,1) if is_hu then table.insert(hu_list,temp_player) end end end if #hu_list > 1 then for _,hu_player in ipairs(hu_list) do --通知客户端当前可以胡牌 self.room:sendMsgToPlyaer(hu_player,"push_player_operator_state",{operator_state = "HU",user_pos = hu_player.user_pos,user_id=hu_player.user_id}) self.waite_operators[player.user_pos] = "WAIT_HU" self.gang_pos = player.user_pos end else --杠了之后再摸一张牌 self:drawCard(player) end return "success" end --过 game["GUO"] = function(self,player,data) local operate = self.waite_operators[player.user_pos] if not operate then return "invaild_operator" end self.waite_operators[player.user_pos] = nil --检测是否有延迟胡牌的情况 local positions = {} for pos,v in pairs(self.waite_operators) do table.insert(positions,pos) end if #positions >= 1 then for i=1,self.room:get("seat_num")-1 do local next_pos = self.gang_pos + 1 if positions[next_pos] then --找到胡牌人中优先级最高的人 if positions[next_pos] == "DELAY_HU" then --如果这个人处于延迟胡状态 local player = self.room:getPlayerByPos(next_pos) local is_hu,tempResult = self:checkHu(player) if is_hu then --延迟胡牌不可能是自摸胡牌,所以这里填写WAIT_HU self:gameOver(player,GAME_OVER_TYPE.NORMAL,"WAIT_HU",tempResult) end end end end end --下一家出牌 local next_pos = self.cur_play_user.user_pos + 1 if next_pos > self.room:get("seat_num") then next_pos = 1 end local next_player = self.room:getPlayerByPos(next_pos) self:drawCard(next_player) return "success" end --胡牌 game["HU"] = function(self,player,data) local operate = self.waite_operators[player.user_pos] local gang_hu = string.find(self.waite_operators[player.user_pos],"WAIT_HU") if not (operate == "WAIT_PLAY_CARD" or gang_hu) then return "invaild_operator" end local positions = {} for pos,v in pairs(self.waite_operators) do positions[pos] = true end if # positions > 1 then for i=1,self.room:get("seat_num")-1 do local next_pos = self.gang_pos + 1 if positions[next_pos] then --找到胡牌人中优先级最高的人,如果当前胡牌人不是这个人 if positions[next_pos] ~= player.user_pos then --延迟胡牌 self.waite_operators[player.user_pos] = "DELAY_HU" return "success" end end end end self.waite_operators[player.user_pos] = nil --抢杠的话,杠是不算的 if gang_hu then local card = nil for _,obj in ipairs(player.card_stack) do if obj.gang_type == GANG_TYPE.PENG_GANG then obj.gang_type = nil obj.type = TYPE.PENG card = obj.value end end --胡牌前,先将这张杠牌加入玩家手牌 self:addHandleCard(player,card) local is_hu = self:checkHu(player) --检查完之后,去掉这张牌 self:removeHandleCard(player,card,1) if is_hu then self:gameOver(player,GAME_OVER_TYPE.NORMAL,operate,tempResult) end return "success" end local is_hu,tempResult = self:checkHu(player) if is_hu then self:gameOver(player,GAME_OVER_TYPE.NORMAL,operate,tempResult) end return "success" end --返回房间 game["BACK_ROOM"] = function(self,player,data) player.fd = data.fd local room_setting = self.room:getPropertys("game_type","round","pay_type","seat_num","is_friend_room","is_open_voice","is_open_gps","other_setting","cur_round") local players_info = self.room:getPlayerInfo("user_id","user_name","user_pic","user_ip","user_pos","is_sit","score","card_stack","gold_num") local rsp_msg = {} rsp_msg.room_setting = room_setting rsp_msg.card_list = player.card_list rsp_msg.players = players_info rsp_msg.operator = self.waite_operators[player.user_pos] self.room:sendMsgToPlyaer(player,"push_all_room_info",rsp_msg) self.room:noticePlayerConnectState(player,true) return "success" end function game:gameCMD(data) local user_id = data.user_id local command = data.command local func = game[command] if not func then return "no_support_command" end local player = self.room:getPlayerByUserId(user_id) local result = func(game,player,data) return result end return game
local table_stack = {} function table_stack.new() return setmetatable({ n = 0 }, table_stack) end function table_stack:push(...) self.n = self.n + 1 local entry = self[self.n] for i = 1, select('#', ...) do entry[i] = select(i, ...) end return entry end function table_stack:peek() return self[self.n] end function table_stack:pop() local prev = self[self.n] self.n = self.n - 1 return prev end function table_stack:clear(n) self.n = n or 0 end local methods = { push = table_stack.push, peek = table_stack.peek, pop = table_stack.pop, clear = table_stack.clear, } local weak_mt = { __mt = 'kv' } function table_stack:__index(index) if methods[index] then return methods[index] end local new_table = setmetatable({}, weak_mt) rawset(self, index, new_table) return new_table end return table_stack
return { library = [[ ```json "Lua.workspace.library": { "C:/lua": true, "../lib": [ "temp/*" ] } ``` ]], disable = [[ ```json "Lua.diagnostics.disable" : [ "unused-local", "lowercase-global" ] ``` ]], globals = [[ ```json "Lua.diagnostics.globals" : [ "GLOBAL1", "GLOBAL2" ] ``` ]], severity = [[ ```json "Lua.diagnostics.severity" : { "redefined-local" : "Warning", "emmy-lua" : "Hint" } ``` ]], ignoreDir = [[ ```json "Lua.workspace.ignoreDir" : [ "temp/*.*", "!temp/*.lua" ] ``` ]], special = [[ ```json "Lua.runtime.special" : { "include" : "require" } ``` ]] }
local Tunnel = module("vrp","lib/Tunnel") local Proxy = module("vrp","lib/Proxy") vRP = Proxy.getInterface("vRP") --[ LOCAIS ]----------------------------------------------------------------------------------------------------------------------------- Resg = Tunnel.getInterface("nav_uniforme-medico") --[ FUNCTION ]--------------------------------------------------------------------------------------------------------------------------- local menuactive = false function ToggleActionMenu() menuactive = not menuactive if menuactive then SetNuiFocus(true,true) SendNUIMessage({ showmenu = true }) else SetNuiFocus(false) SendNUIMessage({ hidemenu = true }) end end --[ BUTTON ]----------------------------------------------------------------------------------------------------------------------------- RegisterNUICallback("ButtonClick",function(data,cb) if data == "diretorgeral" then TriggerServerEvent("diretorgeral") elseif data == "diretorauxiliar" then TriggerServerEvent("diretorauxiliar") elseif data == "medicochefe" then TriggerServerEvent("medicochefe") elseif data == "medicoauxiliar" then TriggerServerEvent("medicoauxiliar") elseif data == "cirurgiao" then TriggerServerEvent("cirurgiao") elseif data == "medico" then TriggerServerEvent("medico") elseif data == "enfermeiro" then TriggerServerEvent("enfermeiro") elseif data == "estagiario" then TriggerServerEvent("estagiario") elseif data == "paramedico" then TriggerServerEvent("paramedico") elseif data == "socorrista" then TriggerServerEvent("socorrista") elseif data == "tirar-uniforme" then TriggerServerEvent("tirar-uniforme") elseif data == "fechar" then ToggleActionMenu() end end) --[ LOCAIS ]----------------------------------------------------------------------------------------------------------------------------- local armarios = { { ['x'] = 298.57, ['y'] = -598.36, ['z'] = 43.29 }, { ['x'] = 303.83, ['y'] = -569.69, ['z'] = 43.29 } } --[ LOCAIS ]----------------------------------------------------------------------------------------------------------------------------- Citizen.CreateThread(function() SetNuiFocus(false,false) while true do local idle = 1000 for k,v in pairs(armarios) do local ped = PlayerPedId() local x,y,z = table.unpack(GetEntityCoords(ped)) local bowz,cdz = GetGroundZFor_3dCoord(v.x,v.y,v.z) local distance = GetDistanceBetweenCoords(v.x,v.y,cdz,x,y,z,true) local armarios = armarios[k] if distance < 5.1 then DrawMarker(23,armarios.x,armarios.y,armarios.z-0.99,0,0,0,0,0,0,0.7,0.7,0.5,136, 96, 240, 180,0,0,0,0) idle = 5 if distance <= 1.2 then if IsControlJustPressed(0,38) and Resg.checkPermissao() then ToggleActionMenu() end end end end Citizen.Wait(idle) end end) --[ FUNÇÕES ]---------------------------------------------------------------------------------------------------------------------------- function DrawText3D(x,y,z, text) -- some useful function, use it if you want! SetDrawOrigin(x, y, z, 0) SetTextFont(4) SetTextProportional(1) SetTextScale(0.28, 0.28) SetTextColour(255, 255, 255, 215) SetTextDropshadow(0, 0, 0, 0, 255) SetTextEdge(2, 0, 0, 0, 150) SetTextDropShadow() SetTextOutline() SetTextEntry("STRING") SetTextCentre(1) AddTextComponentString(text) DrawText(0.0, 0.0) ClearDrawOrigin() end
--海竜神の怒り function c82685480.initial_effect(c) aux.AddCodeList(c,22702055) --activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCountLimit(1,82685480+EFFECT_COUNT_CODE_OATH) e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER+TIMING_END_PHASE) e1:SetCondition(c82685480.condition) e1:SetTarget(c82685480.target) e1:SetOperation(c82685480.activate) c:RegisterEffect(e1) end function c82685480.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.IsEnvironment(22702055) end function c82685480.filter(c) return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_WATER) and c:GetOriginalLevel()>=5 end function c82685480.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) end local ct=Duel.GetMatchingGroupCount(c82685480.filter,tp,LOCATION_MZONE,0,nil) if chk==0 then return ct>0 and Duel.IsExistingTarget(nil,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,nil,tp,0,LOCATION_MZONE,1,ct,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c82685480.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) if g:GetCount()==0 then return end if Duel.Destroy(g,REASON_EFFECT)==0 then return end local val=0 local og=Duel.GetOperatedGroup() local tc=og:GetFirst() while tc do val=val|aux.SequenceToGlobal(tc:GetPreviousControler(),LOCATION_MZONE,tc:GetPreviousSequence()) tc=og:GetNext() end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_DISABLE_FIELD) e1:SetValue(val) e1:SetReset(RESET_PHASE+PHASE_END,2) Duel.RegisterEffect(e1,tp) end
local ObjectManager = require("managers.object.object_manager") NewsnetMenuComponent = { } function NewsnetMenuComponent:fillObjectMenuResponse(pSceneObject, pMenuResponse, pPlayer) local menuResponse = LuaObjectMenuResponse(pMenuResponse) menuResponse:addRadialMenuItem(20, 3, "@gcw:read_headline") -- Read Headline end function NewsnetMenuComponent:handleObjectMenuSelect(pObject, pPlayer, selectedID) if (pPlayer == nil or pObject == nil) then return 0 end if (selectedID ~= 20) then return 0 end local planet = SceneObject(pObject):getZoneName() if (planet == "") then return 0 end local controllingFaction = getControllingFaction(planet) if (planet ~= "naboo" and planet ~= "corellia") then planet = "general" end local headline if (controllingFaction == FACTIONREBEL) then -- Rebels winning headline = "headline_" .. planet .. "_rebel_winning_" .. getRandomNumber(1,4) elseif (controllingFaction == FACTIONIMPERIAL) then headline = "headline_" .. planet .. "_rebel_losing_" .. getRandomNumber(1,4) else headline = "headline_" .. planet .. "_equal" end -- Close open Newsnet SUIs and send the player a new one. local pGhost = CreatureObject(pPlayer):getPlayerObject() if (pGhost ~= nil) then PlayerObject(pGhost):closeSuiWindowType( NEWSNET_INFO ) end local suiManager = LuaSuiManager() suiManager:sendMessageBox(pObject, pPlayer, "@gcw:" .. planet .. "_newsnet_name", "@gcw:" .. headline, "@ok", "NewsnetMenuComponent", "notifyOkPressed", NEWSNET_INFO) return 0 end function NewsnetMenuComponent:notifyOkPressed() end
----------------------------------------- -- Spell: Grand Slam -- Delivers an area attack. Damage varies with TP -- Spell cost: 24 MP -- Monster Type: Beastmen -- Spell Type: Physical (Blunt) -- Blue Magic Points: 2 -- Stat Bonus: INT+1 -- Level: 30 -- Casting Time: 1 seconds -- Recast Time: 14.25 seconds -- Skillchain Element(s): Ice (can open Impaction, Compression, or Fragmentation can close Induration) -- Combos: Defense Bonus ----------------------------------------- require("scripts/globals/bluemagic") require("scripts/globals/status") require("scripts/globals/magic") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local params = {} -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK params.dmgtype = tpz.damageType.BLUNT params.scattr = SC_INDURATION params.numhits = 1 params.multiplier = 1.0 params.tp150 = 1.0 params.tp300 = 1.0 params.azuretp = 1.0 params.duppercap = 33 params.str_wsc = 0.0 params.dex_wsc = 0.0 params.vit_wsc = 0.3 params.agi_wsc = 0.0 params.int_wsc = 0.1 params.mnd_wsc = 0.1 params.chr_wsc = 0.1 damage = BluePhysicalSpell(caster, target, spell, params) damage = BlueFinalAdjustments(caster, target, spell, damage, params) return damage end
modifier_boss_charger_hero_pillar_debuff = class(ModifierBaseClass) function modifier_boss_charger_hero_pillar_debuff:DeclareFunctions() return { MODIFIER_PROPERTY_OVERRIDE_ANIMATION, } end function modifier_boss_charger_hero_pillar_debuff:IsDebuff() return true end function modifier_boss_charger_hero_pillar_debuff:IsHidden() return false end function modifier_boss_charger_hero_pillar_debuff:IsPurgable() return true end function modifier_boss_charger_hero_pillar_debuff:IsStunDebuff() return true end function modifier_boss_charger_hero_pillar_debuff:GetEffectName() return "particles/generic_gameplay/generic_stunned.vpcf" end function modifier_boss_charger_hero_pillar_debuff:GetEffectAttachType() return PATTACH_OVERHEAD_FOLLOW end function modifier_boss_charger_hero_pillar_debuff:GetOverrideAnimation( params ) return ACT_DOTA_DISABLED end function modifier_boss_charger_hero_pillar_debuff:CheckState() local state = { [MODIFIER_STATE_STUNNED] = true } return state end
local moon = require("moon") local socket = require("moon.socket") local conf = ... or {} local total,count,client_num,send_count count = 0 local start_time = 0 local result = {} local connects = {} local time_count = {} local send_data = "Hello World" local n = 0 socket.on("connect",function(fd,msg) connects[fd] = 1 n = n + 1 if n == client_num then for k,v in pairs(connects) do time_count[k] = moon.now() socket.write(k,send_data) end start_time = moon.now() print("start....") end end) socket.on("message",function(fd, msg) count = count + 1 local now = moon.now() local diff = now - time_count[fd] local v = result[diff] if not v then v = 0 end result[diff] = v + 1 local nc = connects[fd] if nc < send_count then connects[fd] = nc + 1 time_count[fd] = now socket.write(fd,send_data) return end socket.close(fd) --print(fd,connects[fd],count,total) if count == total then local qps = total*1000/(moon.now()-start_time) local keys = {} for k,_ in pairs(result) do table.insert( keys, k) end table.sort( keys ) local n = 0 for _,k in pairs(keys) do local v = result[k] n = n + v print(string.format( "%.02f%% <= %d milliseconds",n/total*100,k)) end print(string.format("%.02f requests per second",qps)) end end) socket.on("close",function(fd, msg) --print("close ", fd, moon.decode(msg, "Z")) end) socket.on("error",function(fd, msg) --print("error ", fd, moon.decode(msg, "Z")) end) total = conf.client_num * conf.count print(total) client_num = conf.client_num send_count = conf.count moon.async(function() moon.sleep(10) for _=1,conf.client_num do local fd = socket.connect(conf.host,conf.port,moon.PTYPE_SOCKET) end end)
--[[ MATRIX MODULE v1.0 by RedPolygon All functions (except fill) return new matrices --]] -- INITIALIZE local matrix = {} local mt = {} -- FUNCTIONS function matrix.new( rows, cols ) local m = {} if type(rows) == "table" then -- Filled matrix if type(rows[1]) == "table" then m = rows else -- Vector (basically 1D matrix) m = matrix.vectorToMatrix(rows) end else -- Empty matrix for row = 1, rows do m[row] = {} for col = 1, cols do m[row][col] = 0 end end end m.rows = #m m.cols = #m[1] m.width = m.cols m.height = m.rows return setmetatable( m, mt ) end function matrix.vectorToMatrix(v) local m = {} for i = 1, #v do m[i] = {v[i]} end return setmetatable( m, mt ) end -- Create a new matrix out of 2 matrices function matrix.loop( m1, m2, fn ) if not fn then fn = m2 m2 = nil end local m = {} for row = 1, #m1 do m[row] = {} for col = 1, #m1[row] do m[row][col] = fn( m1[row][col], (m2 and m2[row][col]) ) end end return matrix.new(m) end -- Fill the given matrix with n or using a function(row,col) -- This function modifies the matrix, instead of returning a new one function matrix.fill( m, n ) for row = 1, #m do for col = 1, #m[row] do m[row][col] = (type(n) == "function" and n(row,col) or n) end end end function matrix.add( m1, m2 ) if type(m2) == "number" then return matrix.loop( m1, function(a) return a + m2 end) else return matrix.loop( m1, m2, function(a,b) return a + b end) end end function matrix.sub( m1, m2 ) if type(m2) == "number" then return matrix.loop( m1, function(a) return a - m2 end) else return matrix.loop( m1, m2, function(a,b) return a - b end) end end function matrix.mul( m1, m2 ) if type(m2) == "number" then return matrix.scale( m1, m2 ) else return m1.multiply and m1.multiply( m1, m2 ) or matrix.multiply( m1, m2 ) end end function matrix.div( m1, m2 ) if type(m2) == "number" then return matrix.scale( m1, 1/m2 ) else return matrix.loop( m1, m2, function(a,b) return a / b end) end end function matrix.scale( m1, amount ) return matrix.loop( m1, function(a) return a * amount end) end -- Matrix product function matrix.product( a, b ) -- Multiplying matrices or vector(s) if a.cols ~= b.rows then error("Cols of A not equal to rows of B") end local m = {} for row = 1, a.rows do -- For each row of A m[row] = {} for col = 1, b.cols do -- For each col of B local sum = 0 for i = 1, b.rows do -- For each col of A / row of B sum = sum + a[row][i] * b[i][col] end m[row][col] = sum end end return matrix.new(m) end function matrix.hadamard( m1, m2 ) return matrix.loop( m1, m2, function( a, b ) return a * b end) end function matrix.transpose(m) local new = {} for row = 1, #m[1] do new[row] = {} for col = 1, #m do new[row][col] = m[col][row] end end return matrix.new(new) end function matrix.equals( m1, m2 ) -- Check type and length if type(m1) ~= "table" or type(m2) ~= "table" or #m1 ~= #m2 or #m1[1] ~= #m2[1] then return false end -- Check each cell for row = 1, #m1 do for col = 1, #m1[row] do if m1[row][col] ~= m2[row][col] then return false end end end return true end function matrix.tostring(m) local str = "Matrix ("..#m.." x "..#m[1]..")\n" for row = 1, #m do for col = 1, #m[row] do str = str .. math.floor( m[row][col] * 1000 ) / 1000 .. "\t" end str = str .. "\n" end return string.sub( str, 1, -2 ) -- Trim last newline end -- METAMETHODS mt.__index = matrix mt.__add = matrix.add mt.__sub = matrix.sub mt.__mul = matrix.mul mt.__div = matrix.div mt.__unm = function( m ) return matrix.scale( m, -1 ) end mt.__eq = matrix.equals mt.__tostring = matrix.tostring -- SETTINGS matrix.multiply = matrix.product -- matrix.product or matrix.hadamard -- RETURN return setmetatable( matrix, {__call = function(_,...) return matrix.new(...) end} )
module("XPluginManager", mkSingleton) setmetatable(XPluginManager, {__index=XLuaBehaviour}) function Init(self) -- current plugin list self.plugins = { } end -- start plugin manager function Startup(self) self.gameObject = GameObject("XPluginManager") if not self.gameObject then error("Can't create PluginManager") end GameObject.DontDestroyOnLoad(self.gameObject) self:AddLuaBehaviour(self.gameObject) return true end function LoadPlugin(self, name, classType) local plugin = self.plugins[name] if not plugin then plugin = classType.new(name) if plugin then if plugin.transform then plugin.transform.parent = self.transform end plugin:Install() end TRACE("Load plugin %s", name) self.plugins[name] = plugin end return plugin end function QueryPlugin(self, name) return self.plugins[name] end function UnloadPlugin(self, name) local plugin = self.plugins[name] if not plugin then plugin:Uninstall() TRACE("Unload plugin %s", name) -- shutdown the plugin plugin:Shutdown() if plugin.gameObject then GameObject.Destroy(plugin.gameObject) end end self.plugins[name] = nil end function Shutdown(self) for name, plugin in pairs(self.plugins) do self:UnloadPlugin(name) end self.plugins = {} end -- send a plugin event -- @param szPluginName -- @param nID -- @param evtArgs -- @param szObserverName function SendEvent(self, szPluginName, nID, evtArgs, szObserverName) local plugin = self:QueryPlugin(szPluginName) if plugin then plugin:SendEvent(nID, evtArgs, szObserverName) end end -- send a plugin event -- @param nID -- @param evtArgs function FireEvent(self, nID, evtArgs) if _EDITOR then INFO("FireEvent(id=%s) evtArgs(%s)", tostring(nID), tostring(evtArgs)) end for idx, plugin in pairs(self.plugins) do local bResult = plugin:SendEvent(nID, evtArgs) if bResult then break end end end function PostEvent(self, nID, evtArgs) if _EDITOR then INFO("FireEvent(id=%s) evtArgs(%s)", tostring(nID), tostring(evtArgs)) end for idx, plugin in pairs(self.plugins) do plugin:PostEvent(nID, evtArgs) end end
--- Keymap command support. -- -- This module (and associated autoloads) provides support for -- using standard keymap commands such as `:map` and `:nnoremap`. -- However, consider using the `bex.keymap` API instead. -- -- The right-hand side of a mapping may be a Lua callable instead -- of a raw command or expression, in which case it is invoked with no arguments. -- Use `vim.v` to access any parameters. The following trivial example -- prints the count when the key sequence is pressed: -- -- cmd.nnoremap('<buffer>', '<Leader>zzz', function() print(vim.v.count) end) -- Load keymap so we can use its bridge require('bex.keymap') local cmd = require('bex.cmd') local param = require('bex.param') local bridge = require('bex.bridge').keymap local map_cmds = { 'map', 'nmap', 'vmap', 'xmap', 'smap', 'omap', 'map!', 'imap', 'lmap', 'cmap', 'tmap', 'noremap', 'nnoremap', 'vnoremap', 'xnoremap', 'snoremap', 'noremap!', 'inoremap', 'lnoremap', 'tnoremap' } local unmap_cmds = { 'unmap', 'nunmap', 'vunmap', 'xunmap', 'sunmap', 'unmap!', 'ounmap', 'iunmap', 'lunmap', 'cunmap', 'tunmap' } local clear_cmds = { 'mapclear', 'nmapclear', 'vmapclear', 'xmapclear', 'smapclear', 'omapclear', 'mapclear!', 'imapclear', 'lmapclear', 'cmapclear', 'tmapclear' } local function opt(ctx) arg = vim.trim(ctx:pop()) if vim.api.nvim_replace_termcodes(arg, true, true, true) == arg and vim.startswith(arg, '<') and vim.endswith(arg, '>') then ctx:raw(arg) if string.find(arg, '<expr>') then ctx.is_expr = true end return true end ctx:push(arg) end local function rhs(ctx) arg = ctx:pop() if vim.is_callable(arg) then ident = bridge[arg] if ctx.is_expr then ctx:raw('v:lua.' .. ident .. '()') else ctx:raw('<cmd>call v:lua.' .. ident .. '()<cr>') end else ctx:push(arg) while ctx:remaining() > 0 do ctx:raw(ctx:pop()) end end end for _, name in ipairs(map_cmds) do local c = cmd[name] c.params = {param.star(opt), param.raw, rhs} end for _, name in ipairs(unmap_cmds) do local c = cmd[name] c.params = {param.star(opt), param.raw} end for _, name in ipairs(clear_cmds) do local c = cmd[name] c.params = {param.star(opt)} end
--[[ --MIT License -- --Copyright (c) 2019 manilarome --Copyright (c) 2020 Tom Meyers -- --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. ]] -- For those reading this -- This plugin is not designed to be used daily -- Instead it is a proof of concept of what you can do with our plugin system -- It makes your computer laggy for daily use (because a game is constantly running parallel to the rest of your system local wibox = require("wibox") local beautiful = require("beautiful") local dpi = beautiful.xresources.apply_dpi local gears = require("gears") local awful = require("awful") -- list of all "sections" of the snake local parts = {} -- the location of the fruit local fruit = nil -- information about the game area local screen_width = mouse.screen.workarea.width local screen_height = mouse.screen.workarea.height -- player direction offset -- Could be a vector local xoffset = -1 local yoffset = 0 local timer = nil -- size of the player and fruit local size = dpi(20) -- check if a number is 'close' to another number -- eg 7 and 10 have a margin of error of 3 -- 10 and 50 have a margin of error of 40 -- this function returns true when the margin is smaller that <margin> local function margin_of_error(point1, point2, margin) local smaller = 0 local bigger = 0 if point1 == point2 then return true end if point1 < point2 then smaller = point1 bigger = point2 else smaller = point2 bigger = point1 end return smaller + margin >= bigger end -- check if 2 rectangles are intersecting (rectangles of equal size) local function intersecting(source, target) -- target left top point is in the source circle return margin_of_error(source.x, target.x, size) and margin_of_error(source.y, target.y, size) end -- create one "section" of the snake at a specific x and y position -- if head and fruit define the color of the box local function createPart(x, y, head, fruit) local bg = head or fruit or beautiful.accent.hue_800 local box = wibox( { ontop = true, visible = true, x = x, y = y, type = "dock", bg = bg .. "44", border_width = dpi(1), border_color = bg, width = size, height = size, screen = mouse.screen } ) return box end -- append an extra part to the snake local function add_snake_part() -- No parts means we are generating the head (at the center of the screen) if #parts == 0 then local box = createPart( math.floor((screen_width - size) / size) * size * 0.5, math.floor((screen_height - size) / size) * size * 0.5, beautiful.accent.hue_600 ) table.insert(parts, box) else -- find the location of the last element and append it after that position local head = parts[#parts] local x = head.x - (xoffset * size * 1.7) local y = head.y - (yoffset * size * 1.7) local box = createPart(x, y) table.insert(parts, box) end end -- create a fruit (should be called only once) local function create_fruit() fruit = createPart( math.random(size, math.floor((screen_width - size) / size)) * size, math.random(size, math.floor((screen_height - size) / size)) * size, nil, "#FF033E" ) end -- move the fruit to a new position (randomly) local function update_fruit() fruit.x = math.random(size, math.floor((screen_width - size) / size)) * size fruit.y = math.random(size, math.floor((screen_height - size) / size)) * size end -- stop the game -- and free up resources local function stop() print("Stopping snake") if parts ~= nil then for _, widget in ipairs(parts) do widget.visible = false end end if fruit ~= nil then fruit.visible = false end parts = nil fruit = nil if timer ~= nil then timer:stop() end collectgarbage() end -- move the head into a direction -- If we are out of bounds we wrap to the other side -- Much like a torus local function move_head(widget) widget.x = widget.x + (xoffset * size * 1.2) widget.y = widget.y + (yoffset * size * 1.2) if widget.x < 0 then widget.x = screen_width elseif widget.x > screen_width then widget.x = 0 end if widget.y < 0 then widget.y = screen_height elseif widget.y > screen_height then widget.y = 0 end end -- start the game with a head and a tail add_snake_part() add_snake_part() -- init the fruit create_fruit() -- this is our main game loop (10 fps) timer = gears.timer { timeout = 0.1, call_now = true, autostart = true, callback = function() -- in our game loop we move the head and make all the parts follow it for _index, _ in ipairs(parts) do local index = (#parts + 1) - _index if not (index == 1) then local widget = parts[index] local toLoc = parts[index - 1] widget.x = toLoc.x widget.y = toLoc.y end end move_head(parts[1]) -- if the head intersects with the fruit we gain a section and move the fruit to a new position if intersecting(parts[1], fruit) then add_snake_part() update_fruit() end -- TODO: check if the head is intersecting with any other snake section -- If that is the case the snake "crashed" in itself and the game should stop for i, part in ipairs(parts) do if not (i == 1) and intersecting(parts[1], part) then stop() end end end } -- input handling of the game -- For each input (Up, Down, Right, Left) we change the vector to point in the direction we are moving -- This will then be applied in the gameloop local input = awful.keygrabber { -- Note that it is using the key name and not the modifier name. keybindings = { awful.key { modifiers = {}, key = "Up", on_press = function() if yoffset == 1 then return end xoffset = 0 yoffset = -1 end }, awful.key { modifiers = {}, key = "Left", on_press = function() if xoffset == 1 then return end xoffset = -1 yoffset = 0 end }, awful.key { modifiers = {}, key = "Right", on_press = function() if xoffset == -1 then return end xoffset = 1 yoffset = 0 end }, awful.key { modifiers = {}, key = "Down", on_press = function() if yoffset == -1 then return end xoffset = 0 yoffset = 1 end } }, -- Stop the game when we press Escape stop_key = "Escape", stop_event = "release", stop_callback = stop } -- start input handling input:start()
-- Set keep_alive. The return value specifies if this is possible at all. canKeepAlive = mg.keep_alive(true) now = os.date("!%a, %d %b %Y %H:%M:%S") -- First send the http headers mg.write("HTTP/1.1 200 OK\r\n") mg.write("Content-Type: text/html\r\n") mg.write("Date: " .. now .. " GMT\r\n") mg.write("Cache-Control: no-cache\r\n") mg.write("Last-Modified: " .. now .. " GMT\r\n") if not canKeepAlive then mg.write("Connection: close\r\n") mg.write("\r\n") mg.write("<html><body>Keep alive not possible!</body></html>") return end if mg.request_info.http_version ~= "1.1" then -- wget will use HTTP/1.0 and Connection: keep-alive, so chunked transfer is not possible mg.write("Connection: close\r\n") mg.write("\r\n") mg.write("<html><body>Chunked transfer is only possible for HTTP/1.1 requests!</body></html>") mg.keep_alive(false) return end -- use chunked encoding (http://www.jmarshall.com/easy/http/#http1.1c2) mg.write("Cache-Control: max-age=0, must-revalidate\r\n") --mg.write("Cache-Control: no-cache\r\n") --mg.write("Cache-Control: no-store\r\n") mg.write("Connection: keep-alive\r\n") mg.write("Transfer-Encoding: chunked\r\n") mg.write("\r\n") -- function to send a chunk function send(str) local len = string.len(str) mg.write(string.format("%x\r\n", len)) mg.write(str.."\r\n") end -- send the chunks send("<html>") send("<head><title>Civetweb Lua script chunked transfer test page</title></head>") send("<body>\n") fileCnt = 0 if lfs then send("Files in " .. lfs.currentdir()) send('\n<table border="1">\n') send('<tr><th>name</th><th>type</th><th>size</th></tr>\n') for f in lfs.dir(".") do local at = lfs.attributes(f); if at then send('<tr><td>' .. f .. '</td><td>' .. at.mode .. '</td><td>' .. at.size .. '</td></tr>\n') end fileCnt = fileCnt + 1 end send("</table>\n") end send(fileCnt .. " entries (" .. now .. " GMT)\n") send("</body>") send("</html>") -- end send("")
-- Copyright 2017 Xingwang Liao <kuoruan@gmail.com> -- Licensed to the public under the Apache License 2.0. local m, s, o local sid = arg[1] local qos_gargoyle = "qos_gargoyle" m = Map(qos_gargoyle, translate("Edit Upload Service Class")) m.redirect = luci.dispatcher.build_url("admin/network/qos_gargoyle/upload") if m.uci:get(qos_gargoyle, sid) ~= "upload_class" then luci.http.redirect(m.redirect) return end s = m:section(NamedSection, sid, "upload_class") s.anonymous = true s.addremove = false o = s:option(Value, "name", translate("Service Class Name")) o.rmempty = false o = s:option(Value, "percent_bandwidth", translate("Percent Bandwidth At Capacity"), translate("The percentage of the total available bandwidth that should be allocated to this class " .. "when all available bandwidth is being used. If unused bandwidth is available, more can (and " .. "will) be allocated. The percentages can be configured to equal more (or less) than 100, but " .. "when the settings are applied the percentages will be adjusted proportionally so that they " .. "add to 100. This setting only comes into effect when the WAN link is saturated.")) o.datatype = "range(1, 100)" o.rmempty = false o = s:option(Value, "min_bandwidth", translate("Minimum Bandwidth"), translate("The minimum service this class will be allocated when the link is at capacity. Classes " .. "which specify minimum service are known as realtime classes by the active congestion " .. "controller. Streaming video, VoIP and interactive online gaming are all examples of " .. "applications that must have a minimum bandwith to function. To determine what to enter use " .. "the application on an unloaded LAN and observe how much bandwidth it uses. Then enter a " .. "number only slightly higher than this into this field. QoS will satisfiy the minimum service " .. "of all classes first before allocating to other waiting classes so be careful to use minimum " .. "bandwidths sparingly.")) o:value("0", translate("Zero")) o.datatype = "uinteger" o.default = "0" o = s:option(Value, "max_bandwidth", translate("Maximum Bandwidth"), translate("The maximum amount of bandwidth this class will be allocated in kbit/s. Even if unused " .. "bandwidth is available, this service class will never be permitted to use more than this " .. "amount of bandwidth.")) o:value("", translate("Unlimited")) o.datatype = "uinteger" return m
#!/usr/bin/env lua -- MoonFLTK example: clipboard.lua -- -- Derived from the FLTK examples/clipboard.cxx example (http://www.fltk.org) -- fl = require("moonfltk") -- Displays and follows the content of the clipboard with either image or text data function chess(x, y, h, w) -- a box with a chess-like pattern below its image local self = fl.box_sub('flat box', x, y, h, w) self:align(fl.ALIGN_CENTER | fl.ALIGN_CLIP) self:override_draw(function(_) assert(_ == self) self:draw_box() local im = self:image() if im then -- draw the chess pattern below the box centered image local x, y, w, h = self:xywh() local X, Y, W, H = x+(w-im:w())/2, y+(h-im:h())/2, im:w(), im:h() fl.push_clip(X,Y,W,H) fl.push_clip(x,y,w,h) fl.color(fl.WHITE) fl.rectf(X,Y,W,H) fl.color(fl.LIGHT2) local side = 4 local side2 = 2*side for j = Y, Y+H+1, side do for i = X + (j-Y)%side2, X+W+1, side2 do fl.rectf(i,j,side,side) end end fl.pop_clip() fl.pop_clip() end self:draw_label() -- draw the box image end) return self end TAB_COLOR = fl.DARK3 function clipboard_viewer(x, y, w, h) -- use tabs to display as appropriate the image or textual content of the clipboard local self = fl.tabs_sub(x,y,w,h) self:override_handle(function (_, event) if event ~= 'paste' then return self:super_handle(event) end -- print(event, fl.event_clipboard_type()) if fl.event_clipboard_type() == 'image' then -- an image is being pasted local im = fl.event_clipboard() if not im then return true end title = string.format("%dx%d",im:w(), im:h()) -- display the image original size local scale_x = im:w() / image_box:w() -- rescale the image if larger than the display box local scale_y = im:h() / image_box:h() local scale = scale_x if scale_y > scale then scale = scale_y end if scale > 1 then im = im:copy(math.floor(im:w()/scale), math.floor(im:h()/scale)) end local oldim = image_box:image() -- if oldim then delete oldim end @@ fl.unreference()? image_box:image(im) -- show the scaled image image_size:label(title) self:value(image_box:parent()) self:window():redraw() else -- text is being pasted display:buffer():text(fl.event_text()) self:value(display) display:redraw() end return true end) return self end function cb(_, tabs) -- try to find image or text in the clipboard -- print("image?", fl.clipboard_contains('image')) -- print("text/plain?", fl.clipboard_contains('text/plain')) if fl.clipboard_contains('image') then fl.paste(tabs, 'clipboard', 'image') elseif fl.clipboard_contains('text/plain') then fl.paste(tabs, 'clipboard', 'text/plain') end end function clip_callback(source) -- called after clipboard was changed or at application activation if source == 'clipboard' then cb(nil, tabs) end end -- main ---------------------------------- fl.register_images() -- required to allow pasting of images win = fl.window(500, 550, "clipboard viewer") tabs = clipboard_viewer(0, 0, 500, 500) g = fl.group( 5, 30, 490, 460, 'image') -- g will display the image form g:box('flat box') image_box = chess(5, 30, 490, 450) image_size = fl.box('no box', 5, 485, 490, 10) g:done() g:selection_color(TAB_COLOR) buffer = fl.text_buffer() display = fl.text_display(5,30,490, 460, 'text/plain') -- display will display the text form display:buffer(buffer) display:selection_color(TAB_COLOR) tabs:done() tabs:resizable(display) g2 = fl.group( 10,510,200,25) refresh = fl.button(10,510,200,25, "Refresh from clipboard") refresh:callback(cb, tabs) g2:done() g2:resizable(nil) win:done() win:resizable(tabs) win:show(argc,argv) -- will update with new clipboard content immediately or at application activation: fl.add_clipboard_notify(clip_callback) --, tabs) fl.rgb_scaling('bilinear') -- set bilinear image scaling method return fl.run()
-- Copyright (c) 2020 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT return { csv = require "moonpie.ext.csv", ensureKey = require "moonpie.utility.ensure_key", files = require "moonpie.utility.files", function_timer = require "moonpie.utility.function_timer", isCallable = require "moonpie.utility.is_callable", readOnlyTable = require "moonpie.utility.read_only_table", safecall = require "moonpie.utility.safe_call", script_tools = require "moonpie.utility.script_tools", sleep = require "moonpie.utility.sleep", string = require "moonpie.utility.string", swapFunction = require "moonpie.utility.swap_function", tables = require "moonpie.tables", template = require "moonpie.utility.template", timer = require "moonpie.utility.timer", }
local string = { } local metatable = { __tostring = function (self) return string[ self ] end, } local function tokenizer (input) local next = input: gmatch "." local line = 1 local column = 0 local buffer = "" local state = { } function state.initial (char) if char == "\n" or char == "\r" then column = 0 line = line + 1 return state.space (next ( )) elseif char == " " or char == "\t" then column = column + 1 return state.space (next ( )) elseif char == "\"" then column = column + 1 return state.string (next ( )) elseif char == nil then return else column = column + 1 buffer = buffer .. char return state.word (next ( )) end end function state.space (char) if char == "\r" or char == "\n" then column = 0 line = line + 1 return state.space (next ( )) elseif char == " " or char == "\t" then column = column + 1 return state.space (next ( )) elseif char == "\"" then column = column + 1 return state.string (next ( )) elseif char == nil then return else column = column + 1 buffer = buffer .. char return state.word (next ( )) end end function state.string (char) if char == "\\" then column = column + 1 buffer = buffer .. char local char = next ( ) if char == nil then error (("Expected something after [\\] at line <%d>!"): format (line)) else return state.string (next ( )) end elseif char == "\"" then local reference = { } string[ reference ] = buffer setmetatable (reference, metatable) coroutine.yield (reference) column = column + 1 buffer = "" return state.initial (next ( )) elseif char == nil then error (("Missing a [\"] to close ongoing string (at line <%d>)!"): format (line)) else if char == "\n" or char == "\r" then column = 0 line = line + 1 else column = column + 1 end buffer = buffer .. char return state.string (next ( )) end end function state.word (char) if char == "\n" or char == "\r" then coroutine.yield (buffer) line = line + 1 column = 0 buffer = "" return state.space (next ( )) elseif char == " " or char == "\t" then coroutine.yield (buffer) column = column + 1 buffer = "" return state.space (next ( )) elseif char == "\"" then coroutine.yield (buffer) column = column + 1 buffer = "" return state.string (next ( )) elseif char == nil then coroutine.yield (buffer) return else column = column + 1 buffer = buffer .. char return state.word (next ( )) end end return coroutine.wrap (function ( ) return state.initial (next ( )) end) end -- stack object -- local function stack (next) local self = { } local list = { } function self.pop ( ) if #list == 0 then return next ( ) else return table.remove (list, 1) end end function self.push (value) return table.insert (list, 1, value) end function self.swap ( ) local first = self.pop ( ) local second = self.pop ( ) self.push (first) self.push (second) end function self.rot ( ) local first = self.pop ( ) local second = self.pop ( ) local third = self.pop ( ) self.push (second) self.push (first) self.push (third) end function self.over ( ) local first = self.pop ( ) local second = self.pop ( ) self.push (second) self.push (first) self.push (second) end function self.dup ( ) local first = self.pop ( ) self.push (first) self.push (first) end return self end local function functor (interpreter) local export = { } function export.lines (filename) for line in io.lines (filename) do local tokens = stack (tokenizer (line)) interpreter.state.next = tokens.pop interpreter.state.expand = tokens.push interpreter.state.mode.decoder ( ) end end function export.input ( ) local tokens = stack (tokenizer (io.read ( ))) interpreter.state.next = tokens.pop interpreter.state.expand = tokens.push interpreter.state[ "swap-tokens" ] = tokens.swap interpreter.state[ "rot-tokens" ] = tokens.rot interpreter.state[ "over-tokens" ] = tokens.over interpreter.state[ "dup-tokens" ] = tokens.dup interpreter.state.mode.decoder ( ) end function export.string (reference) return string[ reference ] end return export end return functor
function ItemPurchaseThink() end
function StallVehicle() Citizen.CreateThread(function() IsStalling = true local endTime = GetGameTimer() + GetRandomIntInRange(table.unpack(Config.Stalling.StallTime)) local vehicle = CurrentVehicle while GetGameTimer() < endTime and vehicle == CurrentVehicle do SetVehicleCurrentRpm(vehicle, 0.0) Citizen.Wait(0) end IsStalling = false end) end function Damage.process:Stalling(data, deltas, direction) local damage = (deltas.engine or 0.0) + (deltas.body or 0.0) + (deltas.petrol or 0.0) if damage > Config.Stalling.MinDamage and not IsStalling then StallVehicle() end LastDamageTime = GetGameTimer() LastDamageEntity = data.attacker and IsEntityAPed(data.attacker) and IsPedInAnyVehicle(data.attacker) and GetVehiclePedIsIn(data.attacker) or data.attacker end
Locales['en'] = { ['invoices'] = 'invoices', ['received_invoice'] = 'you ~r~received~s~ an invoice', ['paid_invoice'] = 'you ~g~paid~s~ an invoice of ~r~$', ['received_payment'] = 'you ~g~received~s~ a payment of ~r~$', ['player_not_logged'] = 'the player is not logged in', }
local api = vim.api local lsp = require("feline.providers.lsp") local vi_mode_utils = require("feline.providers.vi_mode") local colors = { bg = "#282c34", fg = "#DCD7BA", yellow = "#DCA561", cyan = "#658594", darkblue = "#223249", green = "#98BB6C", orange = "#FFA066", violet = "#957FB8", magenta = "#D27E99", blue = "#7E9CD8", red = "#FF5D62", } local mode_colors = { NORMAL = colors.green, INSERT = colors.red, VISUAL = colors.magenta, OP = colors.green, BLOCK = colors.blue, REPLACE = colors.violet, ["V-REPLACE"] = colors.violet, ENTER = colors.cyan, MORE = colors.cyan, SELECT = colors.orange, COMMAND = colors.orange, SHELL = colors.green, TERM = colors.green, NONE = colors.yellow, } local comps = { vi_mode = { left = { provider = function() return " " .. vi_mode_utils.get_vim_mode() .. " " end, hl = function() return { name = vi_mode_utils.get_mode_highlight_name(), bg = vi_mode_utils.get_mode_color(), fg = colors.bg, } end, right_sep = " ", }, right = { -- provider = '▊', provider = "", hl = function() return { name = vi_mode_utils.get_mode_highlight_name(), fg = vi_mode_utils.get_mode_color(), } end, left_sep = " ", right_sep = " ", }, }, file = { info = { provider = { name = "file_info", opts = { type = "relative-short", file_readonly_icon = "  ", -- file_readonly_icon = '  ', -- file_readonly_icon = '  ', -- file_readonly_icon = '  ', -- file_modified_icon = '', file_modified_icon = "", -- file_modified_icon = 'ﱐ', -- file_modified_icon = '', -- file_modified_icon = '', -- file_modified_icon = '', }, }, hl = { fg = colors.blue, style = "bold", }, }, encoding = { provider = "file_encoding", left_sep = " ", hl = { fg = colors.violet, style = "bold", }, }, type = { provider = "file_type", }, position = { provider = "position", left_sep = " ", hl = { fg = colors.cyan, -- style = 'bold' }, }, }, line_percentage = { provider = "line_percentage", left_sep = " ", hl = { style = "bold", }, }, scroll_bar = { provider = "scroll_bar", left_sep = " ", hl = { fg = colors.blue, style = "bold", }, }, diagnos = { err = { provider = "diagnostic_errors", -- left_sep = ' ', enabled = function() return lsp.diagnostics_exist("Error") end, hl = { fg = colors.red, }, }, warn = { provider = "diagnostic_warnings", -- left_sep = ' ', enabled = function() return lsp.diagnostics_exist("Warn") end, hl = { fg = colors.yellow, }, }, info = { provider = "diagnostic_info", -- left_sep = ' ', enabled = function() return lsp.diagnostics_exist("Info") end, hl = { fg = colors.blue, }, }, hint = { provider = "diagnostic_hints", -- left_sep = ' ', enabled = function() return lsp.diagnostics_exist("Hint") end, hl = { fg = colors.cyan, }, }, }, lsp = { name = { provider = "lsp_client_names", -- left_sep = ' ', right_sep = " ", icon = " ", -- icon = '慎', hl = { fg = colors.yellow, }, }, }, git = { branch = { provider = "git_branch", icon = " ", left_sep = " ", hl = { fg = colors.violet, style = "bold", }, }, add = { provider = "git_diff_added", hl = { fg = colors.green, }, }, change = { provider = "git_diff_changed", hl = { fg = colors.orange, }, }, remove = { provider = "git_diff_removed", hl = { fg = colors.red, }, }, }, } local components = { active = { {}, {}, {} }, inactive = { {}, {}, {} }, } table.insert(components.active[1], comps.vi_mode.left) table.insert(components.active[1], comps.file.info) table.insert(components.active[1], comps.git.branch) table.insert(components.active[1], comps.git.add) table.insert(components.active[1], comps.git.change) table.insert(components.active[1], comps.git.remove) table.insert(components.inactive[1], comps.vi_mode.left) table.insert(components.inactive[1], comps.file.info) table.insert(components.active[2], comps.lsp.name) table.insert(components.active[3], comps.diagnos.err) table.insert(components.active[3], comps.diagnos.warn) table.insert(components.active[3], comps.diagnos.hint) table.insert(components.active[3], comps.diagnos.info) table.insert(components.active[3], comps.file.position) table.insert(components.active[3], comps.line_percentage) table.insert(components.active[3], comps.scroll_bar) table.insert(components.active[3], comps.vi_mode.right) -- TreeSitter -- local ts_utils = require("nvim-treesitter.ts_utils") -- local ts_parsers = require("nvim-treesitter.parsers") -- local ts_queries = require("nvim-treesitter.query") -- table.insert(components.active[2], { -- provider = function() -- local node = require("nvim-treesitter.ts_utils").get_node_at_cursor() -- return ("%d:%s [%d, %d] - [%d, %d]") -- :format(node:symbol(), node:type(), node:range()) -- end, -- enabled = function() -- local ok, ts_parsers = pcall(require, "nvim-treesitter.parsers") -- return ok and ts_parsers.has_parser() -- end -- }) -- require'feline'.setup {} require("feline").setup({ colors = { bg = colors.bg, fg = colors.fg, }, components = components, vi_mode_colors = mode_colors, force_inactive = { filetypes = { "packer", "NvimTree", "fugitive", "fugitiveblame" }, buftypes = { "terminal" }, bufnames = {}, }, }) require("feline").winbar.setup()
--- Pre-defined Node Sound Groups -- -- @topic node_groups sounds.node = { dig = { --- @sndgroup sounds.node.dig.choppy -- @snd[r3] node_dig_choppy -- @see node sounds.node_choppy choppy = iSoundGroup({"node_dig_choppy"}), --- @sndgroup sounds.node.dig.cracky -- @snd[r3] node_dig_cracky -- @see node sounds.node_cracky cracky = iSoundGroup({"node_dig_cracky"}), --- @sndgroup sounds.node.dig.crumbly -- @snd node_dig_crumbly -- @see node sounds.node_crumbly crumbly = iSoundGroup({"node_dig_crumbly"}), --- @sndgroup sounds.node.dig.snappy -- @snd node_dig_snappy -- @see node sounds.node_snappy snappy = iSoundGroup({"node_dig_snappy"}), --- @sndgroup sounds.node.dig.gravel -- @snd[r2] node_dig_gravel -- @see node sounds.node_gravel gravel = iSoundGroup({"node_dig_gravel"}), --- @sndgroup sounds.node.dig.ice -- @snd[r3] node_dig_ice -- @see node sounds.node_ice ice = iSoundGroup({"node_dig_ice"}), --- @sndgroup sounds.node.dig.metal -- @snd node_dig_metal -- @see node sounds.node_metal metal = iSoundGroup({"node_dig_metal"}), }, --- @sndgroup sounds.node.dug -- @snd[r2] node_dug -- @see node sounds.node dug = iSoundGroup({"node_dug", --- @sndgroup sounds.node.dug.glass -- @snd[r3] node_dug_glass -- @see node sounds.node_glass glass = iSoundGroup({"node_dug_glass"}), --- @sndgroup sounds.node.dug.gravel -- @snd[r3] node_dug_gravel gravel = iSoundGroup({"node_dug_gravel"}), --- @sndgroup sounds.node.dug.ice -- @snd node_dug_ice -- @see node sounds.node_ice ice = iSoundGroup({"node_dug_ice"}), --- @sndgroup sounds.node.dug.metal -- @snd[r2] node_dug_metal -- @see node sounds.node_metal metal = iSoundGroup({"node_dug_metal"}), }), --- @sndgroup sounds.node.place -- @snd[r2] node_place -- @see node sounds.node place = iSoundGroup({"node_place", --- @sndgroup sounds.node.place.metal -- @snd[r2] node_dug_metal -- @see node sounds.node_metal metal = iSoundGroup({"node_dug_metal"}), --- @sndgroup sounds.node.place.soft -- @snd[r3] node_place_soft soft = iSoundGroup({"node_place_soft"}), }), step = { --- @sndgroup sounds.node.step.dirt -- @snd[r2] node_step_dirt -- @see node sounds.node_dirt dirt = iSoundGroup({"node_step_dirt"}), --- @sndgroup sounds.node.step.glass -- @snd node_step_glass -- @see node sounds.node_glass glass = iSoundGroup({"node_step_glass"}), --- @sndgroup sounds.node.step.grass -- @snd[r3] node_step_grass -- @see node sounds.node_grass grass = iSoundGroup({"node_step_grass"}), --- @sndgroup sounds.node.step.gravel -- @snd[r4] node_step_gravel -- @see node sounds.node_gravel gravel = iSoundGroup({"node_step_gravel"}), --- @sndgroup sounds.node.step.hard -- @snd[r3] node_step_hard hard = iSoundGroup({"node_step_hard"}), --- @sndgroup sounds.node.step.ice -- @snd[r3] node_step_ice -- @see node sounds.node_ice ice = iSoundGroup({"node_step_ice"}), --- @sndgroup sounds.node.step.metal -- @snd[r3] node_step_metal -- @see node sounds.node_metal metal = iSoundGroup({"node_step_metal"}), --- @sndgroup sounds.node.step.sand -- @snd[r3] node_step_sand -- @see node sounds.node_sand sand = iSoundGroup({"node_step_sand"}), --- @sndgroup sounds.node.step.snow -- @snd[r5] node_step_snow -- @see node sounds.node_snow snow = iSoundGroup({"node_step_snow"}), --- @sndgroup sounds.node.step.water -- @snd[r4] node_step_water (**Note:** node\_step\_water.4 is silent) -- @see node sounds.node_water water = iSoundGroup({"node_step_water"}), --- @sndgroup sounds.node.step.wood -- @snd[r2] node_step_wood -- @see node sounds.node_wood wood = iSoundGroup({"node_step_wood"}), }, }
setenv("VERSION","3.0")
Ext.Require("Server/Modules/FallDamage.lua") Ext.Require("Server/Modules/GBTalents.lua") Ext.Require("Server/Modules/Corrogic.lua") PersistentVars = {} ------ Real Jumps module ------- function ReplaceAllJumps(toggle) if toggle == "on" then print("RealJump module activated") PersistentVars["DGM_RealJump"] = true CharacterLaunchOsirisOnlyIterator("DGM_CharacterReplaceJumpSkills") else print("RealJump module deactivated") PersistentVars["DGM_RealJump"] = false CharacterLaunchOsirisOnlyIterator("DGM_CharacterReplaceJumpSkillsRevert") end end local function GameStartJumpModule(arg1, arg2) if PersistentVars["DGM_RealJump"] == true then ReplaceAllJumps("on") elseif PersistentVars["DGM_RealJump"] == false then ReplaceAllJumps("off") end end local elligibleSkills = { "Jump_PhoenixDive", "Jump_EnemyPhoenixDive", "Jump_TacticalRetreat", "Jump_EnemyTacticalRetreat", "Jump_EnemyTacticalRetreat_Frog", "Jump_IncarnateJump", "Jump_CloakAndDagger", "Jump_EnemyCloakAndDagger" } local function IsElligibleJump(skill) for i,jump in pairs(elligibleSkills) do if skill == jump then return true end end return false end local function CharacterReplaceJumpSkills(character, eventName) if eventName == "DGM_CharacterReplaceJumpSkills" then local character = Ext.GetCharacter(character) if character == nil then return end --print(character) local skills = character.GetSkills(character) for i,skill in pairs(skills) do for j,jump in pairs(elligibleSkills) do if skill == jump then CharacterRemoveSkill(character.MyGuid, skill) local newJump = string.gsub(skill, "Jump_", "Projectile_") CharacterAddSkill(character.MyGuid, newJump) end end end end if eventName == "DGM_CharacterReplaceJumpSkillsRevert" then local character = Ext.GetCharacter(character) if character == nil then return end local skills = character.GetSkills(character) for i,skill in pairs(skills) do for j,jump in pairs(elligibleSkills) do local projectileJump = string.gsub(jump, "Jump_", "Projectile_") if skill == projectileJump then CharacterRemoveSkill(character.MyGuid, skill) local newJump = string.gsub(skill, "Projectile_", "Jump_") CharacterAddSkill(character.MyGuid, newJump) end end end end end Ext.RegisterOsirisListener("StoryEvent", 2, "before", CharacterReplaceJumpSkills) local function CharacterUnlearnJumpSkill(character, skill) for i,jump in pairs(elligibleSkills) do if skill == jump then --print("Jump learned") local character = Ext.GetCharacter(character) if character == nil then return end CharacterRemoveSkill(character.MyGuid, skill) local newJump = string.gsub(skill, "Jump_", "Projectile_") --print(newJump) CharacterAddSkill(character.MyGuid, newJump) end end end local function CharacterHotReplaceJumps(character, x, y, z, skill, skillType, skillElement) if not PersistentVars.DGM_RealJump then return end if skillType ~= "jump" then return end CharacterUnlearnJumpSkill(character, skill) -- Cancel cast for NPCs if not Ext.GetCharacter(character).IsPlayer and IsElligibleJump(skill) then CharacterUseSkill(character, "Shout_LX_CancelCast", character, 0, 1, 1) CharacterAddActionPoints(character, 1) end end Ext.RegisterOsirisListener("CharacterUsedSkillAtPosition", 7, "before", CharacterHotReplaceJumps) local function ReplaceJumpsOnTurn(char) if not PersistentVars.DGM_RealJump then return end if ObjectIsCharacter(char) ~= 1 then return end char = Ext.GetCharacter(char) for i,skill in pairs(char.GetSkills(char)) do CharacterUnlearnJumpSkill(char.MyGuid, skill) end end Ext.RegisterOsirisListener("ObjectTurnStarted", 1, "after", ReplaceJumpsOnTurn) function EnableFallDamage(cmd) if cmd == "on" then print("Fall damage module activated") PersistentVars["DGM_FallDamage"] = true elseif cmd == "off" then print("Fall damage module deactivated") PersistentVars["DGM_FallDamage"] = false end end function EnableJumpDamage(cmd) if cmd == "on" then print("Jump fall damage module activated") PersistentVars["DGM_FallDamage_Jump"] = true elseif cmd == "off" then print("Jump fall damage module deactivated") PersistentVars["DGM_FallDamage_Jump"] = false end end local function DGM_Modules_consoleCmd(cmd, ...) local params = {...} for i=1,10,1 do local par = params[i] if par == nil then break end if type(par) == "string" then par = par:gsub("&", " ") par = par:gsub("\\ ", "&") params[i] = par end end if cmd == "DGM_Module_RealJump" then ReplaceAllJumps(params[1]) end if cmd == "DGM_Module_FallDamage" then EnableFallDamage(params[1]) end if cmd == "DGM_Module_FallDamage_Jump" then EnableJumpDamage(params[1]) end end local function ActivateModule(flag) if flag == "LXDGM_ModuleRealJump" then ReplaceAllJumps("on") elseif flag == "LXDGM_ModuleFallDamageClassic" then EnableFallDamage("on") elseif flag == "LXDGM_ModuleFallDamageAlternate" then EnableJumpDamage("on") elseif flag == "LXDGM_ModuleDualCC" then Ext.ExtraData.DGM_EnableDualCCParry = 1 elseif flag == "LXDGM_ModuleCorrogicDisable" then Ext.ExtraData.DGM_Corrogic = 0 end end Ext.RegisterOsirisListener("GlobalFlagSet", 1, "after", ActivateModule) local function DeactivateModule(flag) if flag == "LXDGM_ModuleRealJump" then ReplaceAllJumps("off") elseif flag == "LXDGM_ModuleFallDamageClassic" then EnableFallDamage("off") elseif flag == "LXDGM_ModuleFallDamageAlternate" then EnableJumpDamage("off") elseif flag == "LXDGM_ModuleDualCC" then Ext.ExtraData.DGM_EnableDualCCParry = 0 elseif flag == "LXDGM_ModuleCorrogicDisable" then Ext.ExtraData.DGM_Corrogic = 1 end end Ext.RegisterOsirisListener("GlobalFlagCleared", 1, "after", DeactivateModule) Ext.RegisterConsoleCommand("DGM_Module_RealJump", DGM_Modules_consoleCmd) Ext.RegisterConsoleCommand("DGM_Module_FallDamage", DGM_Modules_consoleCmd) Ext.RegisterOsirisListener("CharacterLearnedSkill", 2, "before", CharacterUnlearnJumpSkill) Ext.RegisterOsirisListener("GameStarted", 2, "after", GameStartJumpModule)
local mod = DBM:NewMod(2172, "DBM-Party-BfA", 3, 1041) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 18085 $"):sub(12, -3)) mod:SetCreatureID(136160) mod:SetEncounterID(2143) mod:SetZone() mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_CAST_START 268403 268932 268586 269369", "SPELL_CAST_SUCCESS 269231", "UNIT_DIED", "INSTANCE_ENCOUNTER_ENGAGE_UNIT", "UNIT_SPELLCAST_SUCCEEDED boss1" ) --(ability.id = 268932 or ability.id = 268403 or ability.id = 268586) and type = "begincast" --TODO: pull:12.0, 42.3, 19.7, 23.2 (wtf?) local warnGaleSlash = mod:NewSpellAnnounce(268403, 2) local warnQuakingLeap = mod:NewTargetAnnounce(268932, 2) local specWarnQuakingLeap = mod:NewSpecialWarningYou(268932, nil, nil, nil, 1, 2) local yellQuakingLeap = mod:NewYell(268932) local specWarnQuakingLeapNear = mod:NewSpecialWarningClose(268932, nil, nil, nil, 1, 2) local specWarnBladeCombo = mod:NewSpecialWarningDefensive(268586, nil, nil, nil, 1, 2) local specWarnImpalingSpear = mod:NewSpecialWarningDodge(268796, nil, nil, nil, 2, 2) ----ADDS local specWarnHuntingLeap = mod:NewSpecialWarningYou(269231, nil, nil, nil, 1, 2) local yellHuntingLeap = mod:NewYell(269231) local specWarnDeadlyRoar = mod:NewSpecialWarningSpell(269369, nil, nil, nil, 2, 2) --local specWarnGTFO = mod:NewSpecialWarningGTFO(238028, nil, nil, nil, 1, 8) local timerGaleSlashCD = mod:NewCDTimer(13, 268403, nil, nil, nil, 3) local timerQuakingLeapCD = mod:NewCDTimer(19.3, 268932, nil, nil, nil, 3) local timerBladeComboCD = mod:NewCDTimer(14.5, 268586, nil, nil, nil, 5, nil, DBM_CORE_TANK_ICON) --Adds local timerHuntingLeapCD = mod:NewCDTimer(12.8, 269231, nil, nil, nil, 3) local timerDeathlyRoarCD = mod:NewCDTimer(13.6, 269369, nil, nil, nil, 2) --mod:AddRangeFrameOption(5, 194966) local seenMobs = {} --Handles the ICD that Boss triggers on other abilities local function updateAllTimers(self, ICD) DBM:Debug("updateAllTimers running", 3) if timerGaleSlashCD:GetRemaining() < ICD then local elapsed, total = timerGaleSlashCD:GetTime() local extend = ICD - (total-elapsed) DBM:Debug("timerGaleSlashCD extended by: "..extend, 2) timerGaleSlashCD:Stop() timerGaleSlashCD:Update(elapsed, total+extend) end if timerQuakingLeapCD:GetRemaining() < ICD then local elapsed, total = timerQuakingLeapCD:GetTime() local extend = ICD - (total-elapsed) DBM:Debug("timerQuakingLeapCD extended by: "..extend, 2) timerQuakingLeapCD:Stop() timerQuakingLeapCD:Update(elapsed, total+extend) end if timerBladeComboCD:GetRemaining() < ICD then local elapsed, total = timerBladeComboCD:GetTime() local extend = ICD - (total-elapsed) DBM:Debug("timerBladeComboCD extended by: "..extend, 2) timerBladeComboCD:Stop() timerBladeComboCD:Update(elapsed, total+extend) end end function mod:LeapTarget(targetname, uId) if not targetname then return end if targetname == UnitName("player") then specWarnQuakingLeap:Show() specWarnQuakingLeap:Play("targetyou") yellQuakingLeap:Yell() elseif self:CheckNearby(10, targetname) then specWarnQuakingLeapNear:Show(targetname) specWarnQuakingLeapNear:Play("runaway") else warnQuakingLeap:Show(targetname) end end function mod:OnCombatStart(delay) timerGaleSlashCD:Start(8.4-delay) timerQuakingLeapCD:Start(12-delay) timerBladeComboCD:Start(18-delay) end function mod:OnCombatEnd() table.wipe(seenMobs) -- if self.Options.RangeFrame then -- DBM.RangeCheck:Hide() -- end end function mod:SPELL_CAST_START(args) local spellId = args.spellId if spellId == 268403 then warnGaleSlash:Show() timerGaleSlashCD:Start() --updateAllTimers(self, 4.5)--Not confirmed elseif spellId == 268932 then timerQuakingLeapCD:Stop() timerQuakingLeapCD:Start() self:BossTargetScanner(args.sourceGUID, "LeapTarget", 0.05, 12, true)--0.2 seconds faster than emote still updateAllTimers(self, 4.5) elseif spellId == 268586 then if self:IsTanking("player", "boss1", nil, true) and self:AntiSpam(3, 1) then specWarnBladeCombo:Show() specWarnBladeCombo:Play("defensive") end timerBladeComboCD:Stop() timerBladeComboCD:Start() updateAllTimers(self, 5) elseif spellId == 269369 then specWarnDeadlyRoar:Show() specWarnDeadlyRoar:Play("fearsoon") timerDeathlyRoarCD:Start() end end function mod:SPELL_CAST_SUCCESS(args) local spellId = args.spellId if spellId == 269231 then if args:IsPlayer() then specWarnHuntingLeap:Show() specWarnHuntingLeap:Play("runaway") yellHuntingLeap:Yell() end timerHuntingLeapCD:Start() end end function mod:UNIT_DIED(args) local cid = self:GetCIDFromGUID(args.destGUID) if cid == 136984 then--Reban timerHuntingLeapCD:Stop() elseif cid == 136976 then--T'zala timerDeathlyRoarCD:Stop() end end function mod:INSTANCE_ENCOUNTER_ENGAGE_UNIT() for i = 1, 3 do local unitID = "boss"..i local GUID = UnitGUID(unitID) if GUID and not seenMobs[GUID] then seenMobs[GUID] = true local cid = self:GetCIDFromGUID(GUID) if cid == 136984 then--Reban timerHuntingLeapCD:Start(5) elseif cid == 136976 then--T'zala timerDeathlyRoarCD:Start(8) end end end end --[[ function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId) if spellId == 228007 and destGUID == UnitGUID("player") and self:AntiSpam(2, 4) then specWarnGTFO:Show() specWarnGTFO:Play("watchfeet") end end mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE --]] function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, spellId) if spellId == 269377 then--Spokey Pattern Controller specWarnImpalingSpear:Show() specWarnImpalingSpear:Play("watchstep") end end
local weaponsGUI = {} local weaponTable = { [1]=69, [2]=70, [3]=71, [4]=72, [5]=73, [6]=74, [7]=75, [8]=76, [9]=78, [10]=77, [11]=79 } local thewepFont = "Tahoma bold" local theFontSize = 2 theFont = "Tahoma bold" function onResStart () local dxStatus = dxGetStatus() if tonumber(dxStatus['VideoMemoryFreeForMTA']) > 250 then local testFont = guiCreateFont( "tutano_cc_v2.ttf", 0.07*BGWidth ) if testFont then thewepFont = testFont end end end addEventHandler ( "onClientResourceStart", getResourceRootElement(getThisResource()), onResStart ) local sx, sy = guiGetScreenSize() function isCursorHover(posX,posY,sizeX,sizeY) if posX and posY and sizeX and sizeY then if isCursorShowing() then local x,y = getCursorPosition() local x,y = x*sx,y*sy if x>=posX and x<=posX+sizeX and y>=posY and y<=posY+sizeY then return true end else return false end else return false end end function onOpenWeaponsApp ( ) apps[8][7] = true function drawT() local Pistolstats = (getPedStat(localPlayer,69)) if Pistolstats <= 100 then pr,pg,pb = 255,0,0 elseif Pistolstats > 200 and Pistolstats <= 400 then pr,pg,pb = 255,150,0 elseif Pistolstats > 400 and Pistolstats <= 800 then pr,pg,pb = 255,255,0 elseif Pistolstats >= 950 then Pistolstats = 1000 pr,pg,pb = 0,255,0 end local Silencedstats = (getPedStat(localPlayer,70)) if Silencedstats <= 100 then psr,psg,psb = 255,0,0 elseif Silencedstats > 200 and Silencedstats <= 400 then psr,psg,psb = 255,150,0 elseif Silencedstats > 400 and Silencedstats <= 800 then psr,psg,psb = 255,255,0 elseif Silencedstats >= 950 then psr,psg,psb = 0,255,0 end local Deaglestats = (getPedStat(localPlayer,71)) if Deaglestats <= 100 then dr,dg,db = 255,0,0 elseif Deaglestats > 200 and Deaglestats <= 400 then dr,dg,db = 255,150,0 elseif Deaglestats > 400 and Deaglestats <= 800 then dr,dg,db = 255,255,0 elseif Deaglestats >= 950 then dr,dg,db = 0,255,0 end local Shotgunstats = (getPedStat(localPlayer,72)) if Shotgunstats <= 100 then shr,shg,shb = 255,0,0 elseif Shotgunstats > 200 and Shotgunstats <= 400 then shr,shg,shb = 255,150,0 elseif Shotgunstats > 400 and Shotgunstats <= 800 then shr,shg,shb = 255,255,0 elseif Shotgunstats >= 950 then shr,shg,shb = 0,255,0 end local Sawnstats = (getPedStat(localPlayer,73)) if Sawnstats <= 100 then swr,swg,swb = 255,0,0 elseif Sawnstats > 200 and Sawnstats <= 400 then swr,swg,swb = 255,150,0 elseif Sawnstats > 400 and Sawnstats <= 800 then swr,swg,swb = 255,255,0 elseif Sawnstats >= 950 then Sawnstats = 1000 swr,swg,swb = 0,255,0 end local Spasstats = (getPedStat(localPlayer,74)) if Spasstats <= 100 then Spr,Spg,Spb = 255,0,0 elseif Spasstats > 200 and Spasstats <= 400 then Spr,Spg,Spb = 255,150,0 elseif Spasstats > 400 and Spasstats <= 800 then Spr,Spg,Spb = 255,255,0 elseif Spasstats >= 950 then Spr,Spg,Spb = 0,255,0 end local UZIstats = (getPedStat(localPlayer,75)) if UZIstats <= 100 then UZIr,UZIg,UZIb = 255,0,0 elseif UZIstats > 200 and UZIstats <= 400 then UZIr,UZIg,UZIb = 255,150,0 elseif UZIstats > 400 and UZIstats <= 800 then UZIr,UZIg,UZIb = 255,255,0 elseif UZIstats >= 950 then UZIstats = 1000 UZIr,UZIg,UZIb = 0,255,0 end local MP5stats = (getPedStat(localPlayer,76)) if MP5stats <= 100 then MP5r,MP5g,MP5b = 255,0,0 elseif MP5stats > 200 and MP5stats <= 400 then MP5r,MP5g,MP5b = 255,150,0 elseif MP5stats > 400 and MP5stats <= 800 then MP5r,MP5g,MP5b = 255,255,0 elseif MP5stats >= 950 then MP5r,MP5g,MP5b = 0,255,0 end local M4stats = (getPedStat(localPlayer,78)) if M4stats <= 100 then M4r,M4g,M4b = 255,0,0 elseif M4stats > 200 and M4stats <= 400 then M4r,M4g,M4b = 255,150,0 elseif M4stats > 400 and M4stats <= 800 then M4r,M4g,M4b = 255,255,0 elseif M4stats >= 950 then M4r,M4g,M4b = 0,255,0 end local AKstats = (getPedStat(localPlayer,77)) if AKstats <= 100 then AKr,AKg,AKb = 255,0,0 elseif AKstats > 200 and AKstats <= 400 then AKr,AKg,AKb = 255,150,0 elseif AKstats > 400 and AKstats <= 800 then AKr,AKg,AKb = 255,255,0 elseif AKstats >= 950 then AKr,AKg,AKb = 0,255,0 end local Cstats = (getPedStat(localPlayer,79)) if Cstats <= 100 then Cr,Cg,Cb = 255,0,0 elseif Cstats > 200 and Cstats <= 400 then Cr,Cg,Cb = 255,150,0 elseif Cstats > 400 and Cstats <= 800 then Cr,Cg,Cb = 255,255,0 elseif Cstats >= 950 then Cr,Cg,Cb = 0,255,0 end weaponsGUI[31] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.02*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[32] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.10*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[33] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.18*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[34] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.26*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[35] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.34*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[36] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.42*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[37] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.50*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[38] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.58*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[39] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.66*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[40] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.74*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[41] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.82*BGHeight), 1*BGWidth, 0.060*BGHeight, tocolor(0,0,0, 100), true,true) weaponsGUI[1] = dxDrawRectangle(BGX+(0.0*BGWidth),BGY+(0.02*BGHeight), (Pistolstats/1000)*BGWidth, 0.060*BGHeight, tocolor(pr,pg,pb, 178), true,true) weaponsGUI[2] = dxDrawRectangle( BGX+(0.0*BGWidth),BGY+(0.10*BGHeight), (Silencedstats/1000)*BGWidth, 0.060*BGHeight, tocolor(psr,psg,psb, 178), true,true) weaponsGUI[3] = dxDrawRectangle( BGX+(0.0*BGWidth),BGY+(0.18*BGHeight), (Deaglestats/1000)*BGWidth, 0.060*BGHeight, tocolor(dr,dg,db, 178), true,true) weaponsGUI[4] = dxDrawRectangle( BGX+(0.0*BGWidth),BGY+(0.26*BGHeight), (Shotgunstats/1000)*BGWidth, 0.060*BGHeight, tocolor(shr,shg,shb, 178), true,true) weaponsGUI[5] = dxDrawRectangle( BGX+(0.0*BGWidth),BGY+(0.34*BGHeight), (Sawnstats/1000)*BGWidth, 0.060*BGHeight, tocolor(swr,swg,swb, 178), true,true) weaponsGUI[6] = dxDrawRectangle( BGX+(0.0*BGWidth),BGY+(0.42*BGHeight), (Spasstats/1000)*BGWidth, 0.060*BGHeight, tocolor(Spr,Spg,Spb, 178), true,true) weaponsGUI[7] = dxDrawRectangle( BGX+(0.0*BGWidth),BGY+(0.50*BGHeight), (UZIstats/1000)*BGWidth, 0.060*BGHeight, tocolor(UZIr,UZIg,UZIb, 178), true,true) weaponsGUI[8] = dxDrawRectangle( BGX+(0.0*BGWidth),BGY+(0.58*BGHeight), (MP5stats/1000)*BGWidth, 0.060*BGHeight, tocolor(MP5r,MP5g,MP5b, 178), true,true) weaponsGUI[9] = dxDrawRectangle( BGX+(0.0*BGWidth),BGY+(0.66*BGHeight), (M4stats/1000)*BGWidth, 0.060*BGHeight, tocolor(M4r,M4g,M4b, 178), true,true) weaponsGUI[10] = dxDrawRectangle( BGX+(0.0*BGWidth),BGY+(0.74*BGHeight), (AKstats/1000)*BGWidth, 0.060*BGHeight, tocolor(AKr,AKg,AKb, 178), true,true) weaponsGUI[11] = dxDrawRectangle( BGX+(0.0*BGWidth),BGY+(0.82*BGHeight), (Cstats/1000)*BGWidth, 0.060*BGHeight, tocolor(Cr,Cg,Cb, 178), true,true) local pistol = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.02*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local silenced = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.10*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local deagle = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.18*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local Shotgun = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.26*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local sawnoff = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.34*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local spas = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.42*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local UZI = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.50*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local MP5 = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.58*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local M4 = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.66*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local AK = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.74*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local sniper = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.82*BGHeight), 0.90*BGWidth, 0.060*BGHeight) local note = isCursorHover(BGX+(0.05*BGWidth),BGY+(0.85*BGHeight), 0.90*BGWidth, 0.20*BGHeight) if pistol and weaponsGUI[12] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "Pistol skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif silenced and weaponsGUI[13] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "Silenced skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif deagle and weaponsGUI[14] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "Deagle skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif Shotgun and weaponsGUI[15] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "Shotgun skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif sawnoff and weaponsGUI[16] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "Sawn-off skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif spas and weaponsGUI[17] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "Spas-12 skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif UZI and weaponsGUI[18] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "UZI & Tec-9 skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif MP5 and weaponsGUI[19] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "MP5 skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif M4 and weaponsGUI[20] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "M4 Rifle skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif AK and weaponsGUI[21] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "AK-47 Rifle skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif sniper and weaponsGUI[22] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "Sniper Rifle skills", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-0.3, theFont, "center", "center", false,false,true ) elseif note and weaponsGUI[23] then local x,y = getCursorPosition() local x,y = x*sx,y*sy dxDrawText ( "Only Pistol,Tec-9 and Uzi are dual guns.", x*2,y*2-40, 0.20*BGWidth, 0.060*BGHeight, tocolor ( 255, 255, 255, 255 ), theFontSize-1, theFont, "center", "center", false,true,true ) end end addEventHandler("onClientRender",root,drawT) weaponsGUI[12] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.02*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "Pistol", false, nil ) weaponsGUI[13] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.10*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "Silenced Pistol", false, nil ) weaponsGUI[14] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.18*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "Desert Eagle", false, nil ) weaponsGUI[15] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.26*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "Shotgun", false, nil ) weaponsGUI[16] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.34*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "Sawn-Off Shotgun", false, nil ) weaponsGUI[17] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.42*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "Spas-12", false, nil ) weaponsGUI[18] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.50*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "Uzi / TEC-9", false, nil ) weaponsGUI[19] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.58*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "MP5", false, nil ) weaponsGUI[20] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.66*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "M4", false, nil ) weaponsGUI[21] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.74*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "AK-47", false, nil ) weaponsGUI[22] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.82*BGHeight), 0.90*BGWidth, 0.060*BGHeight, "Country Rifle / Sniper", false, nil ) weaponsGUI[23] = guiCreateLabel( BGX+(0.05*BGWidth),BGY+(0.85*BGHeight), 0.90*BGWidth, 0.20*BGHeight, "", false, nil ) for i=12,23 do guiSetProperty( weaponsGUI[i], "AlwaysOnTop", "True" ) guiSetVisible( weaponsGUI[i],true ) guiBringToFront( weaponsGUI[i] ) guiLabelSetColor ( weaponsGUI[i], 255, 255, 255 ) guiLabelSetHorizontalAlign ( weaponsGUI[i], "center" ) guiLabelSetVerticalAlign ( weaponsGUI[i], "center" ) guiSetFont ( weaponsGUI[i], thewepFont ) end end apps[8][8] = onOpenWeaponsApp function onCloseWeaponsApp () for i=12,23 do guiSetProperty( weaponsGUI[i], "AlwaysOnTop", "True" ) guiSetVisible(weaponsGUI[i],false) end removeEventHandler("onClientRender",root,drawT) apps[8][7] = false end apps[8][9] = onCloseWeaponsApp
nested = require 'nested' local nested_function = require 'nested.function' local nested_ordered = require 'nested.ordered' a = { 1, { segundo = 2 }, 3, b = 'B' } callable = setmetatable({}, { __call = function(self, ...) print('CALLABLE', ...) end }) local _ENV = _ENV or getfenv() _ENV['function'] = function(arguments, body) if not body then body, arguments = arguments, nil end return function(...) local env = _ENV or getfenv() if arguments then env = setmetatable({}, { __index = _ENV or getfenv() }) for i = 1, #arguments do env[arguments[i]] = select(i, ...) end end if type(body) == 'string' then local chunk = assert(load(body, nil, 't', env)) return chunk(...) else return nested_function.evaluate_with_env(body, env) end end end local t = assert(nested.decode([=[ f: [function [x y] ` print(string.format('%d + %d = %d', x, y, x + y)) `] f2: [function `print 'just print'`] self.doidera.demais: 5 [print olars a.1 a.2.segundo a a.b] [print a.b.c outro: 1] [f 1 5 9] [f2 ignored but evaluated args] [[function [print 'evaluate now']]] [callable tables work too] ]=], nested.bool_number_filter, nested_ordered.new)) print(nested.encode(nested_function.evaluate(t)))
local awss3auth = require "resty.s3_auth" local cjson = require "cjson" local xml = require "resty.s3_xml" local util = require "resty.s3_util" local tb = require "resty.iresty_test" local test = tb.new({unit_name="amazon_s3_test"}) local AWSAccessKeyId='THE_ACCESS_KEY_ID' local AWSSecretAccessKey="THE_SECRET_ACCESS_KEY" local aws_bucket = "test" local aws_region = "us-east-1" local aws4_testsuite_dir = "/root/work/lua-resty-s3/test/aws4_testsuite" local debug_file = false local aws4_debugfile_dir = "/root/work/lua-resty-s3/test/aws4_debug" local function datetime_cb() local date = "20110909" local time = "233600" local datetime = date .. "T" .. time .. "Z" return date, time, datetime end function tb:init() self.s3_auth = awss3auth:new(AWSAccessKeyId, AWSSecretAccessKey, aws_bucket, aws_region) end -------------------------------------------------------- -------------------------------------------------------- function split(s, delimiter) local result = {}; for match in string.gmatch(s, "[^"..delimiter.."]+") do table.insert(result, match); end return result; end function split_line(s) local delimiter = "\n" local result = {}; for match in string.gmatch(s, "[^"..delimiter.."]*" .. delimiter) do match = string.sub(match, 1, #match-1) table.insert(result, match); if match == "" then local idx = string.find(s, delimiter .. delimiter) if idx then local body = string.sub(s, idx + 2) table.insert(result, body) end break end end return result; end function trim (s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local function parse_req_line(req_line) local space_idx = string.find(req_line, " ") if not space_idx then return false end local method = string.sub(req_line, 1, space_idx-1) local last_space_pos = req_line:reverse():find(" ") last_space_pos = #req_line - last_space_pos + 1 local url = string.sub(req_line, space_idx+1, last_space_pos-1) local http_ver = string.sub(req_line, last_space_pos+1) return true, method, url, http_ver end local function parse_req(req) local arr = split_line(req) local req_line = arr[1] --[[ local req_line = split(arr[1], " ") if #req_line ~= 3 then error("req_line [" .. arr[1] .. "] invalid ") end local method = req_line[1] local url = req_line[2] local http_ver = req_line[3] ]] local ok, method, url, http_ver = parse_req_line(req_line) if not ok then error("req_line [" .. req_line .. "] invalid ") end local headers = util.new_headers() local body_idx = 2 for i, head in ipairs(arr) do if i >= 2 then if head == "" or head == nil then body_idx = i + 1 break end local idx = string.find(head, ":") if idx == nil then ngx.log(ngx.ERR, "----invalid HEAD:", head) else local key = string.lower(string.sub(head, 1, idx-1)) local value = trim(string.sub(head, idx+1)) if headers[key] == nil then headers[key] = value else local old_value = headers[key] local values = nil if type(old_value) == 'table' then values = old_value else values = {old_value} end table.insert(values, value) headers[key] = values end end end end local body = nil if body_idx > #arr then body = "" else local body_lines = {} for i = body_idx, #arr do table.insert(body_lines, arr[i]) end body = table.concat(body_lines, "\n") end return {method=method, url=url, headers=headers, body=body} end -------------------------------------------- function file_read(filename) local file = io.open(filename, "r") if file == nil then return false, "not-exist" end local content = file:read("*a") file:close() return true, content end local function file_write(filename, content) local file = io.open(filename, "w") if file == nil then return false, "not-exist" end local content = file:write(content) file:close() return true end local function write_debug_file(filename, content) if not debug_file then return end local fullfilename = aws4_debugfile_dir .. "/" .. filename file_write(fullfilename, content) end function tb:_s3_auth_v4_test(data, filename) local req_str = data.req local req = parse_req(req_str) local auth, sign, extinfo = self.s3_auth:authorization_v4_4test(req.method, req.url, req.headers, req.body) if extinfo.request == data.creq then self.log(filename .. " creq OK") else write_debug_file(filename .. ".creq", extinfo.request) error(filename .. " creq error! cale creq [\n" .. extinfo.request .. "\n] ok creq [\n" .. data.creq .. "\n]") end if extinfo.string_to_sign == data.sts then self.log("sts OK") else write_debug_file(filename .. ".sts", extinfo.string_to_sign) error(filename .. " sts error! cale sts [\n" .. extinfo.string_to_sign .. "\n] ok sts [\n" .. data.sts .. "\n]") end if extinfo.authorization == data.authz then self.log("authz OK") else write_debug_file(filename .. ".authz", extinfo.authorization) error(filename .. " sts error! cale authz [\n" .. extinfo.authorization .. "\n] ok authz [\n" .. data.authz .. "\n]") end end function read_data(filename) local suffixs = {"req", "creq", "sts", "authz", "sreq"} local data = {} for _, suffix in ipairs(suffixs) do local fullfilename = filename .. "." .. suffix local ok, content = file_read(fullfilename) if not ok then error("file [" .. fullfilename .. "] not exist!") return ok, content end content = string.gsub(content, "\r\n", "\n") data[suffix] = content --ngx.log(ngx.INFO, "-----", suffix, ">>>>", content) end return true, data end function tb:_file_test(filename) local dir = aws4_testsuite_dir local fullfilename = dir .. "/" .. filename local ok, data = read_data(fullfilename) if not ok then error("file test [" .. filename .."] failed! err:" .. data) return end self:_s3_auth_v4_test(data, filename) self:log("test [" .. filename .."] OK") end ---- shell 生成的代码。 --[[ cd aws4_testsuite && find . | grep -v "txt" | awk -F[/\.] '{print $3}' | uniq |awk ' {fn=$1;gsub(/-/,"_",$1); printf("function tb:test_%s()\n self:_file_test(\"%s\")\nend\n\n", $1, fn);}' ]] function tb:test_get_header_key_duplicate() self:_file_test("get-header-key-duplicate") end function tb:test_get_header_value_order() self:_file_test("get-header-value-order") end function tb:test_get_header_value_trim() self:_file_test("get-header-value-trim") end function tb:test_get_relative_relative() self:_file_test("get-relative-relative") end function tb:test_get_relative() self:_file_test("get-relative") end function tb:test_get_slash_dot_slash() self:_file_test("get-slash-dot-slash") end function tb:test_get_slash_pointless_dot() self:_file_test("get-slash-pointless-dot") end function tb:test_get_slash() self:_file_test("get-slash") end function tb:test_get_slashes() self:_file_test("get-slashes") end function tb:test_get_space() self:_file_test("get-space") end function tb:test_get_unreserved() self:_file_test("get-unreserved") end function tb:test_get_utf8() self:_file_test("get-utf8") end function tb:test_get_vanilla_empty_query_key() self:_file_test("get-vanilla-empty-query-key") end function tb:test_get_vanilla_query_order_key_case() self:_file_test("get-vanilla-query-order-key-case") end function tb:test_get_vanilla_query_order_key() self:_file_test("get-vanilla-query-order-key") end function tb:test_get_vanilla_query_order_value() self:_file_test("get-vanilla-query-order-value") end function tb:test_get_vanilla_query_unreserved() self:_file_test("get-vanilla-query-unreserved") end function tb:test_get_vanilla_query() self:_file_test("get-vanilla-query") end function tb:test_get_vanilla_ut8_query() self:_file_test("get-vanilla-ut8-query") end function tb:test_get_vanilla() self:_file_test("get-vanilla") end function tb:test_post_header_key_case() self:_file_test("post-header-key-case") end function tb:test_post_header_key_sort() self:_file_test("post-header-key-sort") end function tb:test_post_header_value_case() self:_file_test("post-header-value-case") end function tb:test_post_vanilla_empty_query_value() self:_file_test("post-vanilla-empty-query-value") end --[[ function tb:test_post_vanilla_query_nonunreserved() self:_file_test("post-vanilla-query-nonunreserved") end function tb:test_post_vanilla_query_space() self:_file_test("post-vanilla-query-space") end ]] function tb:test_post_vanilla_query() self:_file_test("post-vanilla-query") end function tb:test_post_vanilla() self:_file_test("post-vanilla") end function tb:test_post_x_www_form_urlencoded_parameters() self:_file_test("post-x-www-form-urlencoded-parameters") end function tb:test_post_x_www_form_urlencoded() self:_file_test("post-x-www-form-urlencoded") end -- units test test:run() -- bench units test -- test:bench_run()
local itsOn = false -- chart preview state local stepsdisplayx = SCREEN_WIDTH * 0.56 - 54 local thesteps = nil local rowwidth = 60 local rowheight = 17 local cursorwidth = 6 local cursorheight = 17 local numshown = 7 local currentindex = 1 local displayindexoffset = 0 local sd = Def.ActorFrame { Name = "StepsDisplay", InitCommand = function(self) self:xy(stepsdisplayx, 68):valign(0) end, OffCommand = function(self) self:visible(false) end, OnCommand = function(self) self:visible(true) end, TabChangedMessageCommand = function(self, params) self:finishtweening() if getTabIndex() < 3 and GAMESTATE:GetCurrentSong() then -- dont display this if the score nested tab is already online -- prevents repeat 3 presses to break the display -- (let page 2 handle this specifically) if params.to == 2 then return end self:playcommand("On") self:playcommand("UpdateStepsRows") else self:playcommand("Off") end end, CurrentSongChangedMessageCommand = function(self, song) local song = song.ptr if song then thesteps = song:GetChartsMatchingFilter() -- if in online scores tab it still pops up for 1 frame -- so the bug fixed in the above command makes a return -- how sad if getTabIndex() < 3 then self:playcommand("On") end self:playcommand("UpdateStepsRows") else self:playcommand("Off") end end, DelayedChartUpdateMessageCommand = function(self) local leaderboardEnabled = playerConfig:get_data(pn_to_profile_slot(PLAYER_1)).leaderboardEnabled and DLMAN:IsLoggedIn() if leaderboardEnabled and GAMESTATE:GetCurrentSteps() then local chartkey = GAMESTATE:GetCurrentSteps():GetChartKey() if SCREENMAN:GetTopScreen():GetMusicWheel():IsSettled() then DLMAN:RequestChartLeaderBoardFromOnline( chartkey, function(leaderboard) end ) end end end, ChartPreviewOnMessageCommand = function(self) if not itsOn then self:addx(capWideScale(12, 0)):addy(capWideScale(18, 0)) itsOn = true end end, ChartPreviewOffMessageCommand = function(self) if itsOn then self:addx(capWideScale(-12, 0)):addy(capWideScale(-18, 0)) itsOn = false end end, CalcInfoOnMessageCommand = function(self) self:x(20) end, CalcInfoOffMessageCommand = function(self) self:x(stepsdisplayx) end } local function stepsRows(i) local o = Def.ActorFrame { InitCommand = function(self) self:y(rowheight * (i - 1)) end, UIElements.QuadButton(1, 1) .. { InitCommand = function(self) self:zoomto(rowwidth, rowheight):halign(0) end, UpdateStepsRowsCommand = function(self) local steps = thesteps[i + displayindexoffset] if steps then self:visible(true) local diff = steps:GetDifficulty() self:diffuse(getDifficultyColor(diff)) self:diffusealpha(0.4) else self:visible(false) end end, MouseDownCommand = function(self, params) local steps = thesteps[i + displayindexoffset] if steps and params.event == "DeviceButton_left mouse button" then SCREENMAN:GetTopScreen():ChangeSteps(i - currentindex) SCREENMAN:GetTopScreen():ChangeSteps(0) end end }, Def.Quad { InitCommand = function(self) self:zoomto(24, rowheight):halign(0) end, UpdateStepsRowsCommand = function(self) local steps = thesteps[i + displayindexoffset] if steps then self:visible(true) local diff = steps:GetDifficulty() self:diffuse(byDifficulty(diff)) else self:visible(false) end end }, -- Chart defined "Meter" value, not msd (useful to have this for reference) LoadFont("Common Large") .. { InitCommand = function(self) self:x(rowwidth - cursorwidth - 2):addy(-1):zoom(0.35):settext(""):halign(1):maxwidth(75) end, UpdateStepsRowsCommand = function(self) local steps = thesteps[i + displayindexoffset] if steps then self:settext(steps:GetMeter()) else self:settext("") end end }, --chart difficulty name LoadFont("Common Large") .. { InitCommand = function(self) self:x(12):zoom(0.18):settext(""):halign(0.5):valign(0) end, UpdateStepsRowsCommand = function(self) local steps = thesteps[i + displayindexoffset] if steps then local diff = steps:GetDifficulty() self:settext(getShortDifficulty(diff)) else self:settext("") end end }, --chart steps type LoadFont("Common Large") .. { InitCommand = function(self) self:x(12):addy(-9):zoom(0.18):settext(""):halign(0.5):valign(0):maxwidth(23 / 0.18) end, UpdateStepsRowsCommand = function(self) local steps = thesteps[i + displayindexoffset] if steps then local st = THEME:GetString("StepsDisplay StepsType", ToEnumShortString(steps:GetStepsType())) self:settext(st) else self:settext("") end end } } return o end local sdr = Def.ActorFrame { Name = "StepsRows", } for i = 1, numshown do sdr[#sdr + 1] = stepsRows(i) end sd[#sd + 1] = sdr local center = math.ceil(numshown / 2) -- cursor goes on top sd[#sd + 1] = Def.Quad { Name = "StepsCursor", InitCommand = function(self) self:x(rowwidth):zoomto(cursorwidth, cursorheight):halign(1):valign(0.5):diffusealpha(0.6) end, CurrentStepsChangedMessageCommand = function(self, steps) for i = 1, 20 do if thesteps and thesteps[i] and thesteps[i] == steps.ptr then currentindex = i break end end if currentindex <= center then displayindexoffset = 0 elseif #thesteps - displayindexoffset > numshown then displayindexoffset = currentindex - center currentindex = center else currentindex = currentindex - displayindexoffset end if #thesteps > numshown and #thesteps - displayindexoffset < numshown then displayindexoffset = #thesteps - numshown end self:finishtweening() self:smooth(0.03):y(cursorheight * (currentindex - 1)) if self:GetParent():GetVisible() then self:GetParent():GetChild("StepsRows"):playcommand("UpdateStepsRows") end end } return sd
SB.Include(Path.Join(SB.DIRS.SRC, 'view/editor.lua')) ObjectPropertyWindow = Editor:extends{} ObjectPropertyWindow:Register({ name = "objectPropertyWindow", tab = "Objects", caption = "Properties", tooltip = "Edit object properties", image = Path.Join(SB.DIRS.IMG, 'anatomy.png'), order = 2, no_serialize = true, }) function ObjectPropertyWindow:_GetValue(name) return self.bridge.s11n:Get(self.objectID, name) end function ObjectPropertyWindow:AddPosField() self:AddControl("pos-sep", { Label:New { caption = "Position", }, Line:New { x = 50, width = self.VALUE_POS, } }) self:AddField(GroupField({ NumericField({ name = "posx", title = "X:", tooltip = "Position (x)", value = 1, minValue = 0, maxValue = Game.mapSizeX, step = 1, width = 100, decimals = 0, }), NumericField({ name = "posy", title = "Y:", tooltip = "Position (y)", value = 0, step = 1, width = 100, decimals = 0, }), NumericField({ name = "posz", title = "Z:", tooltip = "Position (z)", value = 1, minValue = 0, maxValue = Game.mapSizeZ, step = 1, width = 100, decimals = 0, }), BooleanField({ name = "stickToGround", title = "S", tooltip = "Stick to ground", width = 50, value = true, }), BooleanField({ name = "avgPos", title = "G", tooltip = "Alter the position of the object selection as a group.", width = 50, value = self.__avgPosValue, }), })) end function ObjectPropertyWindow:AddAngleField() self:AddControl("rot-sep", { Label:New { caption = "Angle", }, Line:New { x = 50, width = self.VALUE_POS, } }) self:AddField(GroupField({ NumericField({ name = "rotx", title = "X:", tooltip = "Angle (x)", value = 0, step = 0.2, width = 100, }), NumericField({ name = "roty", title = "Y:", tooltip = "Angle (y)", value = 0, step = 0.2, width = 100, }), NumericField({ name = "rotz", title = "Z:", tooltip = "Angle (z)", value = 0, step = 0.2, width = 100, }), Field({ name = "btn-align-ground", width = 150, components = { Button:New { caption = "Align", x = 0, width = 135, height = 30, tooltip = "Align to heightmap", OnClick = { function() local selection = SB.view.selectionManager:GetSelection() local objectID, bridge if #selection.unit > 0 then objectID = selection.unit[1] bridge = unitBridge elseif #selection.feature > 0 then objectID = selection.feature[1] bridge = featureBridge end local x, z = self.fields["posx"].value, self.fields["posz"].value local dirX, dirY, dirZ = Spring.GetGroundNormal(x, z) local frontDir = bridge.s11n:Get(objectID, "dir") local upDir = {x=dirX, y=dirY, z=dirZ} local rightDir = CrossProduct(frontDir, upDir) frontDir = CrossProduct(upDir, rightDir) self:OnFieldChange("dir", frontDir) --self:OnFieldChange("dir", {x=1, y=0, z=0}) end } }, } }) })) end function ObjectPropertyWindow:AddStateField() self:AddControl("state-sep", { Label:New { caption = "State", }, Line:New { x = 50, width = self.VALUE_POS, } }) self:AddField(GroupField({ ChoiceField({ name = "fireState", tooltip = "Fire state", items = {0, 1, 2}, captions = {"Hold fire", "Return fire", "Fire at will"}, width = 100, }), ChoiceField({ name = "moveState", tooltip = "Move state", items = {0, 1, 2}, captions = {"Hold pos", "Maneuver", "Roam"}, width = 100, }), BooleanField({ name = "active", title = "Active", tooltip = "Active/passive unit", width = 100, }), BooleanField({ name = "repeat", title = "Repeat", tooltip = "Should the unit repeat orders", width = 100, }), })) self:AddField(GroupField({ BooleanField({ name = "cloak", title = "Cloak", tooltip = "Cloak state", width = 100, }), BooleanField({ name = "trajectory", title = "Trajectory", tooltip = "Shoot using a trajectory", width = 100, }), BooleanField({ name = "autoRepairLevel", title = "Auto repair", tooltip = "Auto repair level", width = 100, }), BooleanField({ name = "loopbackAttack", title = "Loopback", tooltip = "Loopback attack", width = 100, }), })) self:AddField(BooleanField({ name = "autoLand", title = "Auto land", tooltip = "Auto land", width = 100, })) end function ObjectPropertyWindow:AddTeamField() local teamIDs = Table.GetField(SB.model.teamManager:getAllTeams(), "id") for i = 1, #teamIDs do teamIDs[i] = tostring(teamIDs[i]) end local teamCaptions = Table.GetField(SB.model.teamManager:getAllTeams(), "name") self:AddField(ChoiceField({ name = "team", items = teamIDs, captions = teamCaptions, title = "Team: ", })) end function ObjectPropertyWindow:AddS11NField(name, value, s11nField) local humanName = s11nField.humanName if not humanName then humanName = String.Capitalize(name) end local dtype = type(value) if name == "pos" then self:AddPosField() elseif name == "rot" then self:AddAngleField() elseif name == "states" then self:AddStateField() elseif name == "team" then self:AddTeamField() else if dtype == "number" then self:AddField(NumericField({ name = name, title = String.Capitalize(name) .. ":", minValue = s11nField.minValue, maxValue = s11nField.maxValue, value = self:_GetValue(name), -- step = 1, })) elseif dtype == "string" then self:AddField(StringField({ name = name, title = String.Capitalize(name) .. ":", value = self:_GetValue(name), })) elseif dtype == "boolean" then self:AddField(BooleanField({ name = name, title = String.Capitalize(name) .. ":", value = self:_GetValue(name), })) elseif dtype == "table" then self:AddControl(name .. "-sep", { Label:New { caption = humanName, }, Line:New { x = 50, width = self.VALUE_POS, } }) local tkeys = Table.GetKeys(value) table.sort(tkeys) local fields = {} local count = 0 for _, tkey in pairs(tkeys) do tkey = tostring(tkey) local opts = { name = name .. tkey, title = String.Capitalize(tkey) .. ":", tooltip = humanName .. " (" .. tkey .. ")", value = value[tkey], width = 140, } local elType = type(opts.value) local field if elType == "number" then field = NumericField(opts) elseif elType == "string" then field = StringField(opts) elseif elType == "boolean" then field = BooleanField(opts) end self.__keys[name .. tkey] = name table.insert(fields, field) count = count + 1 if count == 3 then count = 0 self:AddField(GroupField(fields)) fields = {} end end if count > 0 then self:AddField(GroupField(fields)) end else Spring.Echo("unknown type") Spring.Echo(name, dtype) end end end function ObjectPropertyWindow:AddObjectFields(bridge, objectID) self.__keys = {} local objectValues = bridge.s11n:Get(objectID) for _, k in pairs(bridge.s11nFieldOrder) do local v = objectValues[k] if not Table.Contains(bridge.blockedFields, k) and v then local s11nField = bridge.s11n.funcs[k] self:AddS11NField(k, v, s11nField) end end for k, v in pairs(objectValues) do if not Table.Contains(bridge.blockedFields, k) and not Table.Contains(bridge.s11nFieldOrder or {}, k) then local s11nField = bridge.s11n.funcs[k] self:AddS11NField(k, v, s11nField) end end self.rules = {} if bridge == unitBridge or bridge == featureBridge then self:AddObjectRules(objectID, bridge) end end function ObjectPropertyWindow:init() self:super("init") self.__avgPosValue = true local children = {} table.insert(children, ScrollPanel:New { x = 0, y = "0%", bottom = 30, right = 0, borderColor = {0,0,0,0}, horizontalScrollbar = false, children = { self.stackPanel }, } ) self:Finalize(children) SB.view.selectionManager:addListener(self) self:OnSelectionChanged() SB.commandManager:addListener(self) end function CrossProduct(u, v) return {x = u.y * v.z - u.z * v.x, y = u.z * v.x - u.x * v.z, z = u.x * v.y - u.y * v.x} end function ObjectPropertyWindow:OnCommandExecuted() if not self._startedChanging then self.selectionChanging = true if self.__fullRefresh then self:OnSelectionChanged() self.__fullRefresh = true end self:__UpdateFields() self.selectionChanging = false end end function ObjectPropertyWindow:OnStartChange(name) SB.commandManager:execute(SetMultipleCommandModeCommand(true)) end function ObjectPropertyWindow:OnEndChange(name) SB.commandManager:execute(SetMultipleCommandModeCommand(false)) end NewRuleDialog = Editor:extends{} function NewRuleDialog:init(objectPropertyWindow) self:super("init") self.objectPropertyWindow = objectPropertyWindow self:AddField(GroupField({ StringField({ name = "ruleName", title = "Name:", width = 140, }), ChoiceField({ name = "ruleType", title = "Type:", width = 200, items = {"String", "Number"} }) })) local children = { ScrollPanel:New { x = 0, y = 0, bottom = 30, right = 0, borderColor = {0,0,0,0}, horizontalScrollbar = false, children = { self.stackPanel }, }, } self:Finalize(children, { notMainWindow = true, buttons = { "ok", "cancel" }, width = 400, height = 120, }) end function NewRuleDialog:ConfirmDialog() local ruleName = self.fields["ruleName"].value local ruleType = self.fields["ruleType"].value if String.Trim(ruleName) == "" then return false end local value = 0 if ruleType == "String" then value = "empty" end self.objectPropertyWindow:OnFieldChange("rule_" .. ruleName, value) self.objectPropertyWindow.__fullRefresh = true return true end function ObjectPropertyWindow:AddObjectRules(objectID, bridge) self:AddControl("rule-sep", { Label:New { caption = "Rules", }, Line:New { x = 50, width = self.VALUE_POS, } }) for rule, value in pairs(bridge.s11n:Get(objectID, "rules")) do local ruleName = "rule_" .. rule local fields = {} if type(value) == "string" then table.insert(fields, StringField({ name = ruleName, title = rule .. ":", tooltip = "Rule (" .. rule .. ")", value = tostring(value), })) else table.insert(fields, NumericField({ name = ruleName, title = rule .. ":", tooltip = "Rule (" .. rule .. ")", value = value, })) end table.insert(fields, Field({ name = "rem_" .. ruleName, width = SB.conf.B_HEIGHT, components = { Button:New { caption = "", width = SB.conf.B_HEIGHT, height = SB.conf.B_HEIGHT, padding = {2, 2, 2, 2}, tooltip = "Remove rule", classname = "negative_button", children = { Image:New { file = Path.Join(SB.DIRS.IMG, 'cancel.png'), height = "100%", width = "100%", }, }, OnClick = { function() self:OnFieldChange(ruleName, false) self.__fullRefresh = true end } }, } })) self:AddField(GroupField(fields)) table.insert(self.rules, ruleName) end self:AddField(Field({ name = "btn-add-rule", width = 150, components = { Button:New { caption = "Add rule", x = 0, width = 135, height = 30, tooltip = "Add unit rule", OnClick = { function() NewRuleDialog(self) end } }, } })) end function ObjectPropertyWindow:_GetAveragePos() local selection = SB.view.selectionManager:GetSelection() local selCount = SB.view.selectionManager:GetSelectionCount() local avg = {x=0, y=0, z=0} for selType, selected in pairs(selection) do local bridge = ObjectBridge.GetObjectBridge(selType) for _, objectID in pairs(selected) do local pos = bridge.s11n:Get(objectID, "pos") avg.x = avg.x + pos.x avg.y = avg.y + pos.y avg.z = avg.z + pos.z end end avg.x = avg.x / selCount avg.y = avg.y / selCount avg.z = avg.z / selCount return avg end function ObjectPropertyWindow:OnSelectionChanged() local selection = SB.view.selectionManager:GetSelection() self.selectionChanging = true local objectID, bridge for selType, objectIDs in pairs(selection) do if #objectIDs > 0 then bridge = ObjectBridge.GetObjectBridge(selType) objectID = objectIDs[1] break end end for name, _ in pairs(self.fields) do self:RemoveField(name) end if not bridge then self.stackPanel:EnableRealign() self.stackPanel:Invalidate() return end self.bridge = bridge self.objectID = objectID self:AddObjectFields(bridge, objectID) self:__UpdateFields() self.stackPanel:EnableRealign() self.stackPanel:Invalidate() self.selectionChanging = false end function ObjectPropertyWindow:__UpdateFields() local selCount = SB.view.selectionManager:GetSelectionCount() if selCount == 0 then return end local bridge = self.bridge local objectID = self.objectID if not objectID then return end local value = bridge.s11n:Get(objectID) for k, v in pairs(value) do -- if key == "fuel" then -- FIXME: fuel is aircraft only -- local maxFuel = bridge.ObjectDefs[bridge.GetObjectDefID(objectID)].maxFuel -- end if not Table.Contains(bridge.blockedFields, k) and k ~= "pos" and k ~= "rot" then local dtype = type(v) if dtype == "table" then for _, tkey in pairs(Table.GetKeys(v)) do tkey = tostring(tkey) local name = k .. tkey if self.fields[name] then self:Set(name, v[name]) end end elseif self.fields[k] then self:Set(k, v) end end end local pos if self.fields["avgPos"].value then pos = self:_GetAveragePos() else pos = bridge.s11n:Get(objectID, "pos") end self:Set("posx", pos.x) self:Set("posy", pos.y) self:Set("posz", pos.z) if pos.y ~= Spring.GetGroundHeight(pos.x, pos.z) then self:Set("stickToGround", false) end if self.fields.rotx then local rot = bridge.s11n:Get(objectID, "rot") self:Set("rotx", math.deg(rot.x)) self:Set("roty", math.deg(rot.y)) self:Set("rotz", math.deg(rot.z)) end if bridge == unitBridge then local states = bridge.s11n:Get(objectID, "states") -- FIXME: states should always be available if we use globallos ? if states then Log.Debug("ACTIVE", states.active) self:Set("fireState", states.fireState) self:Set("moveState", states.moveState) self:Set("repeat", states["repeat"]) self:Set("cloak", states.cloak) self:Set("active", states.active) self:Set("trajectory", states.trajectory) self:Set("autoLand", states.autoLand) self:Set("autoRepairLevel", states.autoRepairLevel) self:Set("loopbackAttack", states.loopbackAttack) end end end function ObjectPropertyWindow:OnFieldChange(name, value) if self.selectionChanging then return end local selection = SB.view.selectionManager:GetSelection() local selCount = SB.view.selectionManager:GetSelectionCount() if selCount == 0 then return end if name == "avgPos" then self.__avgPosValue = value self:OnSelectionChanged() return end if name == "stickToGround" then if value then self:OnFieldChange("movectrl", false) self:OnFieldChange("gravity", 1) -- Force refreshing the position self:OnFieldChange("posx", self.fields["posx"].value) end return end local commands = {} if name == "posx" or name == "posy" or name == "posz" then local avg if self.fields["avgPos"].value then avg = self:_GetAveragePos() else avg = { x=0, y=0, z=0} end if name == "posx" then value = { x = self.fields["posx"].value - avg.x } elseif name == "posy" then if self.fields["stickToGround"].value then self:Set("stickToGround", false) end value = { y = self.fields["posy"].value - avg.y } elseif name == "posz" then value = { z = self.fields["posz"].value - avg.z } end name = "pos" elseif self.__keys[name] then name = self.__keys[name] local values = self.bridge.s11n:Get(self.objectID, name) value = {} for tkey, _ in pairs(values) do value[tkey] = self.fields[name .. tostring(tkey)].value end elseif name == "rotx" or name == "roty" or name == "rotz" then local rotx = math.rad(self.fields["rotx"].value) local roty = math.rad(self.fields["roty"].value) local rotz = math.rad(self.fields["rotz"].value) value = { x = rotx, y = roty, z = rotz } name = "rot" elseif name == "fireState" or name == "moveState" or name == "repeat" or name == "cloak" or name == "active" or name == "trajectory" or name == "autoLand" or name == "autoRepairLevel" or name == "loopbackAttack" then value = { [name] = self.fields[name].value } name = "states" elseif name:sub(1, #"rule_") == "rule_" then local rule = name:sub(#"rule_"+1) name = "rules" value = { [rule] = value } end for selType, objectIDs in pairs(selection) do if #objectIDs > 0 then local bridge = ObjectBridge.GetObjectBridge(selType) if bridge.s11n.setFuncs[name] then local cmds = self:GetCommands(objectIDs, name, value, bridge) for _, command in pairs(cmds) do table.insert(commands, command) end end end end if #commands > 0 then local compoundCommand = CompoundCommand(commands) SB.commandManager:execute(compoundCommand) end end function ObjectPropertyWindow:GetCommands(objectIDs, name, value, bridge) local commands = {} for _, objectID in pairs(objectIDs) do local modelID = bridge.getObjectModelID(objectID) if name ~= "pos" then table.insert(commands, SetObjectParamCommand(bridge.name, modelID, name, value)) else local pos = bridge.s11n:Get(objectID, "pos") for coordName, coordValue in pairs(value) do if self.fields["avgPos"].value then pos[coordName] = pos[coordName] + coordValue else pos[coordName] = coordValue end end if self.fields["stickToGround"].value then pos.y = Spring.GetGroundHeight(pos.x, pos.z) end table.insert(commands, SetObjectParamCommand(bridge.name, modelID, name, pos)) if bridge == unitBridge then table.insert(commands, SetObjectParamCommand(bridge.name, modelID, "movectrl", true)) table.insert(commands, SetObjectParamCommand(bridge.name, modelID, "gravity", 0)) -- elseif bridge == featureBridge then --table.insert(commands, SetObjectParamCommand(bridge.name, modelID, "lockPos", false)) end end end return commands end
object_tangible_content_wod_crafting_alter_4 = object_tangible_content_shared_wod_crafting_alter_4:new { } ObjectTemplates:addTemplate(object_tangible_content_wod_crafting_alter_4, "object/tangible/content/wod_crafting_alter_4.iff")
local wibox = require('wibox') local awful = require('awful') local naughty = require('naughty') local find_widget_in_wibox = function(wb, widget) local function find_widget_in_hierarchy(h, widget) if h:get_widget() == widget then return h end local result for _, ch in ipairs(h:get_children()) do result = result or find_widget_in_hierarchy(ch, widget) end return result end local h = wb._drawable._widget_hierarchy return h and find_widget_in_hierarchy(h, widget) end local focused = awful.screen.focused() local h = find_widget_in_wibox(focused.top_panel, focused.music) local x, y, width, height = h:get_matrix_to_device():transform_rectangle(0, 0, h:get_size()) -- local geo = focused.mywibox:geometry() -- x, y = x + geo.x, y + geo.y -- print(string.format("The widget is inside of the rectangle (%d, %d, %d, %d) on the screen", x, y, width, height) naughty.notification({message=tostring(height)})
Notify("Starting mariadb container...") require("podman")({ NAME = "mariadb", URL = "docker://docker.io/library/mariadb", TAG = "10.5", IP = "0.255.128.1", CPUS = "3", MEM = "1g", })
function jtorch._saveReshapeNode(node, ofile) local sz = node.size:totable() if #sz <= 0 then error('Bad module') end ofile:writeInt(#sz) for i = 1, #sz do ofile:writeInt(sz[i]) end end
--[[-------------------------------------------------------------------------- -- TomTom - A navigational assistant for World of Warcraft -- -- CrazyTaxi: A crazy-taxi style arrow used for waypoint navigation. -- concept taken from MapNotes2 (Thanks to Mery for the idea, along -- with the artwork.) ----------------------------------------------------------------------------]] local sformat = string.format local L = TomTomLocals local ldb = LibStub("LibDataBroker-1.1") local function ColorGradient(perc, ...) local num = select("#", ...) local hexes = type(select(1, ...)) == "string" if perc == 1 then return select(num-2, ...), select(num-1, ...), select(num, ...) end num = num / 3 local segment, relperc = math.modf(perc*(num-1)) local r1, g1, b1, r2, g2, b2 r1, g1, b1 = select((segment*3)+1, ...), select((segment*3)+2, ...), select((segment*3)+3, ...) r2, g2, b2 = select((segment*3)+4, ...), select((segment*3)+5, ...), select((segment*3)+6, ...) if not r2 or not g2 or not b2 then return r1, g1, b1 else return r1 + (r2-r1)*relperc, g1 + (g2-g1)*relperc, b1 + (b2-b1)*relperc end end local twopi = math.pi * 2 local wayframe = CreateFrame("Button", "TomTomCrazyArrow", UIParent) wayframe:SetHeight(42) wayframe:SetWidth(56) wayframe:EnableMouse(true) wayframe:SetMovable(true) wayframe:SetClampedToScreen(true) wayframe:Hide() -- Frame used to control the scaling of the title and friends local titleframe = CreateFrame("Frame", nil, wayframe) wayframe.title = titleframe:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") wayframe.status = titleframe:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") wayframe.tta = titleframe:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") wayframe.title:SetPoint("TOP", wayframe, "BOTTOM", 0, 0) wayframe.status:SetPoint("TOP", wayframe.title, "BOTTOM", 0, 0) wayframe.tta:SetPoint("TOP", wayframe.status, "BOTTOM", 0, 0) local function OnDragStart(self, button) if not TomTom.db.profile.arrow.lock then self:StartMoving() end end local function OnDragStop(self, button) self:StopMovingOrSizing() self:SetUserPlaced(false) -- point, relativeTo, relativePoint, xOfs, yOfs TomTom.profile.arrow.position = { self:GetPoint() } TomTom.profile.arrow.position[2] = nil -- Note we are relative to UIParent end local function OnEvent(self, event, ...) if (event == "ZONE_CHANGED_NEW_AREA" or event == "ZONE_CHANGED") and TomTom.profile.arrow.enable then self:Show() return end if (event == "PLAYER_ENTERING_WORLD") then wayframe:ClearAllPoints() if not TomTom.profile.arrow.position then TomTom.profile.arrow.position = {"CENTER", nil , "CENTER", 0, 0} end local pos = TomTom.profile.arrow.position wayframe:SetPoint(pos[1], UIParent, pos[3], pos[4], pos[5]) end end wayframe:SetScript("OnDragStart", OnDragStart) wayframe:SetScript("OnDragStop", OnDragStop) wayframe:RegisterForDrag("LeftButton") wayframe:RegisterEvent("ZONE_CHANGED_NEW_AREA") wayframe:RegisterEvent("ZONE_CHANGED") wayframe:RegisterEvent("PLAYER_ENTERING_WORLD") wayframe:SetScript("OnEvent", OnEvent) wayframe.arrow = wayframe:CreateTexture(nil, "OVERLAY") wayframe.arrow:SetTexture("Interface\\Addons\\TomTom\\Images\\Arrow") wayframe.arrow:SetAllPoints() local active_point, arrive_distance, showDownArrow, point_title function TomTom:SetCrazyArrow(uid, dist, title) if active_point and active_point.corpse and self.db.profile.arrow.stickycorpse then -- do not change the waypoint arrow from corpse return end active_point = uid arrive_distance = dist point_title = title if self.profile.arrow.enable then wayframe.title:SetText(title or L["Unknown waypoint"]) wayframe:Show() if wayframe.crazyFeedFrame then wayframe.crazyFeedFrame:Show() end end end function TomTom:IsCrazyArrowEmpty() return not active_point end local status = wayframe.status local tta = wayframe.tta local arrow = wayframe.arrow local count = 0 local last_distance = 0 local tta_throttle = 0 local speed = 0 local speed_count = 0 local function OnUpdate(self, elapsed) if not active_point then self:Hide() return end local dist,x,y = TomTom:GetDistanceToWaypoint(active_point) -- The only time we cannot calculate the distance is when the waypoint -- is on another continent, or we are in an instance if not dist then if not TomTom:IsValidWaypoint(active_point) then active_point = nil -- Change the crazy arrow to point at the closest waypoint if TomTom.profile.arrow.setclosest then TomTom:SetClosestWaypoint() return end end self:Hide() return end status:SetText(sformat(L["%d yards"], dist)) local cell -- Showing the arrival arrow? if dist <= arrive_distance then if not showDownArrow then arrow:SetHeight(70) arrow:SetWidth(53) arrow:SetTexture("Interface\\AddOns\\TomTom\\Images\\Arrow-UP") arrow:SetVertexColor(unpack(TomTom.db.profile.arrow.goodcolor)) showDownArrow = true end count = count + 1 if count >= 55 then count = 0 end local cell = count local column = cell % 9 local row = floor(cell / 9) local xstart = (column * 53) / 512 local ystart = (row * 70) / 512 local xend = ((column + 1) * 53) / 512 local yend = ((row + 1) * 70) / 512 arrow:SetTexCoord(xstart,xend,ystart,yend) else if showDownArrow then arrow:SetHeight(56) arrow:SetWidth(42) arrow:SetTexture("Interface\\AddOns\\TomTom\\Images\\Arrow") showDownArrow = false end local angle = TomTom:GetDirectionToWaypoint(active_point) local player = GetPlayerFacing() if not player then if not TomTom:IsValidWaypoint(active_point) then active_point = nil -- Change the crazy arrow to point at the closest waypoint if TomTom.profile.arrow.setclosest then TomTom:SetClosestWaypoint() return end end self:Hide() return end angle = angle - player local perc = math.abs((math.pi - math.abs(angle)) / math.pi) local gr,gg,gb = unpack(TomTom.db.profile.arrow.goodcolor) local mr,mg,mb = unpack(TomTom.db.profile.arrow.middlecolor) local br,bg,bb = unpack(TomTom.db.profile.arrow.badcolor) local r,g,b = ColorGradient(perc, br, bg, bb, mr, mg, mb, gr, gg, gb) -- If we're 98% heading in the right direction, then use the exact -- color instead of the gradient. This allows us to distinguish 'good' -- from 'on target'. Thanks to Gregor_Curse for the suggestion. if perc > 0.98 then r,g,b = unpack(TomTom.db.profile.arrow.exactcolor) end arrow:SetVertexColor(r,g,b) local cell = floor(angle / twopi * 108 + 0.5) % 108 local column = cell % 9 local row = floor(cell / 9) local xstart = (column * 56) / 512 local ystart = (row * 42) / 512 local xend = ((column + 1) * 56) / 512 local yend = ((row + 1) * 42) / 512 arrow:SetTexCoord(xstart,xend,ystart,yend) end -- Calculate the TTA every second (%01d:%02d) tta_throttle = tta_throttle + elapsed if tta_throttle >= 1.0 then -- Calculate the speed in yards per sec at which we're moving local current_speed = (last_distance - dist) / tta_throttle if last_distance == 0 then current_speed = 0 end if speed_count < 2 then speed = (speed + current_speed) / 2 speed_count = speed_count + 1 else speed_count = 0 speed = current_speed end if speed > 0 then local eta = math.abs(dist / speed) tta:SetFormattedText("%s:%02d", math.floor(eta / 60), math.floor(eta % 60)) else tta:SetText("***") end last_distance = dist tta_throttle = 0 end end function TomTom:ShowHideCrazyArrow() if self.profile.arrow.enable then if self.profile.arrow.hideDuringPetBattles and C_PetBattles and C_PetBattles.IsInBattle() then wayframe:Hide() return end wayframe:Show() if self.profile.arrow.noclick then wayframe:EnableMouse(false) else wayframe:EnableMouse(true) end -- Set the scale and alpha wayframe:SetScale(TomTom.db.profile.arrow.scale) -- Do not allow the arrow to be invisible if TomTom.db.profile.arrow.alpha < 0.1 then TomTom.db.profile.arrow.alpha = 1.0 end -- Set the stratum if TomTom.db.profile.arrow.highstrata then wayframe:SetFrameStrata("HIGH") else wayframe:SetFrameStrata("MEDIUM") end wayframe:SetAlpha(TomTom.db.profile.arrow.alpha) local width = TomTom.db.profile.arrow.title_width local height = TomTom.db.profile.arrow.title_height local scale = TomTom.db.profile.arrow.title_scale wayframe.title:SetWidth(width) wayframe.title:SetHeight(height) titleframe:SetScale(scale) titleframe:SetAlpha(TomTom.db.profile.arrow.title_alpha) if self.profile.arrow.showdistance then wayframe.status:Show() wayframe.tta:ClearAllPoints() wayframe.tta:SetPoint("TOP", wayframe.status, "BOTTOM", 0, 0) else wayframe.status:Hide() wayframe.tta:ClearAllPoints() wayframe.tta:SetPoint("TOP", wayframe, "BOTTOM", 0, 0) end if self.profile.arrow.showtta then tta:Show() else tta:Hide() end else wayframe:Hide() end end wayframe:SetScript("OnUpdate", OnUpdate) --[[------------------------------------------------------------------------- -- Dropdown -------------------------------------------------------------------------]]-- local dropdown_info = { -- Define level one elements here [1] = { { -- Title text = L["TomTom Waypoint Arrow"], isTitle = 1, }, { -- Send waypoint text = L["Send waypoint to"], hasArrow = true, value = "send", }, { -- Clear waypoint from crazy arrow text = L["Clear waypoint from crazy arrow"], func = function() local prior = active_point active_point = nil if TomTom.profile.arrow.setclosest then local uid = TomTom:GetClosestWaypoint() if uid and uid ~= prior then TomTom:SetClosestWaypoint() return end end end, }, { -- Remove a waypoint text = L["Remove waypoint"], func = function() local uid = active_point TomTom:RemoveWaypoint(uid) end, }, { -- Remove all waypoints from this zone text = L["Remove all waypoints from this zone"], func = function() local uid = active_point local data = uid local mapId = data[1] for key, waypoint in pairs(TomTom.waypoints[mapId]) do TomTom:RemoveWaypoint(waypoint) end end, }, { -- Remove all waypoints text = L["Remove all waypoints"], func = function() if TomTom.db.profile.general.confirmremoveall then StaticPopup_Show("TOMTOM_REMOVE_ALL_CONFIRM") else StaticPopupDialogs["TOMTOM_REMOVE_ALL_CONFIRM"].OnAccept() return end end, }, { -- Lock Arrow text = L["Arrow locked"], checked = function () return TomTom.db.profile.arrow.lock; end, func = function () TomTom.db.profile.arrow.lock = not TomTom.db.profile.arrow.lock TomTom:ShowHideCrazyArrow() end, isNotRadio = true, } }, [2] = { send = { { -- Title text = L["Waypoint communication"], isTitle = true, }, { -- Party text = L["Send to party"], func = function() TomTom:SendWaypoint(TomTom.dropdown.uid, "PARTY") end }, { -- Raid text = L["Send to raid"], func = function() TomTom:SendWaypoint(TomTom.dropdown.uid, "RAID") end }, { -- Battleground text = L["Send to battleground"], func = function() TomTom:SendWaypoint(TomTom.dropdown.uid, "BATTLEGROUND") end }, { -- Guild text = L["Send to guild"], func = function() TomTom:SendWaypoint(TomTom.dropdown.uid, "GUILD") end }, }, }, } local function init_dropdown(self, level) -- Make sure level is set to 1, if not supplied level = level or 1 -- Get the current level from the info table local info = dropdown_info[level] -- If a value has been set, try to find it at the current level if level > 1 and UIDROPDOWNMENU_MENU_VALUE then if info[UIDROPDOWNMENU_MENU_VALUE] then info = info[UIDROPDOWNMENU_MENU_VALUE] end end -- Add the buttons to the menu for idx,entry in ipairs(info) do if type(entry.checked) == "function" then -- Make this button dynamic local new = {} for k,v in pairs(entry) do new[k] = v end new.checked = new.checked() entry = new end UIDropDownMenu_AddButton(entry, level) end end local function WayFrame_OnClick(self, button) if active_point then if TomTom.db.profile.arrow.menu then TomTom.dropdown.uid = active_point UIDropDownMenu_Initialize(TomTom.dropdown, init_dropdown) ToggleDropDownMenu(1, nil, TomTom.dropdown, "cursor", 0, 0) end end end wayframe:RegisterForClicks("RightButtonUp") wayframe:SetScript("OnClick", WayFrame_OnClick) local function getCoords(column, row) local xstart = (column * 56) / 512 local ystart = (row * 42) / 512 local xend = ((column + 1) * 56) / 512 local yend = ((row + 1) * 42) / 512 return xstart, xend, ystart, yend end local texcoords = setmetatable({}, {__index = function(t, k) local col,row = k:match("(%d+):(%d+)") col,row = tonumber(col), tonumber(row) local obj = {getCoords(col, row)} rawset(t, k, obj) return obj end}) wayframe:RegisterEvent("ADDON_LOADED") local function wayframe_OnEvent(self, event, arg1, ...) if arg1 == "TomTom" then if TomTom.db.profile.feeds.arrow then -- Create a data feed for coordinates local feed_crazy = ldb:NewDataObject("TomTom_CrazyArrow", { type = "data source", icon = "Interface\\Addons\\TomTom\\Images\\Arrow", staticIcon = "Interface\\Addons\\TomTom\\Images\\StaticArrow", text = "Crazy", iconR = 0.2, iconG = 1.0, iconB = 0.2, iconCoords = texcoords["1:1"], OnTooltipShow = function(tooltip) local dist = TomTom:GetDistanceToWaypoint(active_point) if dist then tooltip:AddLine(point_title or L["Unknown waypoint"]) tooltip:AddLine(sformat(L["%d yards"], dist), 1, 1, 1) end end, OnClick = WayFrame_OnClick, }) local crazyFeedFrame = CreateFrame("Frame") local throttle = TomTom.db.profile.feeds.arrow_throttle local counter = 0 function TomTom:UpdateArrowFeedThrottle() throttle = TomTom.db.profile.feeds.arrow_throttle end wayframe.crazyFeedFrame = crazyFeedFrame crazyFeedFrame:SetScript("OnUpdate", function(self, elapsed) counter = counter + elapsed if counter < throttle then return end counter = 0 if not active_point then self:Hide() end local angle = TomTom:GetDirectionToWaypoint(active_point) local player = GetPlayerFacing() if not angle or not player then feed_crazy.iconCoords = texcoords["1:1"] feed_crazy.iconR = 0.2 feed_crazy.iconG = 1.0 feed_crazy.iconB = 0.2 feed_crazy.text = "No waypoint" return end angle = angle - player local perc = math.abs((math.pi - math.abs(angle)) / math.pi) local gr,gg,gb = unpack(TomTom.db.profile.arrow.goodcolor) local mr,mg,mb = unpack(TomTom.db.profile.arrow.middlecolor) local br,bg,bb = unpack(TomTom.db.profile.arrow.badcolor) local r,g,b = ColorGradient(perc, br, bg, bb, mr, mg, mb, gr, gg, gb) -- If we're 98% heading in the right direction, then use the exact -- color instead of the gradient. This allows us to distinguish 'good' -- from 'on target'. Thanks to Gregor_Curse for the suggestion. if perc > 0.98 then r,g,b = unpack(TomTom.db.profile.arrow.exactcolor) end feed_crazy.iconR = r feed_crazy.iconG = g feed_crazy.iconB = b local cell = floor(angle / twopi * 108 + 0.5) % 108 local column = cell % 9 local row = floor(cell / 9) local key = column .. ":" .. row feed_crazy.iconCoords = texcoords[key] feed_crazy.text = point_title or L["Unknown waypoint"] end) end end end wayframe:HookScript("OnEvent", wayframe_OnEvent) --[[------------------------------------------------------------------------- -- API for manual control of Crazy Arrow -- -- This allow for an addon to specify their own control of the waypoint -- arrow without needing to tip-toe around the API. It may not integrate -- properly, but in general it should work. -- -- Example Usage: -- -- if not TomTom:CrazyArrowIsHijacked() then -- TomTom:HijackCrazyArrow(function(self, elapsed) -- -- Random angle -- local angle = math.random(math.pi * 2) -- TomTom:SetCrazyArrowDirection(angle) -- -- Random color -- local r = math.random(100) / 100 -- local g = math.random(100) / 100 -- local b = math.random(100) / 100 -- TomTom:SetCrazyArrowColor(r, g, b) -- -- Titles -- TomTom:SetCrazyArrowTitle("Hijacked arrow", "Hijacked", "You will never arrive") -- end) -- end -- -- -- At some point later -- TomTom:ReleaseCrazyArrow() -------------------------------------------------------------------------]]-- -- Set the direction of the crazy arrow without taking the player's facing -- into consideration. This can be accomplished by subtracting -- GetPlayerFacing() from the angle before passing it in. function TomTom:SetCrazyArrowDirection(angle) local cell = floor(angle / twopi * 108 + 0.5) % 108 local column = cell % 9 local row = floor(cell / 9) local key = column .. ":" .. row arrow:SetTexCoord(unpack(texcoords[key])) end -- Convenience function to set the color of the crazy arrow function TomTom:SetCrazyArrowColor(r, g, b, a) arrow:SetVertexColor(r, g, b, a) end -- Convenience function to set the title/status and time to arrival text -- of the crazy arrow. function TomTom:SetCrazyArrowTitle(title, status, tta) wayframe.title:SetText(title) wayframe.status:SetText(status) wayframe.tta:SetText(tta) end -- Function to actually hijack the crazy arrow by replacing the OnUpdate script function TomTom:HijackCrazyArrow(onupdate) wayframe:SetScript("OnUpdate", onupdate) wayframe.hijacked = true wayframe:Show() end -- Releases the crazy arrow by restoring the original OnUpdate script function TomTom:ReleaseCrazyArrow() wayframe:SetScript("OnUpdate", OnUpdate) wayframe.hijacked = false end -- Returns whether or not the crazy arrow is currently hijacked function TomTom:CrazyArrowIsHijacked() return wayframe.hijacked end -- Logs Crazy Arrow status function TomTom:DebugCrazyArrow() local msg msg = string.format(L["|cffffff78TomTom:|r CrazyArrow %s hijacked"], (wayframe.hijacked and L["is"]) or L["not"]) ChatFrame1:AddMessage(msg) msg = string.format(L["|cffffff78TomTom:|r CrazyArrow %s visible"], (wayframe:IsVisible() and L["is"]) or L["not"]) ChatFrame1:AddMessage(msg) msg = string.format(L["|cffffff78TomTom:|r Waypoint %s valid"], (active_point and TomTom:IsValidWaypoint(active_point) and L["is"]) or L["not"]) ChatFrame1:AddMessage(msg) local dist,x,y = TomTom:GetDistanceToWaypoint(active_point) msg = string.format("|cffffff78TomTom:|r Waypoint distance=%s", tostring(dist)) ChatFrame1:AddMessage(msg) if wayframe:IsVisible() then local point, relativeTo, relativePoint, xOfs, yOfs = wayframe:GetPoint(1) relativeTo = (relativeTo and relativeTo:GetName()) or "UIParent" msg = string.format("|cffffff78TomTom:|r CrazyArrow point=%s frame=%s rpoint=%s xo=%.2f yo=%.2f", point, relativeTo, relativePoint, xOfs, yOfs) ChatFrame1:AddMessage(msg) end end
local core = require "sys.core" local socket = require "sys.socket" local dns = require "sys.dns" local testaux = require "testaux" return function() local ip = dns.resolve("smtp.sina.com.cn") testaux.assertneq(ip, nil, "dns resolve ip") local fd = socket.connect(string.format("%s:%s", ip, 25)) testaux.assertneq(fd, nil, "dns resolve ip validate") local l = socket.readline(fd) testaux.assertneq(l, nil, "dns resolve ip validate") local f = l:find("220") testaux.assertneq(f, nil, "dns resolve ip validate") end
if ( SERVER ) then AddCSLuaFile( "shared.lua" ) end if ( CLIENT ) then SWEP.PrintName = "DC-15 Side Arm" SWEP.Author = "Syntax_Error752" SWEP.ViewModelFOV = 70 SWEP.Slot = 1 SWEP.SlotPos = 5 SWEP.WepSelectIcon = surface.GetTextureID("HUD/killicons/DC15SA") killicon.Add( "weapon_752_dc15sa", "HUD/killicons/DC15SA", Color( 255, 80, 0, 255 ) ) end SWEP.HoldType = "pistol" SWEP.Base = "tfa_swsft_base" SWEP.Category = "TFA Star Wars" SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.ViewModel = "models/weapons/v_DC15SA.mdl" SWEP.WorldModel = "models/weapons/w_DC15SA.mdl" SWEP.Primary.Sound = Sound ("weapons/DC15SA_fire.wav"); local MaxTimer =64 local CurrentTimer =0 SWEP.Weight = 5 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false SWEP.Primary.Recoil = 0.5 SWEP.Primary.PenetrationMultiplier = 0 --Change the amount of something this gun can penetrate through SWEP.Primary.Damage = 50 SWEP.Primary.NumShots = 1 SWEP.Primary.Spread = 0.0125 SWEP.Primary.ClipSize = 8 SWEP.Primary.RPM = 60/0.2 SWEP.Primary.DefaultClip = 8 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "battery" SWEP.TracerName = "effect_sw_laser_blue" SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.IronSightsPos = Vector (-3.9, -6, 2.5) SWEP.IronSightsAng = Vector (-0.3, -0.05, 0) function SWEP:Think() if (self.Weapon:Clip1() < self.Primary.ClipSize) and SERVER then if (CurrentTimer <= 0) then CurrentTimer = MaxTimer self.Weapon:SetClip1( self.Weapon:Clip1() + 1 ) else CurrentTimer = CurrentTimer-1 end end end function SWEP:Reload() end
local rules = require "scripts.rules" local animations = require "character.animations" local ServantGirl = require "character.servant_girl" local ServantGirlInGranary = ServantGirl:new() function ServantGirlInGranary:new(o, control) o = o or ServantGirl:new(o, control) setmetatable(o, self) self.__index = self return o end function ServantGirlInGranary:create() ServantGirl.create(self) end function ServantGirlInGranary:on_interact(interactor_name) local dialogue = { start = { text = "Did you know that princess Medea kidnapped prince Jason and run away instead of marrying with her fiance, the prince's own brother?", options = { { text = "I see.", go_to = 'end' }, }, callback = function() self.control.data.know_of_elopement = true end }, } if self.control.characters.player.data.stats.ability.cha >= 13 then table.insert(dialogue.start.options, { text = "(Cha 13) Really? You have to tell me everthing about it.", go_to = 'really' }) dialogue.really = { text = "Yes! They went on a stroll in the woods. The princess took prince Jason to the witch and poisoned him so that he would love her and they ran away.", go_to = 'end', callback = function() self.control.data.lead_to_forest = true self.control.data.lead_to_witch = true end } end sfml_dialogue(dialogue) end return ServantGirlInGranary
local function capture(id, opts) -- numbers will coalesce to strings, so we can try and convert back if id ~= nil and tonumber(id) ~= nil then id = tonumber(id) end return {"capture", id, opts} end return function(types) return { handler = capture, args = {types.FACTORY, types.STRING, types.STRING}, names = {"id", "options"}, type_helper = {}, argc = 0, help = "Open a video capture device." } end
ngx.header.content_type = 'text/html' local name = ngx.var.arg_name or "Tester" ngx.say("<br>TEST #4<hr>") ngx.say("<br>Hello, ", name, "!<br>") ngx.say("This is a test for the LUA interpreter, run by the gothings NGINX http proxy<br>") ngx.say("<br><hr><br>") ngx.say("If you see this file it means that:<br>") ngx.say(" &nbsp; &nbsp; - nginx HTTP proxy is running OK<br>") ngx.say(" &nbsp; &nbsp; - configuration files enable the test location<br>") ngx.say(" &nbsp; &nbsp; - LUA interpreter is correctly configured into nginx<br>") ngx.say(" &nbsp; &nbsp; - serving content by LUA interpreter is OK<br>") ngx.say("<br><hr><br>") ngx.say("This page is printed by the LUA interpreter, using statements like ngx.say(\"... \") <br><br>") ngx.say("You can test more content going back to the &nbsp; <a href=\"/\">homepage</a><br>") ngx.say("<br><hr><br>") -- ngx.say("<br>Notes:<br>") -- ngx.say(" &nbsp; &nbsp; - LUA version number: "..ngx.config.nginx_version.."<br>") -- ngx.say(" &nbsp; &nbsp; - HTTP host: ",ngx.var.http_host,"<br>") -- ngx.say(" &nbsp; &nbsp; - Docker container: ",ngx.var.hostname,"<br>") -- ngx.say(" &nbsp; &nbsp; - This file filename is: 'home.lua'<br>") -- ngx.say(" &nbsp; &nbsp; - This file directory is: 'var_www/test/'<br>") -- ngx.say("<br><hr>")
local CorePackages = game:GetService("CorePackages") local UserInputService = game:GetService("UserInputService") local Roact = require(CorePackages.Roact) local RoactRodux = require(CorePackages.RoactRodux) local Components = script.Parent.Parent local PlayerList = Components.Parent local ClosePlayerDropDown = require(PlayerList.Actions.ClosePlayerDropDown) local SetIsUsingGamepad = require(PlayerList.Actions.SetIsUsingGamepad) local EventConnection = require(script.Parent.EventConnection) local UserInputServiceConnector = Roact.PureComponent:extend("UserInputServiceConnector") function UserInputServiceConnector:render() return Roact.createFragment({ InputBeganConnection = Roact.createElement(EventConnection, { event = UserInputService.InputBegan, callback = function(inputObject, isProcessed) if isProcessed then return end local inputType = inputObject.UserInputType if inputType == Enum.UserInputType.Touch or inputType == Enum.UserInputType.MouseButton1 then self.props.closePlayerDropDown() end end, }), LastInputTypeChangedConnection = Roact.createElement(EventConnection, { event = UserInputService.LastInputTypeChanged, callback = function(inputType) local isGamepad = inputType.Name:find("Gamepad") self.props.setIsUsingGamepad(isGamepad ~= nil) end, }) }) end local function mapDispatchToProps(dispatch) return { closePlayerDropDown = function() return dispatch(ClosePlayerDropDown()) end, setIsUsingGamepad = function(value) return dispatch(SetIsUsingGamepad(value)) end, } end return RoactRodux.UNSTABLE_connect2(nil, mapDispatchToProps)(UserInputServiceConnector)
-- -- joiner_client.lua -- -- see joiner.lua for details -- g_Root = getRootElement() g_ResRoot = getResourceRootElement(getThisResource()) addEvent('onClientPlayerJoining') -- Pre join addEvent('onClientPlayerJoined') -- Post join g_JoinedPlayers = {} -- List of joined players maintained at the client --------------------------------- -- -- Hook events -- --------------------------------- g_EventHandlers = { onClientPlayerJoin = {}, -- { i = { elem = elem, fn = fn, getpropagated = bool } } onClientResourceStart = {} } -- Divert 'onEventName' to '_onEventName' for eventName,_ in pairs(g_EventHandlers) do addEvent('_'..eventName) addEventHandler(eventName, g_Root, function(...) triggerEvent( '_'..eventName, source, ... ) end) end -- Catch addEventHandler calls here and save the ones listed in g_EventHandlers _addEventHandler = addEventHandler function addEventHandler(event, elem, fn, getPropagated) getPropagated = getPropagated==nil and true or getPropagated if g_EventHandlers[event] then table.insert(g_EventHandlers[event], { elem = elem, fn = fn, getpropagated = getPropagated }) else _addEventHandler(event, elem, fn, getPropagated) end end -- Catch removeEventHandler calls here and remove saved ones listed in g_EventHandlers _removeEventHandler = removeEventHandler function removeEventHandler(event, elem, fn) if g_EventHandlers[event] then local handler for i=#g_EventHandlers[event],1,-1 do handler = g_EventHandlers[event][i] if handler.elem == elem and handler.fn == fn then table.remove(g_EventHandlers[event], i) end end else _removeEventHandler(event, elem, fn) end end -- call the saved handlers for 'onEventName' function callSavedEventHandlers(eventName, eventSource, ...) for _,handler in ipairs(g_EventHandlers[eventName]) do local triggeredElem = eventSource or g_Root if isElement(triggeredElem) then while true do if triggeredElem == handler.elem then source = eventSource handler.fn(...) break end if not handler.getpropagated or triggeredElem == g_Root then break end triggeredElem = getElementParent(triggeredElem) end end end end ---------------------------------------------------------------------------- -- -- Function patches -- Modify functions to act only on joined players -- ---------------------------------------------------------------------------- -- getElementsByType patch _getElementsByType = getElementsByType function getElementsByType( type, startat ) startat = startat or getRootElement() if type ~= 'player' then return _getElementsByType( type, startat ) else return filterTable(_getElementsByType( type, startat )) end end ---------------------------------------------------------------------------- -- -- Others functions -- ---------------------------------------------------------------------------- -- Remove players not joined from a table function filterTable(playerList) local result = {} for i,player in ipairs(playerList) do if table.find(g_JoinedPlayers,player) then table.insert(result,player) end end return result end ---------------------------------------------------------------------------- -- -- Event handlers -- ---------------------------------------------------------------------------- -- Real onClientPlayerJoin event was fired -- Do nothing addEventHandler('_onClientPlayerJoin', g_Root, function () triggerEvent( 'onClientPlayerJoining', source ); end ) -- Real onClientResourceStart event was fired -- Call the deferred onClientResourceStart event handlers, then tell the server we are loaded. addEventHandler('_onClientResourceStart', g_ResRoot, function() callSavedEventHandlers( 'onClientResourceStart', source ) if _DEBUG_TIMING then setTimer( function() triggerServerEvent('onLoadedAtClient', resourceRoot, g_Me ) end, math.random(1000,15000), 1 ) else triggerServerEvent('onLoadedAtClient', resourceRoot, g_Me ) end end ) -- onMyJoinCompleteAtServer -- This player is now fully joined at the server. addEvent('onMyJoinCompleteAtServer', true) addEventHandler('onMyJoinCompleteAtServer', resourceRoot, function(allJoinedPlayersAtServer) for i,player in ipairs(allJoinedPlayersAtServer) do table.insertUnique(g_JoinedPlayers,player) end end ) -- onOtherJoinCompleteAtServer -- A player is fully joined at the server. Call the deferred onClientPlayerJoin event handlers. addEvent('onOtherJoinCompleteAtServer', true) addEventHandler('onOtherJoinCompleteAtServer', resourceRoot, function( player ) table.insertUnique(g_JoinedPlayers,player) -- Call deferred onClientPlayerJoin event handlers callSavedEventHandlers( 'onClientPlayerJoin', player ) -- Custom event for joiner aware event handlers triggerEvent( 'onClientPlayerJoined', player ) end ) -- onClientPlayerQuit -- Remove player from JoinedPlayers list addEventHandler('onClientPlayerQuit', g_Root, function () table.removevalue(g_JoinedPlayers, source) end )
-- If you edit template.xml, reflect the change here local nodesPerAF = 50 local templatepath = "../main/actors.xml" -- End of config --[[ geno is a library for creating screens in a similar way to how SM5's Def tables work. Part of the nitg-theme project: https://github.com/ArcticFqx/nitg-theme/ ]] -- geno deez nuts haha lmao gotem - jaez actorgen = { Actors = {}, ActorByName = {}, NameByActor = {}, TemplateByActor = {}, ActorFrame = {}, Overlay = { _ = "ignore", n = 0 } } local log = nodesPerAF == 10 and math.log10 or function(n) return math.log(n)/math.log(nodesPerAF) end local stack = {} local ceil = math.ceil local getn = table.getn local lower = string.lower local typespec = assert(loadfile("main/typespec.lua"))() local function GetDepth(t) local depth = ceil(log(getn(t))) --local depth = getn(t) return depth > 0 and depth or 1 end local smeta = {} function smeta:Push(entry) self[getn(self) + 1] = entry end function smeta:Pop() local t = self[getn(self)] self[getn(self)] = nil return t end function smeta:Top() return self[getn(self)] end function smeta:NewLayer(t) self:Push { template = t, -- current layer depth = GetDepth(t), -- depth of tree structure width = getn(t), -- width of layer cd = 1, -- current depth i = 0, -- current template index l = {}, -- current index of node a = {}, -- actorgen.Actors clone ni = 0, -- current node index } end smeta.__index = smeta -- This runs first function actorgen.Cond(index, type) local s = stack:Top() s.l[s.cd] = index or s.ni if s.width <= s.i then return false end if not index then s.ni = s.ni + 1 end return true end -- just a small check function actorgen.HasNext(index, type) local s = stack:Top() return s.width > (index or s.ni) end function actorgen.Type() local s = stack:Top() if s.cd < s.depth then return end s.i = s.i + 1 local template = s.template[s.i] if lower(template.Type) == "actorframe" then if table.getn(template) > 0 then return end end if typespec[template.Type].Type then template.Type = typespec[template.Type].Type end return typespec[template.Type].Type end -- This runs second function actorgen.File() local s = stack:Top() if s.cd < s.depth then s.cd = s.cd + 1 --print("Depth["..table.getn(stack).."]:", s.cd-1, "->", s.cd) return templatepath end local template = s.template[s.i] if lower(template.Type) == "actorframe" then if table.getn(template) > 0 then stack:NewLayer(template) s.a[s.i] = stack:Top().a --print("NewAF["..table.getn(stack).."]:", 0, "->", 1) return templatepath end end if template.File then local rel = string.find(template.File, "^/") and "../" or "" print(rel..template.File) return rel .. template.File end return typespec[template.Type].File or nil end local function patchFunctionChaining(actor) --[[ local mt,at = getmetatable(actor),{} for k,v in pairs(mt) do mt[k],at[k] = nil,v end function mt:__index(k) return function(...) return at[k](unpack(arg)) or arg[1] end end mt.__actorgen = true setmetatable(mt, mt) --]] end function actorgen:Meta() local s = stack:Top() local template = s.template[s.i] local meta = typespec[template.Type][self] if meta then return meta(template) end end function actorgen:RegisterOverlay() local name = self:GetName() if actorgen.Overlay[name] then return end if name == "" then actorgen.Overlay.n = actorgen.Overlay.n+1 name = tostring(actorgen.Overlay.n) self:SetName(name) end actorgen.Overlay[self] = name actorgen.Overlay[name] = self end -- This runs third function actorgen:Init() local s = stack:Top() if s.cd < 1 then s.a[0] = self actorgen.ActorFrame[self] = s.a stack:Pop() s = stack:Top() end local template = s.template[s.i] if s.cd == s.depth then if not s.a[s.i] then s.a[s.i] = self end actorgen.TemplateByActor[self] = template if template.Name then actorgen.ActorByName[template.Name] = self actorgen.NameByActor[self] = template.Name self:SetName(template.Name) end typespec[template.Type].Init(self, template) for k, v in pairs(template) do if string.len(k) > 8 and string.sub(k, -7, -1) == "Command" then --print(k) local cmd_name = string.sub(k, 1, -8) if self:hascommand(cmd_name) then self:removecommand(cmd_name) end self:addcommand(cmd_name, v) --if cmd_name == "Init" then self:playcommand("Init") end end end else self:SetName("_") end if template.Texture then self:Load(GAMESTATE:GetCurrentSong():GetMusicPath() .. "/../" .. template.Texture) end if s.l[s.cd] >= nodesPerAF or s.width <= s.i then s.cd = s.cd - 1 --print("Depth["..table.getn(stack).."]:", s.cd+1, "->", s.cd) end end -- These runs at the very end when everything has been built function actorgen:InitCmd(a) local s = stack:Top() local template = s.template actorgen.Actors[0] = self actorgen.TemplateByActor[self] = template if template.Name then actorgen.ActorByName[template.Name] = self actorgen.NameByActor[self] = template.Name self:SetName(template.Name) end typespec[template.Type].Init(self, template) end -- OnCommand Time function actorgen:OnCmd(a) a = a or actorgen.Actors for k,v in ipairs(a) do if type(v) == "table" then actorgen.OnCmd(self, v) else typespec[v].On(v, actorgen.TemplateByActor[v]) end end typespec[a[0]].On(a[0], actorgen.TemplateByActor[a[0]]) end -- Called from Root function actorgen.Template(template) actorgen.Actors = {} actorgen.ActorByName = {} actorgen.NameByActor = {} actorgen.TemplateByActor = {} actorgen.ActorFrame = {} stack = setmetatable({},smeta) stack:NewLayer(template) local s = stack:Top() s.a = actorgen.Actors --print("Depth["..table.getn(stack).."]:", s.cd-1, "->", s.cd) return true end local defmeta = {} function defmeta:__call(append) for _,v in ipairs(append) do table.insert(self, v) end end actorgen.Def = {} function actorgen.Def:__index(k) return function(t) t.Type = k return setmetatable(t, defmeta) end end _G.Def = {} setmetatable(Def, actorgen.Def) return actorgen
local jit_version = monitoring.gauge("jit_version", "luajit version") local jit_enabled = monitoring.gauge("jit_enabled", "luajit enabled") if jit then if jit.version_num then jit_version.set(jit.version_num) else jit_version.set(0) end local enabled = jit.status() if enabled then jit_enabled.set(1) else jit_enabled.set(0) end else jit_version.set(0) jit_enabled.set(0) end
object_tangible_veteran_reward_tow_retail_reward = object_tangible_veteran_reward_shared_tow_retail_reward:new { } ObjectTemplates:addTemplate(object_tangible_veteran_reward_tow_retail_reward, "object/tangible/veteran_reward/tow_retail_reward.iff")
local Utils = require(script.Parent.Parent.Utils) local function TestIntersectionOfPointAndTriangle2d(point, triA, triB, triC) local u, v, w = Utils.GetBarycentricCoordinates2d(point, triA, triB, triC) return u >= 0 and v >= 0 and w >= 0 end return TestIntersectionOfPointAndTriangle2d
unit_circle = {x = 0, y = 0, radius = 1, color = "black"} c = {x = 4, color = "green"} setmetatable(c, {__index = unit_circle}) assert(c.x == 4 and c.radius == 1)
PLUGIN.Title = "Helptext" PLUGIN.Description = "Hooks into plugins to send helptext" PLUGIN.Author = "#Domestos" PLUGIN.Version = V(1, 4, 0) PLUGIN.HasConfig = true PLUGIN.ResourceID = 676 function PLUGIN:Init() command.AddChatCommand("help", self.Object, "cmdHelp") self:LoadDefaultConfig() end function PLUGIN:LoadDefaultConfig() self.Config.Settings = self.Config.Settings or {} self.Config.Settings.UseCustomHelpText = self.Config.Settings.UseCustomHelpText or "false" self.Config.Settings.AllowHelpTextFromOtherPlugins = self.Config.Settings.AllowHelpTextFromOtherPlugins or "true" self.Config.CustomHelpText = self.Config.CustomHelpText or { "custom helptext", "custom helptext" } self:SaveConfig() end function PLUGIN:cmdHelp(player) if not player then return end if self.Config.Settings.UseCustomHelpText == "true" then for _, helptext in pairs(self.Config.CustomHelpText) do rust.SendChatMessage(player, helptext) end end if self.Config.Settings.AllowHelpTextFromOtherPlugins == "true" then plugins.CallHook("SendHelpText", util.TableToArray({player})) end end