content
stringlengths
5
1.05M
BigWigs:AddSounds("Ivanyr", { [196392] = "Long", [196562] = "Alarm", [196805] = "Info", }) BigWigs:AddSounds("Corstilax", { [195804] = "Info", [196068] = "Alarm", [196115] = "Alert", [220481] = "Alarm", }) BigWigs:AddSounds("General Xakal", { [197810] = "Alert", [212030] = "Alarm", ["dread_felbat"] = "Info", }) BigWigs:AddSounds("Naltira", { [-12687] = "Alarm", [200040] = "Alarm", [200284] = "Warning", [211543] = "Info", }) BigWigs:AddSounds("Advisor Vandros", { [202974] = "Info", [203176] = "Alert", [203882] = "Long", [220871] = "Alarm", }) BigWigs:AddSounds("The Arcway Trash", { [210750] = "Warning", [211115] = "Alarm", [211217] = "Warning", [211632] = "Alarm", [211745] = "Warning", [211757] = "Alarm", [226206] = "Alarm", [226285] = {"Alarm","Info","Warning"}, })
local World, super = Class(Object) function World:init(map) super:init(self) self.layers = { ["tiles"] = 0, ["objects"] = 1, ["below_soul"] = 100, ["soul"] = 200, ["above_soul"] = 300, ["below_bullets"] = 300, ["bullets"] = 400, ["above_bullets"] = 500, ["below_ui"] = 900, ["ui"] = 1000, ["above_ui"] = 1100 } -- states: GAMEPLAY, TRANSITION_OUT, TRANSITION_IN self.state = "GAMEPLAY" self.music = Music() self.map = Map(self) self.width = self.map.width * self.map.tile_width self.height = self.map.height * self.map.tile_height self.light = false self.camera = Camera(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) self.camera:setBounds() self.camera_attached = true self.shake_x = 0 self.shake_y = 0 self.player = nil self.soul = nil self.battle_borders = {} self.transition_fade = 0 self.transition_target = nil self.in_battle = false self.battle_alpha = 0 self.bullets = {} self.followers = {} self.cutscene = nil self.timer = Timer() self.timer.persistent = true self:addChild(self.timer) self.can_open_menu = true self.menu = nil if map then self:loadMap(map) end end function World:heal(target, amount) target:heal(amount) if self.healthbar then for _, actionbox in ipairs(self.healthbar.action_boxes) do if actionbox.chara.id == target.id then local text = HPText("+" .. amount, self.healthbar.x + actionbox.x + 69, self.healthbar.y + actionbox.y + 15) text.layer = self.layers.ui + 1 Game.world:addChild(text) return end end end end function World:hurtParty(amount) Assets.playSound("snd_hurt1") self.shake_x = 4 self.shake_y = 4 self:showHealthBars() local all_killed = true for _,party in ipairs(Game.party) do party.health = party.health - amount if party.health <= 0 then party.health = 1 else all_killed = false end for _,char in ipairs(self.stage:getObjects(Character)) do if char.actor and (char.actor.id == party.actor or char.actor.id == party.lw_actor) then char:statusMessage("damage", amount) end end end if self.player then self.player.hurt_timer = 7 end if all_killed then Game:gameOver(self.soul:getScreenPos()) end end function World:openMenu(menu) if self:hasCutscene() then return end if self.in_battle then return end if not self.can_open_menu then return end if self.menu then self.menu:remove() self.menu = nil end if not menu then if not self.light then self.menu = DarkMenu() else --error("TODO: Light world menu") print("TODO: Light world menu") end else self.menu = menu end if self.menu then self.state = "MENU" self.menu.layer = self.layers["ui"] self:addChild(self.menu) end return self.menu end function World:closeMenu() self.state = "GAMEPLAY" if self.menu then if not self.menu.animate_out and self.menu.transitionOut then self.menu:transitionOut() end end self:hideHealthBars() end function World:showHealthBars() if self.light then return end if self.healthbar then self.healthbar:transitionIn() else self.healthbar = HealthBar() self.healthbar.layer = self.layers["ui"] self:addChild(self.healthbar) end end function World:hideHealthBars() if self.healthbar then if not self.healthbar.animate_out then self.healthbar:transitionOut() end end end function World:keypressed(key) if Game.console.is_open then return end if Kristal.Config["debug"] then if key == "m" then if self.music then if self.music:isPlaying() then self.music:pause() else self.music:resume() end end end end if Game.lock_input then return end if self.state == "GAMEPLAY" then if Input.isConfirm(key) and self.player then self.player:interact() Input.consumePress("confirm") elseif Input.isMenu(key) then self:openMenu() Input.consumePress("menu") end elseif self.state == "MENU" then if self.menu and self.menu.keypressed then self.menu:keypressed(key) end end end function World:getCollision(enemy_check) local col = {} for _,collider in ipairs(self.map.collision) do table.insert(col, collider) end if enemy_check then for _,collider in ipairs(self.map.enemy_collision) do table.insert(col, collider) end end for _,child in ipairs(self.children) do if child.collider and child.solid then table.insert(col, child.collider) end end return col end function World:checkCollision(collider, enemy_check) Object.startCache() for _,other in ipairs(self:getCollision(enemy_check)) do if collider:collidesWith(other) then Object.endCache() return true, other.parent end end Object.endCache() return false end function World:hasCutscene() return self.cutscene and not self.cutscene.ended end function World:startCutscene(group, id, ...) if self.cutscene then error("Attempt to start a cutscene while already in a cutscene.") end self.cutscene = WorldCutscene(group, id, ...) return self.cutscene end function World:showText(text, after) if type(text) ~= "table" then text = {text} end self:startCutscene(function(cutscene) for _,line in ipairs(text) do cutscene:text(line) end if after then after(cutscene) end end) end function World:spawnPlayer(...) local args = {...} local x, y = 0, 0 local chara = self.player and self.player.actor if #args > 0 then if type(args[1]) == "number" then x, y = args[1], args[2] chara = args[3] or chara elseif type(args[1]) == "string" then x, y = self.map:getMarker(args[1]) chara = args[2] or chara end end if type(chara) == "string" then chara = Registry.getActor(chara) end local facing = "down" if self.player then facing = self.player.facing self:removeChild(self.player) end if self.soul then self:removeChild(self.soul) end self.player = Player(chara, x, y) self.player.layer = self.layers["objects"] self.player:setFacing(facing) self:addChild(self.player) self.soul = OverworldSoul(x + 10, y + 24) -- TODO: unhardcode self.soul.layer = self.layers["soul"] self:addChild(self.soul) if self.camera_attached then self.camera:lookAt(self.player.x, self.player.y - (self.player.height * 2)/2) self:updateCamera() end end function World:getActorForParty(chara) return self.light and chara.lw_actor or chara.actor end function World:getPartyCharacter(party) if type(party) == "string" then party = Registry.getPartyMember(party) end for _,char in ipairs(Game.stage:getObjects(Character)) do if char.actor and char.actor.id == self:getActorForParty(party) then return char end end end function World:removeFollower(chara) if type(chara) == "string" then chara = Registry.getActor(chara) end local follower_arg = isClass(chara) and chara:includes(Follower) for i,follower in ipairs(self.followers) do if (follower_arg and follower == chara) or (not follower_arg and follower.actor == chara) then table.remove(self.followers, i) for j,temp in ipairs(Game.temp_followers) do if temp == follower.actor.id or (type(temp) == "table" and temp[1] == follower.actor.id) then table.remove(Game.temp_followers, j) break end end return follower end end end function World:spawnFollower(chara, options) if type(chara) == "string" then chara = Registry.getActor(chara) end options = options or {} local follower if isClass(chara) and chara:includes(Follower) then follower = chara else follower = Follower(chara, self.player.x, self.player.y) follower.layer = self.layers["objects"] follower:setFacing(self.player.facing) end if options["x"] or options["y"] then local ex, ey = follower:getExactPosition() follower:setExactPosition(options["x"] or ex, options["y"] or ey) end if options["index"] then table.insert(self.followers, options["index"], follower) else table.insert(self.followers, follower) end if options["temp"] == false then if options["index"] then table.insert(Game.temp_followers, {follower.actor.id, options["index"]}) else table.insert(Game.temp_followers, follower.actor.id) end end self:addChild(follower) follower:updateIndex() return follower end function World:spawnParty(marker, party, extra) party = party or Game.party or {"kris"} if #party > 0 then if type(marker) == "table" then self:spawnPlayer(marker[1], marker[2], self:getActorForParty(party[1])) else self:spawnPlayer(marker or "spawn", self:getActorForParty(party[1])) end for i = 2, #party do local follower = self:spawnFollower(self:getActorForParty(party[i])) follower:setFacing(self.player.facing) end for _,actor in ipairs(extra or Game.temp_followers or {}) do if type(actor) == "table" then self:spawnFollower(actor[1], {index = actor[2]}) else self:spawnFollower(actor) end end end end function World:spawnBullet(bullet, ...) local new_bullet if isClass(bullet) and bullet:includes(WorldBullet) then new_bullet = bullet elseif Registry.getWorldBullet(bullet) then new_bullet = Registry.createWorldBullet(bullet, ...) else local x, y = ... table.remove(arg, 1) table.remove(arg, 1) new_bullet = WorldBullet(x, y, bullet, unpack(arg)) end new_bullet.layer = self.layers["bullets"] new_bullet.world = self table.insert(self.bullets, new_bullet) if not new_bullet.parent then self:addChild(new_bullet) end return new_bullet end function World:spawnNPC(actor, x, y, properties) return self:spawnObject(NPC(actor, x, y, properties)) end function World:spawnObject(obj, layer) obj.layer = self.layers[layer or "objects"] self:addChild(obj) return obj end function World:loadMap(map, ...) if self.map then self.map:unload() end for _,child in ipairs(self.children) do if not child.persistent then self:removeChild(child) end end self.followers = {} if isClass(map) then self.map = map elseif type(map) == "string" then self.map = Registry.createMap(map, self, ...) elseif type(map) == "table" then self.map = Map(self, map, ...) else self.map = Map(self, nil, ...) end self.map:load() self.light = self.map.light self.layers["objects"] = self.map.object_layer self.camera:setBounds(0, 0, self.map.width * self.map.tile_width, self.map.height * self.map.tile_height) if self.map.markers["spawn"] then local spawn = self.map.markers["spawn"] self.camera:lookAt(spawn.center_x, spawn.center_y) end self.battle_fader = Rectangle(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) self.battle_fader.layer = self.map.battle_fader_layer self:addChild(self.battle_fader) self:transitionMusic(self.map.music) self:updateCamera() end function World:transitionMusic(next, dont_play) if next and next ~= "" then if self.music.current ~= next then if self.music:isPlaying() then self.music:fade(0, 0.1, function() if not dont_play then self.music:play(next, 1) else self.music:stop() end end) elseif not dont_play then self.music:play(next, 1) end else if not self.music:isPlaying() then if not dont_play then self.music:play(next, 1) end else self.music:fade(1) end end else if self.music:isPlaying() then self.music:fade(0, 0.1, function() self.music:stop() end) end end end function World:transition(target) self.state = "TRANSITION_OUT" self.transition_target = Utils.copy(target or {}) if self.transition_target.map and type(self.transition_target.map) == "string" then local map = Registry.createMap(self.transition_target.map) self.transition_target.map = map self:transitionMusic(map.music, true) end end function World:transitionImmediate(target) if target.map then self:loadMap(target.map) end local pos if target.x and target.y then pos = {target.x, target.y} elseif target.marker then pos = target.marker end self:spawnParty(pos) end function World:getCameraTarget() return self.player:getRelativePos(self.player.width/2, self.player.height/2) end function World:updateCamera() if self.shake_x ~= 0 or self.shake_y ~= 0 then local last_shake_x = math.ceil(self.shake_x) local last_shake_y = math.ceil(self.shake_y) self.camera.ox = last_shake_x self.camera.oy = last_shake_y self.shake_x = Utils.approach(self.shake_x, 0, DTMULT) self.shake_y = Utils.approach(self.shake_y, 0, DTMULT) local new_shake_x = math.ceil(self.shake_x) if new_shake_x ~= last_shake_x then self.shake_x = self.shake_x * -1 end local new_shake_y = math.ceil(self.shake_y) if new_shake_y ~= last_shake_y then self.shake_y = self.shake_y * -1 end else self.camera.ox = 0 self.camera.oy = 0 end end function World:createTransform() local transform = super:createTransform(self) transform:apply(self.camera:getTransform(0, 0)) return transform end function World:sortChildren() Utils.pushPerformance("World#sortChildren") -- Sort children by Y position, or by follower index if it's a follower/player (so the player is always on top) Object.startCache() table.sort(self.children, function(a, b) local ax, ay = a:getRelativePos(a.width/2, a.height, self) local bx, by = b:getRelativePos(b.width/2, b.height, self) return a.layer < b.layer or (a.layer == b.layer and (math.floor(ay) < math.floor(by) or(math.floor(ay) == math.floor(by) and (b == self.player or (a:includes(Follower) and b:includes(Follower) and b.index < a.index))))) end) Object.endCache() Utils.popPerformance() end function World:onRemove(parent) super:onRemove(self, parent) self.music:remove() end function World:update(dt) if self.cutscene then if not self.cutscene.ended then self.cutscene:update(dt) end if self.cutscene.ended then self.cutscene = nil end end -- Fade transition if self.state == "TRANSITION_OUT" then self.transition_fade = Utils.approach(self.transition_fade, 1, dt / 0.25) if self.transition_fade == 1 then self:transitionImmediate(self.transition_target or {}) self.transition_target = nil self.state = "TRANSITION_IN" end elseif self.state == "TRANSITION_IN" then self.transition_fade = Utils.approach(self.transition_fade, 0, dt / 0.25) if self.transition_fade == 0 then self.state = "GAMEPLAY" end elseif self.state == "GAMEPLAY" then -- Object collision local collided = {} Object.startCache() for _,obj in ipairs(self.children) do if not obj.solid and obj.onCollide then for _,char in ipairs(self.stage:getObjects(Character)) do if obj:collidesWith(char) then if not obj:includes(OverworldSoul) then table.insert(collided, {obj, char}) end end end end end Object.endCache() for _,v in ipairs(collided) do v[1]:onCollide(v[2]) end end -- Keep camera in bounds self:updateCamera() if self.in_battle then self.battle_alpha = math.min(self.battle_alpha + (0.08 * DTMULT), 1) else self.battle_alpha = math.max(self.battle_alpha - (0.08 * DTMULT), 0) end local half_alpha = self.battle_alpha * 0.52 for _,v in ipairs(self.followers) do v.sprite:setColor(1 - half_alpha, 1 - half_alpha, 1 - half_alpha, 1) end for _,battle_border in ipairs(self.map.battle_borders) do if battle_border:includes(TileLayer) then battle_border.tile_opacity = self.battle_alpha else battle_border.alpha = self.battle_alpha end end if self.battle_fader then --self.battle_fader.layer = self.battle_border.layer - 1 self.battle_fader:setColor(0, 0, 0, half_alpha) local cam_x, cam_y = self.camera:getPosition() self.battle_fader.x = cam_x - 320 self.battle_fader.y = cam_y - 240 end self.map:update(dt) -- Always sort self.update_child_list = true super:update(self, dt) --[[if self.player then local bx, by = self.player:getRelativePos(self.player.width/2, self.player.height/2, self.soul.parent) self.soul.x = bx + 1 self.soul.y = by + 11 -- TODO: unhardcode offset (???) end]] end function World:draw() -- Draw background love.graphics.setColor(self.map.bg_color or {0, 0, 0, 0}) love.graphics.rectangle("fill", 0, 0, self.map.width * self.map.tile_width, self.map.height * self.map.tile_height) love.graphics.setColor(1, 1, 1) super:draw(self) self.map:draw() if DEBUG_RENDER then for _,collision in ipairs(self.map.collision) do collision:draw(0, 0, 1, 0.5) end for _,collision in ipairs(self.map.enemy_collision) do collision:draw(0, 1, 1, 0.5) end end -- Draw transition fade love.graphics.setColor(0, 0, 0, self.transition_fade) love.graphics.rectangle("fill", 0, 0, self.map.width * self.map.tile_width, self.map.height * self.map.tile_height) love.graphics.setColor(1, 1, 1) end return World
VolumeLaplacian = {} setmetatable(VolumeLaplacian, {__index = HiveBaseModule}) VolumeLaplacian.new = function (varname) local this = HiveBaseModule.new(varname) local vf = LoadModule("VolumeFilter") this.vf = vf setmetatable(this, {__index=VolumeLaplacian}) return this end function VolumeLaplacian:Do() self:UpdateValue() local v = self.value if (v.srcvolume == nil) then return "Invalid volume" end self.vf:Laplacian(v.srcvolume) return true end function VolumeLaplacian:volume() return self.vf:VolumeData() end
MaskMaterialModule = MaskMaterialModule or class(ItemModuleBase) MaskMaterialModule.type_name = "MaskMaterial" function MaskMaterialModule:init(...) self.clean_table = table.add(clone(self.clean_table), {{param = "pcs", action = "no_number_indexes" }}) self.required_params = table.add(clone(self.required_params), {"texture"}) return MaskMaterialModule.super.init(self, ...) end function MaskMaterialModule:RegisterHook() self._config.default_amount = self._config.default_amount and tonumber(self._config.default_amount) or 1 Hooks:PostHook(BlackMarketTweakData, "_init_materials", self._config.id .. "AddMaskMaterialData", function(bm_self) if bm_self.materials[self._config.id] then BeardLib:log("[ERROR] Mask Material with id '%s' already exists!", self._config.id) return end local data = table.merge({ name_id = "material_" .. self._config.id .. "_title", dlc = self.defaults.dlc, value = 0, global_value = self.defaults.global_value, custom = true }, self._config.item or self._config) bm_self.materials[self._config.id] = data if data.dlc then TweakDataHelper:ModifyTweak({{ type_items = "materials", item_entry = self._config.id, amount = self._config.default_amount, global_value = data.global_value }}, "dlc", data.dlc, "content", "loot_drops") end end) end BeardLib:RegisterModule(MaskMaterialModule.type_name, MaskMaterialModule)
--[[-- - MIT License - Copyright (c) 2020 NeilKleistGao - 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. - ]] --- @file camera_mover.lua CameraMover = class("CameraMover") function CameraMover:ctor() self._dis = 100 end function CameraMover:enter() self.move("Left") end function CameraMover:updateLeft(delta) pos = Camera:getCameraPosition() if self._dis > 0 then pos.x = pos.x - delta * 100 Camera:moveTo(pos) self._dis = self._dis - 1 else self._dis = 100 self.move("Right") end end function CameraMover:updateRight(delta) pos = Camera:getCameraPosition() if self._dis > 0 then pos.x = pos.x + delta * 100 Camera:moveTo(pos) self._dis = self._dis - 1 else self._dis = 100 self.move("Left") end end function CameraMover:exit() end
local XmlParser = require("examples.util.XmlParser"); local boner = require(LIBNAME); -- Debug local function print_r(t, func, i, found) func = func or print; i = i or 1; if (i == 1) then func("{"); end found = found or {}; local tabs = string.rep(" ", i); found[t] = true; for k, v in pairs(t) do if (type(v) == "table") then if (found[v]) then func(tabs .. tostring(k) .. " : <parent>"); else func(tabs .. tostring(k) .. " :"); func(tabs .. "{"); print_r(v, func, i + 1, found); func(tabs .. "}"); end else func(tabs .. tostring(k) .. " : " .. tostring(v)); end end if (i == 1) then func("}"); end end local function getDirectory(filename) local lastSlash = string.find(filename, "([^/])/[^/]+$"); local path = string.sub(filename, 1, lastSlash) or ""; if (string.sub(path, -1) ~= '/' or string.sub(path, -1) ~= '\\') then path = path .. "/"; end return path; end --[[ Demina XML file structure: Animation FrameRate : value=frameTime/sec LoopFrame : value=frameTime, default=-1 Texture : value=file ... KeyFrame : attrs={frame=frameTime,vflip=?,hflip=?,trigger=?} Bone : attrs={name=boneName} Hidden : ? TextureFlipHorizontal : ? TextureFlipVertical : ? ParentIndex : value=(childNode index of parent in KeyFrame, starting at 0. -1 means no parent.) TextureIndex : value=(textureNode index in Animation, starting at 0.) Position : X : value=x Y : value=y Rotation : value=angle Scale : X : value=x Y : value=y ... ]] local function ParseDeminaTextureDictionaryFile(xmlFile) local content, size = love.filesystem.read( xmlFile ); local xml = XmlParser:ParseXmlText(content); --[[local str = ""; print_r(xml, function(text) str = str .. text .. "\n"; end); love.filesystem.write("test.txt", str);]] if (xml.Name ~= "TextureDictionary") then print("Invalid dictionary file - root node must be of type 'TextureDictionary' - given '" .. xml.Name .. "'"); return; end local fileData = {}; for i = 1, #xml.ChildNodes do local node = xml.ChildNodes[i]; if (node.Name == "TexturePath") then fileData.image = love.graphics.newImage(getDirectory(xmlFile) .. node.Value); elseif (node.Name == "Texture") then local properties = { position = {0, 0}, dimensions = {0, 0}, origin = {0, 0} }; for j = 1, #node.ChildNodes do local prop = node.ChildNodes[j]; if (prop.Name == "X") then properties.position[1] = tonumber(prop.Value); elseif (prop.Name == "Y") then properties.position[2] = tonumber(prop.Value); elseif (prop.Name == "Width") then properties.dimensions[1] = tonumber(prop.Value); elseif (prop.Name == "Height") then properties.dimensions[2] = tonumber(prop.Value); elseif (prop.Name == "OriginX") then properties.origin[1] = tonumber(prop.Value); elseif (prop.Name == "OriginY") then properties.origin[2] = tonumber(prop.Value); end end fileData.quads = fileData.quads or {}; fileData.quads[node.Attributes.name] = properties; end end -- Now we have data in a nicer form. -- From here, we could load it as a skin, a return fileData; end local function RipBone(boneNode) local name = boneNode.Attributes.name; local parent = -1; local texture = -1; local position = {0,0}; local rotation = 0; local scale = {1,1}; for i = 1, #boneNode.ChildNodes do local node = boneNode.ChildNodes[i]; if (node.Name == "ParentIndex") then parent = node.Value; elseif (node.Name == "TextureIndex") then texture = node.Value; elseif (node.Name == "Position") then for _, v in pairs(node.ChildNodes) do if (v.Name == "X") then position[1] = tonumber(v.Value); elseif (v.Name == "Y") then position[2] = tonumber(v.Value); end end elseif (node.Name == "Scale") then for _, v in pairs(node.ChildNodes) do if (v.Name == "X") then scale[1] = tonumber(v.Value); elseif (v.Name == "Y") then scale[2] = tonumber(v.Value); end end elseif (node.Name == "Rotation") then rotation = tonumber(node.Value); end end local boneData = {}; boneData.boneName = name; boneData.parentIndex = parent + 1; boneData.textureIndex = texture + 1; boneData.rotation = rotation; boneData.position = position; boneData.scale = scale; return boneData; end local function RipKeyFrame(frameNode) local frameData = {}; frameData.bones = {}; frameData.frameTime = frameNode.Attributes.frame; if (frameNode.Attributes.trigger and string.len(frameNode.Attributes.trigger) > 0) then frameData.eventName = frameNode.Attributes.trigger end for i = 1, #frameNode.ChildNodes do local node = frameNode.ChildNodes[i]; if (node.Name == "Bone") then local data = RipBone(node); table.insert(frameData.bones, data); end end return frameData; end local function ParseDeminaFile(xmlFile) local content, size = love.filesystem.read( xmlFile ); local xml = XmlParser:ParseXmlText(content); --[[local str = ""; print_r(xml, function(text) str = str .. text .. "\n"; end); love.filesystem.write("test.txt", str);]] if (xml.Name ~= "Animation") then print("Invalid animation file - root node must be of type 'Animation' - given '" .. xml.Name .. "'"); return; end local dictionaryData = {}; local fileData = {}; fileData.frameRate = -1; fileData.loopFrame = -1; fileData.textures = {}; fileData.keyframes = {}; for i = 1, #xml.ChildNodes do local node = xml.ChildNodes[i]; if (node.Name == "FrameRate") then fileData.frameRate = node.Value; elseif (node.Name == "LoopFrame") then fileData.loopFrame = node.Value; elseif (node.Name == "Texture") then local texData = {}; if (node.Attributes.dictionary) then texData.dictionaryPath = getDirectory(xmlFile) .. node.Attributes.dictionary; end texData.dictionaryRefName = node.Attributes.name texData.imagePath = node.Value; if (texData and texData.dictionaryPath and not dictionaryData[texData.dictionaryPath]) then dictionaryData[texData.dictionaryPath] = ParseDeminaTextureDictionaryFile(texData.dictionaryPath); end table.insert(fileData.textures, texData); elseif (node.Name == "Keyframe") then table.insert(fileData.keyframes, RipKeyFrame(node)); end end fileData.textureDictionaries = dictionaryData; -- Now we have data in a nicer form. -- From here, we could load it as a skin, a return fileData; end --[[ Parsed Data Structure: fileData frameRate loopFrame textures filename ... keyframes frame frameTime bones boneName boneName parentIndex textureIndex position rotation scale ... ... How we will interpret these: Split into multiple files: skeleton.anim - Contains the skeleton in its bind pose. Used for validating animation and skin files. animation.anim - Contains an animation. skin.anim - Contains a skin. ]] local function MakeSkeleton(fileData) local skeleton = boner.newSkeleton(); local bindData = fileData.keyframes[1]; local layerData = {}; for boneIndex, boneData in ipairs(bindData.bones) do local name, parent, layer, offset, defaultRotation, defaultTranslation, defaultScale; name = boneData.boneName; layer = boneIndex; offset = boneData.position; defaultRotation = boneData.rotation; defaultTranslation = nil; defaultScale = nil; if (boneData.parentIndex >= 1) then parent = bindData.bones[boneData.parentIndex].boneName; end local bone = boner.newBone(parent, layer, offset, defaultRotation, defaultTranslation, defaultScale); skeleton:SetBone(name, bone); end skeleton:Validate(); --local bindAnim = boner.newAnimation("__bind__", skeleton); return skeleton; end local function MakeAnimation(fileData, skeleton) local anim = boner.newAnimation(skeleton); local firstFrame = {}; for frameIndex, frameData in ipairs(fileData.keyframes) do local boneName, keyTime, rotation, translation, scale; keyTime = frameData.frameTime / fileData.frameRate; if (frameData.eventName) then anim:AddEvent(keyTime, frameData.eventName); end for boneIndex, boneData in ipairs(frameData.bones) do boneName = boneData.boneName; rotation = boneData.rotation; translation = boneData.position; scale = boneData.scale; local xOffset, yOffset = skeleton:GetBone(boneName):GetOffset(); translation[1] = translation[1] - xOffset; translation[2] = translation[2] - yOffset; anim:AddKeyFrame(boneName, keyTime, rotation, translation, scale); if (not firstFrame[boneName]) then firstFrame[boneName] = {boneName, keyTime, rotation, translation, scale}; end end end for name, data in pairs(firstFrame) do local boneName, keyTime, rotation, translation, scale = unpack(data); keyTime = fileData.loopFrame / fileData.frameRate; anim:AddKeyFrame(boneName, keyTime, rotation, translation, scale); end return anim; end local function MakeSkin(fileData, texturePath, skeleton) local skin = {}; if (fileData.keyframes) then local bindData = fileData.keyframes[1]; for boneIndex, boneData in ipairs(bindData.bones) do local boneName, image, origin, quad, angle, scale; boneName = boneData.boneName; origin = {0, 0}; local texIndex = boneData.textureIndex; --print(texIndex, fileData.textures[texIndex]) if (texIndex and fileData.textures[texIndex]) then local texData = fileData.textures[texIndex]; if (texData.dictionaryPath) then local dict = fileData.textureDictionaries[texData.dictionaryPath]; local quadData = dict.quads[texData.dictionaryRefName]; local x, y = unpack(quadData.position); local width, height = unpack(quadData.dimensions); image = dict.image; quad = love.graphics.newQuad(x, y, width, height, image:getDimensions()); origin = quadData.origin; scale = quadData.scale; elseif (texData.imagePath) then texData.imagePath = string.gsub(texData.imagePath, "\\", "/"); image = love.graphics.newImage(texturePath .. texData.imagePath); origin = {image:getWidth()/2, image:getHeight()/2}; end end if (image) then angle = 0; scale = boneData.scale; local vis = boner.newVisual(image, quad); vis:SetOrigin(unpack(origin)); vis:SetRotation(angle); --vis:SetScale(scale); skin[boneName] = vis; end end end return skin; end local function ImportSkeleton(filename) local fileData = ParseDeminaFile(filename); return MakeSkeleton(fileData); end local function ImportAnimation(filename, skeleton) local fileData = ParseDeminaFile(filename); return MakeAnimation(fileData, skeleton); end local function ImportSkin(filename, skeleton) local fileData = ParseDeminaFile(filename); return MakeSkin(fileData, getDirectory(filename), skeleton); end return {ImportSkeleton = ImportSkeleton, ImportAnimation = ImportAnimation, ImportSkin = ImportSkin};
pg = pg or {} pg.CriMgr = singletonClass("CriMgr") pg.CriMgr.Category_CV = "Category_CV" pg.CriMgr.Category_BGM = "Category_BGM" pg.CriMgr.Category_SE = "Category_SE" pg.CriMgr.C_BGM = "C_BGM" pg.CriMgr.C_VOICE = "cv" pg.CriMgr.C_SE = "C_SE" pg.CriMgr.C_BATTLE_SE = "C_BATTLE_SE" pg.CriMgr.C_GALLERY_MUSIC = "C_GALLERY_MUSIC" pg.CriMgr.NEXT_VER = 40 pg.CriMgr.Init = function (slot0, slot1) print("initializing cri manager...") seriesAsync({ function (slot0) slot0:InitCri(slot0) end, function (slot0) slot1 = CueData.New() slot1.cueSheetName = "se-ui" slot1.channelName = slot0.C_SE CriWareMgr.Inst:LoadCueSheet(slot1, function (slot0) slot0() end, true) end, function (slot0) slot1 = CueData.New() slot1.cueSheetName = "se-battle" slot1.channelName = slot0.C_BATTLE_SE CriWareMgr.Inst:LoadCueSheet(slot1, function (slot0) slot0() end, true) end }, slot1) end pg.CriMgr.InitCri = function (slot0, slot1) slot0.criInitializer = GameObject.Find("CRIWARE").GetComponent(slot2, typeof(CriWareInitializer)) slot0.criInitializer.fileSystemConfig.numberOfLoaders = 128 slot0.criInitializer.manaConfig.numberOfDecoders = 128 slot0.criInitializer.atomConfig.useRandomSeedWithTime = true slot0.criInitializer:Initialize() CriWareMgr.Inst:Init(function () CriAtom.SetCategoryVolume(slot0.Category_CV, slot1:getCVVolume()) CriAtom.SetCategoryVolume(slot0.Category_SE, slot1:getSEVolume()) CriAtom.SetCategoryVolume(slot0.Category_BGM, slot1:getBGMVolume()) CriWareMgr.Inst:RemoveChannel("C_VOICE") Object.Destroy(GameObject.Find("CRIWARE/C_VOICE")) CriWareMgr.Inst:CreateChannel(slot0.C_VOICE, CriWareMgr.CRI_CHANNEL_TYPE.MULTI_NOT_REPEAT) CriWareMgr.C_VOICE = slot0.C_VOICE CriWareMgr.Inst:CreateChannel(slot0.C_GALLERY_MUSIC, CriWareMgr.CRI_CHANNEL_TYPE.SINGLE) CriWareMgr.Inst:GetChannelData(slot0.C_BGM).channelPlayer.loop = true slot0.C_BGM() end) slot0.typeNow = nil slot0.bgmNow = nil slot0.lastNormalBGMName = nil end pg.CriMgr.SetTypeBGM = function (slot0, slot1, slot2) slot0.typeNow = slot2 slot0.bgmNow = slot1 if not slot2 then slot0.lastNormalBGMName = slot1 end end pg.CriMgr.ResumeLastNormalBGM = function (slot0) if slot0.lastNormalBGMName then slot0:PlayBGM(slot0.lastNormalBGMName) end end pg.CriMgr.PlayBGM = function (slot0, slot1, slot2) slot0:SetTypeBGM(slot1, slot2) if slot0.bgmName == "bgm-" .. slot1 then return elseif slot0.bgmName ~= nil and slot0.bgmPlaybackInfo == nil then slot0:UnloadCueSheet(slot0.bgmName) end slot0.bgmName = slot3 slot0.bgmPlaybackInfo = nil slot4 = nil if slot0.NEXT_VER <= CSharpVersion then slot4 = CriWareMgr.Inst:GetChannelData(slot0.C_BGM).curCueDataKey end CriWareMgr.Inst:PlayBGM(slot3, CriWareMgr.CRI_FADE_TYPE.FADE_INOUT, function (slot0) if slot0 == nil then warning("Missing BGM :" .. (slot0 or "NIL")) else slot1.bgmPlaybackInfo = slot0 end end) if slot0.NEXT_VER <= CSharpVersion and slot4 ~= nil then CriWareMgr.Inst.GetChannelData(slot5, slot0.C_BGM).curCueDataKey = slot4 end end pg.CriMgr.StopBGM = function (slot0, slot1) CriWareMgr.Inst:StopBGM(CriWareMgr.CRI_FADE_TYPE.FADE_INOUT) slot0.bgmPlaybackInfo = nil slot0.bgmName = nil end pg.CriMgr.LoadCV = function (slot0, slot1, slot2) slot0:LoadCueSheet(slot0.GetCVBankName(slot1), slot2) end pg.CriMgr.LoadBattleCV = function (slot0, slot1, slot2) slot0:LoadCueSheet(slot0.GetBattleCVBankName(slot1), slot2) end pg.CriMgr.UnloadCVBank = function (slot0) slot0.GetInstance():UnloadCueSheet(slot0) end pg.CriMgr.GetCVBankName = function (slot0) return "cv-" .. slot0 end pg.CriMgr.GetBattleCVBankName = function (slot0) return "cv-" .. slot0 .. "-battle" end pg.CriMgr.CheckFModeEvent = function (slot0, slot1, slot2, slot3) if not slot1 then return end string.gsub(slot1, "event:/cv/(.+)/(.+)", function (slot0, slot1) slot0 = "cv-" .. slot0 .. ((tobool(ShipWordHelper.CVBattleKey[string.gsub(slot1, "_%w+", "")]) and "-battle") or "") slot1 = slot1 end) string.gsub(slot1, "event:/tb/(.+)/(.+)", function (slot0, slot1) slot0 = "tb-" .. slot0 slot1 = slot1 end) if nil and slot5 then slot2(slot4, slot5) else slot3(string.gsub(string.gsub(slot1, "event:/(battle)/(.+)", "%1-%2"), "event:/(ui)/(.+)", "%1-%2")) end end pg.CriMgr.CheckHasCue = function (slot0, slot1, slot2) return CriAtom.GetCueSheet(slot1) ~= nil and slot3.acb:Exists(slot2) end pg.CriMgr.PlaySoundEffect_V3 = function (slot0, slot1, slot2) slot0:CheckFModeEvent(slot1, function (slot0, slot1) slot0:PlayCV_V3(slot0, slot1, slot1) end, function (slot0) slot0:PlaySE_V3(slot0, slot0.PlaySE_V3) end) end pg.CriMgr.StopSoundEffect_V3 = function (slot0, slot1) slot0:CheckFModeEvent(slot1, function (slot0, slot1) slot0:StopCV_V3() end, function (slot0) slot0:StopSE_V3() end) end pg.CriMgr.UnloadSoundEffect_V3 = function (slot0, slot1) slot0:CheckFModeEvent(slot1, function (slot0, slot1) slot0:UnloadCueSheet(slot0) end, function (slot0) slot0:StopSE_V3() end) end pg.CriMgr.PlayCV_V3 = function (slot0, slot1, slot2, slot3) CriWareMgr.Inst:PlayVoice(slot2, CriWareMgr.CRI_FADE_TYPE.NONE, slot1, function (slot0) if slot0 ~= nil then slot0(slot0) end end) end pg.CriMgr.StopCV_V3 = function (slot0) CriWareMgr.Inst:GetChannelData(slot0.C_VOICE).channelPlayer:Stop() end pg.CriMgr.PlaySE_V3 = function (slot0, slot1, slot2) if CriAtom.GetCueSheet("se-ui") and slot3.acb and slot3.acb:Exists(slot1) then CriWareMgr.Inst:PlaySE(slot1, nil, function (slot0) if slot0 ~= nil then slot0(slot0) end end) end if CriAtom.GetCueSheet("se-battle") and slot4.acb and slot4.acb.Exists(slot5, slot1) then CriWareMgr.Inst:PlayBattleSE(slot1, nil, function (slot0) if slot0 ~= nil then slot0(slot0) end end) end end pg.CriMgr.StopSE_V3 = function (slot0) CriWareMgr.Inst:GetChannelData(slot0.C_SE).channelPlayer:Stop() CriWareMgr.Inst:GetChannelData(slot0.C_BATTLE_SE).channelPlayer:Stop() end pg.CriMgr.StopSEBattle_V3 = function (slot0) CriWareMgr.Inst:GetChannelData(slot0.C_BATTLE_SE).channelPlayer:Stop() end pg.CriMgr.LoadCueSheet = function (slot0, slot1, slot2) CueData.New().cueSheetName = slot1 CriWareMgr.Inst:LoadCueSheet(CueData.New(), function (slot0) slot0(slot0) end, true) end pg.CriMgr.UnloadCueSheet = function (slot0, slot1) CriWareMgr.Inst:UnloadCueSheet(slot1) end pg.CriMgr.getCVVolume = function (slot0) return PlayerPrefs.GetFloat("cv_vol", DEFAULT_CVVOLUME) end pg.CriMgr.setCVVolume = function (slot0, slot1) PlayerPrefs.SetFloat("cv_vol", slot1) CriAtom.SetCategoryVolume(slot0.Category_CV, slot1) end pg.CriMgr.getBGMVolume = function (slot0) return PlayerPrefs.GetFloat("bgm_vol", DEFAULT_BGMVOLUME) end pg.CriMgr.setBGMVolume = function (slot0, slot1) PlayerPrefs.SetFloat("bgm_vol", slot1) CriAtom.SetCategoryVolume(slot0.Category_BGM, slot1) end pg.CriMgr.getSEVolume = function (slot0) return PlayerPrefs.GetFloat("se_vol", DEFAULT_SEVOLUME) end pg.CriMgr.setSEVolume = function (slot0, slot1) PlayerPrefs.SetFloat("se_vol", slot1) CriAtom.SetCategoryVolume(slot0.Category_SE, slot1) end return
data:extend({{ type = "technology", name = "electric-energy-power-decoupler", icon_size = 128, icon = "__power-decoupler__/graphics/technology/fast-accu-tech.png", localised_name = {"technology-name.electric-energy-power-decoupler"}, effects = { { type = "unlock-recipe", recipe = "power-decoupler" } }, prerequisites = {"electric-energy-accumulators"}, unit = { count = 300, ingredients = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"utility-science-pack", 1} }, time = 30 } }})
local BetViewCtr = class("BetViewCtr",cc.load("boyaa").mvc.BoyaaCtr); local DeskView = require("app.demo.DowneyTang.DeskView.DeskView") local DeskViewConfig = require("app.demo.DowneyTang.DeskView.DeskViewConfig") local DeskViewBehavior = require("app.demo.DowneyTang.DeskView.DeskViewBehavior") local BigChipView = require("app.demo.DowneyTang.BigChipView.BigChipView") function BetViewCtr:ctor() print("BetViewCtr"); end function BetViewCtr:initView(isBehavior) --【创建牌桌,添加组件划分不同的触摸区域】 local newDeskView = DeskView.new(); if isBehavior == 1 then newDeskView:bindBehavior(DeskViewBehavior); elseif isBehavior == 2 then newDeskView:bindBehavior(DeskViewObserverBehavior); end newDeskView:bindCtr(self); local spaceMap = DeskViewConfig:getSpaceMap() newDeskView:addTouchSpace(spaceMap) newDeskView:setScale(0.5) newDeskView:setPosition(600,420) --【创建大筹码】 local newBigChipView = BigChipView.new() newDeskView:bindCtr(self); newBigChipView:setScale(0.6) newBigChipView:setPosition(600,100) local node = cc.Node:create(); newDeskView:addTo(node) newBigChipView:addTo(node) self:setView(node) end function BetViewCtr:registeredTest() -- body self:bindEventListener(EvenConfig.TestEven,function (event) -- body self:getView():showDiyView(event._usedata.str); end) end function BetViewCtr:schedulerTest() -- body self.sd = self:scheduler(function () -- body self:getView():showSchedulerTestView(self.con); self.con = self.con +1; end,0.5,false); end function BetViewCtr:unSchedulerTest() -- body print("====unSchedulerTest======") self:unScheduler(self.sd); end function BetViewCtr:sendEven() -- body self:sendEvenData(EvenConfig.TestEven,{str = "我是自定义事件"}); end return BetViewCtr;
local LineEmitter = require('../lib/emitter').LineEmitter local exports = {} exports['test_line_emitter_single_chunk'] = function(test, asserts) local count = 0 local lines = {'test1', 'test2', 'test3', 'test4'} local le = LineEmitter:new() le:on('data', function(line) count = count + 1 asserts.equals(line, lines[count]) if count == 4 then test.done() end end) le:write('test1\ntest2\ntest3\ntest4\n') end exports['test_line_emitter_multiple_chunks'] = function(test, asserts) local count = 0 local lines = {'test1', 'test2', 'test3', 'test4', 'test5'} local le = LineEmitter:new() le:on('data', function(line) count = count + 1 asserts.equals(line, lines[count]) if count == 5 then test.done() end end) le:write('test1\n') le:write('test2\n') le:write('test3\n') le:write('test4\ntest5') le:write('\n') end return exports
function Gromtor_OnEnterCombat(Unit,Event) Unit:FullCastSpellOnTarget(26281,Unit:GetClosestPlayer()) Unit:RegisterEvent("Gromtor_SunderArmor", 120000, 0) Unit:RegisterEvent("Gromtor_ShieldWall", 22000, 0) Unit:RegisterEvent("Gromtor_ShieldBlock", 40000, 0) Unit:RegisterEvent("Gromtor_HeroicStrike", 4000, 0) Unit:RegisterEvent("Gromtor_BattleShout", 240000, 0) end function Gromtor_SunderArmor(Unit,Event) Unit:FullCastSpellOnTarget(16145,Unit:GetClosestPlayer()) end function Gromtor_ShieldWall(Unit,Event) Unit:FullCastSpellOnTarget(15062,Unit:GetClosestPlayer()) end function Gromtor_ShieldBlock(Unit,Event) Unit:FullCastSpellOnTarget(12169,Unit:GetClosestPlayer()) end function Gromtor_HeroicStrike(Unit,Event) Unit:FullCastSpellOnTarget(29426,Unit:GetClosestPlayer()) end function Gromtor_BattleShout(Unit,Event) Unit:FullCastSpellOnTarget(31403,Unit:GetClosestPlayer()) end function Gromtor_OnLeaveCombat(Unit,Event) Unit:RemoveEvents() end function Gromtor_OnDied(Unit,Event) Unit:RemoveEvents() end RegisterUnitEvent(21291, 1, "Gromtor_OnEnterCombat") RegisterUnitEvent(21291, 2, "Gromtor_OnLeaveCombat") RegisterUnitEvent(21291, 4, "Gromtor_OnDied")
local GameBase = require "GameBase" local GameMetroid = GameBase:new() function GameMetroid:new(o, id, next_id, session) o = o or GameBase:new(o) setmetatable(o, self) self.__index = self self.id = id self.next_id = next_id self.name = "metroid" self.full_name = "Metroid" self.item_check_loc = 0x7FF0 self.items = {} local gear = { { "Bombs", 0x01 }, { "High Jump Boots", 0x02 }, { "Long Beam", 0x04 }, { "Screw Attack", 0x08 }, { "Morph Ball", 0x10 }, { "Varia Suit", 0x20 }, { "Wave Beam", 0x40 }, { "Ice Beam", 0x80 } } for i,w in pairs(gear) do local item = { id=i, name=w[1], loc=0x6878, val=w[2], is_owned=false, update_func="or" } self:create_item_from_session(session, item) end return o end function GameMetroid.warp_check() return memory.readbyte(0x4F) == 0x0E and memory.readbyte(0x50) == 0x01 and memory.readbyte(0x52) >= 0xDD and memory.readbyte(0x51) < 0x50 end function GameMetroid.pre_save() -- set state to samus intro memory.writebyte(0x1E, 0x00) -- advance 4 frames so that the samus intro kicks in before the combo checks emu.frameadvance() emu.frameadvance() emu.frameadvance() emu.frameadvance() end return GameMetroid
--Script made by Diemiers#4209-Qwerty#9972 --Method by Roblox local v =96000000 --Maximal bit stream on client -- (96000000 - 12) -- Maximal bit stream that server accept +-2 local msg = ""..string.rep(" ",(v - 12)) game.Players:Chat(msg)
local theme={colors={normal={blue={0.21176470588235,0.63137254901961,0.4,1},green={0.49019607843137,0.5921568627451,0.14901960784314,1},cyan={0.35686274509804,0.6156862745098,0.28235294117647,1},white={0.57254901960784,0.56862745098039,0.50588235294118,1},red={0.72941176470588,0.3843137254902,0.21176470588235,1},magenta={0.37254901960784,0.56862745098039,0.50980392156863,1},black={0.13333333333333,0.13333333333333,0.10588235294118,1},yellow={0.64705882352941,0.59607843137255,0.050980392156863,1}},primary={background={0.13333333333333,0.13333333333333,0.10588235294118,1},foreground={0.57254901960784,0.56862745098039,0.50588235294118,1}},bright={blue={0.52941176470588,0.52156862745098,0.45098039215686,1},green={0.18823529411765,0.1843137254902,0.15294117647059,1},cyan={0.6156862745098,0.42352941176471,0.48627450980392,1},white={0.95686274509804,0.95294117647059,0.92549019607843,1},red={0.68235294117647,0.45098039215686,0.074509803921569,1},magenta={0.90588235294118,0.90196078431373,0.87450980392157,1},black={0.42352941176471,0.41960784313725,0.35294117647059,1},yellow={0.37254901960784,0.36862745098039,0.30588235294118,1}},cursor={text={0.13333333333333,0.13333333333333,0.10588235294118,1},cursor={0.57254901960784,0.56862745098039,0.50588235294118,1}}}} return theme.colors
-------------------------------------------------------------------------------- -- autogen.lua, v0.3.1: has codes in strings for autogenerating CRUDS based on sailor models -- This file is a part of Sailor project -- Copyright (c) 2014 Etiene Dalcol <[email protected]> -- License: MIT -- http://sailorproject.org -------------------------------------------------------------------------------- local lfs = require "lfs" local M = {} --The code for the autogen page function M.gen() local code = [[ <?lua local model = require "sailor.model" local mogelgen = false local crudgen = false if next(page.POST) then if page.POST.table_name then modelgen = model.generate_model(page.POST.table_name) end if page.POST.model_name then crudgen = model.generate_crud(page.POST.model_name) end end ?> <h2>Generate model</h2> <form method="post"> <input type=text placeholder="Table Name..." name="table_name"/> <input type="submit" /> </form> <?lua if modelgen then ?> Model generated with success! <?lua end ?> <br/><br/> <h2>Generate CRUD</h2> <form method="post"> <input type=text placeholder="Model Name..." name="model_name"/> <input type="submit" /> </form> <?lua if crudgen then ?> CRUD generated with success! <?lua end ?> ]] return code end -- The code for the generated controller -- model: the model from which the generated CRUD will refer to function M.generate_controller(model) local code = [[ local M = {} function M.index(page) local ]]..model["@name"]..[[s = require "sailor.model"("]]..model["@name"]..[["):find_all() page:render('index',{]]..model["@name"]..[[s = ]]..model["@name"]..[[s}) end function M.create(page) local ]]..model["@name"]..[[ = require "sailor.model"("]]..model["@name"]..[["):new() local saved if next(page.POST) then ]]..model["@name"]..[[:get_post(page.POST) saved = ]]..model["@name"]..[[:save() if saved then page:redirect(']]..model["@name"]..[[/index') end end page:render('create',{]]..model["@name"]..[[ = ]]..model["@name"]..[[, saved = saved}) end function M.update(page) local ]]..model["@name"]..[[ = require "sailor.model"("]]..model["@name"]..[["):find_by_id(page.GET.id) if not ]]..model["@name"]..[[ then return 404 end local saved if next(page.POST) then ]]..model["@name"]..[[:get_post(page.POST) saved = ]]..model["@name"]..[[:update() if saved then page:redirect(']]..model["@name"]..[[/index') end end page:render('update',{]]..model["@name"]..[[ = ]]..model["@name"]..[[, saved = saved}) end function M.view(page) local ]]..model["@name"]..[[ = require "sailor.model"("]]..model["@name"]..[["):find_by_id(page.GET.id) if not ]]..model["@name"]..[[ then return 404 end page:render('view',{]]..model["@name"]..[[ = ]]..model["@name"]..[[}) end function M.delete(page) local ]]..model["@name"]..[[ = require "sailor.model"("]]..model["@name"]..[["):find_by_id(page.GET.id) if not ]]..model["@name"]..[[ then return 404 end if ]]..model["@name"]..[[:delete() then page:redirect(']]..model["@name"]..[[/index') end end return M ]] local file = assert(io.open("controllers/"..model["@name"]..".lua", "w")) if file:write(code) then file:close() return true end return false end -- The code for the generated index page of the CRUD -- model: the model from which the generated CRUD will refer to function M.generate_index(model) local code = [[ <style&gt; .table td { cursor: pointer; } </style&gt; <h2&gt;View all</h2&gt; <table class="table"&gt; <tr&gt; ]] for _,attributes in pairs (model.attributes) do for attr in pairs(attributes) do code = code .. [[ <th&gt;]] .. attr .. [[</th&gt; ]] end end code = code .. [[ </tr&gt; <?lua for k,v in pairs(]]..model["@name"]..[[s) do ?&gt; <tr onclick="location.href='<%= page:make_url(']]..model["@name"]..[[/view',{id = v.id}) %&gt;'" &gt; ]] for _,attributes in pairs (model.attributes) do for attr in pairs(attributes) do code = code .. [[ <td&gt; <%= v.]]..attr..[[ %&gt; </td&gt; ]] end end code = code ..[[ </tr&gt; <?lua end ?&gt; </table&gt; <br/&gt; <a href="<%= page:make_url(']]..model["@name"]..[[/create') %&gt;" class="btn btn-primary"&gt;Create new ]]..model["@name"]..[[</a&gt; ]] code = string.gsub(code,"&gt;",">") lfs.mkdir("views/"..model["@name"]) local file = assert(io.open("views/"..model["@name"].."/index.lp", "w")) if file:write(code) then file:close() return true end return false end -- The code for the generated read page of the CRUD -- model: the model from which the generated CRUD will refer to function M.generate_view(model) local code = [[ <h2&gt; View ]]..model["@name"]..[[ #<%= ]]..model["@name"]..[[.id %&gt; <small>(<a href="<%= page:make_url(']]..model["@name"]..[[/update', {id = ]]..model["@name"]..[[.id} ) %&gt;" >update</a&gt;)</small&gt; <small>(<a href="<%= page:make_url(']]..model["@name"]..[[/delete', {id = ]]..model["@name"]..[[.id} ) %&gt;" >delete</a&gt;)</small&gt; </h2&gt; <table class="table"&gt; ]] for _,attributes in pairs (model.attributes) do for attr in pairs(attributes) do code = code .. [[ <tr&gt;<td&gt;]]..attr..[[</td&gt;<td&gt;<%= ]]..model["@name"].."."..attr..[[ %&gt; </td&gt;</tr&gt; ]] end end code = code ..[[ </table&gt; <br/&gt; <a href="<%= page:make_url(']]..model["@name"]..[[/index') %&gt;"&gt;<- Back to View All</a&gt; ]] code = string.gsub(code,"&gt;",">") local file = assert(io.open("views/"..model["@name"].."/view.lp", "w")) if file:write(code) then file:close() return true end return false end -- The code for the generated create page of the CRUD -- model: the model from which the generated CRUD will refer to function M.generate_create(model) local code = [[ <?lua local form = require "sailor.form" ?&gt; <h2&gt;Create ]]..model["@name"]..[[</h2&gt; <?lua if saved == false then ?&gt; There was an error while saving. <?lua end ?&gt; <form method="post"&gt; ]] for _,attributes in pairs (model.attributes) do for attr in pairs(attributes) do code = code ..[[ <div class="form-group"&gt; <label&gt;]]..attr..[[:</label&gt; <%= form.text(]]..model["@name"]..",'"..attr..[[', 'class="form-control" placeholder="]]..attr..[["') %&gt; <span class="help-block"&gt; <%= ]]..model["@name"]..".errors."..attr..[[ or '' %&gt; </span&gt; </div&gt; ]] end end code = code ..[[ <input type="submit" class="btn btn-primary"/&gt; </form&gt; <br/&gt; <a href="<%= page:make_url(']]..model["@name"]..[[/index') %&gt;"&gt;<- Back to View All</a&gt; ]] code = string.gsub(code,"&gt;",">") local file = assert(io.open("views/"..model["@name"].."/create.lp", "w")) if file:write(code) then file:close() return true end return false end -- The code for the generated update page of the CRUD -- model: the model from which the generated CRUD will refer to function M.generate_update(model) local code = [[ <?lua local form = require "sailor.form" ?&gt; <h2&gt;Update ]]..model["@name"]..[[</h2&gt; <?lua if saved == false then ?&gt; There was an error while saving. <?lua end ?&gt; <form method="post"&gt; ]] for _,attributes in pairs (model.attributes) do for attr in pairs(attributes) do code = code ..[[ <div class="form-group"&gt; <label&gt;]]..attr..[[:</label&gt; <%= form.text(]]..model["@name"]..",'"..attr..[[', 'class="form-control" placeholder="]]..attr..[["') %&gt; </div&gt; ]] end end code = code ..[[ <input type="submit" class="btn btn-primary"/&gt; </form&gt; <br/&gt; <a href="<%= page:make_url(']]..model["@name"]..[[/index') %&gt;"&gt;<- Back to View All</a&gt; ]] code = string.gsub(code,"&gt;",">") local file = assert(io.open("views/"..model["@name"].."/update.lp", "w")) if file:write(code) then file:close() return true end return false end return M
----------------------------------- -- Area: Bastok Markets -- NPC: Umberto -- Type: Quest NPC -- Involved in Quest: Too Many Chefs -- !pos -56.896 -5 -134.267 235 ----------------------------------- local ID = require("scripts/zones/Bastok_Markets/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCharVar("TOO_MANY_CHEFS") == 5) then -- end Quest Too Many Chefs player:startEvent(473); else player:startEvent(411); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 473) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,5674); else player:addItem(5674); player:messageSpecial(ID.text.ITEM_OBTAINED,5674); player:addFame(BASTOK,30); player:setCharVar("TOO_MANY_CHEFS",0); player:completeQuest(BASTOK,tpz.quest.id.bastok.TOO_MANY_CHEFS); end end end;
local snax = require 'skynet.snax' return { post = function(self) if lwf.auth.user == 'Guest' then ngx.print(_('You are not logined!')) return end ngx.req.read_body() local post = ngx.req.get_post_args() assert(post.device and post.output and post.value) local cloud = snax.queryservice('cloud') local info = { device = post.device, output = post.output, value = post.value } cloud.post.output_to_device(post.id or "FromWeb-"..lwf.auth.user, info) ngx.print(_('Device output fired!')) end, }
require 'hdf5' require 'torch' include '../utils/shortcut.lua' require 'deptreeutils' require 'sorthdf5' local function getOpts() local cmd = torch.CmdLine() cmd:text('== convert dependency trees to hdf5 format ==') cmd:text() cmd:text('Options:') cmd:option('--dataset', '', 'the resulting dataset (.h5)') cmd:option('--sort', 0, '0: no sorting of the training data; -1: sort training data by their length; k (k > 0): sort the consecutive k batches by their length') cmd:option('--batchSize', 64, 'batch size when --sort > 0 or --sort == -1') return cmd:parse(arg) end local function main() local opts = getOpts() local dataPrefix = opts.dataset:sub(1, -4) local vocabPath = dataPrefix .. '.vocab.t7' if opts.sort ~= 0 then assert(opts.sort == -1 or opts.sort > 0, 'valid values [0, -1, > 0]') print '========begin to sort dataset========' local h5sorter = nil local mid = opts.sort == -1 and 'sort' or string.format('sort%d', opts.sort) local h5sortFile = opts.dataset:sub(1, -4) .. string.format('.%s.h5', mid) local h5sortVocabFile = opts.dataset:sub(1, -4) .. string.format('.%s.vocab.t7', mid) local cmd = string.format('cp %s %s', vocabPath, h5sortVocabFile) print(cmd) os.execute(cmd) h5sorter = SortHDF5(opts.dataset, h5sortFile) h5sorter:sortHDF5(opts.sort, opts.batchSize) printf('save dataset to %s\n', h5sortFile) end end main()
local M = {} local fmt = string.format ---@class DebugOpts ---@field logging boolean ---@class GroupOptions ---@field toggle_hidden_on_enter boolean re-open hidden groups on bufenter ---@class GroupOpts ---@field options GroupOptions ---@field items Group[] ---@class BufferlineOptions ---@field public view string ---@field public debug DebugOpts ---@field public numbers string ---@field public number_style numbers_opt ---@field public buffer_close_icon string ---@field public modified_icon string ---@field public close_icon string ---@field public close_command string ---@field public custom_filter fun(buf: number, bufnums: number[]): boolean ---@field public left_mouse_command string | function ---@field public right_mouse_command string | function ---@field public middle_mouse_command string | function ---@field public indicator_icon string ---@field public left_trunc_marker string ---@field public right_trunc_marker string ---@field public separator_style string ---@field public name_formatter fun(path: string):string ---@field public tab_size number ---@field public max_name_length number ---@field public mappings boolean DEPRECATED ---@field public show_buffer_icons boolean ---@field public show_buffer_close_icons boolean ---@field public show_close_icon boolean ---@field public show_tab_indicators boolean ---@field public enforce_regular_tabs boolean ---@field public always_show_bufferline boolean ---@field public persist_buffer_sort boolean ---@field public max_prefix_length number ---@field public sort_by string ---@field public diagnostics boolean ---@field public diagnostics_indicator function? ---@field public diagnostics_update_in_insert boolean ---@field public offsets table[] ---@field public groups GroupOpts ---@class BufferlineHLGroup ---@field guifg string ---@field guibg string ---@field guisp string ---@field gui string ---@field hl string ---@field hl_name string ---@alias BufferlineHighlights table<string, BufferlineHLGroup> ---@class BufferlineConfig ---@field public options BufferlineOptions ---@field public highlights BufferlineHighlights ---@field private original BufferlineConfig original copy of user preferences --- Convert highlights specified as tables to the correct existing colours ---@param highlights BufferlineHighlights local function convert_highlights(highlights) if not highlights or vim.tbl_isempty(highlights) then return {} end -- we deep copy the highlights table as assigning the attributes -- will only pass the references so will mutate the original table otherwise local updated = vim.deepcopy(highlights) for hl, attributes in pairs(highlights) do for attribute, value in pairs(attributes) do if type(value) == "table" then if value.highlight and value.attribute then updated[hl][attribute] = require("bufferline.colors").get_hex({ name = value.highlight, attribute = value.attribute, }) else updated[hl][attribute] = nil require("bufferline.utils").echomsg( string.format("removing %s as it is not formatted correctly", hl), "WarningMsg" ) end end end end return updated end ---The local class instance of the merged user's configuration ---this includes all default values and highlights filled out ---@type BufferlineConfig local config = {} ---The class definition for the user configuration ---@type BufferlineConfig local Config = {} function Config:new(o) assert(o, "User options must be passed in") self.__index = self -- save a copy of the user's preferences so we can reference exactly what they -- wanted after the config and defaults have been merged. Do this using a copy -- so that reference isn't unintentionally mutated self.original = vim.deepcopy(o) setmetatable(o, self) return o end ---Combine user preferences with defaults preferring the user's own settings ---@param defaults BufferlineConfig ---@return BufferlineConfig function Config:merge(defaults) assert(defaults and type(defaults) == "table", "A valid config table must be passed to merge") self.options = vim.tbl_deep_extend("keep", self.options or {}, defaults.options or {}) self.highlights = vim.tbl_deep_extend( "force", defaults.highlights, -- convert highlight link syntax to resolved highlight colors convert_highlights(self.original.highlights) ) return self end local deprecations = { mappings = { message = "please refer to the BufferLineGoToBuffer section of the README", pending = false, }, number_style = { message = "please specify 'numbers' as a function instead. See :h bufferline-numbers for details", pending = true, }, } ---@param options BufferlineOptions local function handle_deprecations(options) if not options then return end for key, _ in pairs(options) do local deprecation = deprecations[key] if deprecation then vim.schedule(function() local timeframe = deprecation.pending and "will be" or "has been" vim.notify( fmt("'%s' %s deprecated: %s", key, timeframe, deprecation.message), vim.log.levels.WARN ) end) end end end ---Ensure the user has only specified highlight groups that exist ---@param defaults BufferlineConfig function Config:validate(defaults) handle_deprecations(self.options) if self.highlights then local incorrect = {} for k, _ in pairs(self.highlights) do if not defaults.highlights[k] then table.insert(incorrect, k) end end -- Don't continue if there are no incorrect highlights if vim.tbl_isempty(incorrect) then return end local is_plural = #incorrect > 1 local verb = is_plural and " are " or " is " local article = is_plural and " " or " a " local object = is_plural and " groups. " or " group. " local msg = table.concat({ table.concat(incorrect, ", "), verb, "not", article, "valid highlight", object, "Please check the README for all valid highlights", }) require("bufferline.utils").echomsg(msg, "WarningMsg") end end ---Check if a specific feature is enabled ---@param feature '"groups"' ---@return boolean function Config:enabled(feature) if feature == "groups" then return self.options.groups and self.options.groups.items and #self.options.groups.items >= 1 end return false end ---Derive the colors for the bufferline ---@return BufferlineHighlights local function derive_colors() local colors = require("bufferline.colors") local hex = colors.get_hex local shade = colors.shade_color local comment_fg = hex({ name = "Comment", attribute = "fg", fallback = { name = "Normal", attribute = "fg" }, }) local normal_fg = hex({ name = "Normal", attribute = "fg" }) local normal_bg = hex({ name = "Normal", attribute = "bg" }) local string_fg = hex({ name = "String", attribute = "fg" }) local error_fg = hex({ name = "LspDiagnosticsDefaultError", attribute = "fg", fallback = { name = "Error", attribute = "fg" }, }) local warning_fg = hex({ name = "LspDiagnosticsDefaultWarning", attribute = "fg", fallback = { name = "WarningMsg", attribute = "fg" }, }) local info_fg = hex({ name = "LspDiagnosticsDefaultInformation", attribute = "fg", fallback = { name = "Normal", attribute = "fg" }, }) local tabline_sel_bg = hex({ name = "TabLineSel", attribute = "bg", not_match = normal_bg, fallback = { name = "TabLineSel", attribute = "fg", not_match = normal_bg, fallback = { name = "WildMenu", attribute = "fg" }, }, }) -- If the colorscheme is bright we shouldn't do as much shading -- as this makes light color schemes harder to read local is_bright_background = colors.color_is_bright(normal_bg) local separator_shading = is_bright_background and -20 or -45 local background_shading = is_bright_background and -12 or -25 local diagnostic_shading = is_bright_background and -12 or -25 local visible_bg = shade(normal_bg, -8) local duplicate_color = shade(comment_fg, -5) local separator_background_color = shade(normal_bg, separator_shading) local background_color = shade(normal_bg, background_shading) -- diagnostic colors by default are a few shades darker local normal_diagnostic_fg = shade(normal_fg, diagnostic_shading) local comment_diagnostic_fg = shade(comment_fg, diagnostic_shading) local info_diagnostic_fg = shade(info_fg, diagnostic_shading) local warning_diagnostic_fg = shade(warning_fg, diagnostic_shading) local error_diagnostic_fg = shade(error_fg, diagnostic_shading) return { fill = { guifg = comment_fg, guibg = separator_background_color, }, group_separator = { guifg = comment_fg, guibg = separator_background_color, }, group_label = { guibg = comment_fg, guifg = separator_background_color, }, tab = { guifg = comment_fg, guibg = background_color, }, tab_selected = { guifg = tabline_sel_bg, guibg = normal_bg, }, tab_close = { guifg = comment_fg, guibg = background_color, }, close_button = { guifg = comment_fg, guibg = background_color, }, close_button_visible = { guifg = comment_fg, guibg = visible_bg, }, close_button_selected = { guifg = normal_fg, guibg = normal_bg, }, background = { guifg = comment_fg, guibg = background_color, }, buffer = { guifg = comment_fg, guibg = background_color, }, buffer_visible = { guifg = comment_fg, guibg = visible_bg, }, buffer_selected = { guifg = normal_fg, guibg = normal_bg, gui = "bold,italic", }, diagnostic = { guifg = comment_diagnostic_fg, guibg = background_color, }, diagnostic_visible = { guifg = comment_diagnostic_fg, guibg = visible_bg, }, diagnostic_selected = { guifg = normal_diagnostic_fg, guibg = normal_bg, gui = "bold,italic", }, info = { guifg = comment_fg, guisp = info_fg, guibg = background_color, }, info_visible = { guifg = comment_fg, guibg = visible_bg, }, info_selected = { guifg = info_fg, guibg = normal_bg, gui = "bold,italic", guisp = info_fg, }, info_diagnostic = { guifg = comment_diagnostic_fg, guisp = info_diagnostic_fg, guibg = background_color, }, info_diagnostic_visible = { guifg = comment_diagnostic_fg, guibg = visible_bg, }, info_diagnostic_selected = { guifg = info_diagnostic_fg, guibg = normal_bg, gui = "bold,italic", guisp = info_diagnostic_fg, }, warning = { guifg = comment_fg, guisp = warning_fg, guibg = background_color, }, warning_visible = { guifg = comment_fg, guibg = visible_bg, }, warning_selected = { guifg = warning_fg, guibg = normal_bg, gui = "bold,italic", guisp = warning_fg, }, warning_diagnostic = { guifg = comment_diagnostic_fg, guisp = warning_diagnostic_fg, guibg = background_color, }, warning_diagnostic_visible = { guifg = comment_diagnostic_fg, guibg = visible_bg, }, warning_diagnostic_selected = { guifg = warning_diagnostic_fg, guibg = normal_bg, gui = "bold,italic", guisp = warning_diagnostic_fg, }, error = { guifg = comment_fg, guibg = background_color, guisp = error_fg, }, error_visible = { guifg = comment_fg, guibg = visible_bg, }, error_selected = { guifg = error_fg, guibg = normal_bg, gui = "bold,italic", guisp = error_fg, }, error_diagnostic = { guifg = comment_diagnostic_fg, guibg = background_color, guisp = error_diagnostic_fg, }, error_diagnostic_visible = { guifg = comment_diagnostic_fg, guibg = visible_bg, }, error_diagnostic_selected = { guifg = error_diagnostic_fg, guibg = normal_bg, gui = "bold,italic", guisp = error_diagnostic_fg, }, modified = { guifg = string_fg, guibg = background_color, }, modified_visible = { guifg = string_fg, guibg = visible_bg, }, modified_selected = { guifg = string_fg, guibg = normal_bg, }, duplicate_selected = { guifg = duplicate_color, gui = "italic", guibg = normal_bg, }, duplicate_visible = { guifg = duplicate_color, gui = "italic", guibg = visible_bg, }, duplicate = { guifg = duplicate_color, gui = "italic", guibg = background_color, }, separator_selected = { guifg = separator_background_color, guibg = normal_bg, }, separator_visible = { guifg = separator_background_color, guibg = visible_bg, }, separator = { guifg = separator_background_color, guibg = background_color, }, indicator_selected = { guifg = tabline_sel_bg, guibg = normal_bg, }, pick_selected = { guifg = error_fg, guibg = normal_bg, gui = "bold,italic", }, pick_visible = { guifg = error_fg, guibg = visible_bg, gui = "bold,italic", }, pick = { guifg = error_fg, guibg = background_color, gui = "bold,italic", }, } end -- Ideally this plugin should generate a beautiful tabline a little similar -- to what you would get on other editors. The aim is that the default should -- be so nice it's what anyone using this plugin sticks with. It should ideally -- work across any well designed colorscheme deriving colors automagically. ---@return BufferlineConfig local function get_defaults() return { ---@type BufferlineOptions options = { view = "default", numbers = "none", number_style = "superscript", buffer_close_icon = "", modified_icon = "●", close_icon = "", close_command = "bdelete! %d", left_mouse_command = "buffer %d", right_mouse_command = "bdelete! %d", middle_mouse_command = nil, -- U+2590 ▐ Right half block, this character is right aligned so the -- background highlight doesn't appear in th middle -- alternatives: right aligned => ▕ ▐ , left aligned => ▍ indicator_icon = "▎", left_trunc_marker = "", right_trunc_marker = "", separator_style = "thin", name_formatter = nil, tab_size = 18, max_name_length = 18, mappings = false, show_buffer_icons = true, show_buffer_close_icons = true, show_close_icon = true, show_tab_indicators = true, enforce_regular_tabs = false, always_show_bufferline = true, persist_buffer_sort = true, max_prefix_length = 15, sort_by = "id", diagnostics = false, diagnostics_indicator = nil, diagnostics_update_in_insert = true, offsets = {}, groups = { items = nil, options = { toggle_hidden_on_enter = true, }, }, debug = { logging = false, }, }, highlights = derive_colors(), } end ---Generate highlight groups from user ---@param highlights table<string, table> --- TODO: can this become part of a metatable for each highlight group so it is done at the point ---of usage local function add_highlight_groups(highlights) for name, tbl in pairs(highlights) do require("bufferline.highlights").add_group(name, tbl) end end --- Merge user config with defaults --- @return BufferlineConfig function M.apply() local defaults = get_defaults() config:validate(defaults) config:merge(defaults) if config:enabled("groups") then require("bufferline.groups").setup(config) end add_highlight_groups(config.highlights) return config end ---Keep track of a users config for use throughout the plugin as well as ensuring ---defaults are set. This is also so we can diff what the user set this is useful ---for setting the highlight groups etc. once this has been merged with the defaults ---@param conf BufferlineConfig function M.set(conf) config = Config:new(conf or {}) end ---Update highlight colours when the colour scheme changes function M.update_highlights() config:merge({ highlights = derive_colors() }) if config:enabled("groups") then require("bufferline.groups").reset_highlights(config.highlights) end add_highlight_groups(config.highlights) return config end ---Get the user's configuration or a key from it ---@param key string? ---@return BufferlineConfig ---@overload fun(key: '"options"'): BufferlineOptions ---@overload fun(key: '"highlights"'): BufferlineHighlights function M.get(key) if not config then return end return config[key] or config end --- This function is only intended for use in tests ---@private function M.__reset() config = nil end return M
print(a); print(b); print(c);
require 'jps' function testSimple() local map={ { 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1 } } local pathable = function(x, y) return map and y <= #map and map[y] and x <= #map[y] and map[y][x] and map[y][x] == 1 end local check = function(src, tgt, delta) -- print("Testing: " .. src.x .. "x" .. src.y .. " -> " .. tgt.x .. "x" .. tgt.y .. " [" .. delta.x .. "x" .. delta.y .. "]") local result = jump(pathable, { pos = src }, delta, tgt) assert(result and result.pos.x == tgt.x and result.pos.y == tgt.y) end print ">>> Horizontal" check({ x = 2, y = 3 }, { x = 5, y = 3 }, { x = 1, y = 0 }) -- l -> r check({ x = 5, y = 3 }, { x = 2, y = 3 }, { x =-1, y = 0 }) -- l <- r print ">>> Vertical" check({ x = 3, y = 1 }, { x = 3, y = 5 }, { x = 0, y = 1 }) -- t -> d check({ x = 3, y = 5 }, { x = 3, y = 1 }, { x = 0, y =-1 }) -- t <- d print ">>> Diagonal" check({ x = 2, y = 1 }, { x = 5, y = 4 }, { x = 1, y = 1 }) -- tl -> br check({ x = 5, y = 4 }, { x = 2, y = 1 }, { x =-1, y =-1 }) -- br -> tl check({ x = 5, y = 1 }, { x = 2, y = 4 }, { x =-1, y = 1 }) -- tr -> bl check({ x = 2, y = 4 }, { x = 5, y = 1 }, { x = 1, y =-1 }) -- bl -> tr end function testSimpleWithStop() local map={ { 1, 1, 1, 1, 1, }, { 1, 1, 1, 1, 1, }, { 1, 1, 0, 1, 1, }, { 1, 1, 1, 1, 1, }, { 1, 1, 1, 1, 1, } } local pathable = function(x, y) return map and y <= #map and map[y] and x <= #map[y] and map[y][x] and map[y][x] == 1 end local check = function(src, tgt, delta, expectedPos) print("Testing: " .. src.x .. "x" .. src.y .. " -> " .. tgt.x .. "x" .. tgt.y .. " [" .. delta.x .. "x" .. delta.y .. "]") local result = jump(pathable, { pos = src}, delta, tgt) if result then print("Result {" .. result.pos.x .. "x" .. result.pos.y .. "}") else print("No result") end assert(result and result.pos.x == expectedPos.x and result.pos.y == expectedPos.y) end print ">>> Horizontal" --check({ x = 2, y = 3 }, { x = 5, y = 3 }, { x = 1, y = 0 }, { x = 3, y = 2 }) -- l -> r check({ x = 2, y = 2 }, { x = 5, y = 2 }, { x = 1, y = 0 }, { x = 3, y = 2 }) -- l -> r check({ x = 2, y = 4 }, { x = 5, y = 4 }, { x = 1, y = 0 }, { x = 3, y = 4 }) -- l -> r --check({ x = 5, y = 3 }, { x = 2, y = 3 }, { x =-1, y = 0 }) -- l <- r check({ x = 5, y = 2 }, { x = 2, y = 2 }, { x =-1, y = 0 }, { x = 3, y = 2 }) -- l <- r check({ x = 5, y = 4 }, { x = 2, y = 4 }, { x =-1, y = 0 }, { x = 3, y = 4 }) -- l <- r print ">>> Vertical" --check({ x = 3, y = 1 }, { x = 3, y = 5 }, { x = 0, y = 1 }) -- t -> d check({ x = 2, y = 2 }, { x = 2, y = 4 }, { x = 0, y = 1 }, { x = 2, y = 3 }) -- l -> r check({ x = 4, y = 2 }, { x = 4, y = 4 }, { x = 0, y = 1 }, { x = 4, y = 3 }) -- l -> r --check({ x = 3, y = 5 }, { x = 3, y = 1 }, { x = 0, y =-1 }) -- t <- d check({ x = 2, y = 4 }, { x = 2, y = 2 }, { x = 0, y =-1 }, { x = 2, y = 3 }) -- l <- r check({ x = 4, y = 4 }, { x = 4, y = 2 }, { x = 0, y =-1 }, { x = 4, y = 3 }) -- l <- r print ">>> Diagonal" -- \ # 3 -- # X 6 -- 7 8 9 check({ x = 1, y = 2 }, { x = 4, y = 5 }, { x = 1, y = 1 }, { x = 3, y = 4 }) check({ x = 4, y = 5 }, { x = 1, y = 2 }, { x =-1, y =-1 }, { x = 2, y = 3 }) check({ x = 2, y = 1 }, { x = 5, y = 4 }, { x = 1, y = 1 }, { x = 4, y = 3 }) check({ x = 5, y = 4 }, { x = 2, y = 1 }, { x =-1, y =-1 }, { x = 3, y = 2 }) check({ x = 2, y = 5 }, { x = 5, y = 2 }, { x = 1, y =-1 }, { x = 4, y = 3 }) check({ x = 5, y = 2 }, { x = 2, y = 5 }, { x =-1, y = 1 }, { x = 3, y = 4 }) check({ x = 1, y = 4 }, { x = 4, y = 1 }, { x = 1, y =-1 }, { x = 3, y = 2 }) check({ x = 4, y = 1 }, { x = 1, y = 4 }, { x =-1, y = 1 }, { x = 2, y = 3 }) -- Reminder -- { 1, 1, 1, 1, 1, }, -- { 1, 1, 1, 1, 1, }, -- { 1, 1, 0, 1, 1, }, -- { 1, 1, 1, 1, 1, }, -- { 1, 1, 1, 1, 1, } end function love.keypressed(key) love.event.quit() end function love.load() testSimple() testSimpleWithStop() end function love.draw() love.graphics.print("Hello", 50, 10) end
msg = Instance.new("Message", game.Workspace) msg.Text = "The world is ending!" wait(3) msg.Text = "Save your childrens before it's too late!!!" wait(3) msg:Destroy()
return {'bukken','buks','buksboom','bukskin','buken','bukkems','bukman','buk','buksbomen','buksen','bukt','bukte','bukten','bukkend'}
object_draft_schematic_weapon_component_new_weapon_comp_gas_cartridge_advanced = object_draft_schematic_weapon_component_shared_new_weapon_comp_gas_cartridge_advanced:new { } ObjectTemplates:addTemplate(object_draft_schematic_weapon_component_new_weapon_comp_gas_cartridge_advanced, "object/draft_schematic/weapon/component/new_weapon_comp_gas_cartridge_advanced.iff")
-- core.lua - OCR switch core local cqueues = require('cqueues') local _CORE = {} function _CORE.new(config_file) local self = { async = cqueues.new() } local _plugins = {} self.config = require('configurator').new(config_file) { plugin = 'list', switch = 'scalar', } -- Subsystems: -- self.switch = require('switch').new(core) function self.load_plugin(plugin_file) local plugin_obj = require(plugin_file).new(self) table.insert(_plugins, plugin_obj) plugin_obj.pre_init() -- Load time (pre) initialization print('Loaded plugin: ' .. plugin_file .. '.lua') end function self.run() -- Load plugins: for _,plugin_name in ipairs(self.config.data['plugin']) do self.load_plugin(plugin_name) end -- Runtime (post) ininitialization: for _,plugin in ipairs(_plugins) do plugin.init() end -- Begin loop: assert(self.async:loop()) end return self end return _CORE
local cpml = require "cpml" local anim = { _LICENSE = "anim9 is distributed under the terms of the MIT license. See LICENSE.md.", _URL = "https://github.com/excessive/anim9", _VERSION = "0.1.1", _DESCRIPTION = "Animation library for LÖVE3D.", } anim.__index = anim local function calc_bone_matrix(pos, rot, scale) local out = cpml.mat4() return out :translate(out, pos) :rotate(out, rot) :scale(out, scale) end local function bind_pose(skeleton) local pose = {} for i = 1, #skeleton do pose[i] = { translate = skeleton[i].position, rotate = skeleton[i].rotation, scale = skeleton[i].scale } end return pose end local function add_poses(skeleton, p1, p2) local new_pose = {} for i = 1, #skeleton do local inv = p1[i].rotate:clone() inv:inverse(inv) new_pose[i] = { translate = p1[i].translate + (p2[i].translate - p1[i].translate), rotate = (p2[i].rotate * inv) * p1[i].rotate, scale = p1[i].scale + (p2[i].scale - p1[i].scale) } end return new_pose end local function mix_poses(skeleton, p1, p2, weight) local new_pose = {} for i = 1, #skeleton do local r = cpml.quat():slerp(p1[i].rotate, p2[i].rotate, weight) r:normalize(r) new_pose[i] = { translate = cpml.vec3():lerp(p1[i].translate, p2[i].translate, weight), rotate = r, scale = cpml.vec3():lerp(p1[i].scale, p2[i].scale, weight) } end return new_pose end local function update_matrices(skeleton, base, pose) local animation_buffer = {} local transform = {} local bone_lookup = {} for i, joint in ipairs(skeleton) do local m = calc_bone_matrix(pose[i].translate, pose[i].rotate, pose[i].scale) local render if joint.parent > 0 then assert(joint.parent < i) transform[i] = m * transform[joint.parent] render = base[i] * transform[i] else transform[i] = m render = base[i] * m end bone_lookup[joint.name] = transform[i] table.insert(animation_buffer, render:to_vec4s()) end table.insert(animation_buffer, animation_buffer[#animation_buffer]) return animation_buffer, bone_lookup end local function new(data, anims) if not data.skeleton then return end local t = { active = {}, animations = {}, skeleton = data.skeleton, inverse_base = {}, bind_pose = bind_pose(data.skeleton) } -- Calculate inverse base pose. for i, bone in ipairs(data.skeleton) do local m = calc_bone_matrix(bone.position, bone.rotation, bone.scale) local inv = cpml.mat4():invert(m) if bone.parent > 0 then assert(bone.parent < i) t.inverse_base[i] = t.inverse_base[bone.parent] * inv else t.inverse_base[i] = inv end end local o = setmetatable(t, anim) if anims ~= nil and not anims then return o end for _, v in ipairs(anims or data) do o:add_animation(v, data.frames) end return o end function anim:add_animation(animation, frame_data) local new_anim = { name = animation.name, frames = {}, length = animation.last - animation.first, framerate = animation.framerate, loop = animation.loop } for i = animation.first, animation.last do table.insert(new_anim.frames, frame_data[i]) end self.animations[new_anim.name] = new_anim end local function new_animation(name, weight, rate, callback) return { name = assert(name), frame = 1, time = 0, marker = 0, rate = rate or 1, weight = weight or 1, callback = callback or false, playing = true } end function anim:reset(name) if not self.active[name] then for _, v in ipairs(self.active) do self:reset(v.name) end return end if not self.active[name] then return end self.active[name].time = 0 self.active[name].marker = 0 self.active[name].frame = 1 end function anim:play(name, weight, rate, callback) if self.active[name] then self.active[name].playing = true return end assert(self.animations[name], string.format("Invalid animation: '%s'", name)) self.active[name] = new_animation(name, weight, rate, callback) table.insert(self.active, self.active[name]) end function anim:pause(name) if not self.active[name] then for _, v in ipairs(self.active) do self:pause(v.name) end return end self.active[name].playing = not self.active[name].playing end function anim:stop(name) if not self.active[name] then for _, v in ipairs(self.active) do self:stop(v.name) end return end self.active[name] = nil for i, v in ipairs(self.active) do if v.name == name then table.remove(self.active, i) break end end end function anim:length(aname) local _anim = assert(self.animations[aname], string.format("Invalid animation: \'%s\'", aname)) return _anim.length / _anim.framerate end function anim:step(name, reverse) assert(self.active[name], string.format("Invalid animation: '%s'", name)) local _anim = self.animations[name] local length = _anim.length / _anim.framerate local meta = self.active[name] if reverse then meta.time = meta.time - (1/_anim.framerate) else meta.time = meta.time + (1/_anim.framerate) end if _anim.loop then if meta.time < 0 then meta.time = meta.time + length end meta.time = cpml.utils.wrap(meta.time, length) else if meta.time < 0 then meta.time = 0 end meta.time = math.min(meta.time, length) end local position = self.current_time * _anim.framerate local frame = _anim.frames[math.floor(position)+1] meta.frame = frame -- Update the final pose local pose = mix_poses(self.skeleton, frame, frame, 0) self.current_pose, self.current_matrices = update_matrices( self.skeleton, self.inverse_base, pose ) end function anim:update(dt) if #self.active == 0 then return end local pose = self.bind_pose for _, meta in ipairs(self.active) do local over = false local _anim = self.animations[meta.name] local length = _anim.length / _anim.framerate meta.time = meta.time + dt * meta.rate if meta.time >= length then if type(meta.callback) == "function" then meta.callback(self) end end -- If we're not looping, we just want to leave the animation at the end. if _anim.loop then meta.time = cpml.utils.wrap(meta.time, length) else if meta.time > length then over = true end meta.time = math.min(meta.time, length) end local position = meta.time * _anim.framerate local f1, f2 = math.floor(position), math.ceil(position) position = position - f1 f2 = f2 % (_anim.length) meta.frame = f1 -- Update the final pose local interp = mix_poses( self.skeleton, _anim.frames[f1+1], _anim.frames[f2+1], position ) local mix = mix_poses(self.skeleton, pose, interp, meta.weight) pose = add_poses(self.skeleton, pose, mix) if over then self:stop(meta.name) end end self.current_pose, self.current_matrices = update_matrices( self.skeleton, self.inverse_base, pose ) end return setmetatable({ new = new }, { __call = function(_, ...) return new(...) end })
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:27' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ZO_LEVEL_UP_REWARDS_BACKGROUND_TEXTURE_WIDTH = 512 ZO_LEVEL_UP_REWARDS_BACKGROUND_TEXTURE_HEIGHT = 256 ZO_LEVEL_UP_REWARDS_BACKGROUND_USED_TEXTURE_WIDTH = 448 ZO_LEVEL_UP_REWARDS_BACKGROUND_USED_TEXTURE_HEIGHT = 138 ZO_LEVEL_UP_REWARDS_ART_RIGHT_TEXTURE_COORD = ZO_LEVEL_UP_REWARDS_BACKGROUND_USED_TEXTURE_WIDTH / ZO_LEVEL_UP_REWARDS_BACKGROUND_TEXTURE_WIDTH ZO_LEVEL_UP_REWARDS_ART_BOTTOM_TEXTURE_COORD = ZO_LEVEL_UP_REWARDS_BACKGROUND_USED_TEXTURE_HEIGHT / ZO_LEVEL_UP_REWARDS_BACKGROUND_TEXTURE_HEIGHT ZO_LEVEL_UP_REWARDS_ART_REWARDS_SPACING = 10 function ZO_LevelUpRewardsArtTile_OnInitialized(self) self.frameTexture = self:GetNamedChild("Frame") self.artTexture = self:GetNamedChild("Art") self.titleControl = self:GetNamedChild("Title") local maskControl = self:GetNamedChild("Mask") self.maskControl = maskControl local layerAnimation = ZO_TextureLayerRevealAnimation:New(maskControl) local animationTimeline = layerAnimation:GetAnimationTimeline() animationTimeline:SetPlaybackType(ANIMATION_PLAYBACK_LOOP, LOOP_INDEFINITELY) self.layerAnimation = layerAnimation local function ParticleSystemFactory(pool) local particleSystem = ZO_ControlParticleSystem:New(ZO_BentArcParticle_Control) particleSystem:SetParentControl(maskControl) particleSystem:SetParticleParameter("AnchorRelativePoint", TOPLEFT) return particleSystem end local function ParticleSystemReset(particleSystem, pool) particleSystem:Stop() end self.particleSystemPool = ZO_ObjectPool:New(ParticleSystemFactory, ParticleSystemReset) maskControl:SetHandler("OnEffectivelyShown", function() if layerAnimation:HasLayers() then animationTimeline:PlayFromStart() end for _, particleSystem in pairs(self.particleSystemPool:GetActiveObjects()) do particleSystem:Start() end end) maskControl:SetHandler("OnEffectivelyHidden", function() animationTimeline:Stop() for _, particleSystem in pairs(self.particleSystemPool:GetActiveObjects()) do particleSystem:Stop() end end) end function ZO_LevelUpRewardsArtTileAndRewards_OnInitialized(self) ZO_LevelUpRewardsArtTile_OnInitialized(self) self.rewardsContainer = self:GetNamedChild("Rewards") end function ZO_LevelUpRewardsArtTile_SetupTileForLevel(self, level) local levelBackground = GetLevelUpBackground(level) self.artTexture:SetTexture(levelBackground) local layerAnimation = self.layerAnimation layerAnimation:RemoveAllLayers() local numTextureLayerRevealAnimations = GetNumLevelUpTextureLayerRevealAnimations(level) for i = 1, numTextureLayerRevealAnimations do local animationId = GetLevelUpTextureLayerRevealAnimation(level, i) local layer = layerAnimation:AddLayer() layer:SetTexture(GetTextureLayerRevealAnimationTexture(animationId)) layer:SetTextureCoords(0, ZO_LEVEL_UP_REWARDS_ART_RIGHT_TEXTURE_COORD, 0, ZO_LEVEL_UP_REWARDS_ART_BOTTOM_TEXTURE_COORD) layer:SetTextureBlendMode(GetTextureLayerRevealAnimationBlendMode(animationId)) layer:SetWindowNormalizedDimensions(GetTextureLayerRevealAnimationWindowDimensions(animationId)) layer:SetWindowNormalizedEndPoints(GetTextureLayerRevealAnimationWindowEndPoints(animationId)) layer:SetWindowMovementDurationMS(GetTextureLayerRevealAnimationWindowMovementDuration(animationId)) layer:SetWindowMovementOffsetMS(GetTextureLayerRevealAnimationWindowMovementOffset(animationId)) for gradientIndex = 1, 2 do local x, y, normalizedDistance = GetTextureLayerRevealAnimationWindowFadeGradientInfo(animationId, gradientIndex) if normalizedDistance > 0 then layer:SetWindowFadeGradient(gradientIndex, x, y, normalizedDistance) end end end layerAnimation:Commit() if layerAnimation:HasLayers() then local minDurationMS = GetLevelUpTextureLayerRevealAnimationsMinDuration(level) layerAnimation:GetAnimationTimeline():SetMinDuration(minDurationMS) if not self.maskControl:IsHidden() then layerAnimation:GetAnimationTimeline():PlayFromStart() end end self.particleSystemPool:ReleaseAllObjects() local numParticleEffects = GetNumLevelUpGuiParticleEffects(level) local maskWidth, maskHeight = self.maskControl:GetDimensions() for i = 1, numParticleEffects do local particleSystem = self.particleSystemPool:AcquireObject() local texture, normalizedVelocityMin, normalizedVelocityMax, durationMinS, durationMaxS, particlesPerSecond, startScaleMin, startScaleMax, endScaleMin, endScaleMax, startAlpha, endAlpha, r, g, b, normalizedStartPoint1X, normalizedStartPoint1Y, normalizedStartPoint2X, normalizedStartPoint2Y, angleRadians = GetLevelUpGuiParticleEffectInfo(level, i) local startPoint1X = normalizedStartPoint1X * maskWidth local startPoint1Y = normalizedStartPoint1Y * maskHeight local startPoint2X = normalizedStartPoint2X * maskWidth local startPoint2Y = normalizedStartPoint2Y * maskHeight local velocityMin, velocityMax local percentageOfUnitCircle = angleRadians / (2 * math.pi) if (percentageOfUnitCircle > 1/8 and percentageOfUnitCircle < 3/8) or (percentageOfUnitCircle > 5/8 and percentageOfUnitCircle < 7/8) then --Points more in the Y direction than the X, normalize the particle velocity against height velocityMin = normalizedVelocityMin * maskHeight velocityMax = normalizedVelocityMax * maskHeight else --Points more in the X direction than the Y, normalize the particle velocity against width velocityMin = normalizedVelocityMin * maskWidth velocityMax = normalizedVelocityMax * maskWidth end particleSystem:SetParticlesPerSecond(particlesPerSecond) particleSystem:SetParticleParameter("Texture", texture) particleSystem:SetParticleParameter("BentArcElevationStartRadians", angleRadians) particleSystem:SetParticleParameter("BentArcElevationChangeRadians", 0) particleSystem:SetParticleParameter("BentArcAzimuthStartRadians", 0) particleSystem:SetParticleParameter("BentArcAzimuthChangeRadians", 0) particleSystem:SetParticleParameter("BentArcVelocity", ZO_UniformRangeGenerator:New(velocityMin, velocityMax)) particleSystem:SetParticleParameter("Size", 8) particleSystem:SetParticleParameter("StartScale", ZO_UniformRangeGenerator:New(startScaleMin, startScaleMax)) particleSystem:SetParticleParameter("EndScale", ZO_UniformRangeGenerator:New(endScaleMin, endScaleMax)) particleSystem:SetParticleParameter("DurationS", ZO_UniformRangeGenerator:New(durationMinS, durationMaxS)) particleSystem:SetParticleParameter("StartAlpha", startAlpha) particleSystem:SetParticleParameter("EndAlpha", endAlpha) particleSystem:SetParticleParameter("StartColorR", r) particleSystem:SetParticleParameter("StartColorG", g) particleSystem:SetParticleParameter("StartColorB", b) particleSystem:SetParticleParameter("StartOffsetX", "StartOffsetY", ZO_UniformRangeGenerator:New(startPoint1X, startPoint2X, startPoint1Y, startPoint2Y)) particleSystem:SetParticleParameter("BlendMode", TEX_BLEND_MODE_ADD) if not self.maskControl:IsHidden() then particleSystem:Start() end end end
strBatchList = "ACQ_macrolua.mis;Q_far_mk_link_sa2.mis"
local playsession = { {"mewmew", {245579}}, {"Biker", {1184}}, {"Quadrum", {426744}}, {"Delqvs", {125502}}, {"nix0n", {11550}}, {"zbirka", {1178}}, {"ZoeAustin", {780}}, {"Esquired25", {9860}}, {"CheeseLord", {25754}}, {"strongfive", {4423}}, {"everLord", {1075}}, {"jer93", {28825}}, {"Kalkune", {1030}}, {"CGYT", {2318}}, {"milesanator", {9248}}, {"donglepuss", {5865}}, {"Renoh", {36625}}, {"nik12111", {4024}}, {"Pumba81", {16921}}, {"redlabel", {605}}, {"Bonny", {2410}}, {"JC1223", {439}}, {"Death_Falcon", {3250}}, {"emilquast", {194420}}, {"Chmizuno", {130922}}, {"viktori726", {21380}}, {"flooxy", {181248}} } return playsession
--夜雀¤白泽球 function c22220005.initial_effect(c) aux.EnablePendulumAttribute(c) --pos local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(22220005,1)) e2:SetCategory(CATEGORY_POSITION) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetRange(LOCATION_PZONE) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCode(EVENT_FREE_CHAIN) e2:SetCountLimit(1) e2:SetCondition(c22220005.poscon) e2:SetTarget(c22220005.postg) e2:SetOperation(c22220005.posop) c:RegisterEffect(e2) --equip local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(22220005,0)) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCategory(CATEGORY_EQUIP) e1:SetRange(LOCATION_MZONE) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,0x1e0) e1:SetTarget(c22220005.eqtg1) e1:SetOperation(c22220005.eqop) c:RegisterEffect(e1) --Destroy local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(22220005,2)) e1:SetCategory(CATEGORY_DESTROY) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_GRAVE) e1:SetCountLimit(1) e1:SetCost(c22220005.cost) e1:SetTarget(c22220005.target) e1:SetOperation(c22220005.operation) c:RegisterEffect(e1) end c22220005.named_with_Shirasawa_Tama=1 function c22220005.IsShirasawaTama(c) local m=_G["c"..c:GetCode()] return m and m.named_with_Shirasawa_Tama end function c22220005.poscon(e,tp,eg,ep,ev,re,r,rp) local seq=e:GetHandler():GetSequence() local tc=Duel.GetFieldCard(tp,LOCATION_SZONE,13-seq) return tc and c22220005.IsShirasawaTama(tc) end function c22220005.posfilter(c) return c:IsFaceup() and c:IsCanTurnSet() end function c22220005.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and c22220005.posfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c22220005.posfilter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) local g=Duel.SelectTarget(tp,c22220005.posfilter,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0) end function c22220005.posop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() and e:GetHandler():IsRelateToEffect(e) then Duel.ChangePosition(tc,POS_FACEDOWN_DEFENSE) end Duel.Destroy(e:GetHandler(),REASON_EFFECT) end function c22220005.eefilter(c) return c:IsFaceup() and c22220005.IsShirasawaTama(c) end function c22220005.eqtg1(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() and chkc~=e:GetHandler() end if chk==0 then return e:GetHandler():GetFlagEffect(22220005)==0 and Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingTarget(c22220005.eefilter,tp,LOCATION_MZONE,0,1,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) local g=Duel.SelectTarget(tp,c22220005.eefilter,tp,LOCATION_MZONE,0,1,1,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_EQUIP,g,1,0,0) e:GetHandler():RegisterFlagEffect(22220005,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1) end function c22220005.eqop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if not c:IsRelateToEffect(e) or c:IsFacedown() then return end if not tc:IsRelateToEffect(e) or tc:IsFacedown() then Duel.SendtoGrave(c,REASON_EFFECT) return end if not Duel.Equip(tp,c,tc,false) then return end --unequip local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(22220005,1)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,0x1e0) e1:SetRange(LOCATION_SZONE) e1:SetTarget(c22220005.sptg) e1:SetOperation(c22220005.spop) e1:SetReset(RESET_EVENT+0x1fe0000) c:RegisterEffect(e1) --immune local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_EQUIP) e5:SetCode(EFFECT_IMMUNE_EFFECT) e5:SetValue(c22220005.efilter) c:RegisterEffect(e5) --eqlimit local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_EQUIP_LIMIT) e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e4:SetValue(c22220005.eqlimit) e4:SetReset(RESET_EVENT+0x1fe0000) e4:SetLabelObject(tc) c:RegisterEffect(e4) end function c22220005.efilter(e,te) return te:IsActiveType(TYPE_SPELL) and te:GetOwnerPlayer()~=e:GetHandlerPlayer() end function c22220005.eqlimit(e,c) return c==e:GetLabelObject() end function c22220005.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetFlagEffect(22220005)==0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,true,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) e:GetHandler():RegisterFlagEffect(22220005,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1) end function c22220005.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP) end end function c22220005.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c22220005.filter(c) return c:IsFacedown() end function c22220005.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c22220005.filter,tp,0,LOCATION_MZONE,1,nil) end Duel.SetOperationInfo(0,CATEGORY_DESTROY,nil,1,1-tp,LOCATION_MZONE) end function c22220005.operation(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(c22220005.filter,tp,0,LOCATION_MZONE,nil) Duel.Destroy(g,REASON_EFFECT) end
return { name = 'ArcType', description = 'Different types of arcs that can be drawn.', constants = { { name = 'pie', description = 'The arc is drawn like a slice of pie, with the arc circle connected to the center at its end-points.', }, { name = 'open', description = 'The arc circle\'s two end-points are unconnected when the arc is drawn as a line. Behaves like the "closed" arc type when the arc is drawn in filled mode.', }, { name = 'closed', description = 'The arc circle\'s two end-points are connected to each other.', }, }, }
object_tangible_furniture_flooring_tile_frn_flooring_tile_s75 = object_tangible_furniture_flooring_tile_shared_frn_flooring_tile_s75:new { } ObjectTemplates:addTemplate(object_tangible_furniture_flooring_tile_frn_flooring_tile_s75, "object/tangible/furniture/flooring/tile/frn_flooring_tile_s75.iff")
local _2afile_2a = "fnl/conjure/client/fennel/aniseed.fnl" local _2amodule_name_2a = "conjure.client.fennel.aniseed" local _2amodule_2a do package.loaded[_2amodule_name_2a] = {} _2amodule_2a = package.loaded[_2amodule_name_2a] end local _2amodule_locals_2a do _2amodule_2a["aniseed/locals"] = {} _2amodule_locals_2a = (_2amodule_2a)["aniseed/locals"] end local autoload = (require("conjure.aniseed.autoload")).autoload local a, client, config, extract, fs, log, mapping, nvim, str, text, ts, view = autoload("conjure.aniseed.core"), autoload("conjure.client"), autoload("conjure.config"), autoload("conjure.extract"), autoload("conjure.fs"), autoload("conjure.log"), autoload("conjure.mapping"), autoload("conjure.aniseed.nvim"), autoload("conjure.aniseed.string"), autoload("conjure.text"), autoload("conjure.tree-sitter"), autoload("conjure.aniseed.view") do end (_2amodule_locals_2a)["a"] = a _2amodule_locals_2a["client"] = client _2amodule_locals_2a["config"] = config _2amodule_locals_2a["extract"] = extract _2amodule_locals_2a["fs"] = fs _2amodule_locals_2a["log"] = log _2amodule_locals_2a["mapping"] = mapping _2amodule_locals_2a["nvim"] = nvim _2amodule_locals_2a["str"] = str _2amodule_locals_2a["text"] = text _2amodule_locals_2a["ts"] = ts _2amodule_locals_2a["view"] = view local function form_node_3f(node) return ts["node-surrounded-by-form-pair-chars?"](node, {{"#(", ")"}}) end _2amodule_2a["form-node?"] = form_node_3f local buf_suffix = ".fnl" _2amodule_2a["buf-suffix"] = buf_suffix local context_pattern = "%(%s*module%s+(.-)[%s){]" _2amodule_2a["context-pattern"] = context_pattern local comment_prefix = "; " _2amodule_2a["comment-prefix"] = comment_prefix config.merge({client = {fennel = {aniseed = {mapping = {run_buf_tests = "tt", run_all_tests = "ta", reset_repl = "rr", reset_all_repls = "ra"}, aniseed_module_prefix = "conjure.aniseed.", use_metadata = true}}}}) local cfg = config["get-in-fn"]({"client", "fennel", "aniseed"}) do end (_2amodule_locals_2a)["cfg"] = cfg local ani_aliases = {nu = "nvim.util"} _2amodule_locals_2a["ani-aliases"] = ani_aliases local function ani(mod_name, f_name) local mod_name0 = a.get(ani_aliases, mod_name, mod_name) local mod = require((cfg({"aniseed_module_prefix"}) .. mod_name0)) if f_name then return a.get(mod, f_name) else return mod end end _2amodule_locals_2a["ani"] = ani local function anic(mod, f_name, ...) return ani(mod, f_name)(...) end _2amodule_locals_2a["anic"] = anic local repls = ((_2amodule_2a).repls or {}) do end (_2amodule_locals_2a)["repls"] = repls local function reset_repl(filename) local filename0 = (filename or fs["localise-path"](extract["file-path"]())) do end (repls)[filename0] = nil return log.append({("; Reset REPL for " .. filename0)}, {["break?"] = true}) end _2amodule_2a["reset-repl"] = reset_repl local function reset_all_repls() local function _2_(filename) repls[filename] = nil return nil end a["run!"](_2_, a.keys(repls)) return log.append({"; Reset all REPLs"}, {["break?"] = true}) end _2amodule_2a["reset-all-repls"] = reset_all_repls local default_module_name = "conjure.user" _2amodule_2a["default-module-name"] = default_module_name local function module_name(context, file_path) if context then return context elseif file_path then return (fs["file-path->module-name"](file_path) or default_module_name) else return default_module_name end end _2amodule_2a["module-name"] = module_name local function repl(opts) local filename = a.get(opts, "filename") local function _7_() local ret = {} local _ local function _4_(err) ret["ok?"] = false ret.results = {err} return nil end opts["error-handler"] = _4_ _ = nil local eval_21 = anic("eval", "repl", opts) local repl0 local function _5_(code) ret["ok?"] = nil ret.results = nil local results = eval_21(code) if a["nil?"](ret["ok?"]) then ret["ok?"] = true ret.results = results else end return ret end repl0 = _5_ repl0(("(module " .. a.get(opts, "moduleName") .. ")")) do end (repls)[filename] = repl0 return repl0 end return ((not a.get(opts, "fresh?") and a.get(repls, filename)) or _7_()) end _2amodule_2a["repl"] = repl local function display_result(opts) if opts then local _let_8_ = opts local ok_3f = _let_8_["ok?"] local results = _let_8_["results"] local result_str local function _10_() if ok_3f then if not a["empty?"](results) then return str.join("\n", a.map(view.serialise, results)) else return nil end else return a.first(results) end end result_str = (_10_() or "nil") local result_lines = str.split(result_str, "\n") if not opts["passive?"] then local function _12_() if ok_3f then return result_lines else local function _11_(_241) return ("; " .. _241) end return a.map(_11_, result_lines) end end log.append(_12_()) else end if opts["on-result-raw"] then opts["on-result-raw"](results) else end if opts["on-result"] then return opts["on-result"](result_str) else return nil end else return nil end end _2amodule_2a["display-result"] = display_result local function eval_str(opts) local function _17_() local out local function _18_() if (cfg({"use_metadata"}) and not package.loaded.fennel) then package.loaded.fennel = anic("fennel", "impl") else end local eval_21 = repl({filename = opts["file-path"], moduleName = module_name(opts.context, opts["file-path"]), useMetadata = cfg({"use_metadata"}), ["fresh?"] = (("file" == opts.origin) or ("buf" == opts.origin) or text["starts-with"](opts.code, ("(module " .. (opts.context or ""))))}) local _let_20_ = eval_21((opts.code .. "\n")) local ok_3f = _let_20_["ok?"] local results = _let_20_["results"] opts["ok?"] = ok_3f opts.results = results return nil end out = anic("nu", "with-out-str", _18_) if not a["empty?"](out) then log.append(text["prefixed-lines"](text["trim-last-newline"](out), "; (out) ")) else end return display_result(opts) end return client.wrap(_17_)() end _2amodule_2a["eval-str"] = eval_str local function doc_str(opts) a.assoc(opts, "code", (",doc " .. opts.code)) return eval_str(opts) end _2amodule_2a["doc-str"] = doc_str local function eval_file(opts) opts.code = a.slurp(opts["file-path"]) if opts.code then return eval_str(opts) else return nil end end _2amodule_2a["eval-file"] = eval_file local function wrapped_test(req_lines, f) log.append(req_lines, {["break?"] = true}) local res = anic("nu", "with-out-str", f) local _23_ if ("" == res) then _23_ = "No results." else _23_ = res end return log.append(text["prefixed-lines"](_23_, "; ")) end _2amodule_locals_2a["wrapped-test"] = wrapped_test local function run_buf_tests() local c = extract.context() if c then local function _25_() return anic("test", "run", c) end return wrapped_test({("; run-buf-tests (" .. c .. ")")}, _25_) else return nil end end _2amodule_2a["run-buf-tests"] = run_buf_tests local function run_all_tests() return wrapped_test({"; run-all-tests"}, ani("test", "run-all")) end _2amodule_2a["run-all-tests"] = run_all_tests local function on_filetype() mapping.buf("n", "FnlRunBufTests", cfg({"mapping", "run_buf_tests"}), _2amodule_name_2a, "run-buf-tests") mapping.buf("n", "FnlRunAllTests", cfg({"mapping", "run_all_tests"}), _2amodule_name_2a, "run-all-tests") mapping.buf("n", "FnlResetREPL", cfg({"mapping", "reset_repl"}), _2amodule_name_2a, "reset-repl") return mapping.buf("n", "FnlResetAllREPLs", cfg({"mapping", "reset_all_repls"}), _2amodule_name_2a, "reset-all-repls") end _2amodule_2a["on-filetype"] = on_filetype local function value__3ecompletions(x) if ("table" == type(x)) then local function _29_(_27_) local _arg_28_ = _27_ local k = _arg_28_[1] local v = _arg_28_[2] return {word = k, kind = type(v), menu = nil, info = nil} end local function _32_(_30_) local _arg_31_ = _30_ local k = _arg_31_[1] local v = _arg_31_[2] return not text["starts-with"](k, "aniseed/") end local function _33_() if x["aniseed/autoload-enabled?"] then do local _ = x["trick-aniseed-into-loading-the-module"] end return x["aniseed/autoload-module"] else return x end end return a.map(_29_, a.filter(_32_, a["kv-pairs"](_33_()))) else return nil end end _2amodule_2a["value->completions"] = value__3ecompletions local function completions(opts) local code if not str["blank?"](opts.prefix) then local prefix = string.gsub(opts.prefix, ".$", "") code = ("((. (require :" .. _2amodule_name_2a .. ") :value->completions) " .. prefix .. ")") else code = nil end local mods = value__3ecompletions(package.loaded) local locals do local ok_3f, m = nil, nil local function _36_() return require(opts.context) end ok_3f, m = pcall(_36_) if ok_3f then locals = a.concat(value__3ecompletions(m), value__3ecompletions(a.get(m, "aniseed/locals")), mods) else locals = mods end end local result_fn local function _38_(results) local xs = a.first(results) local function _41_() if ("table" == type(xs)) then local function _39_(x) local function _40_(_241) return (opts.prefix .. _241) end return a.update(x, "word", _40_) end return a.concat(a.map(_39_, xs), locals) else return locals end end return opts.cb(_41_()) end result_fn = _38_ local ok_3f, err_or_res = nil, nil if code then local function _42_() return eval_str({["file-path"] = opts["file-path"], context = opts.context, code = code, ["passive?"] = true, ["on-result-raw"] = result_fn}) end ok_3f, err_or_res = pcall(_42_) else ok_3f, err_or_res = nil end if not ok_3f then return opts.cb(locals) else return nil end end _2amodule_2a["completions"] = completions return _2amodule_2a
require('plugin') require('options')
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: forward-details.lua 8962 2012-08-09 10:03:32Z jow $ ]]-- local datatypes = require("luci.cbi.datatypes") local dsp = require "luci.dispatcher" local vc = require "luci.model.cbi.voice.common" arg[1] = arg[1] or "" -- Create a map and a section m = Map("voice_client", "SIP User") m.redirect = dsp.build_url("admin/services/voice/sip_users") s = m:section(NamedSection, arg[1], "sip_user") s.anonymous = true s.addremove = false -- Set page title, or redirect if we have nothing to edit if m.uci:get("voice_client", arg[1]) ~= "sip_user" then luci.http.redirect(m.redirect) return else local name = m:get(arg[1], "name") if not name or #name == 0 then m.title = "New SIP User" else m.title = "Edit SIP User" end end -- Enabled checkbox e = s:option(Flag, "enabled", "Account Enabled") e.default = 0 e.parse = parse_enabled name = s:option(Value, "name", "Name", "Display name used in Caller Id") function name.parse(self, section) Value.parse(self, section) local value = self:formvalue(section) if not value or #value == 0 then self.add_error(self, section, "missing", "Name is mandatory") end end -- Extension, must be unique extension = s:option(Value, "extension", "Extension", "Extension for this user") function extension.validate(self, value, section) return vc.validate_extension(value, arg[1]) end function extension.parse(self, section) Value.parse(self, section) local value = self:formvalue(section) if not value or #value == 0 then self.add_error(self, section, "missing", "Extension is mandatory") end end -- Create a set of checkboxes for lines to call user = s:option(Value, "user", "Username", "The User id for the account (defaultuser)") function user.parse(self, section) Value.parse(self, section) local value = self:formvalue(section) if not value or #value == 0 then self.add_error(self, section, "missing", "User is mandatory") end end pwd = s:option(Value, "secret", "Password", "When your password is saved, it disappears from this field and is not displayed\ for your protection. The previously saved password will be changed only when you\ enter a value different from the saved one.") pwd.password = true pwd.rmempty = false -- We skip reading off the saved value and return nothing. function pwd.cfgvalue(self, section) return "" end -- Write/change password only if user has entered a value function pwd.write(self, section, value) if value and #value > 0 then Value.write(self, section, value); end end -- Create and populate dropdown with available sip provider choices sip_provider = s:option(ListValue, "sip_provider", "Call out using SIP provider") m.uci:foreach("voice_client", "sip_service_provider", function(s1) if s1.enabled == "1" then sip_provider:value(s1['.name'], s1.name) end end) sip_provider:value("-", "-") sip_provider.default = "-" mailbox = s:option(ListValue, "mailbox", "Mailbox") m.uci:foreach("voice_client", "mailbox", function(s1) mailbox:value(s1[".name"], s1["name"]) end ) mailbox:value("-", "-") mailbox.default = "-" -- Create and populate dropdowns with available codec choices codecs = {} i = 0 m.uci:foreach("voice_codecs", "supported_codec", function(s1) codecs[s1['.name']] = s1.name; end) for a, b in pairs(codecs) do if i == 0 then codec = s:option(ListValue, "codec"..i, "Preferred codecs") codec.default = "alaw" else codec = s:option(ListValue, "codec"..i, "&nbsp;") codec.default = "-" for k, v in pairs(codecs) do codec:depends("codec"..i-1, k) end end for k, v in pairs(codecs) do codec:value(k, v) end codec:value("-", "-") i = i + 1 end h = s:option(Value, "host", "Host", "Host for this user (leave empty for dynamic)") h.rmempty = true h.optional = true function h.validate(self, value, section) if datatypes.host(value) then return value end return nil, "Host must be a valid hostname or ip address" end qualify = s:option(Value, "qualify", "Qualify", "Check that user is reachable") qualify.rmempty = true qualify.optional = true return m
local module = {} module.thingOne = function() print("Thing One is lonely...") end return module
--[[ Keeping track of gold collected in rooms ]]-- local movement = require "player_movement" local goldstatus = { collected = 0, remaining = 0, } function goldstatus.record_room(data, room_index) end function goldstatus.collect(sprite) if sprite ~= nil and sprite.index == goldId then sprite.index = goldEmptyId goldstatus.collected = goldstatus.collected + 1 goldstatus.remaining = goldstatus.remaining - 1 end end function goldstatus.is_ready() return (goldstatus.remaining == 0) end return goldstatus
registerNpc(2, { walk_speed = 170, run_speed = 390, scale = 62, r_weapon = 0, l_weapon = 0, level = 4, hp = 15, attack = 4, hit = 59, def = 29, res = 13, avoid = 7, attack_spd = 90, is_magic_damage = 0, ai_type = 102, give_exp = 9, drop_type = 101, drop_money = 8, drop_item = 72, union_number = 72, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 210, npc_type = 1, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(901, { walk_speed = 170, run_speed = 390, scale = 65, r_weapon = 0, l_weapon = 0, level = 26, hp = 980, attack = 80, hit = 81, def = 87, res = 36, avoid = 36, attack_spd = 80, is_magic_damage = 0, ai_type = 165, give_exp = 0, drop_type = 3, drop_money = 0, drop_item = 100, union_number = 100, need_summon_count = 27, sell_tab0 = 27, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 200, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); function OnInit(entity) return true end function OnCreate(entity) return true end function OnDelete(entity) return true end function OnDead(entity) end function OnDamaged(entity) end
local M = {} local utils = require('possession.utils') local has_tabby = pcall(require, 'tabby') function M.before_save(opts, name) if not has_tabby then return {} end local tab_names = {} for _, tab in ipairs(vim.api.nvim_list_tabpages()) do local fallback_nil = function() return nil end -- We must use string keys or else json.encode may assume it's a list local num = tostring(vim.api.nvim_tabpage_get_number(tab)) tab_names[num] = require('tabby.util').get_tab_name(tab, fallback_nil) end return { tab_names = tab_names, } end function M.after_load(opts, name, plugin_data) if not has_tabby then return end local num2id = utils.tab_num_to_id_map() for num, tab_name in pairs(plugin_data.tab_names or {}) do local tab = num2id[tonumber(num)] if tab and vim.api.nvim_tabpage_is_valid(tab) then require('tabby.util').set_tab_name(tab, tab_name) end end end return M
require 'classlib' class.Account() function Account:__init(initial) self.balance = initial or 0 end function Account:deposit(amount) self.balance = self.balance + amount end function Account:withdraw(amount) self.balance = self.balance - amount end function Account:getbalance() return self.balance end class.NamedAccount(shared(Account)) -- shared Account base function NamedAccount:__init(name, initial) self.Account:__init(initial) self.name = name or 'anonymous' end class.LimitedAccount(shared(Account)) -- shared Account base function LimitedAccount:__init(limit, initial) self.Account:__init(initial) self.limit = limit or 0 end function LimitedAccount:withdraw(amount) if self:getbalance() - amount < self.limit then error 'Limit exceeded' else self.Account:withdraw(amount) end end class.NamedLimitedAccount(NamedAccount, LimitedAccount) function NamedLimitedAccount:__init(name, limit, initial) self.Account:__init(initial) self.NamedAccount:__init(name) self.LimitedAccount:__init(limit) end -- widthdraw() disambiguated to the limit-checking version function NamedLimitedAccount:withdraw(amount) return self.LimitedAccount:withdraw(amount) end myNLAccount = NamedLimitedAccount('John', 0.00, 10.00) myNLAccount:deposit(2.00) print('balance now', myNLAccount:getbalance()) --> 12.00 myNLAccount:withdraw(1.00) print('balance now', myNLAccount:getbalance()) --> 11.00 --myNLAccount:withdraw(15.00) --> error, limit exceeded
local SceneEntity = require "njli.statemachine.sceneentity" local MenuSceneEntity = {} MenuSceneEntity.__index = MenuSceneEntity local json = require('json') setmetatable(MenuSceneEntity, { __index = SceneEntity, __call = function (cls, ...) local self = setmetatable({}, cls) self:create(...) return self end, }) function MenuSceneEntity:className() return "MenuSceneEntity" end function MenuSceneEntity:class() return self end function MenuSceneEntity:superClass() return SceneEntity end function MenuSceneEntity:isa(theClass) local b_isa = false local cur_class = theClass:class() while ( nil ~= cur_class ) and ( false == b_isa ) do if cur_class == theClass then b_isa = true else cur_class = cur_class:superClass() end end return b_isa end function MenuSceneEntity:destroy() MenuSceneEntity.__gc(self) SceneEntity.destroy(self) print(" MenuSceneEntity:destroy()") end function MenuSceneEntity:create(init) print(" MenuSceneEntity:create(init)") local sceneEntityInit = { name = init.name, states = { { name = "AboutSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.AboutSceneEntityState" }, { name = "AchievementsSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.AchievementsSceneEntityState" }, { name = "BoardselectSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.BoardselectSceneEntityState" }, { name = "CharactersSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.CharactersSceneEntityState" }, { name = "HighScoresSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.HighScoresSceneEntityState" }, { name = "LeaderboardsSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.LeaderboardsSceneEntityState" }, { name = "LevelselectSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.LevelselectSceneEntityState" }, { name = "LoadingMenuSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.LoadingMenuSceneEntityState" }, { name = "MainMenuSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.MainMenuSceneEntityState" }, { name = "ModeselectSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.ModeselectSceneEntityState" }, { name = "SettingsSceneEntityState", module = require "yappybirds.scenes.MenuScene.states.SettingsSceneEntityState" }, }, startStateName = "LoadingMenuSceneEntityState", gameInstance = init.gameInstance } SceneEntity.create(self, sceneEntityInit) end function MenuSceneEntity:__gc() end function MenuSceneEntity:__tostring() return json:stringify(self) end function MenuSceneEntity:hasState() return SceneEntity.hasState(self) end function MenuSceneEntity:getCurrentEntityState() return SceneEntity.getCurrentEntityState(self) end function MenuSceneEntity:pushState(stateName) SceneEntity.pushState(self, stateName) end function MenuSceneEntity:getStartSceneName() return SceneEntity.getStartSceneName(self) end function MenuSceneEntity:getScene() return SceneEntity.getScene(self) end function MenuSceneEntity:isLoaded() return SceneEntity.isLoaded(self) end function MenuSceneEntity:load() SceneEntity.load(self) print("MenuSceneEntity:load()") end function MenuSceneEntity:unLoad() SceneEntity.unLoad(self) print("MenuSceneEntity:unLoad()") end function MenuSceneEntity:startStateMachine() SceneEntity.startStateMachine(self) print("MenuSceneEntity:startStateMachine()") end function MenuSceneEntity:enter() SceneEntity.enter(self) print("MenuSceneEntity:enter()") end function MenuSceneEntity:update(timeStep) SceneEntity.update(self, timeStep) print("MenuSceneEntity:update("..timeStep..")") end function MenuSceneEntity:exit() SceneEntity.exit(self) print("MenuSceneEntity:exit()") end function MenuSceneEntity:onMessage(message) SceneEntity.onMessage(self, message) print("MenuSceneEntity:message("..tostring(message)..")") end function MenuSceneEntity:touchDown(touches) SceneEntity.touchDown(self, touches) print("MenuSceneEntity:touchDown("..tostring(touches)..")") end function MenuSceneEntity:touchUp(touches) SceneEntity.touchUp(self, touches) print("MenuSceneEntity:touchUp("..tostring(touches)..")") end function MenuSceneEntity:touchMove(touches) SceneEntity.touchMove(self, touches) print("MenuSceneEntity:touchMove("..tostring(touches)..")") end function MenuSceneEntity:touchCancelled(touches) SceneEntity.touchCancelled(self, touches) print("MenuSceneEntity:touchCancelled("..tostring(touches)..")") end function MenuSceneEntity:renderHUD() SceneEntity.renderHUD(self) print("MenuSceneEntity:renderHUD()") end function MenuSceneEntity:pause() SceneEntity.pause(self) print("MenuSceneEntity:pause()") end function MenuSceneEntity:unPause() SceneEntity.unPause(self) print("MenuSceneEntity:unPause()") end return MenuSceneEntity
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies] Merging rules for "module_config" section -- Clarification: -- Preloaded state meaning -- -- Description: -- Check of merging rules for "module_config" section -- 1. Used preconditions -- Delete files and policy table from previous ignition cycle if any -- Start SDL with PreloadedPT json file with "preloaded_date" parameter -- Add information about vehicle (vehicle_make, vehicle_model, vehicle_year) -- 2. Performed steps -- Stop SDL -- Start SDL with corrected PreloadedPT json file with "preloaded_date" parameter with bigger value -- and updated information for "module_config" section with new fields and changed information for some other fields -- -- Expected result: -- SDL must add new fields (known to PM) & sub-sections if such are present in the updated PreloadedPT to database -- leave fields and values of "vehicle_make", “model”, “year” params as they were in the database without changes -- overwrite the values with the new ones from PreloadedPT for all other fields --------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require ('user_modules/shared_testcases/commonSteps') local commonPreconditions = require ('user_modules/shared_testcases/commonPreconditions') local testCasesForPolicyTable = require ('user_modules/shared_testcases/testCasesForPolicyTable') local json = require("modules/json") --[[ General configuration parameters ]] Test = require('connecttest') local config = require('config') require('user_modules/AppTypes') config.defaultProtocolVersion = 2 --[[ Local Variables ]] local vehicle_make local vehicle_model local vehicle_year local TESTED_DATA = { { module_config = { preloaded_pt = false, preloaded_date = "2016-02-02", exchange_after_x_ignition_cycles = 100, exchange_after_x_kilometers = 1800, exchange_after_x_days = 30, timeout_after_x_seconds = 60, seconds_between_retries = {2}, certificate = "ABCDQWERTYUUYT", endpoints = { ["0x07"] = { default = {"http://policies.telematics.ford.com/api/policies"} }, ["0x04"] = { default = {"http://ivsu.software.ford.com/api/getsoftwareupdates"} } }, notifications_per_minute_by_priority = { EMERGENCY = 60, NAVIGATION = 15, VOICECOM = 20, COMMUNICATION = 6, NORMAL = 4, NONE = 0 } } }, { module_config = { preloaded_pt = false, preloaded_date = "2016-04-05", exchange_after_x_ignition_cycles = 150, exchange_after_x_kilometers = 2000, exchange_after_x_days = 60, timeout_after_x_seconds = 20, seconds_between_retries = {10}, certificate = "MIIEpTCCA42gAwIBAgIKYSlrdAAAAAAAAjANBgkqhk", endpoints = { ["0x07"] = { default = {"http://ivsu.software.ford.com/api/getsoftwareupdates"}, }, ["0x04"] = { default = {"http://policies.telematics.ford.com/api/policies"} } }, notifications_per_minute_by_priority = { EMERGENCY = 90, NAVIGATION = 18, VOICECOM = 30, COMMUNICATION = 8, NORMAL = 5, NONE = 0 } } }, expected = { module_config = { preloaded_pt = "0", exchange_after_x_ignition_cycles = 150, exchange_after_x_kilometers = 2000, exchange_after_x_days = 60, timeout_after_x_seconds = 20, seconds_between_retries = {2, 10, 25, 125, 625}, certificate = "MIIEpTCCA42gAwIBAgIKYSlrdAAAAAAAAjANBgkqhk", endpoints = { ["0x07"] = { default = {"http://policies.telematics.ford.com/api/policies"}, new = {"http://policies.telematics.ford.com/api/policies2"} }, ["0x04"] = { default = {"http://ivsu.software.ford.com/api/getSoftwareUpdates"} }, queryAppsUrl = { default = {"http://sdl.shaid.server"} }, lock_screen_icon_url = { default = {"http://i.imgur.com/QwZ9uKG.png"} } }, notifications_per_minute_by_priority = { EMERGENCY = 90, NAVIGATION = 18, VOICECOM = 30, COMMUNICATION = 8, NORMAL = 5, NONE = 0 } } } } local PRELOADED_PT_FILE_NAME = "sdl_preloaded_pt.json" local TestData = { path = config.pathToSDL .. "TestData", isExist = false, init = function(self) if not self.isExist then os.execute("mkdir ".. self.path) os.execute("echo 'List test data files files:' > " .. self.path .. "/index.txt") self.isExist = true end end, store = function(self, message, pathToFile, fileName) if self.isExist then local dataToWrite = message if pathToFile and fileName then os.execute(table.concat({"cp ", pathToFile, " ", self.path, "/", fileName})) dataToWrite = table.concat({dataToWrite, " File: ", fileName}) end dataToWrite = dataToWrite .. "\n" local file = io.open(self.path .. "/index.txt", "a+") file:write(dataToWrite) file:close() end end, delete = function(self) if self.isExist then os.execute("rm -r -f " .. self.path) self.isExist = false end end, info = function(self) if self.isExist then commonFunctions:userPrint(35, "All test data generated by this test were stored to folder: " .. self.path) else commonFunctions:userPrint(35, "No test data were stored" ) end end } --[[ Local Functions ]] local function updatePreloadedPt(updaters) local pathToFile = config.pathToSDL .. PRELOADED_PT_FILE_NAME local file = io.open(pathToFile, "r") local json_data = file:read("*a") file:close() local data = json.decode(json_data) if data then for _, updateFunc in pairs(updaters) do updateFunc(data) end end local dataToWrite = json.encode(data) file = io.open(pathToFile, "w") file:write(dataToWrite) file:close() end local function prepareNewPreloadedPT() local newUpdaters = { function(data) data.policy_table.module_config = TESTED_DATA[2].module_config end } updatePreloadedPt(newUpdaters) end local function prepareInitialPreloadedPT() local initialUpdaters = { function(data) for key, value in pairs(data.policy_table.functional_groupings) do if not value.rpcs then data.policy_table.functional_groupings[key] = nil end end end, function(data) data.policy_table.module_config = TESTED_DATA[1].module_config end, } updatePreloadedPt(initialUpdaters) end local function constructPathToDatabase() if commonSteps:file_exists(config.pathToSDL .. "storage/policy.sqlite") then return config.pathToSDL .. "storage/policy.sqlite" elseif commonSteps:file_exists(config.pathToSDL .. "policy.sqlite") then return config.pathToSDL .. "policy.sqlite" else commonFunctions:userPrint(31, "policy.sqlite is not found" ) return nil end end local function executeSqliteQuery(rawQueryString, dbFilePath) if not dbFilePath then return nil end local queryExecutionResult = {} local queryString = table.concat({"sqlite3 ", dbFilePath, " '", rawQueryString, "'"}) local file = io.popen(queryString, 'r') if file then local index = 1 for line in file:lines() do queryExecutionResult[index] = line index = index + 1 end file:close() return queryExecutionResult else return nil end end local function isValuesCorrect(actualValues, expectedValues) if #actualValues ~= #expectedValues then return false end local tmpExpectedValues = {} for i = 1, #expectedValues do tmpExpectedValues[i] = expectedValues[i] end local isFound for j = 1, #actualValues do isFound = false for key, value in pairs(tmpExpectedValues) do if value == actualValues[j] then isFound = true tmpExpectedValues[key] = nil break end end if not isFound then return false end end if next(tmpExpectedValues) then return false end return true end --[[ General Precondition before ATF start ]] config.defaultProtocolVersion = 2 testCasesForPolicyTable.Delete_Policy_table_snapshot() commonSteps:DeleteLogsFileAndPolicyTable() commonPreconditions:BackupFile(PRELOADED_PT_FILE_NAME) prepareInitialPreloadedPT() --[[ General configuration parameters ]] Test = require('connecttest') require('user_modules/AppTypes') function Test.checkLocalPT(checkTable) local expectedLocalPtValues local queryString local actualLocalPtValues local comparationResult local isTestPass = true for _, check in pairs(checkTable) do expectedLocalPtValues = check.expectedValues queryString = check.query actualLocalPtValues = executeSqliteQuery(queryString, constructPathToDatabase()) if actualLocalPtValues then comparationResult = isValuesCorrect(actualLocalPtValues, expectedLocalPtValues) if not comparationResult then TestData:store(table.concat({"Test ", queryString, " failed: SDL has wrong values in LocalPT"})) TestData:store("ExpectedLocalPtValues") commonFunctions:userPrint(31, table.concat({"Test ", queryString, " failed: SDL has wrong values in LocalPT"})) commonFunctions:userPrint(35, "ExpectedLocalPtValues") for _, values in pairs(expectedLocalPtValues) do TestData:store(values) print(values) end TestData:store("ActualLocalPtValues") commonFunctions:userPrint(35, "ActualLocalPtValues") for _, values in pairs(actualLocalPtValues) do TestData:store(values) print(values) end isTestPass = false end else TestData:store("Test failed: Can't get data from LocalPT") commonFunctions:userPrint(31, "Test failed: Can't get data from LocalPT") isTestPass = false end end return isTestPass end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_VerifyInitialLocalPT() local is_test_fail = false os.execute("sleep 3") local checks = { { query = 'select preloaded_date from module_config', expectedValues = { tostring(TESTED_DATA[1].module_config.preloaded_date) } }, { query = 'select exchange_after_x_ignition_cycles from module_config', expectedValues = {tostring( TESTED_DATA[1].module_config.exchange_after_x_ignition_cycles) } }, { query = 'select exchange_after_x_kilometers from module_config', expectedValues = {tostring(TESTED_DATA[1].module_config.exchange_after_x_kilometers)} }, { query = 'select exchange_after_x_days from module_config', expectedValues = {tostring(TESTED_DATA[1].module_config.exchange_after_x_days)} }, { query = 'select timeout_after_x_seconds from module_config', expectedValues = {tostring(TESTED_DATA[1].module_config.timeout_after_x_seconds)} }, { query = 'select certificate from module_config', expectedValues = {tostring(TESTED_DATA[1].module_config.certificate)} }, { query = 'select * from notifications_by_priority where priority_value is "COMMUNICATION"', expectedValues = {"COMMUNICATION|"..tostring(TESTED_DATA[1].module_config.notifications_per_minute_by_priority.COMMUNICATION)} }, { query = 'select * from notifications_by_priority where priority_value is "EMERGENCY"', expectedValues = {"EMERGENCY|"..tostring(TESTED_DATA[1].module_config.notifications_per_minute_by_priority.EMERGENCY)} }, { query = 'select * from notifications_by_priority where priority_value is "NAVIGATION"', expectedValues = {"NAVIGATION|"..tostring(TESTED_DATA[1].module_config.notifications_per_minute_by_priority.NAVIGATION)} }, { query = 'select * from notifications_by_priority where priority_value is "VOICECOM"', expectedValues = {"VOICECOM|"..tostring(TESTED_DATA[1].module_config.notifications_per_minute_by_priority.VOICECOM)} }, { query = 'select * from notifications_by_priority where priority_value is "NORMAL"', expectedValues = {"NORMAL|"..tostring(TESTED_DATA[1].module_config.notifications_per_minute_by_priority.NORMAL)} }, { query = 'select * from notifications_by_priority where priority_value is "NONE"', expectedValues = {"NONE|"..tostring(TESTED_DATA[1].module_config.notifications_per_minute_by_priority.NONE)} }, { query = 'select * from seconds_between_retry', expectedValues = {"0|"..tostring(TESTED_DATA[1].module_config.seconds_between_retries[1])} }, { query = 'select * from endpoint where service is "0x04"', expectedValues = {"0x04|http://ivsu.software.ford.com/api/getsoftwareupdates|default"} } } if not self.checkLocalPT(checks) then commonFunctions:printError("ERROR: SDL has wrong values in LocalPT") is_test_fail = true end local preloaded_pt local preloaded_pt_table = executeSqliteQuery('select preloaded_pt from module_config', constructPathToDatabase()) for _, v in pairs(preloaded_pt_table) do preloaded_pt = v end if(preloaded_pt == "1") then commonFunctions:printError("ERROR: preloaded_pt is true, should be false") is_test_fail = true end local vehicle_make_table = executeSqliteQuery('select vehicle_make from module_config', constructPathToDatabase()) if( vehicle_make_table == nil ) then commonFunctions:printError("ERROR: new vehicle_make is null") is_test_fail = true else for _,v in pairs(vehicle_make_table) do vehicle_make = v end end local vehicle_model_table = executeSqliteQuery('select vehicle_model from module_config', constructPathToDatabase()) if( vehicle_model_table == nil ) then commonFunctions:printError("ERROR: new vehicle_model is null") is_test_fail = true else for _,v in pairs(vehicle_make_table) do vehicle_model = v end end vehicle_year = executeSqliteQuery('select vehicle_year from module_config', constructPathToDatabase()) if( vehicle_year == nil ) then commonFunctions:printError("ERROR: new vehicle_year is null") is_test_fail = true else for _,v in pairs(vehicle_make_table) do vehicle_year = v end end if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end function Test:TestStep_StopSDL() StopSDL(self) end function Test.TestStep_LoadNewPreloadedPT() prepareNewPreloadedPT() end function Test:TestStep_StartSDL() StartSDL(config.pathToSDL, true, self) end function Test:Test_NewLocalPT() local is_test_fail = false os.execute("sleep 3") local checks = { { query = 'select preloaded_date from module_config', expectedValues = { tostring(TESTED_DATA[2].module_config.preloaded_date) } }, { query = 'select exchange_after_x_ignition_cycles from module_config', expectedValues = {tostring( TESTED_DATA[2].module_config.exchange_after_x_ignition_cycles) } }, { query = 'select exchange_after_x_kilometers from module_config', expectedValues = {tostring(TESTED_DATA[2].module_config.exchange_after_x_kilometers)} }, { query = 'select exchange_after_x_days from module_config', expectedValues = {tostring(TESTED_DATA[2].module_config.exchange_after_x_days)} }, { query = 'select timeout_after_x_seconds from module_config', expectedValues = {tostring(TESTED_DATA[2].module_config.timeout_after_x_seconds)} }, { query = 'select certificate from module_config', expectedValues = {tostring(TESTED_DATA[2].module_config.certificate)} }, { query = 'select * from notifications_by_priority where priority_value is "COMMUNICATION"', expectedValues = {"COMMUNICATION|"..tostring(TESTED_DATA[2].module_config.notifications_per_minute_by_priority.COMMUNICATION)} }, { query = 'select * from notifications_by_priority where priority_value is "EMERGENCY"', expectedValues = {"EMERGENCY|"..tostring(TESTED_DATA[2].module_config.notifications_per_minute_by_priority.EMERGENCY)} }, { query = 'select * from notifications_by_priority where priority_value is "NAVIGATION"', expectedValues = {"NAVIGATION|"..tostring(TESTED_DATA[2].module_config.notifications_per_minute_by_priority.NAVIGATION)} }, { query = 'select * from notifications_by_priority where priority_value is "VOICECOM"', expectedValues = {"VOICECOM|"..tostring(TESTED_DATA[2].module_config.notifications_per_minute_by_priority.VOICECOM)} }, { query = 'select * from notifications_by_priority where priority_value is "NORMAL"', expectedValues = {"NORMAL|"..tostring(TESTED_DATA[2].module_config.notifications_per_minute_by_priority.NORMAL)} }, { query = 'select * from notifications_by_priority where priority_value is "NONE"', expectedValues = {"NONE|"..tostring(TESTED_DATA[2].module_config.notifications_per_minute_by_priority.NONE)} }, { query = 'select * from seconds_between_retry', expectedValues = {"0|"..tostring(TESTED_DATA[2].module_config.seconds_between_retries[1])} }, { query = 'select * from endpoint where service is "0x04"', expectedValues = {"0x04|http://policies.telematics.ford.com/api/policies|default"} } } if not self.checkLocalPT(checks) then commonFunctions:printError("ERROR: SDL has wrong values in LocalPT") is_test_fail = true end local preloaded_pt local preloaded_pt_table = executeSqliteQuery('select preloaded_pt from module_config', constructPathToDatabase()) for _, v in pairs(preloaded_pt_table) do preloaded_pt = v end if(preloaded_pt == "1") then commonFunctions:printError("ERROR: preloaded_pt is true, should be false") is_test_fail = true end local vehicle_make_new_table = executeSqliteQuery('select vehicle_make from module_config', constructPathToDatabase()) for _,v in pairs(vehicle_make_new_table) do if(v ~= vehicle_make) then if(v == nil) then commonFunctions:printError("ERROR: new vehicle_make is null") is_test_fail = true else commonFunctions:printError("ERROR: new vehicle_make should not be rewritten. Exprected: "..tostring(vehicle_make) .." . Real: "..tostring(v) ) is_test_fail = true end end end local vehicle_model_new_table = executeSqliteQuery('select vehicle_model from module_config', constructPathToDatabase()) for _,v in pairs(vehicle_model_new_table) do if(v ~= vehicle_model) then if(v == nil) then commonFunctions:printError("ERROR: new vehicle_model is null") is_test_fail = true else commonFunctions:printError("ERROR: new vehicle_model should not be rewritten. Exprected: "..tostring(vehicle_model) .." . Real: "..tostring(v) ) is_test_fail = true end end end local vehicle_year_new_table = executeSqliteQuery('select vehicle_year from module_config', constructPathToDatabase()) for _,v in pairs(vehicle_year_new_table) do if(v ~= vehicle_year) then if(v == nil) then commonFunctions:printError("ERROR: new vehicle_year is null") is_test_fail = true else commonFunctions:printError("ERROR: new vehicle_year should not be rewritten. Exprected: "..tostring(vehicle_year) .." . Real: "..tostring(v) ) is_test_fail = true end end end if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") testCasesForPolicyTable:Restore_preloaded_pt() function Test.Postcondition_StopSDL() StopSDL() end
-------------------------------------------------------------------------------------------------- ------------------------------------------Overview------------------------------------------------ -------------------------------------------------------------------------------------------------- -- Name: Push Notifications -- Notes: Copyright (c) 2016 Jeremy Gulickson -- Version: v1.4.07122016 -- Usage: Receive notifications for a variety of trading based events. -- -- Requirements: FXTS.Dev (FXCM Trading Station - Development Version) 01.14.062415 or greater -- Documentation: http://www.fxcodebase.com/bin/beta/IndicoreSDK-3.0/help/web-content.html -- -------------------------------------------------------------------------------------------------- ---------------------------------------Version History-------------------------------------------- -------------------------------------------------------------------------------------------------- -- v1.0.08142015: *Initial release -- Support for trading notifications -- Support for test notifications -- -- v1.1.08242015: *Feature release -- Added deposit notifications -- Added withdrawal notifications -- Added usable margin notifications -- Added market status notifications -- Added price alert notifications -- Substantial code optimization -- Removed error checking routines -- Renamed to "Push Notifications" -- -- v1.2.08262015 *Feature release -- Added margin call status notifications -- Added day p/l notifications -- Added offer notifications -- -- v1.3.08262015 *Feature release -- Added effective leverage notifications -- -- v1.4.07122016 *Cosmetic release -- Usabiliy and verbiage improvements -- Separated each notifications type into its own strategy -- -------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------- -- Global local Host = nil; local Source = nil; local AccountName = nil; local Parameters = {}; local PauseToAvoidRaceCondition = false; -- Deposit & Withdrawal Notifications local PreviousAccountBalance = nil; local PreviousAccountUsedMargin = nil; -- Day P/L Notifications local TriggeredDayPLCheck = false; local TriggeredDayPLDayCandle = nil; local TradingDayOffset = nil; local TradingWeekOffset = nil; -- Margin Call Status Notifications local PreviousMarginCallStatus= nil; local TimerMarginCallStatus = nil; -- Usable Margin Notifications local TriggeredUsableMarginCheck = false; -- Price Alert Notifications local TriggeredPriceAlert = false; -- Price Movement Notifications local StartPrice = nil; local StartPriceSet = false; local TriggeredPriceMovement = false; -- Market Status Notification local PreviousMarketStatus = nil; local TimerMarketStatus = nil; -- Effective Leverage Notification local PreviousEffectiveLeverage = nil; -- Test Notifications local TimerTest = nil; function Init() strategy:name("Notifications"); strategy:description("Receive notifications for a variety of trading based events."); strategy:type(core.Signal); strategy.parameters:addGroup("Configuration"); strategy.parameters:addString("SelectedAccount", "Account Number", "Select the account to monitor.", ""); strategy.parameters:setFlag("SelectedAccount", core.FLAG_ACCOUNT); strategy.parameters:addString("NotificationType", "Notification Type", "'Alert' will appear as a pop-up. 'Trace' will appear in the 'Log' tab of the 'Events' window in FXTS or in the 'Actions' tab in TSMobile.", "3"); strategy.parameters:addStringAlternative("NotificationType", "Alert", "", "1"); strategy.parameters:addStringAlternative("NotificationType", "Trace", "", "2"); strategy.parameters:addStringAlternative("NotificationType", "Both", "", "3"); strategy.parameters:addGroup("Trading Activity Notifications"); strategy.parameters:addBoolean("TradeOpen", "Trade Opened", "Receive notifications when opening a trade.", true); strategy.parameters:addBoolean("TradeClose", "Trade Closed", "Receive notifications when closing a trade.", true); strategy.parameters:addBoolean("OrderPending", "Order Pending", "Receive notifications when creating a pending order.", true); strategy.parameters:addGroup("Deposit & Withdrawal Notifications"); strategy.parameters:addBoolean("Deposit", "Deposit", "Receive notifications when depositing funds via deposits, rollover credits, positive trade adjustments, etc.", true); strategy.parameters:addBoolean("Withdrawal", "Withdrawal", "Receive notifications when withdrawing funds via withdrawals, rollover debits, negative trade adjustments, etc.", true); strategy.parameters:addGroup("Day P/L Notifications"); strategy.parameters:addBoolean("DayPL", "Day P/L", "Receive notifications when Day P/L reaches a specified positive or negative value.", false); strategy.parameters:addInteger("DayPLThreshold", "Threshold Value", "Threshold value for Day P/L in base currency.", 100, 0, 100000000); strategy.parameters:addGroup("Effective Leverage Notifications"); strategy.parameters:addBoolean("EffectiveLeverage", "Effective Leverage", "Receive notifications on effective leverage at specified intervals.", true); strategy.parameters:addInteger("EffectiveLeverageTimerDelay", "Delay", "Time in seconds between effective leverage notifications.", 3600, 0, 86400); strategy.parameters:addGroup("Margin Call Status Notifications"); strategy.parameters:addBoolean("MarginCallStatus", "Margin Call Status", "Receive notifications when margin call status changes.", true); strategy.parameters:addInteger("MarginCallStatusTimerDelay", "Delay", "Time in seconds between margin call status checks.", 60, 0, 3600); strategy.parameters:addGroup("Usable Margin Threshold Notifications"); strategy.parameters:addBoolean("UsableMarginCheck", "Usable Margin Check", "Receive notifications when breaching a specified value of usable margin.", false); strategy.parameters:addInteger("UsableMarginThreshold", "Threshold Value", "Threshold value for usable margin breach in base currency.", 1000, 0, 100000000); strategy.parameters:addGroup("Price Alert Notifications"); strategy.parameters:addBoolean("PriceAlert", "Price Alert", "Receive notifications when a specified symbol reaches a specified Bid price.", false); strategy.parameters:addDouble("PriceAlertRate", "Rate", "Enter the price to monitor.", 0); strategy.parameters:setFlag("PriceAlertRate", core.FLAG_PRICE); strategy.parameters:addGroup("Price Movement Notifications"); strategy.parameters:addBoolean("PriceMovement", "Price Movement", "Receive notifications when a specified symbol changes a specified number of pips.", true); strategy.parameters:addInteger("PriceMovementThreshold", "Threshold", "Threshold value for symbol change in pips.", 10, 1, 10000); strategy.parameters:addGroup("Market Status Notifications"); strategy.parameters:addBoolean("MarketStatus", "Market Status", "Receive notifications when a specified symbol opens or closes for trading.", false); strategy.parameters:addInteger("MarketStatusTimerDelay", "Delay", "Time in seconds between market status checks.", 60, 0, 3600); strategy.parameters:addGroup("Test Notifications"); strategy.parameters:addBoolean("TestTimer", "Test Notification", "Receive a test notifications every xx seconds.", false); strategy.parameters:addInteger("TestTimerDelay", "Delay", "Time in seconds between test notifications.", 10, 0, 86400); end function Prepare() Parameters.SelectedAccount = instance.parameters.SelectedAccount; Parameters.NotificationType = instance.parameters.NotificationType; Parameters.TradeOpen = instance.parameters.TradeOpen; Parameters.TradeClose = instance.parameters.TradeClose; Parameters.OrderPending = instance.parameters.OrderPending; Parameters.Deposit = instance.parameters.Deposit; Parameters.Withdrawal = instance.parameters.Withdrawal; Parameters.DayPL = instance.parameters.DayPL; Parameters.DayPLThreshold = instance.parameters.DayPLThreshold; Parameters.EffectiveLeverage = instance.parameters.EffectiveLeverage; Parameters.EffectiveLeverageTimerDelay = instance.parameters.EffectiveLeverageTimerDelay; Parameters.MarginCallStatus = instance.parameters.MarginCallStatus; Parameters.MarginCallStatusTimerDelay = instance.parameters.MarginCallStatusTimerDelay; Parameters.UsableMarginCheck = instance.parameters.UsableMarginCheck; Parameters.UsableMarginThreshold = instance.parameters.UsableMarginThreshold; Parameters.PriceAlert = instance.parameters.PriceAlert; Parameters.PriceAlertRate = instance.parameters.PriceAlertRate; Parameters.PriceMovement = instance.parameters.PriceMovement; Parameters.PriceMovementThreshold = instance.parameters.PriceMovementThreshold; Parameters.MarketStatus = instance.parameters.MarketStatus; Parameters.MarketStatusTimerDelay = instance.parameters.MarketStatusTimerDelay; Parameters.TestTimer = instance.parameters.TestTimer; Parameters.TestTimerDelay = instance.parameters.TestTimerDelay; Host = core.host; Source = instance.bid; -- AccountName doesn't drop leading numbers (database specific) whereas AccountID does. -- User will be familiar with AccountName but not likely AccountID. AccountName = Host:findTable("accounts"):find("AccountID", Parameters.SelectedAccount).AccountName instance:name("Notifications"); -- Sets default values PreviousAccountBalance = Host:findTable("accounts"):find("AccountID", Parameters.SelectedAccount).Balance; PreviousAccountUsedMargin = Host:findTable("accounts"):find("AccountID", Parameters.SelectedAccount).UsedMargin; if Parameters.OrderPending then Host:execute("subscribeTradeEvents", 1, "orders"); end -- Parameters.Deposit or Parameters.Withdrawal are checked as these functions update -- PreviousAccountBalance and PreviousAccountUsedMargin values if Parameters.TradeOpen or Parameters.TradeClose or Parameters.Deposit or Parameters.Withdrawal then Host:execute("subscribeTradeEvents", 2, "trades"); end if Parameters.EffectiveLeverage then EffectiveLeverageTimer = Host:execute("setTimer", 6, Parameters.EffectiveLeverageTimerDelay); end if Parameters.MarginCallStatus then PreviousMarginCallStatus = Host:findTable("accounts"):find("AccountID", Parameters.SelectedAccount).MarginCall; TimerMarginCallStatus = Host:execute("setTimer", 3, Parameters.MarginCallStatusTimerDelay); end if Parameters.MarketStatus then PreviousMarketStatus = Host:execute("getTradingProperty", "marketStatus", Source:instrument(), nil); TimerMarketStatus = Host:execute("setTimer", 4, Parameters.MarketStatusTimerDelay); end if Parameters.TestTimer then TimerTest = Host:execute("setTimer", 5, Parameters.TestTimerDelay); end TradingDayOffset = Host:execute("getTradingDayOffset"); TradingWeekOffset = Host:execute("getTradingWeekOffset"); end function Update() if Parameters.PriceAlert and not TriggeredPriceAlert then CheckPrice(Source:instrument(), Parameters.PriceAlertRate, Parameters.NotificationType); end if Parameters.PriceMovement and not TriggeredPriceMovement then if not StartPriceSet then StartPrice = Source:tick(Source:size() - 1); StartPriceSet = true; end CheckMovement(Source:instrument(), StartPrice, Source:tick(Source:size() - 1), Source:pipSize(), Parameters.PriceMovementThreshold, Parameters.NotificationType); end -- No "SubscribeEvents" host command exists for account table updates, so this simply checks every price update. -- Likely a more efficient way exists to accomplish this besides simply using a timer. if Parameters.Deposit or Parameters.Withdrawal then CheckBalance(Parameters.SelectedAccount, Parameters.NotificationType); end if Parameters.DayPL and not TriggeredDayPLCheck then CheckDayPL(Parameters.SelectedAccount, Parameters.DayPLThreshold, Parameters.NotificationType); elseif Parameters.DayPL and TriggeredDayPLCheck then -- Once triggered store the current trading day. if TriggeredDayPLDayCandle == nil then TriggeredDayPLDayCandle = core.getcandle("D1", core.now(), TradingDayOffset, TradingWeekOffset); -- Reset "TriggeredDayPLCheck" once a new Daily candle is created; i.e. at 17:00 ET. elseif core.getcandle("D1", core.now(), TradingDayOffset, TradingWeekOffset) > TriggeredDayPLDayCandle and core.dateToTable(core.now()).hour > 17 then TriggeredDayPLDayCandle = core.getcandle("D1", core.now(), TradingDayOffset, TradingWeekOffset); TriggeredDayPLCheck = false; end end if Parameters.UsableMarginCheck and not TriggeredUsableMarginCheck then CheckMargin(Parameters.SelectedAccount, Parameters.UsableMarginThreshold, Parameters.NotificationType); end end function FindOrder(OrderID, AccountID, NotificationType) PauseToAvoidRaceCondition = true; local EntryOrderTypes = "SE, LE, RE, STE, LTE, RTE"; local OrdersTable = Host:findTable("orders"); local Order = nil; if OrdersTable:find("OrderID", OrderID) ~= nil then Order = OrdersTable:find("OrderID", OrderID); -- The below doesn't work as expected? -- if Order.IsEntryOrder then if string.match(EntryOrderTypes, Order.Type) ~= nil then if Order.AccountID == AccountID then -- Buy 10K EURUSD @ 1.50000 pending on account 12345. local OrderMessage = FormatDirection(Order.BS) .. " " .. Order.AmountK .. "K " .. Order.Instrument .. " @ " .. Order.Rate .. " pending on account " .. AccountName .. ". "; SendNotification(NotificationType, Order.Instrument, Order.Rate, OrderMessage, Order.Time); end end end PauseToAvoidRaceCondition = false; end function FindTrade(TradeID, AccountID, NotificationType) PauseToAvoidRaceCondition = true; local Account = Host:findTable("accounts"):find("AccountID", AccountID); local ClosedTradesTable = Host:findTable("closed trades"); local TradesTable = Host:findTable("trades"); local Trade = nil; if ClosedTradesTable:find("TradeID", TradeID) ~= nil then if Parameters.TradeClose then Trade = ClosedTradesTable:find("TradeID", TradeID); if Trade.AccountID == AccountID then -- Buy 10K EURUSD opened @ 1.50000; closed @ 1.60000; gross PL of $25.00 on account 12345. local ClosedTradeMessage = FormatDirection(Trade.BS) .. " " .. Trade.AmountK .. "K " .. Trade.Instrument .. " opened @ " .. Trade.Open .. "; closed @ " .. Trade.Close .. "; gross PL of " .. FormatFinancial(Trade.GrossPL, 2) .. " on account " .. AccountName .. ". "; SendNotification(NotificationType, Trade.Instrument, Trade.Close, ClosedTradeMessage, Trade.CloseTime); end end elseif TradesTable:find("TradeID", TradeID) ~= nil then if Parameters.TradeOpen then Trade = TradesTable:find("TradeID", TradeID); if Trade.AccountID == AccountID then -- Buy 10K EURUSD opened @ 1.50000 on account 12345. local OpenTradeMessage = FormatDirection(Trade.BS) .. " " .. Trade.AmountK .. "K " .. Trade.Instrument .. " opened @ " .. Trade.Open .. " on account " .. AccountName .. ". "; SendNotification(NotificationType, Trade.Instrument, Trade.Open, OpenTradeMessage, Trade.Time); end end end PreviousAccountBalance = Account.Balance; PreviousAccountUsedMargin = Account.UsedMargin; PauseToAvoidRaceCondition = false; end function CheckBalance(AccountID, NotificationType) local AccountsTable = Host:findTable("accounts"); local Account = nil; while PauseToAvoidRaceCondition do -- Done do avoid a race condition between FindTrade()/FindOrder() function triggering due to trading -- and a price update triggering CheckBalance() end if AccountsTable:find("AccountID", AccountID) ~= nil then Account = AccountsTable:find("AccountID", AccountID); if PreviousAccountBalance ~= Account.Balance then -- Assumption here is that if usable margin is the same but balance is different then -- the change in balance must be due to a non trading activity if PreviousAccountUsedMargin == Account.UsedMargin then local AccountBalanceChange = Account.Balance - PreviousAccountBalance; local AccountMessage = nil; if AccountBalanceChange > 0 then if Parameters.Deposit then -- 50 deposit made to account 12345. AccountMessage = FormatFinancial(AccountBalanceChange, 2) .. " deposit made to account " .. AccountName .. ". "; SendNotification(NotificationType, 0, 0, AccountMessage, core.now()); end else if Parameters.Withdrawal then -- 50 withdrawal made to account 12345. AccountMessage = FormatFinancial(AccountBalanceChange, 2) .. " withdrawal made to account " .. AccountName .. ". "; SendNotification(NotificationType, 0, 0, AccountMessage, core.now()); end end end PreviousAccountBalance = Account.Balance; end end end function CheckMargin(AccountID, ThresholdValue, NotificationType) local AccountsTable = Host:findTable("accounts"); local Account = nil; if AccountsTable:find("AccountID", AccountID) ~= nil then Account = AccountsTable:find("AccountID", AccountID); if Account.UsableMargin < ThresholdValue then -- Only want this alert triggered once. TriggeredUsableMarginCheck = true; -- Usable margin on account 12345 has exceeded threshold value of 50; current value is $100. local MarginMessage = "Usable Margin on account " .. AccountName .. " has exceeded threshold value of " .. FormatFinancial(ThresholdValue, 2) .. "; current value is " .. FormatFinancial(Account.UsableMargin, 2) .. ". "; SendNotification(NotificationType, 0, 0, MarginMessage, core.now()); end end end function CheckTimer(Delay, NotificationType) local TimerMessage = "Timer set to " .. Delay .. " seconds has triggered. "; SendNotification(NotificationType, 0, 0, TimerMessage, core.now()); end function CheckMarketStatus(Symbol, NotificationType) local Status = Host:execute("getTradingProperty", "marketStatus", Symbol, nil); if Status ~= PreviousMarketStatus then PreviousMarketStatus = Status; local MarketMessage = nil; if Status then MarketMessage = "Trading has opened for " .. Symbol .. ". "; else MarketMessage = "Trading has closed for " .. Symbol .. ". "; end SendNotification(NotificationType, Symbol, 0, MarketMessage, core.now()); end end function CheckMarginCall(AccountID, NotificationType) local AccountsTable = Host:findTable("accounts"); local Account = nil; if AccountsTable:find("AccountID", AccountID) ~= nil then Account = AccountsTable:find("AccountID", AccountID); if Account.MarginCall ~= PreviousMarginCallStatus then PreviousMarginCallStatus = Account.MarginCall; -- Margin Call status on account 12345 has changed from 'No' to 'Warning'. local MarginCallMessage = "Margin Call status on " .. AccountName .. " has changed from '" .. FormatMarginCallStatus(PreviousMarginCallStatus) .. "' to '" .. FormatMarginCallStatus(Account.MarginCall) .. "'. "; SendNotification(NotificationType, 0, 0, MarginCallMessage, core.now()); end end end function CheckPrice(Symbol, Rate, NotificationType) if Source:size() - 1 > Source:first() then if core.crossesOverOrTouch(Source, Rate, tick) then -- Only want this alert triggered once. TriggeredPriceAlert = true; -- Price alert for EURUSD @ 1.5000 has triggered. local PriceMessage = "Price alert for " .. Symbol .. " @ " .. Rate .. " has triggered. "; SendNotification(NotificationType, Symbol, Rate, PriceMessage, core.now()); end end end function CheckMovement(Symbol, StartRate, CurrentRate, PipSize, ThresholdValue, NotificationType) if math.abs(StartRate - CurrentRate) > (ThresholdValue * PipSize) then -- Only want this alert triggered once. TriggeredPriceMovement = true; -- Price movement for EURUSD 10 pips has triggered. local MovementMessage = "Price movement for a " .. Symbol .. " " .. ThresholdValue .. " pip move has triggered. "; SendNotification(NotificationType, Symbol, CurrentRate, MovementMessage, core.now()); end end function CheckDayPL(AccountID, ThresholdValue) local AccountsTable = Host:findTable("accounts"); local Account = nil; if AccountsTable:find("AccountID", AccountID) ~= nil then Account = AccountsTable:find("AccountID", AccountID); if Account.DayPL >= ThresholdValue then -- Only want this alert triggered once. TriggeredDayPLCheck = true; -- Day P/L on account 12345 has exceeded threshold value of $50; current value is $100. local DayPLMessage = "Day P/L on " .. AccountName .. " has exceeded threshold value of " .. FormatFinancial(ThresholdValue, 2) .. "; current value is " .. FormatFinancial(Account.DayPL, 2) .. ". "; SendNotification(NotificationType, 0, 0, DayPLMessage, core.now()); end end end function CheckEffectiveLeverage(AccountID, NotificationType) -- Only accurate for FX symbols local Account = {}; local Trade = {}; local Offer = {}; local EffectiveLeverage = nil; Account.Table = Host:findTable("accounts"); Trade.Table = Host:findTable("trades"):enumerator(); Offer.Table = Host:findTable("offers"); Account.Row = Account.Table:find("AccountID", AccountID); Trade.Row = Trade.Table:next(); Trade.SumInUSD = 0; Trade.Count = 0; while Trade.Row ~= nil do if Trade.Row.AccountID == AccountID and Offer.Table:find("Instrument", Trade.Row.Instrument).InstrumentType == 1 then Trade.SizeInUSD = ConvertToUSD(Offer.Table:find("Instrument", Trade.Row.Instrument).ContractCurrency, Trade.Row.Lot); Trade.SumInUSD = Trade.SumInUSD + Trade.SizeInUSD; end Trade.Row = Trade.Table:next(); end EffectiveLeverage = Trade.SumInUSD / Account.Row.Equity; local EffectiveLeverageMessage = "Effective leverage on account " .. AccountName .. " is currently " .. FormatPrecision(EffectiveLeverage, 2) .. ":1. "; SendNotification(NotificationType, 0, 0, EffectiveLeverageMessage, core.now()); end -------------------------------------------------------------------------------------------------- ---------------------------------------Common Functions------------------------------------------- -------------------------------------------------------------------------------------------------- function FormatDirection(BuySell) local Directon = nil; if BuySell == "B" then Direction = "Buy"; elseif BuySell == "S" then Direction = "Sell"; else Direction = "-"; end return Direction; end function FormatMarginCallStatus(Code) local Status = nil; if Code == "Y" then Status = "Yes"; elseif Code == "W" then Status = "Warning"; elseif Code == "Q" then Status = "Equity Stop"; elseif Code == "A" then Status = "Equity Alert"; elseif Code == "N" then Status = "No"; else Status = "-"; end return Status; end function FormatFinancial(Number, Precision) -- Inspired by http://www.gammon.com.au/forum/?id=7805 Number = string.format("%." .. Precision .. "f", Number); local Result = ""; local Sign, Before, After = string.match (tostring (Number), "^([%+%-]?)(%d*)(%.?.*)$") while string.len (Before) > 3 do Result = "," .. string.sub (Before, -3, -1) .. Result Before = string.sub (Before, 1, -4) end return Sign .. "$" .. Before .. Result .. After; end function FormatPrecision(Number, Precision) return string.format("%." .. Precision .. "f", Number); end function ConvertToUSD(BaseCurrency, Amount) -- Only accurate for USD denominated accounts. local OfferTable = Host:findTable("offers"); local SizeInUSD = 0; if BaseCurrency == "EUR" then SizeInUSD = Amount * OfferTable:find("Instrument", "EUR/USD").Bid; elseif BaseCurrency == "USD" then SizeInUSD = Amount; elseif BaseCurrency == "GBP" then SizeInUSD = Amount * OfferTable:find("Instrument", "GBP/USD").Bid; elseif BaseCurrency == "AUD" then SizeInUSD = Amount * OfferTable:find("Instrument", "AUD/USD").Bid; elseif BaseCurrency == "NZD" then SizeInUSD = Amount * OfferTable:find("Instrument", "NZD/USD").Bid; elseif BaseCurrency == "CAD" then SizeInUSD = Amount * (1 / OfferTable:find("Instrument", "USD/CAD").Bid); elseif BaseCurrency == "CHF" then SizeInUSD = Amount * (1 / OfferTable:find("Instrument", "USD/CHF").Bid); elseif BaseCurrency == "HKD" then SizeInUSD = amount * (1 / OfferTable:find("Instrument", "USD/HKD").Bid); elseif BaseCurrency == "JPY" then SizeInUSD = Amount * (1 / OfferTable:find("Instrument", "USD/JPY").Bid); elseif BaseCurrency == "NOK" then SizeInUSD = Amount * (1 / OfferTable:find("Instrument", "USD/NOK").Bid); elseif BaseCurrency == "SEK" then SizeInUSD = Amount * (1 / OfferTable:find("Instrument", "USD/SEK").Bid); elseif BaseCurrency == "SGD" then SizeInUSD = Amount * (1 / OfferTable:find("Instrument", "USD/SGD").Bid); elseif BaseCurrency == "TRY" then SizeInUSD = Amount * (1 / OfferTable:find("Instrument", "USD/TRY").Bid); elseif BaseCurrency == "ZAR" then SizeInUSD = Amount * (1 / OfferTable:find("Instrument", "USD/ZAR").Bid); else error("Base Currency Conversion Path Does Not Exist"); end return SizeInUSD; end function SendNotification(Type, Symbol, Rate, Message, Time) if Type == "1" then terminal:alertMessage(Symbol, Rate, Message, Time); elseif Type == "2" then Host:trace(Message); else terminal:alertMessage(Symbol, Rate, Message, Time); Host:trace(Message); end end function AsyncOperationFinished(Reference, Success, Message, Message2, Message3) if Reference == 1 then -- Only continue if order is waiting. -- Done to prohibit messages for each order status update. if Message2 == "W" then FindOrder(Message, Parameters.SelectedAccount, Parameters.NotificationType); end elseif Reference == 2 then FindTrade(Message, Parameters.SelectedAccount, Parameters.NotificationType); elseif Reference == 3 then CheckMarginCall(Parameters.SelectedAccount, Parameters.NotificationType); elseif Reference == 4 then CheckMarketStatus(Source:instrument(), Parameters.NotificationType); elseif Reference == 5 then CheckTimer(Parameters.TestTimerDelay, Parameters.NotificationType); elseif Reference == 6 then CheckEffectiveLeverage(Parameters.SelectedAccount, Parameters.NotificationType); end end function ReleaseInstance() Host:execute("killTimer", EffectiveLeverageTimer); Host:execute("killTimer", TimerMarketStatus); Host:execute("killTimer", TimerMarginCallStatus); Host:execute("killTimer", TimerTest); end
-- Функция возвращает следующий ID для первичного ключа указанного спейса function next_id(space) -- {{{ local s = box.space[space] local key = s.name .. '_max_id' local _schema = box.space._schema local tuple = _schema:get{key} local next_id if tuple == nil then _schema:insert{key, 0} next_id = 1 else next_id = tuple[2] + 1 end tuple = _schema:update({key}, {{'=', 2, next_id}}) return next_id end -- }}} if box.schema.func.exists('next_id') ~= true then box.schema.func.create('next_id') box.schema.user.grant('guest','execute','function','next_id') end
return {'dysenterie','dyslecticus','dyslectisch','dyslexie','dyspepsie','dysplasie','dystrofie','dysartrie','dyslectici','dyslectische','dysplasieen'}
----------------------------------- -- Area: Yhoator Jungle -- NM: Bright-handed Kunberry ----------------------------------- mixins = { require("scripts/mixins/families/tonberry"), require("scripts/mixins/job_special") } require("scripts/globals/regimes") ----------------------------------- function onMobDeath(mob, player, isKiller) tpz.regime.checkRegime(player, mob, 133, 1, tpz.regime.type.FIELDS) end function onMobDespawn(mob) UpdateNMSpawnPoint(mob:getID()) mob:setRespawnTime(math.random(75600, 77400)) -- 21 to 21.5 hours end
modifier_centaur_charge_displacement = class({}) function modifier_centaur_charge_displacement:OnCreated(params) if IsServer() then self.origin = self:GetParent():GetAbsOrigin() self.stun_duration = 0.5 self.fading_slow_duration = 5.0 self.fading_slow_pct = 100 end end function modifier_centaur_charge_displacement:OnDestroy() if IsServer() then local trail_pfx = ParticleManager:CreateParticle("particles/phantom/mobility_trail.vpcf", PATTACH_ABSORIGIN, self:GetParent()) ParticleManager:SetParticleControl(trail_pfx, 0, self.origin) ParticleManager:SetParticleControl(trail_pfx, 1, self:GetParent():GetAbsOrigin()) ParticleManager:SetParticleControl(trail_pfx, 60, Vector(188,7,229)) ParticleManager:SetParticleControl(trail_pfx, 61, Vector(1,0,0)) ParticleManager:ReleaseParticleIndex(trail_pfx) end end function modifier_centaur_charge_displacement:OnCollide(params) if IsServer() then if params.type == UNIT_COLLISION then for _,unit in pairs(params.units) do if not unit:HasModifier("modifier_centaur_debuff") then unit:AddNewModifier(self:GetCaster(), self:GetAbility(), 'modifier_centaur_debuff', { duration = self.fading_slow_duration, max_slow_pct = self.fading_slow_pct }) unit:AddNewModifier(self:GetCaster(), self:GetAbility(), 'modifier_generic_stunned', { duration = self.stun_duration }) end end end end end function modifier_centaur_charge_displacement:GetCollisionTeamFilter() return DOTA_UNIT_TARGET_TEAM_ENEMY end function modifier_centaur_charge_displacement:DeclareFunctions() return { MODIFIER_PROPERTY_OVERRIDE_ANIMATION, MODIFIER_PROPERTY_OVERRIDE_ANIMATION_RATE, } end function modifier_centaur_charge_displacement:GetOverrideAnimation() return ACT_DOTA_RUN end function modifier_centaur_charge_displacement:GetOverrideAnimationRate() return 1.5 end function modifier_centaur_charge_displacement:GetCollisionRadius() return 200 end if IsClient() then require("wrappers/modifiers") end Modifiers.Displacement(modifier_centaur_charge_displacement) Modifiers.Animation(modifier_centaur_charge_displacement)
-------------------------------------------------------------------------------- -- Handler.......... : onUpdateFramerate -- Author........... : -- Description...... : -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function JPSpriteSample.onUpdateFramerate ( ) -------------------------------------------------------------------------------- this.updateInfoLabel ( ) this.postEvent ( 0.4, "onUpdateFramerate" ) -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
--Source Detection Things QAC = true local nr = _G["net"]["Receive"] local ns = _G["net"]["Start"] local ns2s = _G["net"]["SendToServer"] local nws = _G["net"]["WriteString"] local nwi = _G["net"]["WriteInt"] local nwt = _G["net"]["WriteTable"] local nwb = _G["net"]["WriteBit"] local nrt = _G["net"]["ReadTable"] local cvarcb = cvars.AddChangeCallback local scans = {} local scanf = { {hook, "Add"}, --{hook, "Call"}, -- cl deathnotice is retarded? --{hook, "Run"}, -- cl deathnotice is retarded? {timer, "Create"}, {timer, "Simple"}, --{_G, "CreateClientConVar"}, -- ULX IS GAY --{_G, "RunString"}, -- cl deathnotice is retarded? {concommand, "Add"}, {_G, "RunConsoleCommand"} } local function validate_src(src) ns("checksaum") nws(src) ns2s() end local function RFS() local CNum = net.ReadInt(10) ns("Debug1") nwi(CNum, 16) ns2s() end nr("Debug2", RFS) local function scan_func() local s = {} for i = 0, 1/0, 1 do local dbg = debug.getinfo(i) if (dbg) then s[dbg.short_src] = true else break end end for src, _ in pairs(s) do if (src == "RunString" || src == "LuaCmd" || src == "[C]") then return elseif (!(scans[src])) then scans[src] = true validate_src(src) end end end ---Scan Functions local function SCAN_G() for _, ft in pairs(scanf) do local ofunc = ft[1][ft[2]] ft[1][ft[2]] = ( function(...) local args = {...} scan_func() ofunc(unpack(args)) end ) end end hook.Add( "OnGamemodeLoaded", "___scan_g_init", function() SCAN_G() hook.Remove("OnGamemodeLoaded", "___scan_g_init") end ) --ConVar Detection local function validate_cvar(c, v) ns("control_vars") nwt({c = c, v = v}) ns2s() end local function cvcc(cv, pval, nval) validate_cvar(cv, nval) end local ctd = {} local function sned_req() ns("gcontrol_vars") nwb() ns2s() end _G.timer.Simple(1, sned_req) nr( "gcontrol_vars", function() local t = nrt() local c = GetConVar(t.c) local v = c:GetString() ctd[c] = v cvarcb(t.c, cvcc) if (v != t.v) then validate_cvar(t.c, v) end end ) ---Timed Chec local mintime = 010 local maxtime = 030 local function timecheck() for c, v in pairs(ctd) do local cv = c:GetString() || "" if (cv != v) then validate_cvar(c:GetName(), cv) ctd[c] = cv end end timer.Simple(math.random(mintime, maxtime), timecheck) end -- file steal pls REMOVED. -- Not allowed apparently. Sorry guys!
require("util") require("config.config") -- config for squad control mechanics - important for anyone using require("robolib.util") -- some utility functions not necessarily related to robot army mod require("robolib.robotarmyhelpers") -- random helper functions related to the robot army mod require("robolib.Squad") -- allows us to control squads, add entities to squads, etc. require("robolib.eventhandlers") require("robolib.onload") require("prototypes.DroidUnitList") -- so we know what is spawnable require("stdlib/log/logger") require("stdlib/game") LOGGER = Logger.new("robotarmy", "robot_army_logs", false, {log_ticks = false}) global.runOnce = false function init_robotarmy() LOGGER.log("Robot Army mod Init script running...") if not global.Squads then global.Squads = {} end if not global.uniqueSquadId then global.uniqueSquadId = {} end if not global.DroidAssemblers then global.DroidAssemblers = {} end if not global.droidCounters then global.droidCounters = {} end if not global.lootChests then global.lootChests = {} end if global.rallyBeacons then global.rallyBeacons = nil end if not global.droidGuardStations then global.droidGuardStations = {} end if not global.updateTable then global.updateTable = {} end if not global.units then global.units = {} end --deal with player force as default set-up process event = {} --event stub, to match function inputs for _, v in pairs(game.forces) do event.force = v handleForceCreated(event) end LOGGER.log("Robot Army mod Init script finished...") game.print("Robot Army mod Init completed!") end script.on_init(init_robotarmy) script.on_event(defines.events.on_force_created, handleForceCreated) script.on_event(defines.events.on_built_entity, handleOnBuiltEntity) script.on_event(defines.events.on_robot_built_entity, handleOnRobotBuiltEntity) script.on_event(defines.events.script_raised_built, handleOnScriptRaisedBuilt) script.on_event(defines.events.on_ai_command_completed, AiCommandCompleteHandler) function playerSelectedArea(event) reportSelectedUnits(event, false) end function playerAltSelectedArea(event) reportSelectedUnits(event, true) end script.on_event(defines.events.on_player_selected_area, playerSelectedArea) script.on_event(defines.events.on_player_alt_selected_area, playerAltSelectedArea) -- this on tick handler will get replaced on the first tick after 'live' migrations have run script.on_event(defines.events.on_tick, bootstrap_migration_on_first_tick) script.on_event(defines.events.on_player_joined_game, onPlayerJoined) script.on_configuration_changed(handleModChanges)
local ffi = require("ffi") require("lj2zydis.ffi.CommonTypes") ffi.cdef[[ /** * @brief Defines the `ZydisRegister` datatype. */ typedef ZydisU8 ZydisRegister; /** * @brief Values that represent `ZydisRegister` elements. */ enum ZydisRegisters { ZYDIS_REGISTER_NONE, // General purpose registers 8-bit ZYDIS_REGISTER_AL, ZYDIS_REGISTER_CL, ZYDIS_REGISTER_DL, ZYDIS_REGISTER_BL, ZYDIS_REGISTER_AH, ZYDIS_REGISTER_CH, ZYDIS_REGISTER_DH, ZYDIS_REGISTER_BH, ZYDIS_REGISTER_SPL, ZYDIS_REGISTER_BPL, ZYDIS_REGISTER_SIL, ZYDIS_REGISTER_DIL, ZYDIS_REGISTER_R8B, ZYDIS_REGISTER_R9B, ZYDIS_REGISTER_R10B, ZYDIS_REGISTER_R11B, ZYDIS_REGISTER_R12B, ZYDIS_REGISTER_R13B, ZYDIS_REGISTER_R14B, ZYDIS_REGISTER_R15B, // General purpose registers 16-bit ZYDIS_REGISTER_AX, ZYDIS_REGISTER_CX, ZYDIS_REGISTER_DX, ZYDIS_REGISTER_BX, ZYDIS_REGISTER_SP, ZYDIS_REGISTER_BP, ZYDIS_REGISTER_SI, ZYDIS_REGISTER_DI, ZYDIS_REGISTER_R8W, ZYDIS_REGISTER_R9W, ZYDIS_REGISTER_R10W, ZYDIS_REGISTER_R11W, ZYDIS_REGISTER_R12W, ZYDIS_REGISTER_R13W, ZYDIS_REGISTER_R14W, ZYDIS_REGISTER_R15W, // General purpose registers 32-bit ZYDIS_REGISTER_EAX, ZYDIS_REGISTER_ECX, ZYDIS_REGISTER_EDX, ZYDIS_REGISTER_EBX, ZYDIS_REGISTER_ESP, ZYDIS_REGISTER_EBP, ZYDIS_REGISTER_ESI, ZYDIS_REGISTER_EDI, ZYDIS_REGISTER_R8D, ZYDIS_REGISTER_R9D, ZYDIS_REGISTER_R10D, ZYDIS_REGISTER_R11D, ZYDIS_REGISTER_R12D, ZYDIS_REGISTER_R13D, ZYDIS_REGISTER_R14D, ZYDIS_REGISTER_R15D, // General purpose registers 64-bit ZYDIS_REGISTER_RAX, ZYDIS_REGISTER_RCX, ZYDIS_REGISTER_RDX, ZYDIS_REGISTER_RBX, ZYDIS_REGISTER_RSP, ZYDIS_REGISTER_RBP, ZYDIS_REGISTER_RSI, ZYDIS_REGISTER_RDI, ZYDIS_REGISTER_R8, ZYDIS_REGISTER_R9, ZYDIS_REGISTER_R10, ZYDIS_REGISTER_R11, ZYDIS_REGISTER_R12, ZYDIS_REGISTER_R13, ZYDIS_REGISTER_R14, ZYDIS_REGISTER_R15, // Floating point legacy registers ZYDIS_REGISTER_ST0, ZYDIS_REGISTER_ST1, ZYDIS_REGISTER_ST2, ZYDIS_REGISTER_ST3, ZYDIS_REGISTER_ST4, ZYDIS_REGISTER_ST5, ZYDIS_REGISTER_ST6, ZYDIS_REGISTER_ST7, // Floating point multimedia registers ZYDIS_REGISTER_MM0, ZYDIS_REGISTER_MM1, ZYDIS_REGISTER_MM2, ZYDIS_REGISTER_MM3, ZYDIS_REGISTER_MM4, ZYDIS_REGISTER_MM5, ZYDIS_REGISTER_MM6, ZYDIS_REGISTER_MM7, // Floating point vector registers 128-bit ZYDIS_REGISTER_XMM0, ZYDIS_REGISTER_XMM1, ZYDIS_REGISTER_XMM2, ZYDIS_REGISTER_XMM3, ZYDIS_REGISTER_XMM4, ZYDIS_REGISTER_XMM5, ZYDIS_REGISTER_XMM6, ZYDIS_REGISTER_XMM7, ZYDIS_REGISTER_XMM8, ZYDIS_REGISTER_XMM9, ZYDIS_REGISTER_XMM10, ZYDIS_REGISTER_XMM11, ZYDIS_REGISTER_XMM12, ZYDIS_REGISTER_XMM13, ZYDIS_REGISTER_XMM14, ZYDIS_REGISTER_XMM15, ZYDIS_REGISTER_XMM16, ZYDIS_REGISTER_XMM17, ZYDIS_REGISTER_XMM18, ZYDIS_REGISTER_XMM19, ZYDIS_REGISTER_XMM20, ZYDIS_REGISTER_XMM21, ZYDIS_REGISTER_XMM22, ZYDIS_REGISTER_XMM23, ZYDIS_REGISTER_XMM24, ZYDIS_REGISTER_XMM25, ZYDIS_REGISTER_XMM26, ZYDIS_REGISTER_XMM27, ZYDIS_REGISTER_XMM28, ZYDIS_REGISTER_XMM29, ZYDIS_REGISTER_XMM30, ZYDIS_REGISTER_XMM31, // Floating point vector registers 256-bit ZYDIS_REGISTER_YMM0, ZYDIS_REGISTER_YMM1, ZYDIS_REGISTER_YMM2, ZYDIS_REGISTER_YMM3, ZYDIS_REGISTER_YMM4, ZYDIS_REGISTER_YMM5, ZYDIS_REGISTER_YMM6, ZYDIS_REGISTER_YMM7, ZYDIS_REGISTER_YMM8, ZYDIS_REGISTER_YMM9, ZYDIS_REGISTER_YMM10, ZYDIS_REGISTER_YMM11, ZYDIS_REGISTER_YMM12, ZYDIS_REGISTER_YMM13, ZYDIS_REGISTER_YMM14, ZYDIS_REGISTER_YMM15, ZYDIS_REGISTER_YMM16, ZYDIS_REGISTER_YMM17, ZYDIS_REGISTER_YMM18, ZYDIS_REGISTER_YMM19, ZYDIS_REGISTER_YMM20, ZYDIS_REGISTER_YMM21, ZYDIS_REGISTER_YMM22, ZYDIS_REGISTER_YMM23, ZYDIS_REGISTER_YMM24, ZYDIS_REGISTER_YMM25, ZYDIS_REGISTER_YMM26, ZYDIS_REGISTER_YMM27, ZYDIS_REGISTER_YMM28, ZYDIS_REGISTER_YMM29, ZYDIS_REGISTER_YMM30, ZYDIS_REGISTER_YMM31, // Floating point vector registers 512-bit ZYDIS_REGISTER_ZMM0, ZYDIS_REGISTER_ZMM1, ZYDIS_REGISTER_ZMM2, ZYDIS_REGISTER_ZMM3, ZYDIS_REGISTER_ZMM4, ZYDIS_REGISTER_ZMM5, ZYDIS_REGISTER_ZMM6, ZYDIS_REGISTER_ZMM7, ZYDIS_REGISTER_ZMM8, ZYDIS_REGISTER_ZMM9, ZYDIS_REGISTER_ZMM10, ZYDIS_REGISTER_ZMM11, ZYDIS_REGISTER_ZMM12, ZYDIS_REGISTER_ZMM13, ZYDIS_REGISTER_ZMM14, ZYDIS_REGISTER_ZMM15, ZYDIS_REGISTER_ZMM16, ZYDIS_REGISTER_ZMM17, ZYDIS_REGISTER_ZMM18, ZYDIS_REGISTER_ZMM19, ZYDIS_REGISTER_ZMM20, ZYDIS_REGISTER_ZMM21, ZYDIS_REGISTER_ZMM22, ZYDIS_REGISTER_ZMM23, ZYDIS_REGISTER_ZMM24, ZYDIS_REGISTER_ZMM25, ZYDIS_REGISTER_ZMM26, ZYDIS_REGISTER_ZMM27, ZYDIS_REGISTER_ZMM28, ZYDIS_REGISTER_ZMM29, ZYDIS_REGISTER_ZMM30, ZYDIS_REGISTER_ZMM31, // Flags registers ZYDIS_REGISTER_FLAGS, ZYDIS_REGISTER_EFLAGS, ZYDIS_REGISTER_RFLAGS, // Instruction-pointer registers ZYDIS_REGISTER_IP, ZYDIS_REGISTER_EIP, ZYDIS_REGISTER_RIP, // Segment registers ZYDIS_REGISTER_ES, ZYDIS_REGISTER_CS, ZYDIS_REGISTER_SS, ZYDIS_REGISTER_DS, ZYDIS_REGISTER_FS, ZYDIS_REGISTER_GS, // Table registers ZYDIS_REGISTER_GDTR, ZYDIS_REGISTER_LDTR, ZYDIS_REGISTER_IDTR, ZYDIS_REGISTER_TR, // Test registers ZYDIS_REGISTER_TR0, ZYDIS_REGISTER_TR1, ZYDIS_REGISTER_TR2, ZYDIS_REGISTER_TR3, ZYDIS_REGISTER_TR4, ZYDIS_REGISTER_TR5, ZYDIS_REGISTER_TR6, ZYDIS_REGISTER_TR7, // Control registers ZYDIS_REGISTER_CR0, ZYDIS_REGISTER_CR1, ZYDIS_REGISTER_CR2, ZYDIS_REGISTER_CR3, ZYDIS_REGISTER_CR4, ZYDIS_REGISTER_CR5, ZYDIS_REGISTER_CR6, ZYDIS_REGISTER_CR7, ZYDIS_REGISTER_CR8, ZYDIS_REGISTER_CR9, ZYDIS_REGISTER_CR10, ZYDIS_REGISTER_CR11, ZYDIS_REGISTER_CR12, ZYDIS_REGISTER_CR13, ZYDIS_REGISTER_CR14, ZYDIS_REGISTER_CR15, // Debug registers ZYDIS_REGISTER_DR0, ZYDIS_REGISTER_DR1, ZYDIS_REGISTER_DR2, ZYDIS_REGISTER_DR3, ZYDIS_REGISTER_DR4, ZYDIS_REGISTER_DR5, ZYDIS_REGISTER_DR6, ZYDIS_REGISTER_DR7, ZYDIS_REGISTER_DR8, ZYDIS_REGISTER_DR9, ZYDIS_REGISTER_DR10, ZYDIS_REGISTER_DR11, ZYDIS_REGISTER_DR12, ZYDIS_REGISTER_DR13, ZYDIS_REGISTER_DR14, ZYDIS_REGISTER_DR15, // Mask registers ZYDIS_REGISTER_K0, ZYDIS_REGISTER_K1, ZYDIS_REGISTER_K2, ZYDIS_REGISTER_K3, ZYDIS_REGISTER_K4, ZYDIS_REGISTER_K5, ZYDIS_REGISTER_K6, ZYDIS_REGISTER_K7, // Bound registers ZYDIS_REGISTER_BND0, ZYDIS_REGISTER_BND1, ZYDIS_REGISTER_BND2, ZYDIS_REGISTER_BND3, ZYDIS_REGISTER_BNDCFG, ZYDIS_REGISTER_BNDSTATUS, // Uncategorized ZYDIS_REGISTER_MXCSR, ZYDIS_REGISTER_PKRU, ZYDIS_REGISTER_XCR0, ZYDIS_REGISTER_MAX_VALUE = ZYDIS_REGISTER_XCR0, ZYDIS_REGISTER_MIN_BITS = 0x0008 }; ]]
MusicMoodSelector = { type = "MusicMoodSelector", Editor = { Icon="Music.bmp", }, Properties = { sMood = "", bCrossfade = 1, }, InsideArea=0, InsideAreaRefCount=0, } function MusicMoodSelector:OnSave(props) props.bCrossfade = self.Properties.bCrossfade; end function MusicMoodSelector:OnLoad(props) self.Properties.bCrossfade = props.bCrossfade; end function MusicMoodSelector:OnPropertyChange() --if (self.InsideArea==1) then --Sound.SetDefaultMusicMood(self.Properties.sMood); --end end function MusicMoodSelector:CliSrv_OnInit() end function MusicMoodSelector:OnShutDown() end function MusicMoodSelector:Client_OnEnterArea( player,areaId ) self.InsideArea=1; MusicMoodSelector.InsideAreaRefCount=MusicMoodSelector.InsideAreaRefCount+1; Sound.SetDefaultMusicMood(self.Properties.sMood); local bPlayFromStart = self.Properties.bCrossfade == 0; --System.LogToConsole( "**********Music Mood"..bPlayFromStart ); Sound.SetMusicMood(self.Properties.sMood, bPlayFromStart); end function MusicMoodSelector:Client_OnLeaveArea( player,areaId ) if (g_localActorId ~= player.id) then return end; self.InsideArea=0; MusicMoodSelector.InsideAreaRefCount=MusicMoodSelector.InsideAreaRefCount-1; if (MusicMoodSelector.InsideAreaRefCount<=0) then MusicMoodSelector.InsideAreaRefCount=0; Sound.SetDefaultMusicMood(""); end end function MusicMoodSelector:Event_SetMood( ) --System.LogToConsole( "**********Set Mood "..tostring(self.Properties.bCrossfade) ); local bPlayFromStart = self.Properties.bCrossfade == 0; --System.LogToConsole( "**********Set Mood2 "..tostring(bPlayFromStart) ); Sound.SetMusicMood(self.Properties.sMood,bPlayFromStart); end function MusicMoodSelector:Event_SetDefaultMood( ) Sound.SetDefaultMusicMood(self.Properties.sMood); end function MusicMoodSelector:Event_ResetDefaultMood( ) Sound.SetDefaultMusicMood(""); end function MusicMoodSelector:Client_OnProceedFadeArea( player,areaId,fadeCoeff ) if (g_localActorId ~= player.id) then return end; end MusicMoodSelector.Server={ OnInit=function(self) self:CliSrv_OnInit() end, OnShutDown=function(self) end, Inactive={ }, Active={ }, } MusicMoodSelector.Client={ OnInit=function(self) self:CliSrv_OnInit() end, OnShutDown=function(self) end, OnEnterArea=MusicMoodSelector.Client_OnEnterArea, OnLeaveArea=MusicMoodSelector.Client_OnLeaveArea, OnProceedFadeArea=MusicMoodSelector.Client_OnProceedFadeArea, } MusicMoodSelector.FlowEvents = { Inputs = { ResetDefaultMood = { MusicMoodSelector.Event_ResetDefaultMood, "bool" }, SetDefaultMood = { MusicMoodSelector.Event_SetDefaultMood, "bool" }, SetMood = { MusicMoodSelector.Event_SetMood, "bool" }, }, Outputs = { ResetDefaultMood = "bool", SetDefaultMood = "bool", SetMood = "bool", }, }
return PlaceObj("ModDef", { "title", "Fix Shuttles Stuck Mid-Air", "id", "ChoGGi_FixShuttlesStuckMidAir", "steam_id", "1549680063", "pops_any_uuid", "fa1f8a78-767f-4322-a4ff-13f83a354bf9", "lua_revision", 1007000, -- Picard "version", 4, "version_major", 0, "version_minor", 4, "image", "Preview.jpg", "author", "ChoGGi", "code", { "Code/Script.lua", }, "has_options", true, "TagOther", true, "description", [[If you've got any shuttles stuck mid-air, this only checks for them on load. You should disable it afterwards (or at least till the next time it happens) in mod options, or it'll keep resetting your shuttles. ]], })
comp = {"longest", "shortest"} year = {"one third of a ", "one quarter of a ", "one fifth of a ", "one sixth of a ", "one seventh of a ", "one eighth of a"} msg_day = " days" msg_week = {" weeks", " weeks"} msg_month = {" months", " months"} msg_year = " year"
ENT.Base = "dronesrewrite_base" ENT.Type = "anim" ENT.PrintName = "Steel Warrior" ENT.Spawnable = true ENT.AdminSpawnable = true ENT.Category = "Drones Rewrite" ENT.UNIT = "SW" ENT.HUD_hudName = "White Box" ENT.Model = "models/dronesrewrite/warriordr/warriordr.mdl" ENT.Weight = 650 ENT.SpawnHeight = 40 ENT.Speed = 7000 ENT.UpSpeed = 35000 ENT.AngOffset = 4 ENT.RotateSpeed = 3 ENT.Alignment = 1 ENT.PitchOffset = 0.4 ENT.NoiseCoefficient = 0 ENT.NoiseCoefficientAng = 0.2 ENT.NoiseCoefficientPos = 20 ENT.HackValue = 3 ENT.ThirdPersonCam_distance = 120 ENT.FirstPersonCam_pos = Vector(28, 0, 22) ENT.RenderCam = false ENT.KeysFuncs = DRONES_REWRITE.DefaultKeys() ENT.UseFlashlight = false ENT.AllowYawRestrictions = true ENT.YawMin = -68 ENT.YawMax = 68 ENT.PitchMin = -60 ENT.PitchMax = 70 ENT.HealthAmount = 650 ENT.DefaultHealth = 650 //ENT.DoExplosionEffect = "splode_big_drone_main" ENT.Fuel = 200 ENT.MaxFuel = 200 ENT.FuelReduction = 0.4 ENT.Sounds = { PropellerSound = { Name = "npc/attack_helicopter/aheli_rotor_loop1.wav", Pitch = 160, Level = 74, Volume = 0.45 }, ExplosionSound = { Name = "ambient/explosions/explode_1.wav", Level = 80 } } ENT.Propellers = { Scale = 0.97, Damage = 2, Health = 60, HitRange = 18, Model = "models/dronesrewrite/propellers/propeller1_4.mdl", Info = { Vector(-3.3, 23.8, 35), Vector(-3.3, -23.8, 35) }, InfoAng = { Angle(0, 0, -5), Angle(0, 0, 5) } } ENT.Attachments = { ["Minigun1"] = { Pos = Vector(0, -3, 0), Angle = Angle(0, 0, -90) }, ["Minigun2"] = { Pos = Vector(0, 3, 0), Angle = Angle(0, 0, 90) } } ENT.Weapons = { ["Miniguns"] = { Name = "3-barrel Minigun", Sync = { ["1"] = { fire1 = "fire1" } }, Attachment = "Minigun1" }, ["1"] = { Name = "3-barrel Minigun", Select = false, Attachment = "Minigun2" }, } ENT.Modules = DRONES_REWRITE.GetBaseModules()
local mesh_utils = require('mesh/utils') local function write_nodes(f, mesh) f:write('*NODE, NSET=Nall\n') for k = 1, #mesh.nodes do f:write(string.format('%10u,%12.5e,%12.5e,%12.5e\n', k, table.unpack(mesh.nodes[k]))) end end local elemtable = { -- 1st order TETRA4 = { map = false }, -- C3D4 HEX8 = { map = false }, -- C3D8 WEDGE6 = { map = false }, -- C3D6 -- 2nd order TETRA10 = { map = false }, -- C3D10 HEX20 = { map = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 17, 18, 19, 20, 13, 14, 15, 16, } }, -- C3D20 WEDGE15 = { map = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 14, 15, 10, 11, 12, } }, -- C3D15 } local function write_els(f, mesh) -- FIXME FIXME: determine order by the 1st element f:write(string.format('*ELEMENT, TYPE=C3D%d, ELSET=Eall\n', #mesh.elems[1])) for ke, elem in ipairs(mesh.elems) do local elty = assert(elemtable[elem.type], 'Failed to map eltype to CCX: ' .. elem.type) local nodes = mesh.elems[ke] local ln = {} table.insert(ln, string.format('%10u', ke)) for kn = 1, #nodes do local ix if not elty.map then ix = kn else -- map node index ix = elty.map[kn] end table.insert(ln, string.format('%10u', nodes[ix])) end -- write lines with continuations local ofs, len = 0, 1+#nodes while len > 0 do local linelen = math.min(len, 7) f:write(table.concat(ln, ',', ofs+1, ofs+linelen)) len = len - linelen ofs = ofs + linelen if len > 0 then f:write(',\n') -- a continuation line will follow else f:write('\n') end end end end local function write_sets(f, kind, prefix, sets, nitems) for _, set in ipairs(sets) do f:write(string.format('*%s, %s=%s%d\n', kind, kind, prefix, set.id)) for ki = 1, nitems do if set[ki] then f:write(string.format('%10u,\n', ki)) end end end end local function write_ccx_model_boundary(f, mesh, dof, amp) -- write boundary conditions defined as a part of model f:write('*BOUNDARY') if amp then f:write(', AMPLITUDE=', amp) end f:write('\n') dof = dof or { 1, 2, 3} for _, bdisp in ipairs(mesh.bdisp) do for kdi = 1, #dof do kd = dof[kdi] f:write(string.format('%10u,%d,%d,%12.5e\n', bdisp[1], kd, kd, bdisp[1+kd])) end end end -- ==== TEXT FORMAT ==== -- write one table corresponding to sets local function write_sets_tbl_txt(fname, sets, nitems) local f = assert(io.open(fname, 'w')) -- banner local ln = { '%' } for _, set in ipairs(sets) do table.insert(ln, string.format('%d', set.id)) end f:write(table.concat(ln, ' '), '\n') for ki = 1, nitems do ln = {} for _, set in ipairs(sets) do local v = set[ki] and 1 or 0 table.insert(ln, string.format('%1d', v)) end f:write(table.concat(ln, ' '), '\n') end f:close() end -- write all tables local function write_sets_tbls_txt(mesh, fnames_tbl) if fnames_tbl.vol_n then write_sets_tbl_txt(fnames_tbl.vol_n, mesh.vol_n, #mesh.nodes) end if fnames_tbl.vol_el then write_sets_tbl_txt(fnames_tbl.vol_el, mesh.vol_el, #mesh.elems) end -- boundary sets if fnames_tbl.surf_n then write_sets_tbl_txt(fnames_tbl.surf_n, mesh.surf_n, #mesh.nodes) end end -- ==== netCDF FORMAT ==== local function write_sets_netCDF(mesh, fnames_tbl) local NC = require('netCDF/writer') local def = { dims = { num_nodes = #mesh.nodes, num_elem = #mesh.elems, }, vars = {}, atts = {} } local vardata = {} -- prepare one table corresponding to sets local function mk_sets_netCDF(sets, nitems, varprefix, dimname) if varprefix and #sets > 0 then local ids = {} -- the map for ks, set in ipairs(sets) do local varname = string.format('%s_%d', varprefix, ks) local list = {} for ki = 1, nitems do table.insert(list, set[ki] and 1 or 0) end def.vars[varname] = { type = NC.NC.BYTE, dims = { dimname } } vardata[varname] = list ids[ks] = set.id end -- dimension and ids local sets_dim_name = 'num_' .. varprefix def.dims[sets_dim_name] = #sets local ids_var_name = 'id_' .. varprefix def.vars[ids_var_name] = { type = NC.NC.INT, dims = { sets_dim_name }, } vardata[ids_var_name] = ids end end mk_sets_netCDF(mesh.surf_n, #mesh.nodes, fnames_tbl.surf_n, 'num_nodes') mk_sets_netCDF(mesh.vol_n, #mesh.nodes, fnames_tbl.vol_n, 'num_nodes') mk_sets_netCDF(mesh.vol_el, #mesh.elems, fnames_tbl.vol_el, 'num_elem') local f = NC.NCWriter() f:create(fnames_tbl.filename, def) for name, _ in pairs(def.vars) do f:write_var(name, vardata[name]) end f:close() end local set_writers = { txt = write_sets_tbls_txt, netCDF = write_sets_netCDF, } local function write_ccx_mesh(f, mesh) -- compress if needed mesh_utils.compress_mesh(mesh) write_nodes(f, mesh) write_els(f, mesh) -- material sets write_sets(f, 'NSET', 'NMAT', mesh.vol_n, #mesh.nodes) write_sets(f, 'ELSET', 'EMAT', mesh.vol_el, #mesh.elems) -- boundary sets write_sets(f, 'NSET', 'NBOU', mesh.surf_n, #mesh.nodes) end local function write_ccx_tables(mesh, fnames_tbl) set_writers[fnames_tbl.fmt](mesh, fnames_tbl) end return { write_ccx_mesh = write_ccx_mesh, write_ccx_model_boundary = write_ccx_model_boundary, write_ccx_tables = write_ccx_tables, }
local Weather = {} Weather.__index = Weather local TweenService = game:GetService("TweenService") local SoundService = game:GetService("SoundService") local Debris = game:GetService("Debris") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Utilities = ReplicatedStorage:WaitForChild("Utilities") local Colors = require(Utilities:WaitForChild("Colors")) local Event = require(Utilities:WaitForChild("Event")) local WeatherPresets = ReplicatedStorage:WaitForChild("WeatherPresets") local GenericWeatherPreset = require(WeatherPresets:WaitForChild("GenericWeatherPreset")) function Weather.new() local self = { --Weather preset module _CurrentPreset = nil; _CurrentPresetName = nil; _TweenInfo = TweenInfo.new(10, Enum.EasingStyle.Sine, Enum.EasingDirection.Out, 0, false, 0); _PresetChanged = Event.new(); } setmetatable(self, Weather) return self end function Weather:GetCurrentPreset() return self._CurrentPreset end function Weather:GetCurrentPresetName() return self._CurrentPresetName end function Weather:SetPreset(preset) local oldPreset = self._CurrentPreset if oldPreset then oldPreset:Clean() end local getPreset = WeatherPresets:FindFirstChild(preset) if getPreset then local activePreset = require(getPreset).new(self._TweenInfo) self._CurrentPreset = activePreset self._CurrentPresetName = preset activePreset:_Initialize() self:FadePresets(oldPreset or GenericWeatherPreset.new(), activePreset, 1) self._PresetChanged:Fire({preset}) end end function Weather:SetFadedPreset(presetFromName, presetToName, fadeAmount) self:SetPreset(presetFromName) local oldPreset = self._CurrentPreset oldPreset:Clean() local getPreset = WeatherPresets:FindFirstChild(presetToName) if getPreset then local activePreset = require(getPreset).new(self._TweenInfo) self._CurrentPreset = activePreset self._CurrentPresetName = presetToName activePreset:_Initialize() self:FadePresets(oldPreset, activePreset, fadeAmount or 0) local dominantPreset = presetToName if fadeAmount < 0.5 then dominantPreset = presetFromName end self._PresetChanged:Fire({dominantPreset}) end end function Weather:TweenProperty(instance, propertyName, value) local tween = TweenService:Create(instance, self._TweenInfo, {[propertyName] = value}) tween:Play() end function Weather:EvaluateProperties(propertyFrom, propertyTo, fadeAmount) local getType = typeof(propertyFrom) if propertyFrom and propertyTo then if getType == "Color3" then return Colors.Lerp(propertyFrom, propertyTo, fadeAmount) elseif getType == "number" then return (propertyFrom + (propertyTo - propertyFrom) * fadeAmount) end else if getType == "number" and propertyTo == nil then return (propertyFrom + (0 - propertyFrom) * fadeAmount) elseif propertyFrom == nil and typeof(propertyTo) == "number" then return (0 + (propertyTo - 0) * fadeAmount) end return propertyTo end end function Weather:FadePresets(presetFrom, presetTo, fadeAmount) local startingPreset = self._CurrentPreset self:ApplyToServices(presetFrom, presetTo, fadeAmount or 0) self:ApplyWeatherGlobals(presetFrom, presetTo, fadeAmount or 0) task.spawn(function() task.wait(self._TweenInfo.Time * .3) if startingPreset == self._CurrentPreset then self:ApplySounds(presetFrom, presetTo, fadeAmount or 0) end end) end function Weather:ApplyToServices(presetFrom, presetTo, fadeAmount) for service, propertySet in pairs(presetFrom._Services) do for propertyName, propertyFrom in pairs(propertySet) do local propertyTo = presetTo._Services[service][propertyName] local result = self:EvaluateProperties(propertyFrom, propertyTo, fadeAmount or 0) if result then self:TweenProperty(service, propertyName, result) else self:TweenProperty(service, propertyName, GenericWeatherPreset.new()._Services[service][propertyName]) end end end end function Weather:ApplyWeatherGlobals(presetFrom, presetTo, fadeAmount) local currentPreset = self._CurrentPreset for weatherGlobal, propertySet in pairs(presetTo._WeatherGlobals) do local parent = propertySet.Parent local className = propertySet.ClassName local find = parent:FindFirstChildWhichIsA(className) if not find then find = Instance.new(className) find.Parent = parent end for propertyName, propertyTo in pairs(propertySet) do if propertyName ~= "Parent" and propertyName ~= "ClassName" then local propertyFrom = nil local getToWeatherGlobal = presetFrom._WeatherGlobals[weatherGlobal] if getToWeatherGlobal then propertyFrom = presetFrom._WeatherGlobals[weatherGlobal][propertyName] end local result = self:EvaluateProperties(propertyFrom, propertyTo, fadeAmount) if not result then local default = Instance.new(className) result = default[propertyName] print("Set", default.Name.."'s", propertyName, "setting to", result) default:Destroy() task.spawn(function() task.wait(self._TweenInfo.Time) if self._CurrentPreset == currentPreset then find:Destroy() end end) end if result then self:TweenProperty(find, propertyName, result) else self:TweenProperty(find, propertyName, GenericWeatherPreset.new()._WeatherGlobals[weatherGlobal][propertyName]) end end end end end function Weather:ApplySounds(presetFrom, presetTo, fadeAmount) local getWeatherSounds = SoundService:FindFirstChild("WeatherSounds") if not getWeatherSounds then getWeatherSounds = Instance.new("Folder") getWeatherSounds.Name = "WeatherSounds" getWeatherSounds.Parent = SoundService end for soundName, propertySet in pairs(presetTo._Sounds) do local getSound = getWeatherSounds:FindFirstChild(soundName) if not getSound then getSound = Instance.new("Sound") getSound.Name = soundName getSound.Parent = getWeatherSounds getSound.SoundId = propertySet.SoundId getSound.Volume = 0 getSound.Looped = propertySet.Looped getSound:Play() end local volumeFrom = nil local volumeTo = nil local getFrom = presetFrom._Sounds[soundName] local getTo = presetTo._Sounds[soundName] if getFrom then volumeFrom = getFrom.Volume end if getTo then volumeTo = getTo.Volume end local result = self:EvaluateProperties(volumeFrom, volumeTo, fadeAmount) self:TweenProperty(getSound, "Volume", result) end for soundName, _ in pairs(presetFrom._Sounds) do local getSound = getWeatherSounds:FindFirstChild(soundName) if getSound then local checkSound = presetTo._Sounds[soundName] if not checkSound then local volumeFrom = nil local volumeTo = nil local getFrom = presetFrom._Sounds[soundName] local getTo = presetTo._Sounds[soundName] if getFrom then volumeFrom = getFrom.Volume end if getTo then volumeTo = getTo.Volume end local result = self:EvaluateProperties(volumeFrom, volumeTo, fadeAmount) or 0 self:TweenProperty(getSound, "Volume", result) if result == 0 then task.spawn(function() local currentPreset = self._CurrentPreset task.wait(self._TweenInfo.Time) if self._CurrentPreset == currentPreset then getSound:Destroy() end end) end end end end for _, sound in pairs(getWeatherSounds:GetChildren()) do if presetFrom._Sounds[sound.Name] == nil and presetTo._Sounds[sound.Name] == nil then local result = self:EvaluateProperties(sound.Volume, 0, 1) self:TweenProperty(sound, "Volume", result) if result == 0 then task.spawn(function() local currentPreset = self._CurrentPreset task.wait(self._TweenInfo.Time) if self._CurrentPreset == currentPreset then sound:Destroy() end end) end end end end local Singleton = Weather.new() Singleton:SetPreset("ClearSkiesDay") return Singleton
local M = {} local fn = vim.fn function M.setup() local install_path = fn.stdpath("data") .. "/site/pack/packer/start/packer.nvim" if fn.empty(fn.glob(install_path)) > 0 then fn.system({"git", "clone", "--depth", "1", "https://github.com/wbthomason/packer.nvim", install_path}) end end function M.init() return { opt_default = false, display = { non_interactive = false, -- open_fn = nil, open_fn = function() return require('packer.util').float({ border = 'single' }) end, open_cmd = '65vnew \\[packer\\]', working_sym = '⟳', error_sym = '✗', done_sym = '✓', removed_sym = '-', moved_sym = '→', header_sym = '━', show_all_info = true, prompt_border = 'double', keybindings = { quit = 'q', toggle_info = '<CR>', diff = 'd', prompt_revert = 'r', } } } end return M
-- config: (lint (only format:op-space format:separator-space)) local x,y, z local x = 0,1, 2 local x=0 local x =0 local x = 0 -- ok local x -- dubious, but ok = 0
NabooTheedScreenPlay = CityScreenPlay:new { numberOfActs = 1, screenplayName = "NabooTheedScreenPlay", planet = "naboo", gcwMobs = { {"stormtrooper", "rebel_trooper", -5206.32, 6, 4182.8, 329.254, 0, "", ""}, {"stormtrooper", "rebel_trooper", -4800, 6, 4113, 121.097, 0, "", ""}, {"stormtrooper", "rebel_trooper", -5126.48, 6.52214, 4130.79, 184.164, 0, "", ""}, {"stormtrooper", "rebel_trooper", -5132.44, 6, 4087.27, 158.596, 0, "", ""}, {"stormtrooper", "rebel_trooper", -5016.16, 6, 4107, 226.021, 0, "", ""}, {"stormtrooper", "rebel_trooper", -4848.1, 6.55806, 4172.25, 222.445, 0, "", ""}, {"stormtrooper", "rebel_trooper", -4933.43, 6, 4233.84, 32.6463, 0, "", ""}, {"stormtrooper_groupleader", "rebel_resistance_leader", -4857.84, 6.43289, 4178.31, 222.445, 0, "", ""}, {"stormtrooper_groupleader", "rebel_resistance_leader", -5969.83, 6, 4246.76, 173.432, 0, "npc_imperial", "conversation"}, {"stormtrooper_rifleman", "rebel_gungan_bomber", -5160.99, 6.52214, 4159.54, 216.801, 0, "", ""}, {"stormtrooper_rifleman", "rebel_gungan_bomber", -4845.17, 6.43094, 4167.68, 222.445, 0, "", ""}, {"naboo_police", "naboo_police", -5138.49,6,4228.36,0,0, "", ""}, {"naboo_police", "naboo_police", -4911.53,6,4089.7,127.784,0, "",""}, {"naboo_police", "naboo_police", -5889.07,6,4235.87,170.679,0, "", ""}, {"naboo_police", "naboo_police", -6012.09,6,4241.61,83.2023,0, "", ""}, {"naboo_police_chief", "naboo_police_chief", -5555.25,6,4241.44,63.404,0, "npc_imperial", ""}, {"naboo_police_officer", "naboo_police_officer", -5544.22,6,4232.32,267.981,0, "npc_imperial", ""}, }, } registerScreenPlay("NabooTheedScreenPlay", true) function NabooTheedScreenPlay:start() if (isZoneEnabled(self.planet)) then self:spawnMobiles() self:spawnSceneObjects() self:spawnGcwMobiles() end end function NabooTheedScreenPlay:spawnSceneObjects() --outside starport spawnSceneObject(self.planet, "object/tangible/crafting/station/public_space_station.iff", -4830.96, 6, 4141.53, 0, math.rad(-140) ) spawnSceneObject(self.planet, "object/tangible/crafting/station/public_space_station.iff", -4886.07, 6, 4188.23, 0, math.rad(-140) ) end function NabooTheedScreenPlay:spawnMobiles() --Outside local pNpc = spawnMobile(self.planet, "agriculturalist",60,-5827.81,6,4173.98,180.005,0) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "noble",300,-5258.93,6,4187.17,180.005,0) self:setMoodString(pNpc, "conversation") spawnMobile(self.planet, "bounty_hunter",300,-5082.41,6,4261.15,180.005,0) spawnMobile(self.planet, "commoner",60,-5394.06,6,4519.32,169.904,0) spawnMobile(self.planet, "commoner",60,-5384.95,6,4283.38,71.1905,0) spawnMobile(self.planet, "commoner",60,-5256.72,6,4254.43,243.769,0) spawnMobile(self.planet, "commoner",60,-5319.27,6,4365.19,286.546,0) spawnMobile(self.planet, "commoner",60,-5320.16,6,4236.39,175.933,0) spawnMobile(self.planet, "commoner",60,-5327.58,6,4267.42,170.655,0) spawnMobile(self.planet, "commoner",60,-5281.75,6,4325.98,47.2066,0) spawnMobile(self.planet, "commoner",60,-5140.78,6,4404.92,212.214,0) spawnMobile(self.planet, "commoner",60,-6036.18,6,4286.85,147.238,0) spawnMobile(self.planet, "commoner",60,-6055.49,6,4319.64,186.501,0) spawnMobile(self.planet, "commoner",60,-6040.72,6,4260.46,325.963,0) spawnMobile(self.planet, "commoner",60,-5291.01,6,4428.53,322.605,0) spawnMobile(self.planet, "commoner",60,-5282.92,6,4405.65,279.205,0) spawnMobile(self.planet, "commoner",60,-5280.52,6,4372.79,226.645,0) spawnMobile(self.planet, "commoner",60,-5306.24,6,4357.56,77.2615,0) spawnMobile(self.planet, "commoner",60,-5326.21,6,4292.88,155.604,0) spawnMobile(self.planet, "commoner",60,-5309.23,6,4307.01,78.4133,0) spawnMobile(self.planet, "commoner",60,-5371.2,6,4337.4,57.5394,0) spawnMobile(self.planet, "commoner",60,-5392.94,6,4361.06,74.0902,0) spawnMobile(self.planet, "commoner",60,-5370.57,6,4384.5,150.505,0) spawnMobile(self.planet, "commoner",60,-5399.67,6,4424.78,313.827,0) spawnMobile(self.planet, "commoner",60,-5380.45,6,4628.71,65.0141,0) spawnMobile(self.planet, "commoner",60,-5396.24,6,4492.81,306.733,0) spawnMobile(self.planet, "commoner",60,-6023.52,6,4213.29,308.957,0) spawnMobile(self.planet, "commoner",60,-5219.06,6,4291.75,225.099,0) spawnMobile(self.planet, "commoner",60,-5194.95,6,4189.82,3.74494,0) spawnMobile(self.planet, "commoner",60,-5135.69,6,4219.76,3.98419,0) spawnMobile(self.planet, "commoner",60,-5124.32,6,4230.7,188.301,0) spawnMobile(self.planet, "commoner",60,-5165.37,6,4173.32,44.4267,0) spawnMobile(self.planet, "commoner",60,-5171.36,6,4148.39,89.3505,0) spawnMobile(self.planet, "commoner",60,-5123.13,6,4201.32,268.516,0) spawnMobile(self.planet, "commoner",60,-5101.22,6,4246.47,39.2932,0) spawnMobile(self.planet, "commoner",60,-5106.97,6,4296.89,278.927,0) spawnMobile(self.planet, "commoner",60,-5069.74,6,4262.45,304.456,0) spawnMobile(self.planet, "commoner",60,-5075.93,6,4204.5,258.103,0) spawnMobile(self.planet, "commoner",60,-5053.71,6,4151.61,236.952,0) spawnMobile(self.planet, "commoner",60,-5090.67,6,4173.27,324.898,0) spawnMobile(self.planet, "commoner",60,-5088.5,6,4152.21,228.099,0) spawnMobile(self.planet, "commoner",60,-5076.56,6,4162.09,47.5912,0) spawnMobile(self.planet, "commoner",60,-5032.44,6,4131.62,179.986,0) spawnMobile(self.planet, "commoner",60,-5019.1,6,4125.83,354.895,0) spawnMobile(self.planet, "commoner",60,-5023.92,6,4040.07,112.362,0) spawnMobile(self.planet, "commoner",60,-5004.8,6,4067.54,285.879,0) spawnMobile(self.planet, "commoner",60,-5037.78,6,4078.71,14.5782,0) spawnMobile(self.planet, "commoner",60,-5007.98,6,4111.83,156.739,0) spawnMobile(self.planet, "commoner",60,-5021.05,6,4230.04,13.8244,0) spawnMobile(self.planet, "commoner",60,-4866.72,6,4160.45,346.733,0) spawnMobile(self.planet, "commoner",60,-4991.86,6,4125.22,355.866,0) spawnMobile(self.planet, "commoner",60,-4970.37,6,4069.78,230.918,0) spawnMobile(self.planet, "commoner",60,-4924.84,6,4034.9,112.799,0) spawnMobile(self.planet, "commoner",60,-4892.24,6,4083,131.075,0) spawnMobile(self.planet, "commoner",60,-4902.73,6,4106.81,350.732,0) spawnMobile(self.planet, "commoner",60,-4933.63,6,4090.17,355.935,0) spawnMobile(self.planet, "commoner",60,-4921.08,6,4061.48,324.756,0) spawnMobile(self.planet, "commoner",60,-4896.15,6,4167.85,352.84,0) spawnMobile(self.planet, "commoner",60,-4897.7,6,4193.27,70.95,0) spawnMobile(self.planet, "commoner",60,-4978.62,6,4119.77,158.522,0) spawnMobile(self.planet, "commoner",60,-4941.05,6,4184.26,54.3125,0) spawnMobile(self.planet, "commoner",60,-4968.55,6,4158.78,56.9517,0) spawnMobile(self.planet, "commoner",60,-4978.84,6,4263.64,225.699,0) spawnMobile(self.planet, "commoner",60,-4973.93,6,4220.31,28.5203,0) spawnMobile(self.planet, "commoner",60,-4981.69,6,4244.41,37.6517,0) spawnMobile(self.planet, "commoner",60,-4985.97,6,4212.75,54.7999,0) spawnMobile(self.planet, "commoner",60,-4974.13,6,4196.91,163.185,0) spawnMobile(self.planet, "commoner",60,-4973.2,6,4175.16,163.034,0) spawnMobile(self.planet, "commoner",60,-4956.42,6,4205.06,106.528,0) spawnMobile(self.planet, "commoner",60,-5054.68,6,4228.23,0,0) spawnMobile(self.planet, "commoner",60,-5803.39,6,4101.34,219.092,0) spawnMobile(self.planet, "commoner",60,-5858.79,6,4147.3,177.298,0) spawnMobile(self.planet, "commoner",60,-5941.62,6,4339.4,156.272,0) spawnMobile(self.planet, "commoner",60,-5996.82,6,4309.73,327.452,0) spawnMobile(self.planet, "commoner",60,-5968.83,6,4287.92,169.112,0) spawnMobile(self.planet, "commoner",60,-5996.87,6,4269.75,70.6282,0) spawnMobile(self.planet, "commoner",60,-5928.72,6,4217.24,56.7839,0) spawnMobile(self.planet, "commoner",60,-5727.93,6,4316.95,342.377,0) spawnMobile(self.planet, "commoner",60,-5741.57,6,4304.91,133.504,0) spawnMobile(self.planet, "commoner",60,-5757.67,6,4411.04,296.772,0) spawnMobile(self.planet, "commoner",60,-5818.26,6,4407.8,25.7365,0) spawnMobile(self.planet, "commoner",60,-5751.98,6,4147.86,61.2467,0) spawnMobile(self.planet, "commoner",60,-5729.03,6,4120.76,304.577,0) spawnMobile(self.planet, "commoner",60,-5709.29,6,4134.09,24.3295,0) spawnMobile(self.planet, "commoner",60,-5675.02,6,4238.39,193.294,0) spawnMobile(self.planet, "commoner",60,-5686.06,6,4307.41,304.1,0) spawnMobile(self.planet, "commoner",60,-5663.64,6,4136.03,34.2804,0) spawnMobile(self.planet, "commoner",60,-5690.65,6,4124.1,313.987,0) spawnMobile(self.planet, "commoner",60,-5632.25,6,4137.72,121.318,0) spawnMobile(self.planet, "commoner",60,-5592.68,6,4154.97,125.654,0) spawnMobile(self.planet, "commoner",60,-5600.12,6,4053.65,55.2097,0) spawnMobile(self.planet, "commoner",60,-5418.26,6,4347.1,173.931,0) spawnMobile(self.planet, "commoner",60,-5409.46,6,4386.55,51.6472,0) spawnMobile(self.planet, "commoner",60,-5425.82,6,4371.62,158.964,0) spawnMobile(self.planet, "commoner",60,-5416.72,6,4413.87,130.124,0) spawnMobile(self.planet, "commoner",60,-5428.98,6,4447.99,285.357,0) spawnMobile(self.planet, "commoner",60,-5449.78,6,4428.75,8.98008,0) spawnMobile(self.planet, "commoner",60,-5457.38,6,4469.32,299.901,0) spawnMobile(self.planet, "commoner",60,-5468.87,6,4432.8,25.9495,0) spawnMobile(self.planet, "commoner",60,-5458.78,6,4343.19,264.89,0) spawnMobile(self.planet, "commoner",60,-5485.31,6,4373.11,251.552,0) spawnMobile(self.planet, "commoner",60,-5492.21,6,4337.69,94.7447,0) spawnMobile(self.planet, "commoner",60,-5507.67,6,4309.38,330.512,0) spawnMobile(self.planet, "commoner",60,-5520.11,6,4349.32,243.736,0) spawnMobile(self.planet, "commoner",60,-5489.16,6,4404.33,229.081,0) spawnMobile(self.planet, "commoner",60,-5525.24,6,4430.28,32.9667,0) spawnMobile(self.planet, "commoner",60,-5537.28,6,4411.34,252.902,0) spawnMobile(self.planet, "commoner",60,-5545.73,6,4466.12,324.904,0) spawnMobile(self.planet, "commoner",60,-5586.88,6,4495.26,212.866,0) spawnMobile(self.planet, "commoner",60,-5565.53,6,4469.02,122.256,0) spawnMobile(self.planet, "commoner",60,-5541.82,6,4394.46,238.528,0) spawnMobile(self.planet, "commoner",60,-5547.21,6,4383.24,155.163,0) spawnMobile(self.planet, "commoner",60,-5554.8,6,4319.26,256.528,0) spawnMobile(self.planet, "commoner",60,-5541.38,6,4302.99,60.5745,0) spawnMobile(self.planet, "commoner",60,-5558.64,6,4283.8,12.7491,0) spawnMobile(self.planet, "commoner",60,-5599.43,6,4261.62,241.361,0) spawnMobile(self.planet, "commoner",60,-5583.5,6,4237.52,344.261,0) spawnMobile(self.planet, "commoner",60,-5562.58,6,4208.34,326.3,0) spawnMobile(self.planet, "commoner",60,-5507.69,6,4195.83,129.185,0) spawnMobile(self.planet, "commoner",60,-5487.23,6,4193.99,298.896,0) spawnMobile(self.planet, "commoner",60,-5453.08,6,4198.55,346.123,0) spawnMobile(self.planet, "commoner",60,-5457.43,6,4156.44,21.7515,0) spawnMobile(self.planet, "commoner",60,-5497.13,6,4148.57,166.606,0) spawnMobile(self.planet, "commoner",60,-5404.2,6,4199.59,80.6257,0) spawnMobile(self.planet, "commoner",60,-5437.58,6,4301.41,199.461,0) pNpc = spawnMobile(self.planet, "commoner_naboo",60,-5778.43,6,4397.54,180.005,0) self:setMoodString(pNpc, "nervous") spawnMobile(self.planet, "explorer",60,-5127.71,6,4336.34,0,0) spawnMobile(self.planet, "explorer",60,-4870.86,6,4179.63,0,0) spawnMobile(self.planet, "gungan_hunter",300,-5138.49,6,4229.36,180.005,0) pNpc = spawnMobile(self.planet, "gungan_outcast",300,-5794.03,6,4150.76,0,0) self:setMoodString(pNpc, "conversation") spawnMobile(self.planet, "imperial_recruiter",0,-4928,6,4231,174,0) spawnMobile(self.planet, "imperial_recruiter",0,-4936,6,4231,174,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-4833,6,4134,0,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-4892,6,4216,0,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-4962,6,4259,0,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-5100,6,4146,0,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-5455,6,4277,0,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-5436,6,4133,0,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-5369,6,4178,0,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-5477,6,4089,0,0) spawnMobile(self.planet, "j1_po",60,-4856.56,6,4158.12,237.016,0) spawnMobile(self.planet, "miner",60,-4965.4,6,4194.15,180.005,0) pNpc = spawnMobile(self.planet, "miner",60,-5886.59,6,4369.23,180.005,0) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "official",300,-5886.59,6,4368.23,0,0) self:setMoodString(pNpc, "conversation") spawnMobile(self.planet, "junk_dealer", 0, -5884.3, 6, 4214.3, 83, 0) pNpc = spawnMobile(self.planet, "junk_dealer", 0, -5762.59, 6.6, 4234.66, 87, 0) if pNpc ~= nil then AiAgent(pNpc):setConvoTemplate("junkDealerFineryConvoTemplate") end spawnMobile(self.planet, "junk_dealer", 0, -5222.78, 6, 4217.68, -130, 0) spawnMobile(self.planet, "junk_dealer", 0, -5086.83, 6, 4142.32, 37, 0) spawnMobile(self.planet, "junk_dealer", 0, -4999.46, 6, 4120.26, 113, 0) spawnMobile(self.planet, "trainer_1hsword",0,-5565,6,4304,84,0) spawnMobile(self.planet, "trainer_2hsword",0,-5382,6,4327,180,0) spawnMobile(self.planet, "trainer_architect",0,-4931,6,4020,39,0) spawnMobile(self.planet, "trainer_artisan",0,-4946,6,4131,138,0) spawnMobile(self.planet, "trainer_artisan",0,-5996.85,6,4287.56,69,0) spawnMobile(self.planet, "trainer_bioengineer",0,-5017,6,4009,0,0) spawnMobile(self.planet, "trainer_brawler",0,-5942,6,4253,169,0) spawnMobile(self.planet, "trainer_brawler",0,-4858,6,4087,-47,0) spawnMobile(self.planet, "trainer_brawler",0,-4684,6,3947,-71,0) spawnMobile(self.planet, "trainer_chef",0,-4877,6,4065,0,0) spawnMobile(self.planet, "trainer_doctor",0,-5038,6,4146,180,0) spawnMobile(self.planet, "trainer_entertainer",0,-4840,6,4082,66,0) spawnMobile(self.planet, "trainer_entertainer",0,-5834,6,4241,104,0) spawnMobile(self.planet, "trainer_marksman",0,-4674,6,3995,180,0) spawnMobile(self.planet, "trainer_marksman",0,-5982,6,4254,180,0) spawnMobile(self.planet, "trainer_marksman",0,-4863,6,4079,0,0) spawnMobile(self.planet, "trainer_medic",0,-4592,6,4125,217,0) spawnMobile(self.planet, "trainer_medic",0,-5968,6,4277,-96,0) spawnMobile(self.planet, "trainer_medic",0,-4934,6,4153,129,0) spawnMobile(self.planet, "trainer_merchant",0,-5129,6,4238,112,0) spawnMobile(self.planet, "trainer_polearm",0,-5375.06,6,4310.92,84,0) spawnMobile(self.planet, "trainer_scout",0,-4909.36,6,4025.86,11,0) spawnMobile(self.planet, "trainer_scout",0,-5986.5,6,4232.79,104,0) spawnMobile(self.planet, "trainer_scout",0,-4796,6,4103,240,0) spawnMobile(self.planet, "trainer_unarmed",0,-5649,6,4206,0,0) --Creatures spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -5195, 6, getRandomNumber(10) + 3988, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -5200, 6, getRandomNumber(10) + 3997, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -5207, 6, getRandomNumber(10) + 3992, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -5205, 6, getRandomNumber(10) + 3989, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -5201, 6, getRandomNumber(10) + 3981, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -5202, 6, getRandomNumber(10) + 3975, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5152.02, 6, getRandomNumber(10) + 3882.86, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5156.30, 6, getRandomNumber(10) + 3880.18, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5145.15, 6, getRandomNumber(10) + 3882.41, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5148.77, 6, getRandomNumber(10) + 3879.10, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5153.03, 6, getRandomNumber(10) + 3876.91, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5143.66, 6, getRandomNumber(10) + 3875.17, getRandomNumber(360), 0) spawnMobile(self.planet, "nuna", 300, getRandomNumber(10) + -5054.71, 6, getRandomNumber(10) + 3959.16, getRandomNumber(360), 0) spawnMobile(self.planet, "nuna", 300, getRandomNumber(10) + -5049.91, 6, getRandomNumber(10) + 3959.13, getRandomNumber(360), 0) spawnMobile(self.planet, "nuna", 300, getRandomNumber(10) + -5056.38, 6, getRandomNumber(10) + 3954.13, getRandomNumber(360), 0) spawnMobile(self.planet, "nuna", 300, getRandomNumber(10) + -5050.76, 6, getRandomNumber(10) + 3955.11, getRandomNumber(360), 0) spawnMobile(self.planet, "nuna", 300, getRandomNumber(10) + -5046.74, 6, getRandomNumber(10) + 3956.10, getRandomNumber(360), 0) spawnMobile(self.planet, "nuna", 300, getRandomNumber(10) + -5050.08, 6, getRandomNumber(10) + 3951.88, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -5068.63, 6, getRandomNumber(10) + 3874.93, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -5063.50, 6, getRandomNumber(10) + 3874.98, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -5059.21, 6, getRandomNumber(10) + 3873.08, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -5064.77, 6, getRandomNumber(10) + 3870.68, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -5069.20, 6, getRandomNumber(10) + 3867.40, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -5059.54, 6, getRandomNumber(10) + 3866.31, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -5062.01, 6, getRandomNumber(10) + 3771.87, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -5070.54, 6, getRandomNumber(10) + 3772.20, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -5067.63, 6, getRandomNumber(10) + 3777.25, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -5072.20, 6, getRandomNumber(10) + 3778.46, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -5065.83, 6, getRandomNumber(10) + 3781.39, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -5061.01, 6, getRandomNumber(10) + 3779.68, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -4952.30, 6, getRandomNumber(10) + 3863.72, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -4947.92, 6, getRandomNumber(10) + 3863.87, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -4944.95, 6, getRandomNumber(10) + 3866.25, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -4948.41, 6, getRandomNumber(10) + 3869.46, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -4946.46, 6, getRandomNumber(10) + 3873.06, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -4952.32, 6, getRandomNumber(10) + 3873.58, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -4969.69, 6, getRandomNumber(10) + 3767.96, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -4962.60, 6, getRandomNumber(10) + 3767.81, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -4960.24, 6, getRandomNumber(10) + 3772.21, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -4965.28, 6, getRandomNumber(10) + 3772.93, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -4970.08, 6, getRandomNumber(10) + 3776.47, getRandomNumber(360), 0) spawnMobile(self.planet, "hermit_spider", 300, getRandomNumber(10) + -4967.46, 6, getRandomNumber(10) + 3780.19, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -4862.57, 6, getRandomNumber(10) + 3768.61, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -4854.70, 6, getRandomNumber(10) + 3768.47, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -4858.64, 6, getRandomNumber(10) + 3773.44, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -4866.15, 6, getRandomNumber(10) + 3775.88, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -4860.42, 6, getRandomNumber(10) + 3778.87, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -4856.47, 6, getRandomNumber(10) + 3776.79, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5041, 6, getRandomNumber(10) + 3681, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5050, 6, getRandomNumber(10) + 3682, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5046, 6, getRandomNumber(10) + 3675, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5040, 6, getRandomNumber(10) + 3671, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5039, 6, getRandomNumber(10) + 3685, getRandomNumber(360), 0) spawnMobile(self.planet, "nightspider", 300, getRandomNumber(10) + -5047, 6, getRandomNumber(10) + 3686, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -4946.98, 6, getRandomNumber(10) + 3644.18, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -4939.79, 6, getRandomNumber(10) + 3645.60, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -4942.72, 6, getRandomNumber(10) + 3647.44, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -4946.78, 6, getRandomNumber(10) + 3650.67, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -4943.30, 6, getRandomNumber(10) + 3652.44, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 300, getRandomNumber(10) + -4939.35, 6, getRandomNumber(10) + 3653.82, getRandomNumber(360), 0) --Med Center spawnMobile(self.planet, "trainer_combatmedic",0,-16.4871,0.26,10.7738,176,1697364) spawnMobile(self.planet, "trainer_combatmedic",0,26.5469,0.26,5.31169,90,1697360) spawnMobile(self.planet, "trainer_doctor",0,16.0979,0.26,-0.105232,266,1697360) spawnMobile(self.planet, "trainer_medic",0,13.7645,0.26,4.7703,149,1697360) spawnMobile(self.planet, "trainer_medic",0,-17.1613,0.26,-0.82884,167,1697364) spawnMobile(self.planet, "comm_operator",300,-32.8,0.3,13.892,92,1697365) spawnMobile(self.planet, "commoner_technician",60,-5041.71,13.3,4193.94,180.005,0) spawnMobile(self.planet, "medic",60,-5041.71,13.3,4192.84,0,0) --Hotel spawnMobile(self.planet, "commoner_tatooine",60,2.04307,0.999959,21.6541,270.005,1697375) spawnMobile(self.planet, "commoner",60,0.043072,0.999959,21.6541,89.9998,1697375) spawnMobile(self.planet, "commoner",60,-21.2681,1.59776,11.3505,270.004,1697379) spawnMobile(self.planet, "commoner",60,-23.2681,1.6,11.3505,90.0019,1697379) spawnMobile(self.planet, "commoner_technician",60,-1.60874,0.999962,6.25947,360.011,1697377) spawnMobile(self.planet, "artisan",60,-23.0798,1.59166,3.00121,180.006,1697379) spawnMobile(self.planet, "sullustan_male",300,-1.60874,0.999952,7.35947,180,1697377) spawnMobile(self.planet, "commoner_naboo",300,18.9004,1.28309,-6.40631,0,1697378) spawnMobile(self.planet, "chiss_male",300,7.0973,1.00001,8.95992,0,1697377) spawnMobile(self.planet, "chiss_female",300,-24.1798,1.5815,3.00112,135.006,1697379) spawnMobile(self.planet, "ithorian_male",60,-21.5772,1.6,-14.1795,180.023,1697383) spawnMobile(self.planet, "bounty_hunter",60,-7.0383,1.6,-12.1532,360.011,1697381) spawnMobile(self.planet, "twilek_slave",60,-7.0383,1.6,-11.0532,179.988,1697381) --Guild Hall -5450 4267 pNpc = spawnMobile(self.planet, "mercenary",300,6.3,1.2,-3.9,-89,1305892) self:setMoodString(pNpc, "angry") pNpc = spawnMobile(self.planet, "businessman",300,5.4,1.2,-3.9,87,1305892) self:setMoodString(pNpc, "happy") pNpc = spawnMobile(self.planet, "contractor",300,11.7898,1.75,-1.89849,180.002,1305892) self:setMoodString(pNpc, "worried") pNpc = spawnMobile(self.planet, "commoner_old",60,-17.0001,2.25,17.4832,270.003,1305888) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "commoner",60,-19.0001,2.25,17.4832,90.0053,1305888) self:setMoodString(pNpc, "neutral") --Guild Hall -5457 4122 spawnMobile(self.planet, "trainer_brawler",0,-11,1,-13,0,1692075) spawnMobile(self.planet, "trainer_marksman",0,0,1.13306,-13,0,1692074) spawnMobile(self.planet, "trainer_scout", 0, -11.9, 1.13306, 5.1, 179, 1692072) spawnMobile(self.planet, "junk_dealer", 0, -14.3, 1.1, 3, 107, 1692072) --Guild Hall -5368 4138 spawnMobile(self.planet, "trainer_artisan",0,0.0417929,1.13306,-13.5584,2,1692084) --Guild Hall -5452 4014 spawnMobile(self.planet, "trainer_architect",0,11,1.133,-14.5,0,1692093) spawnMobile(self.planet, "trainer_armorsmith",0,-15,1.1,0,90,1692092) spawnMobile(self.planet, "trainer_droidengineer",0,-11,1.13306,-13,0,1692095) spawnMobile(self.planet, "trainer_merchant",0,12,1.13306,6,180,1692091) spawnMobile(self.planet, "trainer_weaponsmith",0,-3.1,1.1,-8.2,91,1692094) --Cantina pNpc = spawnMobile(self.planet, "junk_dealer", 0, -5.8, -0.9, -20.9, -52, 96) if pNpc ~= nil then AiAgent(pNpc):setConvoTemplate("junkDealerArmsConvoTemplate") end --Hotel pNpc = spawnMobile(self.planet, "businessman",60,15.5641,1.28309,-2.37071,135.005,1677395) self:setMoodString(pNpc, "worried") pNpc = spawnMobile(self.planet, "businessman",60,-4.2087,0.999986,2.15452,179.993,1677394) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "mercenary",60,4.2931,1,-7.62435,360.011,1677394) self:setMoodString(pNpc, "angry") pNpc = spawnMobile(self.planet, "mercenary",60,-11.7266,1.6,-16.4722,0,1677399) self:setMoodString(pNpc, "nervous") pNpc = spawnMobile(self.planet, "noble",300,16.6641,1.28309,-3.47071,360.011,1677395) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "corellia_times_investigator",300,-11.7266,1.6,-15.4722,180.001,1677399) self:setMoodString(pNpc, "conversation") spawnMobile(self.planet, "comm_operator",300,16.6641,1.28309,-2.37071,180.007,1677395) pNpc = spawnMobile(self.planet, "bounty_hunter",300,-4.2087,0.999986,1.15452,0,1677394) self:setMoodString(pNpc, "angry") pNpc = spawnMobile(self.planet, "ysnide_omewror",60,4.2931,1.00001,-6.52435,180.012,1677394) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "commoner_old",300,-22.6115,1.6,-10.3739,179.996,1677400) self:setMoodString(pNpc, "sad") pNpc = spawnMobile(self.planet, "noble",300,-22.6115,1.6,-11.4739,0,1677400) self:setMoodString(pNpc, "conversation") --Guild Hall/Theater pNpc = spawnMobile(self.planet, "mercenary",60,-6.34119,0.6,-9.37965,360.011,5475480) self:setMoodString(pNpc, "neutral") pNpc = spawnMobile(self.planet, "comm_operator",300,-6.34119,0.6,-8.27965,180.012,5475480) self:setMoodString(pNpc, "neutral") pNpc = spawnMobile(self.planet, "commoner_technician",60,22.86,2.1,58.4,0,5475486) self:setMoodString(pNpc, "worried") pNpc = spawnMobile(self.planet, "etheli_drenel",60,12.4716,2.31216,25.6024,180.001,5475485) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "sullustan_male",300,12.4716,2.41226,24.5116,5.24304,5475485) self:setMoodString(pNpc, "neutral") pNpc = spawnMobile(self.planet, "pilot",300,22.7,2.1,60.0,180,5475486) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "chiss_female",60,3.05224,2.12878,72.5469,180.005,5475487) self:setMoodString(pNpc, "npc_consoling") pNpc = spawnMobile(self.planet, "chiss_male",300,3.05224,2.12878,71.4469,0,5475487) self:setMoodString(pNpc, "nervous") pNpc = spawnMobile(self.planet, "medic",60,-11.5446,2.12878,75.9709,0,5475487) self:setMoodString(pNpc, "conversation") spawnMobile(self.planet, "trainer_dancer",0,18.2374,2.12871,53.9343,6,5475487) spawnMobile(self.planet, "trainer_entertainer",0,28.3235,2.12854,73.5353,90,5475487) spawnMobile(self.planet, "trainer_musician",0,28.3,2.12801,54,-39,5475486) pNpc = spawnMobile(self.planet, "vendor",60,-11.5446,2.12878,76.8966,179.996,5475487) self:setMoodString(pNpc, "happy") spawnMobile(self.planet, "trainer_imagedesigner",0,-22.9,2.1287,74.7,121,5475488) --Starport pNpc = spawnMobile(self.planet, "trainer_shipwright",0,0.2,0.7,-71.4,-177,1692101) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "pilot",300,-29.8622,7.9418,10.8957,180.008,1692104) self:setMoodString(pNpc, "happy") pNpc = spawnMobile(self.planet, "commoner_technician",300,-37.5788,7.9418,22.3791,0,1692104) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "chassis_dealer",60,-1.0,0.7,-72.2,50,1692101) self:setMoodString(pNpc, "neutral") --double waterfall island near Palace spawnMobile(self.planet, "mott_calf", 600, getRandomNumber(10) + -5201.0, 6, getRandomNumber(10) + 4542.6, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 600, getRandomNumber(10) + -5195.0, 6, getRandomNumber(10) + 4537.4, getRandomNumber(360), 0) spawnMobile(self.planet, "mott_calf", 600, getRandomNumber(10) + -5202.4, 6, getRandomNumber(10) + 4552.0, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -5176.4, 6, getRandomNumber(10) + 4612.2, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -5161.3, 6, getRandomNumber(10) + 4601.7, getRandomNumber(360), 0) spawnMobile(self.planet, "flewt", 300, getRandomNumber(10) + -5193.3, 6, getRandomNumber(10) + 4610.0, getRandomNumber(360), 0) end
return { name = 'TohruMKDM/Tohru-Admin', version = '1.0.0', description = 'A ROBLOX admin script designed with exploits in mind.', tags = {'roblox', 'admin', 'exploit'}, license = 'MIT', author = {name = 'Tohru~ (トール)', email = '[email protected]'}, homepage = 'https://github.com/TohruMKDM/Tohru-Admin', files = {'**.lua'} }
local mg = require "moongen" local arp = require "proto.arp" local thread = { arpDevices = {}, flows = {} } local function doesArp(flow) for _,dep in pairs(flow.packet.depvars) do if dep.tbl[1] == "arp" then return true end end return false end local function addIp(dev, ip) -- luacheck: read globals ipString ip = ipString(ip) -- see dependencies/arp.lua local tbl = thread.arpDevices[dev] if not tbl then tbl = {} thread.arpDevices[dev] = tbl end tbl[ip] = true end function thread.prepare(flows, devices) for _,flow in ipairs(flows) do if doesArp(flow) then table.insert(thread.flows, flow) local ft = flow.packet.fillTbl for _,dev in ipairs(flow:property "tx") do addIp(dev, ft.ip4Src or ft.ip6Src) end for _,dev in ipairs(flow:property "rx") do addIp(dev, ft.ip4Dst or ft.ip6Dst) end end end for dev in pairs(thread.arpDevices) do devices:reserveTx(dev) devices:reserveRx(dev) end end function thread.start(devices) if #thread.flows == 0 then return end local queues = {} for dev, ips in pairs(thread.arpDevices) do local ipList = {} for ip in pairs(ips) do table.insert(ipList, ip) end table.insert(queues, { rxQueue = devices:rxQueue(dev), txQueue = devices:txQueue(dev), ips = ipList }) end arp.startArpTask(queues) mg.startSharedTask("__INTERFACE_ARP_MANAGER", thread.flows) end local function arpManagerThread(flows) local isActive = true while isActive do mg.sleepMillis(1000) isActive = false for _,flow in ipairs(flows) do if not flow.properties.counter:isZero() then isActive = true end end end arp.stopArpTask() end __INTERFACE_ARP_MANAGER = arpManagerThread -- luacheck: globals __INTERFACE_ARP_MANAGER return thread
height = 5 width = 5 author = "test1" title = "test1" help = "nothing" -- the following shape is the target -- **& -- *&& -- target= "*-&=(-1,0)" map= "**223".. "*44 3".. "55 66".. "7 89&".. "7bb&&".. ""
require("math/math") Obligation={} function Obligation.FluxInFine(self,T,r,Ve,Vn ) if tiNspire.toNumber(T)~=nil then local res="[0,-"..tostring(Ve)..",-"..tostring(Ve); for i = 1,T do local calc = tostring(r).."*"..tostring(Vn) if i==tiNspire.toNumber(T) then res = tostring(res)..";"..tostring(i)..","..tostring(Vn).."+"..calc..","..tostring(tiNspire.execute(tostring(Vn).."+"..calc)) else res = tostring(res)..";"..tostring(i)..","..calc..","..tostring(tiNspire.execute(calc)) end end self:appendMathToResult(res.."]") end end function Obligation.TABInFine(self,T,r,Ve,Vn) if tiNspire.toNumber(T)~=nil then local eq = tostring(Ve).."=" local calc = tostring(r).."*"..tostring(Vn) local coupon = tostring(tiNspire.execute(calc)); local calc = calc.."="..tostring(coupon) self:appendToResult("\ncoupon : ") self:appendMathToResult(calc) for i = 1,T do if i==tiNspire.toNumber(T) then calc="("..tostring(Vn).."+"..coupon..")/(rx^"..tostring(i)..")" else calc=coupon.."/(rx^"..tostring(i)..")+" end eq=eq..calc end self:appendMathToResult(eq) self:appendMathToResult(tostring(tiNspire.solve(tiNspire.solve(eq,"rx"),"rx"))) self:appendToResult("\n since rx>0 : ") self:appendMathToResult(tostring(tiNspire.solveCond(tiNspire.solveCond(eq,"rx","rx>0"),"rx","rx>0"))) self:appendToResult("\n rx=1+r* => r*=rx-1 : ") self:appendToResult("\n=> TAB "..a_acute.." l'"..e_acute.."mission : r*=") local res = tostring(tiNspire.nSolveCond(eq,"rx","rx>0")); self:appendMathToResult(res.."-1="..tostring(tiNspire.approx("("..res.."-1)*100")).."%") end end
AddCSLuaFile(); util.AddNetworkString( "cl.replace_prop_to_breakable.warning_menu_open" ); util.AddNetworkString( "sv.replace_prop_to_breakable.duplicator" ); util.AddNetworkString( "sv.replace_prop_to_breakable.adv2duplicator" ); util.AddNetworkString( "sv.replace_prop_to_breakable.clear" ); -- Global CreateConVar("breakprops_active", 1, FCVAR_ARCHIVE, "Turns on or off the destroyed props. (1:ON, 0:OFF)"); CreateConVar("breakprops_change_map_doors", 1, FCVAR_ARCHIVE, "Replaces all doors on the map with destructible ones. (1:ON, 0:OFF)"); CreateConVar("breakprops_change_map_props", 1, FCVAR_ARCHIVE, "Replaces all props on the map with destructible ones. (1:ON, 0:OFF)"); CreateConVar("breakprops_change_playerspawn_prop", 1, FCVAR_ARCHIVE, "It makes the prop disruptible if it is spawned by the player. (1:ON, 0:OFF)"); -- Local concommand.Add( "breakprops_localcvars_active", function( ply, command, args ) local uid64 = "single_player"; if ( not game.SinglePlayer() ) then uid64 = tostring( ply:SteamID64() ); end; if ( args[ 1 ] == nil ) then local arg = file.Read( "rpb_data/" .. uid64 .. "/breakprops_localcvars_active.dat", "DATA" ); local description = "Activation or deactivation of client parameters."; ply:SendLua( [[ MsgN( "breakprops_localcvars_active = ]] .. arg .. [[" ) ]] ); ply:SendLua( [[ MsgN( "Description: ]] .. description .. [[" ) ]] ); end; if ( args[ 1 ] == '1' ) then file.Write( "rpb_data/" .. uid64 .. "/breakprops_localcvars_active.dat", "1" ); elseif ( args[ 1 ] == '0' ) then file.Write( "rpb_data/" .. uid64 .. "/breakprops_localcvars_active.dat", "0" ); end; end ); concommand.Add( "breakprops_change_playerspawn_prop_local", function( ply, command, args ) local uid64 = "single_player"; if ( not game.SinglePlayer() ) then uid64 = tostring( ply:SteamID64() ); end; if ( args[ 1 ] == nil ) then local arg = file.Read( "rpb_data/" .. uid64 .. "/breakprops_change_playerspawn_prop.dat", "DATA" ); local description = "Enables or disables the creation of player destructible objects, if the variable on the server is negative."; ply:SendLua( [[ MsgN( "breakprops_change_playerspawn_prop = ]] .. arg .. [[" ) ]] ); ply:SendLua( [[ MsgN( "Description:" ) ]] ); ply:SendLua( [[ MsgN( "Description: ]] .. description .. [[" ) ]] ); end; if ( file.Read( "rpb_data/" .. uid64 .. "/breakprops_localcvars_active.dat", "DATA" ) == "0" ) then return; end; if ( file.Read( "rpb_data/" .. uid64 .. "/breakprops_change_playerspawn_prop.dat", "DATA" ) == "0" ) then return; end; if ( args[ 1 ] == '1' ) then file.Write( "rpb_data/" .. uid64 .. "/breakprops_change_playerspawn_prop.dat", "1" ); elseif ( args[ 1 ] == '0' ) then file.Write( "rpb_data/" .. uid64 .. "/breakprops_change_playerspawn_prop.dat", "0" ); end; end ); local CreateConstraintFromEnts; local hookIndex = "ReplacePropToBreakProp_"; local doors_save = {}; local function IsDoorLocked( ent ) return ent:GetSaveTable().m_bLocked; end; local function getReplaceModel( model ) local new_model = nil; if ( string.sub( model, 8, 16 ) == "props_c17" ) then new_model = "models/nseven/" .. string.sub( model, 18 ); elseif ( string.sub( model, 8, 17 ) == "props_junk" ) then new_model = "models/nseven/" .. string.sub( model, 19 ); elseif ( string.sub( model, 8, 16 ) == "props_lab" ) then new_model = "models/nseven/" .. string.sub( model, 18 ); elseif ( string.sub( model, 8, 22 ) == "props_wasteland" ) then new_model = "models/nseven/" .. string.sub( model, 24 ); elseif ( string.sub( model, 8, 22 ) == "props_interiors" ) then new_model = "models/nseven/" .. string.sub( model, 24 ); elseif ( string.sub( model, 8, 20 ) == "props_combine" ) then new_model = "models/nseven/" .. string.sub( model, 22 ); elseif ( string.sub( model, 8, 21 ) == "props_vehicles" ) then new_model = "models/nseven/" .. string.sub( model, 23 ); elseif ( string.sub( model, 8, 25 ) == "props_trainstation" ) then new_model = "models/nseven/" .. string.sub( model, 27 ); elseif ( string.sub( model, 8, 21 ) == "props_borealis" ) then new_model = "models/nseven/" .. string.sub( model, 23 ); elseif ( string.sub( model, 8, 27 ) == "props_phx/construct/" ) then new_model = "models/nseven/" .. string.sub( model, 28, string.len( model ) ); end; return new_model; end; local function isBreakableModel( model ) if ( string.find( model, "nseven" ) ) then return true; end; return false; end; local function propReplace( ply, model, ent, class, delay_remove_time, isDuplicator ) class = class or "prop_physics"; delay_remove_time = delay_remove_time or 0; isDuplicator = isDuplicator or false; local new_model = getReplaceModel( model ); if ( new_model ~= nil and util.IsValidModel( new_model ) ) then local class = class; local pos = ent:GetPos(); local ang = ent:GetAngles(); local skin = ent:GetSkin(); local bodygroups = ent:GetBodyGroups(); local color = ent:GetColor(); local phys = ent:GetPhysicsObject(); local drag = phys:IsDragEnabled(); local gravity = phys:IsGravityEnabled(); local collision = phys:IsCollisionEnabled(); local motion = phys:IsMotionEnabled(); local collisionGroup = ent:GetCollisionGroup(); local velocity = ent:GetVelocity(); local doorLock = nil; if ( class == "prop_door_rotating" ) then doorLock = IsDoorLocked( ent ); end ent:SetCollisionGroup( COLLISION_GROUP_WORLD ); local nEnt = ents.Create(class); nEnt:SetModel( new_model ); nEnt:SetPos( pos ); nEnt:SetAngles( ang ); nEnt:SetSkin( skin ); nEnt:SetBodyGroups( bodygroups ); nEnt:SetColor( color ); nEnt.Owner = ply or game.GetWorld(); if ( DPP ~= nil ) then DPP.SetOwner( nEnt, nEnt.Owner ); elseif ( FPP ~= nil ) then nEnt.FPPOwner = nEnt.Owner; end; nEnt:SetCollisionGroup( collisionGroup ); if ( class == "prop_door_rotating" ) then if ( doorLock ) then nEnt:Fire( "Lock" ); else nEnt:Fire( "Unlock" ); end; end; nEnt.IsBreakableNsevenProp = true; nEnt:Spawn(); if ( delay_remove_time ~= nil and delay_remove_time ~= 0 ) then ent:SetNoDraw( true ); phys:EnableMotion( false ); phys:EnableCollisions( false ); phys:EnableDrag( false ); phys:EnableGravity( false ); end; nEnt:Activate(); phys = nEnt:GetPhysicsObject(); if ( IsValid( phys ) ) then phys:EnableDrag( drag ); phys:EnableGravity( gravity ); phys:EnableCollisions( collision ); phys:EnableMotion( motion ); phys:SetVelocity( velocity ); end; if (ply ~= NULL) then timer.Simple( 0.01, function() if ( not isDuplicator ) then undo.ReplaceEntity( ent, nEnt ); cleanup.ReplaceEntity( ent, nEnt ); end; if ( delay_remove_time == nil or delay_remove_time == 0 ) then ent:Remove(); else timer.Simple( delay_remove_time, function() if ( IsValid( ent ) ) then ent:Remove(); end; end ); end; end ); else timer.Simple( 0.01, function() if ( not isDuplicator ) then cleanup.ReplaceEntity( ent, nEnt ); end; if ( delay_remove_time == nil or delay_remove_time == 0 ) then ent:Remove(); else timer.Simple( delay_remove_time, function() if ( IsValid( ent ) ) then ent:Remove(); end; end ); end; end ); end; return nEnt; elseif ( string.sub( model, 1, 13 ) == "models/nseven" ) then ent.Owner = ply or game.GetWorld(); ent.IsBreakableNsevenProp = true; return ent; end; return NULL; end; local function PropReplaceInMap() if ( GetConVar("breakprops_active"):GetInt() <= 0 ) then return; end; table.Empty( doors_save ); do if ( GetConVar("breakprops_change_map_doors"):GetInt() == 1 ) then local doors = ents.FindByClass( "prop_door_rotating" ); local j = #doors; if (j ~= 0) then for i = 1, j do local ent = doors[i]; if ( ent:GetClass() == "prop_door_rotating" ) then local new_model = getReplaceModel( ent:GetModel() ); if ( new_model ~= nil ) then local info = { entity = ent, model = new_model, skin = ent:GetSkin(), pos = ent:GetPos(), ang = ent:GetAngles(), spawn = false, }; local index = table.insert( doors_save, info ); ent.doorIndex = index; end; end; end; end; end; end; do local props = ents.FindByClass( "prop_physics" ); local j = #props; if (j ~= 0) then for i = 1, j do local ent = props[i]; local class = ent:GetClass(); if ( class == "prop_physics" ) then if ( GetConVar("breakprops_change_map_props"):GetInt() <= 0 ) then return; end; propReplace( NULL, ent:GetModel(), ent, class ); end; end; end; end; end; hook.Add( "InitPostEntity", hookIndex.."InitPostEntity", PropReplaceInMap ); hook.Add( "PostCleanupMap", hookIndex.."PostCleanupMap", PropReplaceInMap ); local isUseDefaultDuplicator = false; local isUseDefaultDuplicator_Delay = 0; hook.Add( "CanTool", hookIndex.."CanTool", function( ply, tr, tool ) if ( tool == "duplicator" ) then isUseDefaultDuplicator = true; isUseDefaultDuplicator_Delay = CurTime() + 0.2; end; end ); hook.Add( "PlayerInitialSpawn", hookIndex.."PlayerInitialSpawn", function( ply ) local uid64 = "single_player"; if ( not game.SinglePlayer() ) then uid64 = tostring( ply:SteamID64() ); end; ply.IsDuplicatorUse = false; if ( not file.IsDir( "rpb_data", "DATA" ) ) then file.CreateDir( "rpb_data" ); end; if ( not file.IsDir( "rpb_data/" .. uid64, "DATA" ) ) then file.CreateDir( "rpb_data/" .. uid64 ); end; if ( not file.Exists( "rpb_data/" .. uid64 .. "/breakprops_change_playerspawn_prop.dat", "DATA" ) ) then file.Write( "rpb_data/" .. uid64 .. "/breakprops_change_playerspawn_prop.dat", "1" ); end; if ( not file.Exists( "rpb_data/" .. uid64 .. "/breakprops_localcvars_active.dat", "DATA" ) ) then file.Write( "rpb_data/" .. uid64 .. "/breakprops_localcvars_active.dat", "0" ); end; end ); net.Receive( "sv.replace_prop_to_breakable.clear", function( len, ply ) table.Empty( ply.DuplicatorEntities ); table.Empty( ply.Adv2DuplicatorEntities ); end ); net.Receive( "sv.replace_prop_to_breakable.duplicator", function( len, ply ) CreateConstraintFromEnts( ply, ply.DuplicatorEntities ); timer.Simple( 0.2, function() table.Empty( ply.DuplicatorEntities ); end ); end ); net.Receive( "sv.replace_prop_to_breakable.adv2duplicator", function( len, ply ) CreateConstraintFromEnts( ply, ply.Adv2DuplicatorEntities ); timer.Simple( 0.2, function() table.Empty( ply.Adv2DuplicatorEntities ); end ); end ); hook.Add( "PlayerSpawnedProp", hookIndex.."PlayerSpawnedProp", function( ply, model, ent ) if ( GetConVar("breakprops_active"):GetInt() <= 0 ) then return; end; if ( GetConVar("breakprops_change_playerspawn_prop"):GetInt() <= 0 ) then local falue = true; local uid64 = "single_player"; if ( not game.SinglePlayer() ) then uid64 = tostring( ply:SteamID64() ); end; if ( file.Read( "rpb_data/" .. uid64 .. "/breakprops_localcvars_active.dat", "DATA" ) == "1" ) then if ( file.Read( "rpb_data/" .. uid64 .. "/breakprops_change_playerspawn_prop.dat", "DATA" ) == "1" ) then falue = false; end; end; if ( falue ) then return; end; end; if ( isBreakableModel( model ) ) then ent.IsBreakableNsevenProp = true; end; ply.Adv2DuplicatorEntities = ply.Adv2DuplicatorEntities or {}; ply.DuplicatorEntities = ply.DuplicatorEntities or {}; --[[ Заметка: как то нужно сделать эти ёбаные соединения ]]-- -- ply.Adv2DuplicatorEntitiesConstruct = ply.Adv2DuplicatorEntitiesConstruct or {}; --[[ Заметка: как то нужно сделать эти ёбаные соединения ]]-- if ( ply.AdvDupe2 ~= nil and ply.AdvDupe2.Pasting ) then do ent.Owner = ply; table.insert( ply.Adv2DuplicatorEntities, ent ); local check = {}; check.func = function() if ( not ply.AdvDupe2.Pasting ) then if ( #ply.Adv2DuplicatorEntities ~= 0 ) then -- CreateConstraintFromEnts( ply, ply.Adv2DuplicatorEntities ); -- timer.Simple( 0.1, function() -- if ( not ply.AdvDupe2.Pasting ) then -- table.Empty( ply.Adv2DuplicatorEntities ); -- end; -- end ); -- Хочу какать for _, select_ent in pairs( ply.Adv2DuplicatorEntities ) do if ( select_ent.isBreakableChecked ) then return; end; if ( IsValid( select_ent ) and not isBreakableModel( select_ent:GetModel() ) ) then for _, select_ent2 in pairs( ply.Adv2DuplicatorEntities ) do select_ent2.isBreakableChecked = true; end; net.Start( "cl.replace_prop_to_breakable.warning_menu_open" ); net.WriteBool( false ); net.WriteString( "adv2duplicator" ); net.Send( ply ); return; end; end; table.Empty( ply.Adv2DuplicatorEntities ); end; else timer.Simple( 0.1, check.func ); end; end; check.func(); end; elseif ( isUseDefaultDuplicator ) then do ent.Owner = ply; table.insert( ply.DuplicatorEntities, ent ); local check = {}; check.func = function() if ( isUseDefaultDuplicator and isUseDefaultDuplicator_Delay < CurTime() ) then isUseDefaultDuplicator = false; if ( #ply.DuplicatorEntities ~= 0 ) then local isEmptyTable = true; for _, select_ent in pairs( ply.DuplicatorEntities ) do if ( select_ent.isBreakableChecked ) then return; end; if ( IsValid( select_ent ) and not isBreakableModel( select_ent:GetModel() ) ) then for _, select_ent2 in pairs( ply.Adv2DuplicatorEntities ) do select_ent2.isBreakableChecked = true; end; net.Start( "cl.replace_prop_to_breakable.warning_menu_open" ); net.WriteBool( false ); net.WriteString( "duplicator" ); net.Send( ply ); isEmptyTable = false; return; end; end; table.Empty( ply.DuplicatorEntities ); end; else timer.Simple( 0.1, check.func ); end; end; check.func(); end; elseif ( ( ply.AdvDupe2 == nil or not ply.AdvDupe2.Pasting ) ) then propReplace( ply, model, ent, ent:GetClass() ); end; end ); hook.Add( "EntityTakeDamage", hookIndex.."Door_EntityTakeDamage", function( ent, dmg ) if ( GetConVar("breakprops_change_map_doors"):GetInt() == 1 and ent:GetClass() == "prop_door_rotating" ) then if ( ent.doorIndex ~= nil and doors_save[ent.doorIndex] ~= nil and not doors_save[ent.doorIndex].spawn and not ent:GetNoDraw() ) then ent.propBreakableDoorHp = ent.propBreakableDoorHp or 150; ent.propBreakableDoorHp = ent.propBreakableDoorHp - dmg:GetDamage(); if ( ent.propBreakableDoorHp <= 0 ) then ent:SetNotSolid( true ); ent:SetNoDraw( true ); local door_info = doors_save[ent.doorIndex]; local dir = dmg:GetDamageForce():GetNormalized(); local force = dir * math.max( math.sqrt( dmg:GetDamageForce():Length() / 1000 ), 1 ) * 1000; local door = ents.Create( "prop_physics" ); door:SetModel( door_info.model ); door:SetSkin( door_info.skin ); door:SetPos( door_info.pos ); door:SetAngles( door_info.ang ); door.DestructDoor = true; door:Spawn(); door:SetVelocity( force ); door:GetPhysicsObject():ApplyForceOffset( force, dmg:GetDamagePosition() ); door:SetPhysicsAttacker( dmg:GetAttacker() ); door:EmitSound( "physics/wood/wood_furniture_break" .. tostring( math.random( 1, 2 ) ) .. ".wav", 110, math.random( 90, 110 ) ); doors_save[ent.doorIndex].spawn = true; ent.propBreakableDoorHp = 150; door:TakeDamageInfo( dmg ); local respawn = {}; respawn.door = function( door, break_door ) if ( IsValid( break_door ) ) then break_door:Remove(); end; if ( IsValid( door ) and door.doorIndex ~= nil ) then local obb_mins = LocalToWorld( door:OBBMins(), Angle(), door:GetPos(), door:GetAngles() ); local obb_max = LocalToWorld( door:OBBMaxs(), Angle(), door:GetPos(), door:GetAngles() ); local objects = ents.FindInBox( obb_mins, obb_max ); local notspawn = false; for _, v in pairs ( objects ) do if ( v:IsPlayer() ) then notspawn = true; timer.Simple( 1, function() respawn.door( door, NULL ); end ); break; end; end; if ( notspawn ) then return; end; doors_save[door.doorIndex].spawn = false; door:SetNotSolid( false ); door:SetNoDraw( false ); end; end; timer.Simple( 60, function() respawn.door( ent, door ); end ); end; end; end; end ); hook.Add("EntityTakeDamage", hookIndex.."EntityTakeDamage", function( ent, dmg ) if ( GetConVar("breakprops_active"):GetInt() <= 0 ) then return; end; local class = ent:GetClass(); if ( class == "prop_physics" ) then local model = ent:GetModel(); if ( ent.IsBreakableNsevenProp or ( string.len( model ) > 14 and string.sub( model, 1, 14 ) == "models/nseven/" ) ) then local old_prop = ent; local owner = old_prop.Owner; local getpos = old_prop:GetPos(); local DestructDoor = old_prop.DestructDoor; --[[ Заметка: возможная система поиска пропов ]]-- -- local obb_mins = LocalToWorld( old_prop:OBBMins(), Angle(), old_prop:GetPos(), old_prop:GetAngles() ); -- local obb_max = LocalToWorld( old_prop:OBBMaxs(), Angle(), old_prop:GetPos(), old_prop:GetAngles() ); --[[ Заметка: возможная система поиска пропов ]]-- local more = false; timer.Simple( 0.01, function() local objects = ents.FindInSphere( getpos, 10 ); --[[ Заметка: возможная система поиска пропов ]]-- -- local objects = ents.FindInBox( obb_mins, obb_max ); -- for _, v in pairs ( objects ) do -- print( v:GetModel() ) -- end; --[[ Заметка: возможная система поиска пропов ]]-- if ( table.Count( objects ) > 1 ) then more = true; undo.Create( "Prop" ); undo.SetPlayer( owner ); end; for _, prop in pairs( objects ) do if ( IsValid( prop ) and prop ~= old_prop and prop:GetClass() == "prop_physics" ) then local new_model = prop:GetModel(); if ( string.sub( new_model , 1, 20 ) == "models/nseven/debris" or string.sub( new_model , 1, 11 ) == "models/gibs" or string.sub( new_model , 1, 13 ) == "models/nseven" ) then if ( not IsValid( owner ) and DestructDoor ) then prop.DestructDoor = true; timer.Simple( 30, function() if ( IsValid( prop ) ) then prop:Remove(); end; end ); else prop.Owner = owner; prop.IsBreakableNsevenProp = true; if ( DPP ~= nil ) then DPP.SetOwner( prop, owner ); elseif ( FPP ~= nil ) then prop.FPPOwner = owner; end; if ( owner ~= NULL and owner:IsPlayer() ) then if ( more ) then undo.AddEntity( prop ); elseif ( old_prop == NULL ) then undo.Create( "Prop" ); undo.SetPlayer( owner ); undo.AddEntity( prop ); undo.Finish(); elseif ( not more ) then undo.ReplaceEntity( old_prop, prop ); cleanup.ReplaceEntity( old_prop, prop ); old_prop = NULL; end; end; end; end; end; end; if ( more ) then undo.Finish(); end; end ); end; end; end) CreateConstraintFromEnts = function( ply, Original_EntList ) local Old_Ents = {}; local New_Ents = {}; local Ents = {}; local Ents_Keys = {}; local Constraints = {}; local Constraints_Keys = {}; duplicator.GetAllConstrainedEntitiesAndConstraints( Original_EntList[ 1 ], Ents, Constraints ); for key, _ in pairs( Constraints ) do table.insert( Constraints_Keys, key ); end; for key, _ in pairs( Ents ) do table.insert( Ents_Keys, key ); end; undo.Create( "Prop" ); undo.SetPlayer( ply ); for _, sEnt in pairs( Original_EntList ) do if ( IsValid( sEnt ) ) then local _getEnt = propReplace( sEnt.Owner, sEnt:GetModel(), sEnt, sEnt:GetClass(), 30, true ); if ( IsValid( _getEnt ) ) then table.insert( Old_Ents, sEnt ); table.insert( New_Ents, { New = _getEnt, Old = sEnt } ); undo.AddEntity( _getEnt ); else undo.AddEntity( sEnt ); end; end; end; undo.Finish(); local _get_constraint = {}; for i_constraint = 1, table.Count( Constraints_Keys ) do _get_constraint = Constraints[ Constraints_Keys[ i_constraint ] ]; -- Create NoCollide constraint do if ( _get_constraint[ 'Type' ] == "NoCollide" ) then local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; local result = constraint.NoCollide( Ent1, Ent2, Bone1, Bone2 ); end; end; -- Create Weld constraint do if ( _get_constraint[ 'Type' ] == "Weld" ) then local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local Forcelimit = _get_constraint[ 'forcelimit' ]; local NoCollide = _get_constraint[ 'nocollide' ]; local DeleteonBreak = _get_constraint[ 'deleteonbreak' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.Weld( Ent1, Ent2, Bone1, Bone2, Forcelimit, NoCollide, DeleteonBreak ); end; end; -- Create Rope constraint do if ( _get_constraint[ 'Type' ] == "Rope" ) then local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local LPos1 = _get_constraint[ 'LPos1' ]; local LPos2 = _get_constraint[ 'LPos2' ]; local Length = _get_constraint[ 'length' ]; local Addlength = _get_constraint[ 'addlength' ]; local Forcelimit = _get_constraint[ 'forcelimit' ]; local Width = _get_constraint[ 'width' ]; local Material = _get_constraint[ 'material' ]; local Rigid = _get_constraint[ 'rigid' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.Rope( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Length, Addlength, Forcelimit, Width, Material, Rigid ); end; end; -- Create Hydraulic constraint do if ( _get_constraint[ 'Type' ] == "Hydraulic" ) then local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local LPos1 = _get_constraint[ 'LPos1' ]; local LPos2 = _get_constraint[ 'LPos2' ]; local Length1 = _get_constraint[ 'Length1' ]; local Length2 = _get_constraint[ 'Length2' ]; local Key = _get_constraint[ 'key' ]; local Speed = _get_constraint[ 'speed' ]; local Width = _get_constraint[ 'width' ]; local Material = _get_constraint[ 'material' ]; local Fixed = _get_constraint[ 'fixed' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.Hydraulic( ply, Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Length1, Length2, Width, Key, Fixed, Speed, material ); end; end; -- Create Keepupright constraint do if ( _get_constraint[ 'Type' ] == "Keepupright" ) then local Ent = _get_constraint[ 'ent' ]; local Ang = _get_constraint[ 'ang' ]; local Bone = _get_constraint[ 'bone' ]; local AngularLimit = _get_constraint[ 'angularLimit' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent' ] == value.Old ) then Ent = value.New; end; end; constraint.Keepupright( Ent, Ang, Bone, AngularLimit ); end; end; -- Create Motor constraint do if ( _get_constraint[ 'Type' ] == "Motor" ) then local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local LPos1 = _get_constraint[ 'LPos1' ]; local LPos2 = _get_constraint[ 'LPos2' ]; local Friction = _get_constraint[ 'friction' ]; local Torque = _get_constraint[ 'torque' ]; local Forcetime = _get_constraint[ 'forcetime' ]; local NoCollide = _get_constraint[ 'nocollide' ]; local Toggle = _get_constraint[ 'toggle' ]; local Forcelimit = _get_constraint[ 'forcelimit' ]; local NumpadkeyFWD = _get_constraint[ 'numpadkey_fwd' ]; local NumpadkeyBWD = _get_constraint[ 'numpadkey_bwd' ]; local Direction = _get_constraint[ 'direction' ]; local LocalAxis = _get_constraint[ 'LocalAxis' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.Motor( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Friction, Torque, Forcetime, NoCollide, Toggle, ply, Forcelimit, NumpadkeyFWD, NumpadkeyBWD, Direction, LocalAxis ); end; end; -- Create AdvBallsocket constraint do if ( _get_constraint[ 'Type' ] == "AdvBallsocket" ) then local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local LPos1 = _get_constraint[ 'LPos1' ]; local LPos2 = _get_constraint[ 'LPos2' ]; local Forcelimit = _get_constraint[ 'forcelimit' ]; local Torquelimit = _get_constraint[ 'torquelimit' ]; local Xmin = _get_constraint[ 'xmin' ]; local YMin = _get_constraint[ 'ymin' ]; local ZMin = _get_constraint[ 'zmin' ]; local Xmax = _get_constraint[ 'xmax' ]; local YMax = _get_constraint[ 'ymax' ]; local ZMax = _get_constraint[ 'zmax' ]; local XFric = _get_constraint[ 'xfric' ]; local YFric = _get_constraint[ 'yfric' ]; local ZFric = _get_constraint[ 'zfric' ]; local OnlyRotation = _get_constraint[ 'onlyrotation' ]; local Torquelimit = _get_constraint[ 'torquelimit' ]; local NoCollide = _get_constraint[ 'nocollide' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.AdvBallsocket( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Forcelimit, Torquelimit, Xmin, YMin, ZMin, Xmax, YMax, ZMax, XFric, YFric, ZFric, OnlyRotation, NoCollide ); end; end; -- Create Axis constraint do if ( _get_constraint[ 'Type' ] == "Axis" ) then local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local LPos1 = _get_constraint[ 'LPos1' ]; local LPos2 = _get_constraint[ 'LPos2' ]; local Friction = _get_constraint[ 'friction' ]; local Forcelimit = _get_constraint[ 'forcelimit' ]; local Torquelimit = _get_constraint[ 'torquelimit' ]; local LocalAxis = _get_constraint[ 'LocalAxis' ]; local DontAddTable = _get_constraint[ 'DontAddTable' ]; local OnlyRotation = _get_constraint[ 'onlyrotation' ]; local Torquelimit = _get_constraint[ 'torquelimit' ]; local NoCollide = _get_constraint[ 'nocollide' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.Axis( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Forcelimit, Torquelimit, Friction, NoCollide, LocalAxis, DontAddTable ); end; end; -- Create Ballsocket constraint do if ( _get_constraint[ 'Type' ] == "Ballsocket" ) then local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local LocalPos = _get_constraint[ 'LPos' ]; local Forcelimit = _get_constraint[ 'forcelimit' ]; local Torquelimit = _get_constraint[ 'torquelimit' ]; local NoCollide = _get_constraint[ 'nocollide' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.Ballsocket( Ent1, Ent2, Bone1, Bone2, LocalPos, Forcelimit, Torquelimit, NoCollide ); end; end; -- Create Elastic constraint do if ( _get_constraint[ 'Type' ] == "Elastic" ) then local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local LPos1 = _get_constraint[ 'LPos1' ]; local LPos2 = _get_constraint[ 'LPos2' ]; local Constant = _get_constraint[ 'constant' ]; local Damping = _get_constraint[ 'damping' ]; local Rdamping = _get_constraint[ 'rdamping' ]; local Material = _get_constraint[ 'material' ]; local Width = _get_constraint[ 'width' ]; local Stretchonly = _get_constraint[ 'stretchonly' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.Elastic( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Constant, Damping, Rdamping, Material, Width, Stretchonly ); end; end; -- Create Muscle constraint do if ( _get_constraint[ 'Type' ] == "Muscle" ) then local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local LPos1 = _get_constraint[ 'LPos1' ]; local LPos2 = _get_constraint[ 'LPos2' ]; local Length1 = _get_constraint[ 'Length1' ]; local Length2 = _get_constraint[ 'Length2' ]; local Key = _get_constraint[ 'key' ]; local Material = _get_constraint[ 'material' ]; local Width = _get_constraint[ 'width' ]; local Fixed = _get_constraint[ 'fixed' ]; local Period = _get_constraint[ 'period' ]; local Amplitude = _get_constraint[ 'amplitude' ]; local Starton = _get_constraint[ 'starton' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.Muscle( ply, Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Length1, Length2, width, Key, Fixed, Period, Amplitude, Starton, Material ); end; end; -- Create Pulley constraint do if ( _get_constraint[ 'Type' ] == "Pulley" ) then local Ent1 = _get_constraint[ 'Ent1' ]; local Ent4 = _get_constraint[ 'Ent2' ]; local Bone1 = _get_constraint[ 'Bone1' ]; local Bone4 = _get_constraint[ 'Bone4' ]; local LPos1 = _get_constraint[ 'LPos1' ]; local LPos4 = _get_constraint[ 'LPos4' ]; local WPos2 = _get_constraint[ 'WPos2' ]; local WPos3 = _get_constraint[ 'WPos3' ]; local Forcelimit = _get_constraint[ 'forcelimit' ]; local Rigid = _get_constraint[ 'rigid' ]; local Material = _get_constraint[ 'material' ]; local Width = _get_constraint[ 'width' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent4' ] == value.Old ) then Ent4 = value.New; end; end; constraint.Pulley( Ent1, Ent4, Bone1, Bone4, LPos1, LPos4, WPos2, WPos3, Forcelimit, Rigid, Width, Material ); end; end; -- Create Slider constraint do if ( _get_constraint[ 'Type' ] == "Slider" ) then local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local LPos1 = _get_constraint[ 'LPos1' ]; local LPos2 = _get_constraint[ 'LPos2' ]; local Material = _get_constraint[ 'material' ]; local Width = _get_constraint[ 'width' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.Slider( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Width, Material ); end; end; -- Create Winch constraint do if ( _get_constraint[ 'Type' ] == "Winch" ) then local Ent1 = _get_constraint[ 'Ent1' ]; local Ent2 = _get_constraint[ 'Ent2' ]; local Bone1 = _get_constraint[ 'Bone1' ]; local Bone2 = _get_constraint[ 'Bone2' ]; local LPos1 = _get_constraint[ 'LPos1' ]; local LPos2 = _get_constraint[ 'LPos2' ]; local Material = _get_constraint[ 'material' ]; local Width = _get_constraint[ 'width' ]; local fwd_bind = _get_constraint[ 'fwd_bind' ]; local bwd_bind = _get_constraint[ 'bwd_bind' ]; local fwd_speed = _get_constraint[ 'fwd_speed' ]; local bwd_speed = _get_constraint[ 'bwd_speed' ]; local toggle = _get_constraint[ 'toggle' ]; for key, value in pairs( New_Ents ) do if ( _get_constraint[ 'Ent1' ] == value.Old ) then Ent1 = value.New; end; if ( _get_constraint[ 'Ent2' ] == value.Old ) then Ent2 = value.New; end; end; constraint.Winch( ply, Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, Width, fwd_bind, bwd_bind, fwd_speed, bwd_speed, Material, toggle ); end; end; end; for _, OldEnt in pairs( Old_Ents ) do OldEnt:Remove(); end; table.Empty( Old_Ents ); table.Empty( New_Ents ); table.Empty( Ents ); table.Empty( Ents_Keys ); table.Empty( Constraints ); table.Empty( Constraints_Keys ); end; hook.Add("PlayerSay", hookIndex.."PlayerSay", function( ply, text, isTeamChat ) local getText = string.Replace( text, " ", "" ); if ( getText == "!rs_rpb" or getText == "/rs_rpb" ) then net.Start( "cl.replace_prop_to_breakable.warning_menu_open" ); net.WriteBool( true ); net.Send( ply ); end; end );
local K, _, L = unpack(select(2, ...)) local Module = K:GetModule("Miscellaneous") local _G = _G local pairs = _G.pairs local select = _G.select local string_split = _G.string.split local string_sub = _G.string.sub local table_wipe = _G.table.wipe local tonumber = _G.tonumber local unpack = _G.unpack local CreateFrame = _G.CreateFrame local DELETE = _G.DELETE local ERR_INV_FULL = _G.ERR_INV_FULL local ERR_ITEM_MAX_COUNT = _G.ERR_ITEM_MAX_COUNT local ERR_MAIL_DELETE_ITEM_ERROR = _G.ERR_MAIL_DELETE_ITEM_ERROR local GameTooltip = _G.GameTooltip local GetInboxHeaderInfo = _G.GetInboxHeaderInfo local GetInboxItem = _G.GetInboxItem local GetInboxItemLink = _G.GetInboxItemLink local GetInboxNumItems = _G.GetInboxNumItems local GetItemInfo = _G.GetItemInfo local GetItemQualityColor = _G.GetItemQualityColor local InboxTooMuchMail = _G.InboxTooMuchMail local IsModifiedClick = _G.IsModifiedClick local UIErrorsFrame = _G.UIErrorsFrame local hooksecurefunc = _G.hooksecurefunc local deletedelay = 0.5 local mailItemIndex = 0 local inboxItems = {} local button1 local button2 local button3 local lastopened local imOrig_InboxFrame_OnClick local hasNewMail local takingOnlyCash local onlyCurrentMail local needsToWait local skipMail function Module:MailItem_OnClick() mailItemIndex = 7 * (_G.InboxFrame.pageNum - 1) + tonumber(string_sub(self:GetName(), 9, 9)) local modifiedClick = IsModifiedClick("MAILAUTOLOOTTOGGLE") if modifiedClick then _G.InboxFrame_OnModifiedClick(self, self.index) else _G.InboxFrame_OnClick(self, self.index) end end function Module:MailBox_OpenAll() if GetInboxNumItems() == 0 then return end button1:SetScript("OnClick", nil) button2:SetScript("OnClick", nil) button3:SetScript("OnClick", nil) imOrig_InboxFrame_OnClick = _G.InboxFrame_OnClick _G.InboxFrame_OnClick = K.Noop if onlyCurrentMail then button3:RegisterEvent("UI_ERROR_MESSAGE") Module.MailBox_Open(button3, mailItemIndex) else button1:RegisterEvent("UI_ERROR_MESSAGE") Module.MailBox_Open(button1, GetInboxNumItems()) end end function Module:MailBox_Update(elapsed) self.elapsed = (self.elapsed or 0) + elapsed if (not needsToWait) or (self.elapsed > deletedelay) then self.elapsed = 0 needsToWait = false self:SetScript("OnUpdate", nil) local _, _, _, _, money, COD, _, numItems = GetInboxHeaderInfo(lastopened) if skipMail then Module.MailBox_Open(self, lastopened - 1) elseif money > 0 or (not takingOnlyCash and numItems and numItems > 0 and COD <= 0) then Module.MailBox_Open(self, lastopened) else Module.MailBox_Open(self, lastopened - 1) end end end function Module:MailBox_Open(index) if not _G.InboxFrame:IsVisible() or index == 0 then Module:MailBox_Stop() return end local _, _, _, _, money, COD, _, numItems = GetInboxHeaderInfo(index) if not takingOnlyCash then if money > 0 or (numItems and numItems > 0) and COD <= 0 then _G.AutoLootMailItem(index) needsToWait = true end if onlyCurrentMail then Module:MailBox_Stop() return end elseif money > 0 then _G.TakeInboxMoney(index) needsToWait = true end local items = GetInboxNumItems() if (numItems and numItems > 0) or (items > 1 and index <= items) then lastopened = index self:SetScript("OnUpdate", Module.MailBox_Update) else Module:MailBox_Stop() end end function Module:MailBox_Stop() button1:SetScript("OnUpdate", nil) button1:SetScript("OnClick", function() onlyCurrentMail = false Module:MailBox_OpenAll() end) button2:SetScript("OnClick", function() takingOnlyCash = true Module:MailBox_OpenAll() end) button3:SetScript("OnUpdate", nil) button3:SetScript("OnClick", function() onlyCurrentMail = true Module:MailBox_OpenAll() end) if imOrig_InboxFrame_OnClick then _G.InboxFrame_OnClick = imOrig_InboxFrame_OnClick end if onlyCurrentMail then button3:UnregisterEvent("UI_ERROR_MESSAGE") else button1:UnregisterEvent("UI_ERROR_MESSAGE") end takingOnlyCash = false onlyCurrentMail = false needsToWait = false skipMail = false end function Module:MailBox_OnEvent(event, _, msg) if event == "UI_ERROR_MESSAGE" then if msg == ERR_INV_FULL then Module:MailBox_Stop() elseif msg == ERR_ITEM_MAX_COUNT then skipMail = true end elseif event == "MAIL_CLOSED" then if not hasNewMail then _G.MiniMapMailFrame:Hide() end Module:MailBox_Stop() end end function Module:TotalCash_OnEnter() GameTooltip:SetOwner(self, "ANCHOR_RIGHT") local total_cash = 0 for index = 0, GetInboxNumItems() do total_cash = total_cash + select(5, GetInboxHeaderInfo(index)) end if total_cash > 0 then _G.SetTooltipMoney(GameTooltip, total_cash) end GameTooltip:Show() end function Module:MailBox_DelectClick() local selectedID = self.id + (_G.InboxFrame.pageNum - 1) * 7 if _G.InboxItemCanDelete(selectedID) then _G.DeleteInboxItem(selectedID) else UIErrorsFrame:AddMessage("|cff99ccff"..ERR_MAIL_DELETE_ITEM_ERROR) end end function Module:MailItem_AddDelete(i) local bu = CreateFrame("Button", nil, self) bu:SetPoint("BOTTOMRIGHT", self:GetParent(), "BOTTOMRIGHT", -10, 5) bu:SetSize(16, 16) bu.Icon = bu:CreateTexture(nil, "ARTWORK") bu.Icon:SetAllPoints() bu.Icon:SetTexture(136813) bu.Icon:SetTexCoord(unpack(K.TexCoords)) bu.id = i bu:SetScript("OnClick", Module.MailBox_DelectClick) K.AddTooltip(bu, "ANCHOR_RIGHT", DELETE, "system") end function Module:CreatButton(parent, text, w, h, ap, frame, rp, x, y) local button = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate") button:SetWidth(w) button:SetHeight(h) button:SetPoint(ap, frame, rp, x, y) button:SetText(text) return button end function Module:InboxFrame_Hook() hasNewMail = false if select(4, GetInboxHeaderInfo(1)) then for i = 1, GetInboxNumItems() do local wasRead = select(9, GetInboxHeaderInfo(i)) if not wasRead then hasNewMail = true break end end end end function Module:InboxItem_OnEnter() table_wipe(inboxItems) local itemAttached = select(8, GetInboxHeaderInfo(self.index)) if itemAttached then for attachID = 1, 12 do local _, _, _, itemCount = GetInboxItem(self.index, attachID) if itemCount and itemCount > 0 then local _, itemid = string_split(":", GetInboxItemLink(self.index, attachID)) itemid = tonumber(itemid) inboxItems[itemid] = (inboxItems[itemid] or 0) + itemCount end end if itemAttached > 1 then GameTooltip:AddLine(L["Attach List"]) for key, value in pairs(inboxItems) do local itemName, _, itemQuality, _, _, _, _, _, _, itemTexture = GetItemInfo(key) if itemName then local r, g, b = GetItemQualityColor(itemQuality) GameTooltip:AddDoubleLine(" |T"..itemTexture..":12:12:0:0:50:50:4:46:4:46|t "..itemName, value, r, g, b) end end GameTooltip:Show() end end end function Module:CreateMailBox() for i = 1, 7 do local itemButton = _G["MailItem"..i.."Button"] itemButton:SetScript("OnClick", Module.MailItem_OnClick) Module.MailItem_AddDelete(itemButton, i) end button1 = Module:CreatButton(_G.InboxFrame, L["Collect All"], 100, 22, "TOPLEFT", "InboxFrame", "TOPLEFT", 82, -30) button1:RegisterEvent("MAIL_CLOSED") button1:SetScript("OnClick", Module.MailBox_OpenAll) button1:SetScript("OnEvent", Module.MailBox_OnEvent) button2 = Module:CreatButton(_G.InboxFrame, L["Collect Gold"], 100, 22, "TOPRIGHT", "InboxFrame", "TOPRIGHT", -82, -30) button2:SetScript("OnClick", function() takingOnlyCash = true Module:MailBox_OpenAll() end) button2:SetScript("OnEnter", Module.TotalCash_OnEnter) button2:SetScript("OnLeave", K.HideTooltip) button3 = Module:CreatButton(_G.OpenMailFrame, L["Collect Letters"], 82, 22, "RIGHT", "OpenMailReplyButton", "LEFT", 0, 0) button3:SetScript("OnClick", function() onlyCurrentMail = true Module:MailBox_OpenAll() end) button3:SetScript("OnEvent", Module.MailBox_OnEvent) hooksecurefunc("InboxFrame_Update", Module.InboxFrame_Hook) hooksecurefunc("InboxFrameItem_OnEnter", Module.InboxItem_OnEnter) -- Replace the alert frame if InboxTooMuchMail then InboxTooMuchMail:ClearAllPoints() InboxTooMuchMail:SetPoint("BOTTOM", _G.MailFrame, "TOP", 0, 5) end -- Hide Blizz _G.OpenAllMail:Kill() end function Module:CreateImprovedMail() if K.CheckAddOnState("Postal") then return end self:CreateMailBox() end
return Def.ActorFrame { LoadFont("Common Normal") .. { Text="BPM"; InitCommand=function(self) self:horizalign(right):zoom(0.50) end; }; };
local Dta = select(2, ...) local ReskinWindowSettings = { WIDTH = 315, HEIGHT = 250, CLOSABLE = true, MOVABLE = true, POS_X = "ReskinwindowPosX", POS_Y = "ReskinwindowPosY" } function Dta.ui.buildReskinWindow() local Locale = Dta.Locale local x = Dta.settings.get("ReskinwindowPosX") local y = Dta.settings.get("ReskinwindowPosY") local newWindow = Dta.ui.Window.Create("ReskinWindow", Dta.ui.context, Locale.Titles.Reskin, ReskinWindowSettings.WIDTH, ReskinWindowSettings.HEIGHT, x, y, ReskinWindowSettings.CLOSABLE, ReskinWindowSettings.MOVABLE, Dta.ui.hideReskinWindow, Dta.ui.WindowMoved ) local reskinWindow = newWindow.content newWindow.settings = ReskinWindowSettings newWindow.oldFilterLabel = Dta.ui.createText("OldSkinFilter", reskinWindow, 10, 5, Locale.Text.Category, 14) newWindow.oldFilterSelect = Dta.ui.createDropdown("OldCategorySelect", reskinWindow, 120, 5, 180) newWindow.oldFilterSelect:SetItems(Dta.Replacement.loadSkinCategories()) newWindow.oldFilterSelect:SetSelectedIndex(1) newWindow.oldFilterSelect.Event.ItemSelect = Dta.Replacement.FilterOldChanged newWindow.oldSkinLabel = Dta.ui.createText("OldSkinLabel", reskinWindow, 10, 30, Locale.Text.OldSkin, 14) newWindow.oldSkinSelect = Dta.ui.createDropdown("OldSkinSelect", reskinWindow, 120, 30, 180) newWindow.oldSkinSelect:SetItems(Dta.Replacement.loadSkins(nil, true)) newWindow.newFilterLabel = Dta.ui.createText("NewSkinFilter", reskinWindow, 10, 55, Locale.Text.Category, 14) newWindow.newFilterSelect = Dta.ui.createDropdown("OldCategorySelect", reskinWindow, 120, 55, 180) newWindow.newFilterSelect:SetItems(Dta.Replacement.loadSkinCategories()) newWindow.newFilterSelect:SetSelectedIndex(1) newWindow.newFilterSelect.Event.ItemSelect = Dta.Replacement.FilterNewChanged newWindow.newSkinLabel = Dta.ui.createText("NewSkinLabel", reskinWindow, 10, 80, Locale.Text.NewSkin, 14) newWindow.newSkinSelect = Dta.ui.createDropdown("NewSkinSelect", reskinWindow, 120, 80, 180) newWindow.newSkinSelect:SetItems(Dta.Replacement.loadSkins()) newWindow.tile = Dta.ui.createCheckbox("replaceTiles", reskinWindow, 20, 110, Locale.Text.Tile, true) newWindow.rectangle = Dta.ui.createCheckbox("replaceRectangle", reskinWindow, 20, 135, Locale.Text.Rectangle, true) newWindow.triangle = Dta.ui.createCheckbox("replaceTriangles", reskinWindow, 20, 160, Locale.Text.Triangle, true) newWindow.plank = Dta.ui.createCheckbox("replacePlanks", reskinWindow, 20, 185, Locale.Text.Plank, true) -- newWindow.cube = Dta.ui.createCheckbox("replaceCubes", reskinWindow, 155, 110, Locale.Text.Cube, true) newWindow.sphere = Dta.ui.createCheckbox("replaceSpheres", reskinWindow, 155, 135, Locale.Text.Sphere, true) newWindow.pole = Dta.ui.createCheckbox("replacePoles", reskinWindow, 155, 160, Locale.Text.Pole, true) newWindow.disc = Dta.ui.createCheckbox("replaceDiscs", reskinWindow, 155, 185, Locale.Text.Disc, true) newWindow.replaceBtn = Dta.ui.createButton("SkinReplace", reskinWindow, 100, 210, nil, nil, Locale.Buttons.Apply, nil, Dta.Replacement.ReplaceClicked) return newWindow end -- Show the reskin window function Dta.ui.showReskinWindow(reskin_window) reskin_window:SetVisible(true) reskin_window.oldFilterSelect:SetEnabled(true) reskin_window.newFilterSelect:SetEnabled(true) reskin_window.oldSkinSelect:SetEnabled(true) reskin_window.newSkinSelect:SetEnabled(true) end -- Hide the reskin window function Dta.ui.hideReskinWindow(reskin_window) reskin_window:SetVisible(false) reskin_window:ClearKeyFocus() -- workaround for dropdown not closing automatically reskin_window.oldFilterSelect:SetEnabled(false) reskin_window.newFilterSelect:SetEnabled(false) reskin_window.oldSkinSelect:SetEnabled(false) reskin_window.newSkinSelect:SetEnabled(false) end Dta.RegisterTool("Reskin", Dta.ui.buildReskinWindow, Dta.ui.showReskinWindow, Dta.ui.hideReskinWindow)
--Start listening for the Alchemy65 connection local socket = require("socket.core") local PORT = 4064 local FAST = 0.0001 local server = nil local connection = nil local isPaused = false local breakpoints = {} local delayCommand = nil function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end function split(s, delimiter) local result = {}; for match in (s..delimiter):gmatch("(.-)"..delimiter) do table.insert(result, match); end return result; end function log(c) emu.displayMessage("Alchemy65 Debug Host", c) end function onEndFrame() if isPaused ~= false then isPaused = false if connection ~= nil then connection:send("isPaused false\n") end end while alchemy65() do end end function onWhilePaused() if isPaused ~= true then isPaused = true if connection ~= nil then connection:send("isPaused true\n") end end while alchemy65() do end end function memcallback(address) if delayCommand ~= nil then return end --check if pc / prg is in the callback table address = tonumber(address) local prg = emu.getPrgRomOffset(address) if prg ~= -1 and prg ~= nil then if breakpoints["prg-" .. tostring(prg)] ~= nil then connection:send("isPaused true\n") -- log("prg breakpoint!") emu.breakExecution() end return -- we know it's in prg space and we didn't find it so don't check cpu end if breakpoints["cpu-" .. tostring(address)] ~= nil then connection:send("isPaused true\n") -- log("cpu breakpoint!") emu.breakExecution() return end --log("memcallback " .. tostring(address)) return end function clearbreakpoints() for k,ab in pairs(breakpoints) do local address = ab.a --log("clearing " .. tostring(k) .. " " .. tostring(address)) emu.removeMemoryCallback(ab.b,emu.memCallbackType.cpuExec,ab.a) breakpoints[k] = nil end end function setbreakpoint(cpuaddress, prgaddress, id) local ab = {} ab.i = id ab.a = cpuaddress ab.b = emu.addMemoryCallback(memcallback, emu.memCallbackType.cpuExec, cpuaddress) local k = "cpu-" .. tostring(cpuaddress) if prgaddress ~= nil then k = "prg-" .. tostring(prgaddress) end breakpoints[k] = ab --log("sb " .. k) return end function alchemy65() if delayCommand == "reset3" then delayCommand = nil -- emu.resume() -- log("resume") return end if delayCommand == "reset2" then delayCommand = "reset3" emu.reset() -- emu.breakExecution() -- log("reset") return end if delayCommand == "reset" then delayCommand = "reset2" emu.resume() -- log("resume") return end if delayCommand == "resetBreak" then delayCommand = nil if isPaused == true then emu.resume() end emu.reset() emu.breakExecution() connection:send("isPaused true\n") -- log("resetBreak") return end if connection == nil then local client, err = server:accept() if client ~= nil then connection = client connection:settimeout(FAST) log("Client connected") if isPaused then connection:send("isPaused true\n") else connection:send("isPaused false\n") end connection:send("configurationComplete\n") elseif err ~= "timeout" then log("accept_err:" .. err) end end if connection ~= nil then -- receive any messages? local data, err, partial = connection:receive() if partial ~= nil and partial ~= "" then -- log("partial: " .. partial) end if err == "timeout" then return -- this is fine end if err == "closed" then connection = nil log("lost connection") return end if err ~= nil then log("err: " .. err) return end if data == nil then return end local args = split(data, " ") local command = args[1] --log(command) if command == "pauseCheck" then if isPaused then connection:send("isPaused true\n") else connection:send("isPaused false\n") end return true -- keep processing messages end if command == "pause" then if isPaused == false then emu.breakExecution() connection:send("isPaused true\n") -- log("pause") else connection:send("isPaused true\n") -- log("already paused") end return end if command == "resume" then if isPaused == true then emu.resume() connection:send("isPaused false\n") -- log("resume") else connection:send("isPaused false\n") -- log("already resumed") end return end if command == "reset" then if isPaused == true then emu.resume() end delayCommand = "reset" return end if command == "resetBreak" then if isPaused == true then emu.resume() end delayCommand = "resetBreak" return end if command == "resetBreakNow" then emu.breakExecution() emu.reset() emu.breakExecution() connection:send("isPaused true\n") -- log("resetBreak") return end if command == "next" then emu.execute(1, emu.executeCountType.cpuInstructions) connection:send("stepped\n") -- log("stepInto") return end if command == "stepOver" then emu.stepOver() connection:send("stepped\n") -- log("stepOver") return end if command == "stepOut" then emu.stepOut() connection:send("stepped\n") -- log("stepOut") return end if command == "getcpuvars" then local state = emu.getState() local pc_prg = emu.getPrgRomOffset(state.cpu.pc) connection:send("cpuvars " .. tostring(state.cpu.status) .. " " .. tostring(state.cpu.a) .. " " .. tostring(state.cpu.x) .. " " .. tostring(state.cpu.y) .. " " .. tostring(state.cpu.pc) .. " " .. tostring(state.cpu.sp) .. " " .. tostring(pc_prg) .. "\n") --log("cpuvars") return true -- keep processing messages end if command == "getlabel" then local label = args[2] local count = tonumber(args[3]) local label_address = -1 pcall(function() label_address = emu.getLabelAddress(label) end) local label_address_prg = -1 local label_value = "" if label_address ~= -1 then label_address_prg = emu.getPrgRomOffset(label_address) label_value = emu.read(label_address, emu.memType.cpuDebug) local offset = 1 while offset < count do label_value = label_value .. " " .. emu.read(label_address + offset, emu.memType.cpuDebug) offset = offset + 1 end end connection:send("label-" .. label .. " " .. tostring(label_address) .. " " .. tostring(label_address_prg) .. " " .. tostring(label_value) .. "\n") --log("getlabel " .. label) return true -- keep processing messages end if command == "clearbreakpoints" then clearbreakpoints() --log("clearbreakpoints " .. tablelength(breakpoints)) return true -- keep processing messages end if command == "setbreakpoint" then local cpuaddress = tonumber(args[2]) local prgaddress = tonumber(args[3]) -- local id = args[4] setbreakpoint(cpuaddress, prgaddress) --log("setbreakpoint " .. tablelength(breakpoints)) return true -- keep processing messages end if data ~= nil then log("unexpected : " .. data) end end end -- function onInit() -- emu.removeEventCallback(onInit, emu.eventType.endFrame) -- emu.removeEventCallback(onInit, emu.eventType.whilePaused) -- emu.addEventCallback(onEndFrame, emu.eventType.endFrame) -- emu.addEventCallback(onWhilePaused, emu.eventType.whilePaused) -- emu.breakExecution() -- onEndFrame() -- end log("init...") server = socket.tcp(); server:settimeout(2) server:bind("127.0.0.1", PORT) local listen_status, listen_err = server:listen(10) if listen_err ~= nil then log("Listen Error:" .. listen_err) else server:settimeout(FAST) -- make accepts fast -- emu.addEventCallback(onInit, emu.eventType.endFrame) -- emu.addEventCallback(onInit, emu.eventType.whilePaused) emu.addEventCallback(onEndFrame, emu.eventType.endFrame) emu.addEventCallback(onWhilePaused, emu.eventType.whilePaused) log("listening on " .. PORT) -- while true do -- alchemy65() -- end end
Person = { --- create a new Person by name --- @param self --- @param name string --- @param nickName string|nil --- @return Person byName = function(self, name, nickName) return { getFormalName = function() return name end, getNickName = function() return nickName or name end, } end, --- check if the given thing is a person --- @param self --- @param thing any --- @return boolean isPerson = function(self, thing) return isTable(thing) and isFunction(thing.getFormalName) and isFunction(thing.getNickName) end, } setmetatable(Person,{ __index = Generic })
#!/usr/bin/env luajit -- (c) 2014 Team THORwIn local ok = pcall(dofile,'../fiddle.lua') if not ok then dofile'fiddle.lua' end local targetvel = {0,0,0} local targetvel_new = {0,0,0} local WAS_REQUIRED local t_last = Body.get_time() local tDelay = 0.005*1E6 local angle_increment = 5*math.pi/180 DEG_TO_RAD = math.pi/180 RAD_TO_DEG = 1/DEG_TO_RAD local override_target=vector.new({0,0,0, 0,0,0,0}) local movement_target=vector.new({0,0,0}) local char_to_override = { ['i'] = vector.new({0.04, 0, 0, 0,0,0,0}), [','] = vector.new({-.04, 0, 0, 0,0,0,0}), ['j'] = vector.new({0, 0.04, 0, 0,0,0,0}), ['l'] = vector.new({0, -.04, 0, 0,0,0,0}), ['u'] = vector.new({0, 0, 0.04, 0,0,0,0}), ['m'] = vector.new({0,0, -.04, 0,0,0,0}), --Yaw ['h'] = vector.new({0,0,0, 0,0,15,0})*math.pi/180, [';'] = vector.new({0,0,0, 0,0,-15,0})*math.pi/180, --Pitch ['y'] = vector.new({0,0,0, 0,-15,0, 0})*math.pi/180, ['n'] = vector.new({0,0,0, 0,15,0, 0})*math.pi/180, --Roll ['['] = vector.new({0,0,0, -15,0,0,0})*math.pi/180, [']'] = vector.new({0,0,0, 15,0,0,0})*math.pi/180, } local char_to_movetarget = { ['w'] = vector.new({0.1, 0, 0}), ['x'] = vector.new({-.1, 0, 0}), ['a'] = vector.new({0, 0.1, 0}), ['d'] = vector.new({0, -.1, 0}), ['q'] = vector.new({0, 0, 15*math.pi/180}), ['e'] = vector.new({0,0, -15*math.pi/180}), } local char_to_state = { ['='] = 1, ['-'] = -1, } --[[ local char_to_lfinger = { ['z'] = vector.new({-5,-5}), ['a'] = vector.new({0,0}), ['q'] = vector.new({5,5}), } local char_to_rfinger = { ['x'] = vector.new({-5,-5}), ['s'] = vector.new({0,0}), ['w'] = vector.new({5,5}), } --]] local function print_override() print( util.color('Override:','yellow'), string.format("%.2f %.2f %.2f / %.1f %.1f %.1f", override_target[1], override_target[2], override_target[3], override_target[4]*180/math.pi, override_target[5]*180/math.pi, override_target[6]*180/math.pi )) end local function update(key_code) if type(key_code)~='number' or key_code==0 then return end if Body.get_time()-t_last<0.2 then return end t_last = Body.get_time() local key_char = string.char(key_code) local key_char_lower = string.lower(key_char) if key_char_lower==("1") then body_ch:send'init' arm_ch:send'init' --initialize arm to walk position elseif key_char_lower==("0") then body_ch:send'uninit' elseif key_char_lower==("2") then arm_ch:send'teleopoldl' elseif key_char_lower==("3") then arm_ch:send'teleopoldr' elseif key_char_lower==("4") then arm_ch:send'ready' elseif key_char_lower==("8") then body_ch:send'stop' elseif key_char_lower==("9") then motion_ch:send'hybridwalk' -- -- elseif key_char_lower==("k") then override_target=vector.new({0,0,0, 0,0,0,0}) elseif key_char_lower==(" ") then hcm.set_state_override(override_target) -- hcm.set_move_target(movement_target) hcm.set_teleop_waypoint(movement_target) body_ch:send'approach' --todo override_target = vector.zeros(6) movement_target = vector.zeros(3) elseif key_char_lower==("`") then hcm.set_state_override(override_target) -- hcm.set_move_target(movement_target) hcm.set_teleop_waypoint(movement_target) body_ch:send'stepflat' --todo override_target = vector.zeros(6) movement_target = vector.zeros(3) end --notify target transform change local trmod = char_to_override[key_char_lower] if trmod then override_target = override_target+trmod print_override() return end local state_adj = char_to_state[key_char_lower] if state_adj then print( util.color('State advance','yellow'), state_adj ) hcm.set_state_proceed(state_adj) return end local movetarget_adj = char_to_movetarget[key_char_lower] if movetarget_adj then movement_target=movement_target+movetarget_adj print( util.color('Move target: ','yellow'), string.format("%.2f %.2f %d",movement_target[1],movement_target[2],movement_target[3]*180/math.pi ) ) return end end if ... and type(...)=='string' then WAS_REQUIRED = true return {entry=nil, update=update, exit=nil} end local getch = require'getch' local running = true local key_code while running do key_code = getch.block() update(key_code) end
-- -- Send VCS invalidations -- local channel = KEYS[1] local key = KEYS[2] local invals = ARGV[1] local startField = ARGV[2] local startDate = ARGV[3] local lastInvalField = ARGV[4] local invalDate = ARGV[5] local timeout = ARGV[6] redis.call('PUBLISH', channel, invals) redis.call('HSET', key, startField, startDate) redis.call('HSET', key, lastInvalField, invalDate) redis.call('EXPIRE', key, timeout)
--- Eva lang module -- API to work with game localization -- @submodule eva local app = require("eva.app") local luax = require("eva.luax") local const = require("eva.const") local utils = require("eva.modules.utils") local events = require("eva.modules.events") local proto = require("eva.modules.proto") local saver = require("eva.modules.saver") local M = {} local function load_lang(lang) local settings = app.settings.lang local filename = settings.lang_paths[lang] app.clear("lang_dict") app.lang_dict = utils.load_json(filename) or {} end local function get_time_data(seconds) local minutes = math.max(0, math.floor(seconds / 60)) seconds = math.max(0, math.floor(seconds % 60)) local hours = math.max(0, math.floor(minutes / 60)) minutes = math.max(0, math.floor(minutes % 60)) local days = math.max(0, math.floor(hours / 24)) hours = math.max(0, math.floor(hours % 24)) return days, hours, minutes, seconds end --- Return localized time format from seconds -- @function eva.lang.time_format function M.time_format(seconds) local days, hours, minutes, secs = get_time_data(seconds) if days > 0 then return M.txp("time_format_d", days, hours, minutes, secs) elseif hours > 0 then return M.txp("time_format_h", hours, minutes, secs) else return M.txp("time_format_m", minutes, secs) end end --- Set current language -- @function eva.lang.set_lang -- @tparam string lang current language code from eva-settings function M.set_lang(lang) load_lang(lang) if app[const.EVA.LANG].lang ~= lang then app[const.EVA.LANG].lang = lang events.event(const.EVENT.LANG_UPDATE, { lang = lang }) end end --- Get current language -- @function eva.lang.get_lang -- @treturn string return current language code function M.get_lang() return app[const.EVA.LANG].lang end --- Get translation for locale id -- @function eva.lang.txt -- @tparam string lang_id locale id from your localization -- @treturn string translated locale function M.txt(lang_id) assert(lang_id, "You must provide the lang id") return app.lang_dict[lang_id] or lang_id end --- Get translation for locale id with params -- @function eva.lang.txp -- @tparam string lang_id Locale id from your localization -- @tparam string ... Params for string.format for lang_id -- @treturn string Translated locale function M.txp(lang_id, ...) assert(lang_id, "You must provide the lang id") return string.format(M.txt(lang_id), ...) end --- Check is translation with lang_id exist -- @function eva.lang.is_exist -- @tparam strng lang_id Locale id from your localization -- @treturn bool Is translation exist function M.is_exist(lang_id) return luax.toboolean(app.lang_dict[lang_id]) end --- Return list of available languages -- @function eva.lang.get_langs -- @treturn table List of available languages function M.get_langs() return luax.table.list(app.settings.lang.lang_paths) end function M.on_eva_init() local settings = app.settings.lang local default_lang = settings.default local device_lang = string.sub(sys.get_sys_info().device_language, 1, 2) if settings.lang_paths[device_lang] then default_lang = device_lang end app[const.EVA.LANG] = proto.get(const.EVA.LANG) app[const.EVA.LANG].lang = default_lang saver.add_save_part(const.EVA.LANG, app[const.EVA.LANG]) end function M.after_eva_init() M.set_lang(app[const.EVA.LANG].lang) end return M
--------------------------------- --! @file openrtm.lua --! @brief openrtmのモジュールをロードする --------------------------------- --[[ Copyright (c) 2017 Nobuhiko Miyamoto ]] local openrtm = {} --_G["openrtm"] = openrtm --openrtm.Async = require "openrtm.Async" openrtm.BufferBase = require "openrtm.BufferBase" openrtm.BufferStatus = require "openrtm.BufferStatus" openrtm.CdrBufferBase = require "openrtm.CdrBufferBase" openrtm.CdrRingBuffer = require "openrtm.CdrRingBuffer" openrtm.ComponentActionListener = require "openrtm.ComponentActionListener" openrtm.ConfigAdmin = require "openrtm.ConfigAdmin" openrtm.ConfigurationListener = require "openrtm.ConfigurationListener" openrtm.ConnectorBase = require "openrtm.ConnectorBase" openrtm.ConnectorListener = require "openrtm.ConnectorListener" --openrtm.CORBA_IORUtil = require "openrtm.CORBA_IORUtil" openrtm.CORBA_RTCUtil = require "openrtm.CORBA_RTCUtil" openrtm.CORBA_SeqUtil = require "openrtm.CORBA_SeqUtil" openrtm.CorbaConsumer = require "openrtm.CorbaConsumer" openrtm.CorbaNaming = require "openrtm.CorbaNaming" openrtm.CorbaPort = require "openrtm.CorbaPort" --openrtm.CPUAffinity = require "openrtm.CPUAffinity" --openrtm.DataFlowComponentBase = require "openrtm.DataFlowComponentBase" openrtm.DataPortStatus = require "openrtm.DataPortStatus" openrtm.DefaultConfiguration = require "openrtm.DefaultConfiguration" --openrtm.DefaultPeriodicTask = require "openrtm.DefaultPeriodicTask" openrtm.ECFactory = require "openrtm.ECFactory" openrtm.ExecutionContextBase = require "openrtm.ExecutionContextBase" openrtm.ExecutionContextProfile = require "openrtm.ExecutionContextProfile" openrtm.ExecutionContextWorker = require "openrtm.ExecutionContextWorker" --openrtm.ExtTrigExecutionContext = require "openrtm.ExtTrigExecutionContext" openrtm.Factory = require "openrtm.Factory" openrtm.FactoryInit = require "openrtm.FactoryInit" openrtm.GlobalFactory = require "openrtm.GlobalFactory" --openrtm.Guard = require "openrtm.Guard" openrtm.InPort = require "openrtm.InPort" openrtm.InPortBase = require "openrtm.InPortBase" openrtm.InPortConnector = require "openrtm.InPortConnector" openrtm.InPortConsumer = require "openrtm.InPortConsumer" --openrtm.InPortCorbaCdrConsumer = require "openrtm.InPortCorbaCdrConsumer" --openrtm.InPortCorbaCdrProvider = require "openrtm.InPortCorbaCdrProvider" --openrtm.InPortDirectConsumer = require "openrtm.InPortDirectConsumer" --openrtm.InPortDirectProvider = require "openrtm.InPortDirectProvider" openrtm.InPortDSConsumer = require "openrtm.InPortDSConsumer" openrtm.InPortDSProvider = require "openrtm.InPortDSProvider" openrtm.InPortProvider = require "openrtm.InPortProvider" openrtm.InPortPullConnector = require "openrtm.InPortPullConnector" openrtm.InPortPushConnector = require "openrtm.InPortPushConnector" --openrtm.InPortSHMConsumer = require "openrtm.InPortSHMConsumer" --openrtm.InPortSHMProvider = require "openrtm.InPortSHMProvider" --openrtm.Listener = require "openrtm.Listener" openrtm.ListenerHolder = require "openrtm.ListenerHolder" --openrtm.LocalServiceAdmin = require "openrtm.LocalServiceAdmin" --openrtm.LocalServiceBase = require "openrtm.LocalServiceBase" openrtm.LogstreamBase = require "openrtm.LogstreamBase" openrtm.LogstreamFile = require "openrtm.LogstreamFile" openrtm.Manager = require "openrtm.Manager" openrtm.ManagerActionListener = require "openrtm.ManagerActionListener" openrtm.ManagerServant = require "openrtm.ManagerServant" openrtm.ManagerConfig = require "openrtm.ManagerConfig" openrtm.ModuleManager = require "openrtm.ModuleManager" openrtm.NamingManager = require "openrtm.NamingManager" openrtm.NamingServiceNumberingPolicy = require "openrtm.NamingServiceNumberingPolicy" openrtm.NodeNumberingPolicy = require "openrtm.NodeNumberingPolicy" openrtm.NumberingPolicy = require "openrtm.NumberingPolicy" openrtm.NumberingPolicyBase = require "openrtm.NumberingPolicyBase" openrtm.NVUtil = require "openrtm.NVUtil" openrtm.ObjectManager = require "openrtm.ObjectManager" openrtm.OpenHRPExecutionContext = require "openrtm.OpenHRPExecutionContext" openrtm.OutPort = require "openrtm.OutPort" openrtm.OutPortBase = require "openrtm.OutPortBase" openrtm.OutPortConnector = require "openrtm.OutPortConnector" openrtm.OutPortConsumer = require "openrtm.OutPortConsumer" --openrtm.OutPortCorbaCdrConsumer = require "openrtm.OutPortCorbaCdrConsumer" --openrtm.OutPortCorbaCdrProvider = require "openrtm.OutPortCorbaCdrProvider" --openrtm.OutPortDirectConsumer = require "openrtm.OutPortDirectConsumer" --openrtm.OutPortDirectProvider = require "openrtm.OutPortDirectProvider" openrtm.OutPortDSConsumer = require "openrtm.OutPortDSConsumer" openrtm.OutPortDSProvider = require "openrtm.OutPortDSProvider" openrtm.OutPortPushConnector = require "openrtm.OutPortPushConnector" openrtm.OutPortPullConnector = require "openrtm.OutPortPullConnector" --openrtm.OutPortSHMConsumer = require "openrtm.OutPortSHMConsumer" --openrtm.OutPortSHMProvider = require "openrtm.OutPortSHMProvider" --openrtm.PeriodicECSharedComposite = require "openrtm.PeriodicECSharedComposite" openrtm.PeriodicExecutionContext = require "openrtm.PeriodicExecutionContext" --openrtm.PeriodicTask = require "openrtm.PeriodicTask" --openrtm.PeriodicTaskFactory = require "openrtm.PeriodicTaskFactory" openrtm.PortAdmin = require "openrtm.PortAdmin" openrtm.PortBase = require "openrtm.PortBase" openrtm.PortCallBack = require "openrtm.PortCallBack" openrtm.PortConnectListener = require "openrtm.PortConnectListener" --openrtm.PortProfileHelper = require "openrtm.PortProfileHelper" --openrtm.Process = require "openrtm.Process" openrtm.Properties = require "openrtm.Properties" openrtm.PublisherBase = require "openrtm.PublisherBase" openrtm.PublisherFlush = require "openrtm.PublisherFlush" --openrtm.PublisherNew = require "openrtm.PublisherNew" --openrtm.PublisherPeriodic = require "openrtm.PublisherPeriodic" openrtm.RingBuffer = require "openrtm.RingBuffer" openrtm.RTCUtil = require "openrtm.RTCUtil" openrtm.RTObject = require "openrtm.RTObject" openrtm.RTObjectStateMachine = require "openrtm.RTObjectStateMachine" openrtm.SdoConfiguration = require "openrtm.SdoConfiguration" --openrtm.SdoOrganization = require "openrtm.SdoOrganization" --openrtm.SdoService = require "openrtm.SdoService" openrtm.SdoServiceAdmin = require "openrtm.SdoServiceAdmin" openrtm.SdoServiceConsumerBase = require "openrtm.SdoServiceConsumerBase" openrtm.SdoServiceProviderBase = require "openrtm.SdoServiceProviderBase" --openrtm.SharedMemory = require "openrtm.SharedMemory" --openrtm.Singleton = require "openrtm.Singleton" openrtm.StateMachine = require "openrtm.StateMachine" openrtm.StringUtil = require "openrtm.StringUtil" openrtm.SystemLogger = require "openrtm.SystemLogger" openrtm.Task = require "openrtm.Task" --openrtm.TimeMeasure = require "openrtm.TimeMeasure" openrtm.Timer = require "openrtm.Timer" --openrtm.Typename = require "openrtm.Typename" openrtm.TimeValue = require "openrtm.TimeValue" openrtm.version = require "openrtm.version" openrtm.SimulatorExecutionContext = require "openrtm.SimulatorExecutionContext" return openrtm
local sx, sy = guiGetScreenSize() local uStaff, uWaiters = {} local shownPanel = false local w,h = 262, 552 local selectedWaiter = -1 local activeMenu = 1 local totalPrice = 0 local currentTotalPrice = 500 addEvent("uber-system:showUberPanel", true) addEventHandler("uber-system:showUberPanel", root, function(staff,waiters) uStaff, uWaiters = staff,waiters shownPanel = not shownPanel if shownPanel then window = guiCreateWindow(15,sy-h-30,w,h,"",false) guiSetAlpha(window, 0) activeMenu = 1 outputChatBox("[>] #ffffffYön tuşları ile Uber Yönetim paneli içinde gezinebilirsiniz.", 0, 255, 0, true) bindKey("arrow_l", "down", MenuChangerLeft) bindKey("arrow_r", "down", MenuChangerRight) else destroyElement(window) activeMenu = 1 selectedWaiter = -1 unbindKey("arrow_l", "down", MenuChangerLeft) unbindKey("arrow_r", "down", MenuChangerRight) end end ) addEvent("uber-system:updateTable", true) addEventHandler("uber-system:updateTable", root, function(staff,waiters) uStaff, uWaiters = staff,waiters end ) addEvent("uber-system:createNavigation", true) addEventHandler("uber-system:createNavigation", root, function(x,y,z) exports["mrp_navigation"]:findBestWay(x,y,z) end ) function MenuChangerLeft() if activeMenu > 1 then activeMenu = activeMenu - 1 end end function MenuChangerRight() if activeMenu < 2 then activeMenu = activeMenu + 1 end end addEventHandler("onClientRender", root, function() if shownPanel then w,h = 262, 552 x,y = guiGetPosition(window, false) dxDrawImage(x,y,w,h,":phone/images/iphone_front.png",0,0,0,tocolor(255,255,255)) dxDrawImage(x,y,w,h,":phone/images/iphone_front_uberadmin.png",0,0,0,tocolor(255,255,255)) w = w-30 x = x + 15 y = y + 170 if activeMenu == 1 then icount = 0 for index, value in pairs(uWaiters) do icount = icount +1 if selectedWaiter == index then dxDrawRectangle(x,y+(icount*24),w,20, tocolor(70,70,70,210)) else dxDrawRectangle(x,y+(icount*24),w,20, tocolor(70,70,70,140)) end if isInBoxHover(x,y+(icount*24),w,20) and getKeyState("mouse1") then selectedWaiter = index end dxDrawText(value[1]:gsub("_", " ").." - "..getZoneName(value[2],value[3],value[4]),x+10,y+(icount*24),w,20+(y+(icount*24)), tocolor(255,255,255), 1, "default-bold", "left", "center") end --okayButton if isInBoxHover(x+5,y+h-270,w-10,25) then dxDrawRectangle(x+5,y+h-270,w-10,25,tocolor(220,220,220,140)) dxDrawText("Kişiyi Al", x+5,y+h-270,w-10+(x+5),25+(y+h-270), tocolor(0,0,0), 1, "default-bold", "center", "center") else dxDrawRectangle(x+5,y+h-270,w-10,25,tocolor(70,70,70,140)) dxDrawText("Kişiyi Al", x+5,y+h-270,w-10+(x+5),25+(y+h-270), tocolor(255,255,255), 1, "default-bold", "center", "center") end elseif activeMenu == 2 then --oturum sıfırla if isInBoxHover(x+5,y+h-270,w-10,25) then dxDrawRectangle(x+5,y+h-270,w-10,25,tocolor(220,220,220,140)) dxDrawText("Oturum Kazancını Sıfırla", x+5,y+h-270,w-10+(x+5),25+(y+h-270), tocolor(0,0,0), 1, "default-bold", "center", "center") else dxDrawRectangle(x+5,y+h-270,w-10,25,tocolor(70,70,70,140)) dxDrawText("Oturum Kazancını Sıfırla", x+5,y+h-270,w-10+(x+5),25+(y+h-270), tocolor(255,255,255), 1, "default-bold", "center", "center") end --oturum kazancı if isInBoxHover(x+5,y+h-300,w-10,25) then dxDrawRectangle(x+5,y+h-300,w-10,25,tocolor(220,220,220,140)) dxDrawText("Toplam Oturum Kazancı: $"..totalPrice, x+5,y+h-300,w-10+(x+5),25+(y+h-300), tocolor(0,0,0), 1, "default-bold", "center", "center") else dxDrawRectangle(x+5,y+h-300,w-10,25,tocolor(70,70,70,140)) dxDrawText("Toplam Oturum Kazancı: $"..totalPrice, x+5,y+h-300,w-10+(x+5),25+(y+h-300), tocolor(255,255,255), 1, "default-bold", "center", "center") end --taksimetre veh = getPedOccupiedVehicle(localPlayer) local clockState = tonumber(getElementData(veh, "Taxi->clockState") or 0) if clockState == 0 then if isInBoxHover(x+5,y+h-400,w-10,25) then dxDrawRectangle(x+5,y+h-400,w-10,25,tocolor(220,220,220,140)) dxDrawText("Taksimetre başlat ("..currentTotalPrice.."$/km)", x+5,y+h-400,w-10+(x+5),25+(y+h-400), tocolor(0,0,0), 1, "default-bold", "center", "center") else dxDrawRectangle(x+5,y+h-400,w-10,25,tocolor(70,70,70,140)) dxDrawText("Taksimetre başlat", x+5,y+h-400,w-10+(x+5),25+(y+h-400), tocolor(255,255,255), 1, "default-bold", "center", "center") end else local miles = yardToMile(tonumber(getElementData(veh, "Taxi->traveledMeters") or 0)) if isInBoxHover(x+5,y+h-400,w-10,25) then dxDrawRectangle(x+5,y+h-400,w-10,25,tocolor(220,220,220,140)) dxDrawText("Taksimetre durdur", x+5,y+h-400,w-10+(x+5),25+(y+h-400), tocolor(0,0,0), 1, "default-bold", "center", "center") else dxDrawRectangle(x+5,y+h-400,w-10,25,tocolor(70,70,70,140)) dxDrawText("Taksimetre durdur", x+5,y+h-400,w-10+(x+5),25+(y+h-400), tocolor(255,255,255), 1, "default-bold", "center", "center") end dxDrawText(math.ceil(miles*currentTotalPrice).."$", x+5,y+h-370,w-10+(x+5),25+(y+h-370), tocolor(255,255,255), 1, "default-bold", "center", "center") end --[[ --taksimetre $ ayarlama: if isInBoxHover(x+5,y+h-270,w-10,25) then dxDrawRectangle(x+5,y+h-270,w-10,25,tocolor(220,220,220,140)) dxDrawText("Ücret ayarla:", x+15,y+h-270,w-10+(x+5),25+(y+h-270), tocolor(0,0,0), 1, "default-bold", "left", "center") else dxDrawRectangle(x+5,y+h-270,w-10,25,tocolor(70,70,70,140)) dxDrawText("Ücret ayarla:", x+15,y+h-270,w-10+(x+5),25+(y+h-270), tocolor(255,255,255), 1, "default-bold", "left", "center") end]]-- end end end ) addEventHandler("onClientClick", root, function(b,s,_,_,_,_,_,element) if shownPanel then if ((b == "left") and (s == "down")) then if activeMenu == 1 then if isInBoxHover(x+5,y+h-270,w-10,25) then--ok if selectedWaiter ~= -1 then vehicle = getPedOccupiedVehicle(localPlayer) if vehicle then x,y,z = getElementPosition(selectedWaiter) triggerServerEvent("uber-system:receiveWaiterPersonel", localPlayer, localPlayer, selectedWaiter, x, y, z) else outputChatBox("Navigasyonu alabilmek için araca binmen gerekiyor!", 255, 0, 0) end else outputChatBox("Bir seçim yapmanız gerekiyor!", 255, 0, 0) end end elseif activeMenu == 2 then if isInBoxHover(x+5,y+h-270,w-10,25) then totalPrice = 0 outputChatBox("Oturum kazancı sıfırlandı!", 0, 255, 0) elseif isInBoxHover(x+5,y+h-400,w-10,25) then veh = getPedOccupiedVehicle(localPlayer) local clockState = tonumber(getElementData(veh, "Taxi->clockState") or 0) if clockState == 0 then setElementData(veh, "Taxi->traveledMeters", 0) setElementData(veh, "Taxi->clockState", 1) taxiCounter(true, veh) taxi_veh_startX, taxi_veh_startY, taxi_veh_startZ = getElementPosition(veh) else local miles = yardToMile(tonumber(getElementData(veh, "Taxi->traveledMeters") or 0)) totalPrice = totalPrice + math.ceil(miles*currentTotalPrice) print(totalPrice) setElementData(veh, "Taxi->clockState", 0) taxiCounter(false, veh) end end end end end end ) local taxiTimer local oldX, oldY, oldZ = -1, -1, -1 function taxiCounter(state, veh) if state then if not isTimer(taxiTimer) then taxiTimer = setTimer(function() if getElementSpeed(veh, "mph") > 0 then local current_veh_x, current_veh_y, current_veh_z = getElementPosition(veh) if oldX == -1 then oldX, oldY, oldZ = current_veh_x, current_veh_y, current_veh_z end local distance = getDistanceBetweenPoints3D(oldX, oldY, oldZ, current_veh_x, current_veh_y, current_veh_z) setElementData(veh, "Taxi->traveledMeters", math.ceil(getElementData(veh, "Taxi->traveledMeters") + math.abs(distance))) oldX, oldY, oldZ = current_veh_x, current_veh_y, current_veh_z end end, 1000,0) end else if isTimer(taxiTimer) then killTimer(taxiTimer) end end end function getElementSpeed(element, unit) if (unit == nil) then unit = 0 end if (isElement(element)) then local x, y, z = getElementVelocity(element) if (unit == "mph" or unit == 1 or unit == '1') then return math.floor((x^2 + y^2 + z^2) ^ 0.5 * 100) else return math.floor((x^2 + y^2 + z^2) ^ 0.5 * 100 * 1.609344) end else return false end end function conditionToShow() local vehicle = getPedOccupiedVehicle(localPlayer) if isPedInVehicle(localPlayer) and vehicle then return true end return false end function yardToMile(yard) if yard then yard = (yard * 0.000568181818) -- 1 yard = 0.000568181818 miles end return yard end function isInBoxHover(dX, dY, dSZ, dM) if isCursorShowing() then local cX ,cY = getCursorPosition() cX,cY = cX*sx , cY*sy if(cX >= dX and cX <= dX+dSZ and cY >= dY and cY <= dY+dM) then return true, cX, cY else return false end end end -- uber-system // add new personal addEventHandler("onClientElementDataChange", root, function(dataName, oldValue, newValue) if (source == localPlayer) then if (dataName == "job") then local value = getElementData(source, dataName) if tonumber(value) == 7 then triggerServerEvent("uber-system:addNewPerson", source, source) elseif tonumber(value) ~= 7 and oldValue == 7 then triggerServerEvent("uber-system:removePerson", source, source) end end end end )
addEventHandler("onClientResourceStart", resourceRoot, function() ttWin = guiCreateWindow(0.43, 0.28, 0.19, 0.53, "Trend Topics", true) guiSetVisible(ttWin, false) ttGrid = guiCreateGridList(0.04, 0.05, 0.92, 0.86, true, ttWin) guiGridListAddColumn(ttGrid, "Topic", 0.45) guiGridListAddColumn(ttGrid, "Sayı", 0.4) ttClose = guiCreateButton(0.36, 0.93, 0.29, 0.05, "Kapat", true, ttWin) guiSetProperty(ttClose, "NormalTextColour", "FFAAAAAA") addEventHandler ("onClientGUIClick", ttClose, function () guiSetVisible (ttWin, false) showCursor (false) end, false) end ) function toggleTtWin () guiSetVisible (ttWin, not guiGetVisible (ttWin)) showCursor(guiGetVisible (ttWin)) end addEvent ("hashtags.getHashtags", true) addEventHandler ("hashtags.getHashtags", root, function (tbl, toggle) if tbl then if toggle then toggleTtWin() end loadGrid(tbl); end end ) function loadGrid (hashtags) guiGridListClear(ttGrid) for i, v in ipairs (hashtags) do local row = guiGridListAddRow (ttGrid) guiGridListSetItemText (ttGrid, row, 1, v[1], false, false) guiGridListSetItemText (ttGrid, row, 2, v[2], false, false) end end
local playsession = { {"Gerkiz", {279947}}, {"jordyys_", {660}}, {"TiTaN", {155486}}, {"Ardordo", {7540}}, {"JailsonBR", {72834}}, {"A-l-a-n", {21485}}, {"Nikkichu", {46909}} } return playsession
local M = {} M._user_options = {} local did_define_codeactions = false M.setup = function(opts) function M._user_options.picker(...) local pickers = require('sqls.pickers') return (pickers[opts.picker] or pickers.default)(...) end vim.cmd [[command! -buffer -range SqlsExecuteQuery lua require'sqls.commands'.exec('executeQuery', '<mods>', <range> ~= 0, nil, <line1>, <line2>)]] vim.cmd [[command! -buffer -range SqlsExecuteQueryVertical lua require'sqls.commands'.exec('executeQuery', '<mods>', <range> ~= 0, '-show-vertical', <line1>, <line2>)]] vim.cmd [[command! -buffer SqlsShowDatabases lua require'sqls.commands'.exec('showDatabases', '<mods>')]] vim.cmd [[command! -buffer SqlsShowSchemas lua require'sqls.commands'.exec('showSchemas', '<mods>')]] vim.cmd [[command! -buffer SqlsShowConnections lua require'sqls.commands'.exec('showConnections', '<mods>')]] -- Not yet supported by the language server: -- vim.cmd [[command! -buffer SqlsShowTables lua require'sqls.commands'.exec('showTables', '<mods>')]] -- vim.cmd [[command! -buffer SqlsDescribeTable lua require'sqls.commands'.exec('describeTable', '<mods>')]] vim.cmd [[command! -buffer -nargs=? SqlsSwitchDatabase lua require'sqls.commands'.switch_database(<f-args>)]] vim.cmd [[command! -buffer -nargs=? SqlsSwitchConnection lua require'sqls.commands'.switch_connection(<f-args>)]] vim.api.nvim_buf_set_keymap(0, 'n', '<Plug>(sqls-execute-query)', "<Cmd>set opfunc=v:lua.require'sqls.commands'.query<CR>g@", {silent = true}) vim.api.nvim_buf_set_keymap(0, 'x', '<Plug>(sqls-execute-query)', "<Cmd>set opfunc=v:lua.require'sqls.commands'.query<CR>g@", {silent = true}) vim.api.nvim_buf_set_keymap(0, 'n', '<Plug>(sqls-execute-query-vertical)', "<Cmd>set opfunc=v:lua.require'sqls.commands'.query_vertical<CR>g@", {silent = true}) vim.api.nvim_buf_set_keymap(0, 'x', '<Plug>(sqls-execute-query-vertical)', "<Cmd>set opfunc=v:lua.require'sqls.commands'.query_vertical<CR>g@", {silent = true}) if vim.lsp.commands and not did_define_codeactions then vim.lsp.commands['executeQuery'] = function(code_action, command) require('sqls.commands').exec('executeQuery') end vim.lsp.commands['showDatabases'] = function(code_action, command) require('sqls.commands').exec('showDatabases') end vim.lsp.commands['showSchemas'] = function(code_action, command) require('sqls.commands').exec('showSchemas') end vim.lsp.commands['showConnections'] = function(code_action, command) require('sqls.commands').exec('showConnections') end -- vim.lsp.commands['showTables'] = function(code_action, command) -- require('sqls.commands').exec('showTables') -- end -- vim.lsp.commands['describeTable'] = function(code_action, command) -- require('sqls.commands').exec('describeTable') -- end vim.lsp.commands['switchConnections'] = function(code_action, command) require('sqls.commands').switch_connection() end vim.lsp.commands['switchDatabase'] = function(code_action, command) require('sqls.commands').switch_database() end did_define_codeactions = true end end return M
local reporter = require('apicast.policy.3scale_batcher.reporter') local ReportsBatcher = require('apicast.policy.3scale_batcher.reports_batcher') local lrucache = require('resty.lrucache') local resty_lock = require 'resty.lock' local pairs = pairs local insert = table.insert -- ReportsBatcher uses a shdict. For the test we can use a lrucache instead -- but we need to define 2 missing methods (safe_add and get_keys) local function build_fake_shdict() local fake_shdict = lrucache.new(100) fake_shdict.safe_add = function(self, k, v) local current = self:get(k) or 0 self:set(k, current + v) end fake_shdict.get_keys = function(self) local res = {} for k, _ in pairs(self.hasht) do insert(res, k) end return res end return fake_shdict end describe('reporter', function() local test_service_id = 's1' local test_backend_client local spy_report_backend_client before_each(function() test_backend_client = { report = function() return { ok = false } end } spy_report_backend_client = spy.on(test_backend_client, 'report') -- Mock the lock so it can always be acquired and returned without waiting. stub(resty_lock, 'new').returns( { lock = function() return 0 end, unlock = function() return 1 end } ) end) local reports_batcher = ReportsBatcher.new(build_fake_shdict()) it('returns reports to the batcher when sending reports to backend fails', function() local test_reports = { { service_id = test_service_id, user_key = 'uk', metric = 'm1', value = 1 } } reporter.report(test_reports, test_service_id, test_backend_client, reports_batcher) assert.same(test_reports, reports_batcher:get_all(test_service_id)) end) it('does not report call report on the backend client when there are no reports', function() local no_reports = {} reporter.report(no_reports, test_service_id, test_backend_client, reports_batcher) assert.spy(spy_report_backend_client).was_not_called() end) end)
AddCSLuaFile() include("karma_tracker/utils/logging.lua") include("karma_tracker/utils/messaging.lua")
local Logger = require("__DedLib__/modules/logger").create() local Player = require("__DedLib__/modules/player") require("scripts.actions") require("scripts.chest_groups") local Config = require("scripts/config") require("scripts.migrations") require("scripts.storage") require("scripts.ui") script.on_init(Storage:on_init_wrapped()) script.on_load(Storage:on_load_wrapped()) script.on_configuration_changed(Migrations.handle) -- ~~ Events ~~ -- function on_pre_entity_placed(event) local player = game.players[event.player_index] local position = event.position -- Shift building is covered by upgrading events if not event.shift_build then local entities = player.surface.find_entities_filtered{position=position, force=force} if #entities > 0 then Logger:debug("Entity pre build on top of other entities") for _, entity in ipairs(entities) do local name = entity.name local fullGroup = ChestGroups.getFullGroupWithOriginals(name) Logger:debug("Checking if found entity %s is a generic related entity", entity) if fullGroup then local replacementName = fullGroup[name] local lastEvent = Storage.PlayerFastReplaceEvents.get(player, position) Logger:info("Entity %s is generic related, replacement for it is %s. Last event for player is %s", entity, replacementName, lastEvent) -- Exit fast replace if the old chest is a replacement, this allows for the generic to actually get built and the UI drawn -- Drag building triggers this constantly, so needed to introduce a slight lag to it. Otherwise, the normal chest gets replaced then the next tick the replacement turns into a generic if replacementName == name and game.tick > lastEvent + Config.PLAYER_FAST_REPLACE_LAG then Logger:debug("Too recent replacement fast replace, exiting...") return end Logger:info("Saving %s entity on pre build for %s", replacementName, player) Storage.PlayerFastReplace.add(player, replacementName, entity) return end end end end end script.on_event(defines.events.on_pre_build, on_pre_entity_placed) function on_entity_placed(event) local entity = event.created_entity local entityName = entity.name local player = game.players[event.player_index] -- If it is a generic chest, draw GUI and add it and the player match to the table local replacements = ChestGroups.getReplacementsFromGeneric(entityName) if replacements then local fastReplaceChestData = Storage.PlayerFastReplace.get(player) if fastReplaceChestData and fastReplaceChestData.replacementChestName ~= entityName then Logger:info("Generic chest placed %s as fast replace to %s", entity, fastReplaceChestData) Storage.PlayerFastReplaceEvents.add(player, entity.position) Actions.switchChestFromChestData(entity, fastReplaceChestData, player) else Logger:info("Generic chest placed %s", entity) UI.Selection.draw(player, replacements, entity) end Storage.PlayerFastReplace.remove(player) return end -- If the player just placed a replacement chest, and their cursor is empty, try to fill it with generics from their inventory local generic = ChestGroups.getGenericFromReplacement(entityName) if generic and Player.is_cursor_empty(player) then Logger:debug("%s placed last replacement %s, attempting to fill cursor from inventory...", player, entityName) local selection = Storage.PlayerSelection.get(player) if selection then Logger:debug("Found player selection %s", selection) local chestStack = player.get_main_inventory().find_item_stack(generic) if chestStack then Logger:info("Refilling cursor for %s with %s", player, selection) chestStack.set_stack({name = selection, count = chestStack.count}) player.cursor_stack.swap_stack(chestStack) end end return end -- Check for a ghost (from blueprints) if entityName == "entity-ghost" then local ghostName = entity.ghost_name local fullGroupList = ChestGroups.getFullGroupWithOriginalsList(ghostName) if fullGroupList then Logger:debug("Ghost %s found for %s", entity, ghostName) local force = entity.force local position = entity.position local foundReplacements = entity.surface.find_entities_filtered{position=position, name=fullGroupList, force=force} -- Any original/generic/replacement chest under the ghost should be deconstructed, to handle undo scenarios -- TODO - Factorio 1.2 - Should have undo support to do this better for _, replacement in ipairs(foundReplacements) do Logger:debug("Manually marking %s for deconstruction", replacement) replacement.order_deconstruction(force, player) end return end end end script.on_event(defines.events.on_built_entity, on_entity_placed) -- TODO - filters? generics, replacements, ghosts function on_entity_destroyed(event) local entity = event.entity -- If a generic chest is destroyed, check if a player was trying to change it local replacements = ChestGroups.getReplacementsFromGeneric(entity.name) if replacements then Logger:debug("Generic chest %s destroyed", entity) local player = Storage.PlayerUiOpen.removeChest(entity) if player then UI.Selection.destroy(player) end end end local generic_chest_filters = {} for generic, _ in pairs(ChestGroups.getGenericToReplacementMapping()) do table.insert(generic_chest_filters, {filter="name", name=generic}) end Logger:trace_block("Generic Chest Filters: %s", generic_chest_filters) script.on_event(defines.events.on_pre_player_mined_item, on_entity_destroyed, generic_chest_filters) script.on_event(defines.events.on_robot_pre_mined, on_entity_destroyed, generic_chest_filters) script.on_event(defines.events.script_raised_destroy, on_entity_destroyed, generic_chest_filters) script.on_event(defines.events.on_entity_died, on_entity_destroyed, generic_chest_filters) function on_gui_click(event) -- TODO - cleanup - change UI to use tags? local elementName = event.element.name -- Find the UI prefix (for this mod) local modSubString = string.sub(elementName, 1, #Config.MOD_PREFIX) if modSubString == Config.MOD_PREFIX then Logger:info(elementName .. " clicked") local player = game.players[event.player_index] if elementName == UI.Selection.CLOSE_BUTTON then UI.Selection.destroy(player) Storage.PlayerUiOpen.remove(player) else local buttonSubString = string.sub(elementName, #Config.MOD_PREFIX + 1, #UI.Selection.BUTTON_PREFIX) if buttonSubString == UI.Selection.BUTTON_PREFIX_DIFF then local replacementName = string.sub(elementName, #UI.Selection.BUTTON_PREFIX + 1, #elementName) local playerChests = Storage.PlayerUiOpen.get(player) local failedCount = 0 for _, playerChest in ipairs(playerChests) do if not Actions.switchChest(playerChest, replacementName, player) then failedCount = failedCount + 1 end end if failedCount > 0 then player.print({"Generic_Logistic_select_error_chest_not_valid", tostring(failedCount)}) end UI.Selection.destroy(player) Storage.PlayerUiOpen.remove(player) end end end end script.on_event(defines.events.on_gui_click, on_gui_click) function on_player_cursor_stack_changed(event) local player = game.players[event.player_index] if Player.is_cursor_empty(player) then local selection = Storage.PlayerSelection.get(player) if selection then local chestStack = player.get_main_inventory().find_item_stack(selection) if chestStack then Logger:debug("Player returned replacement chest to inventory: %s", chestStack) local chestStackName = chestStack.name local generic = ChestGroups.getGenericFromReplacement(chestStackName) if generic then Logger:info("Resetting %s to generic %s for %s", chestStackName, generic, player) chestStack.set_stack({name = generic, count = chestStack.count}) Storage.PlayerSelection.remove(player) end end end end end script.on_event(defines.events.on_player_cursor_stack_changed, on_player_cursor_stack_changed) function on_player_copied(event) local player = game.players[event.player_index] local entity = player.selected Logger:debug("Custom player copied event for %s copying %s", player, entity) if entity then local entityName = entity.name local nameMapping = ChestGroups.getFullGroupWithOriginals(entityName) if nameMapping then local sourceName = nameMapping[entityName] Logger:info("Copying chest %s as %s for %s", entity, sourceName, player) Storage.PlayerCopyData.add(player, sourceName) else Storage.PlayerCopyData.remove(player) end end end script.on_event("Generic_Logistic_copy_chest", on_player_copied) function on_custom_build(event) local player = game.players[event.player_index] local entity = player.selected Logger:debug("Custom player build event for %s old entity <%s> at same position", player, entity) -- If a player attempts to build a generic on top of a same generic, the game does not fire an event (because nothing happens) -- So, this will open the UI for them if entity then local entityName = entity.name local replacements = ChestGroups.getReplacementsFromGeneric(entityName) local cursor = player.cursor_stack if replacements and cursor and cursor.valid_for_read and cursor.name == entityName then UI.Selection.draw(player, replacements, entity) end end end script.on_event("Generic_Logistic_build", on_custom_build) function on_player_pasted(event) local player = game.players[event.player_index] local target = event.destination Logger:debug("Custom player pasted event for %s pasting %s", player, entity) if target then local chestGroup = ChestGroups.getFullGroup(target.name) if chestGroup then local targetName = target.name Logger:info("Target %s of paste by %s is a generic chest", targetName, player) local sourceName = Storage.PlayerCopyData.get(player) if chestGroup[sourceName] then if targetName == sourceName then Logger:warn("Source chest is the same as target chest, skipping paste...") return end Logger:info("Pasting chest %s onto chest %s", sourceName, target) local newChest = Actions.switchChest(target, sourceName, player) local replacements = ChestGroups.getReplacementsFromGeneric(sourceName) if replacements and newChest then UI.Selection.draw(player, replacements, newChest) end end end end end script.on_event(defines.events.on_pre_entity_settings_pasted, on_player_pasted) function on_player_pipette(event) local player = game.players[event.player_index] local replacements = ChestGroups.getReplacementsFromGeneric(event.item.name) if replacements then Logger:debug("%s pipette a generic related chest", player) local selectedEntity = player.selected if selectedEntity then local replacementName = selectedEntity.name if replacementName == "entity-ghost" then replacementName = selectedEntity.ghost_name end local cursorStack = player.cursor_stack if cursorStack and cursorStack.valid_for_read then -- Generic in the player's cursor from pipette Logger:info("Replacing %s for player %s with %s", cursorStack, player, replacementName) cursorStack.set_stack({name = replacementName, count = cursorStack.count}) else -- Generic ghost in the player's cursor Logger:info("Replacing cursor ghost for player %s with %s", player, replacementName) player.cursor_ghost = replacementName end Storage.PlayerSelection.add(player, replacementName) end end end script.on_event(defines.events.on_player_pipette, on_player_pipette) function build_on_select_scroll(scrollDistance) local direction = "up" --TODO - DedLib - Use Util.ternary() if scrollDistance < 0 then direction = "down" end return function(event) local player = game.players[event.player_index] local cursorStack = player.cursor_stack Logger:debug("Player %s scrolling %s with %s in cursor", player, direction, cursorStack) local cursorChestName, count = nil, nil local isGhost = false if cursorStack and cursorStack.valid and cursorStack.valid_for_read then cursorChestName = cursorStack.name count = cursorStack.count else local ghost = player.cursor_ghost if ghost then cursorChestName = ghost.name isGhost = true end end if cursorChestName then local chestGroup = ChestGroups.getFullGroupList(cursorChestName) if chestGroup then Logger:debug("Cursor is a generic mod entity") local groupCount = #chestGroup local position = 0 for i = 1, groupCount do if chestGroup[i] == cursorChestName then position = i break end end if position > 0 then local newPosition = position + scrollDistance -- Loop around the group if newPosition < 1 then newPosition = groupCount elseif newPosition > groupCount then newPosition = 1 end local newChestName = chestGroup[newPosition] if isGhost then Logger:info("Scrolling ghost %s chest from %s to %s for %s", direction, cursorChestName, newChestName, player) player.cursor_ghost = newChestName else Logger:info("Scrolling chest %s from %s to %s for %s", direction, cursorChestName, newChestName, player) cursorStack.set_stack({name = newChestName, count = count}) Storage.PlayerSelection.add(player, newChestName) end else Logger:error("Did not find chest %s in chestGroup %s", cursorChestName, chestGroup) end end end end end script.on_event("Generic_Logistic_select_scroll_up", build_on_select_scroll(1)) script.on_event("Generic_Logistic_select_scroll_down", build_on_select_scroll(-1)) script.on_nth_tick(Config.DATA_PURGE_PERIOD * 60 * 60, Storage.purge)
local Object = require('core/object') local Game = {} Object:instantiate(Game) function Game:new() self:init() end function Game:init() self.config = {} self.config.playerspeed = 200 self.config.catspeed = 250 self.config.ladderspeed = 200 self.config.spawntime = 6000 self.config.spawnrate = 50 self.main = love.audio.newSource("assets/audio/memoires.mp3", "static") self.main:setVolume(0.8) self.main:setLooping(true) self.main:play() self.drop = love.audio.newSource("assets/audio/ball.wav", "static") self.drop:setVolume(1) self.drop:setLooping(false) self.background = love.graphics.newImage("assets/img/background.png") self.sidehouse = love.graphics.newImage("assets/img/side-house.png") self.smallball = love.graphics.newImage("assets/img/small-ball.png") self.jumper = love.graphics.newImage("assets/img/jumper.png") self.gui = {} self.font = love.graphics.newFont("assets/fonts/9k.ttf", 16) self.gui.text = Object:create('core/ui/font', self.font, 16, 1, 16, 16) self.score = 0 self.pull = 0 self.timer = Object:create('core/animation', 1000, true) self.chrono = 60*2 self.balls = {} self.stage = {} self.stage.title = Object:create('stage/title', self) self.stage.house = Object:create('stage/house', self) self.stage.credit = Object:create('stage/credit', self) self.step = { TITLE = 1, HOUSE = 2, CREDIT = 3 } self.current = self.step.TITLE self.gameover = false end function Game:update(dt) if not self.gameover then if self.current == self.step.TITLE then self.stage.title:update(dt) elseif self.current == self.step.HOUSE then self:runChrono(dt) self.stage.house:update(dt) for i=1,#self.balls do self.balls[i]:update(dt) if self.balls[i]:isRemoved() then table.remove(self.balls, i) break end end elseif self.current == self.step.CREDIT then self.stage.credit:update(dt) end end end function Game:draw() if not self.gameover then if self.current == self.step.TITLE then self.stage.title:draw() elseif self.current == self.step.HOUSE then self.stage.house:draw() for i=1,#self.balls do self.balls[i]:draw() end -- user interface love.graphics.push("all") love.graphics.setColor(1, 1, 1, 0.6) love.graphics.rectangle("fill", 0, 0, 600, 60) love.graphics.pop("all") love.graphics.draw(self.smallball, 32, 8) self.gui.text:draw("PELOTE : " .. self.score, 70, 2, 1) love.graphics.draw(self.jumper, 20, 32) self.gui.text:draw("PULL : " .. self.pull, 70, 29, 1) self.gui.text:draw("Temps restant : " .. self.chrono, 220, 18, 1) elseif self.current == self.step.CREDIT then self.stage.credit:draw() end else love.graphics.draw(self.background, 0, 0) love.graphics.draw(self.sidehouse, 0, 0) love.graphics.push("all") love.graphics.setColor(1, 1, 1, 0.95) love.graphics.rectangle("fill", 0, 300 - 60, 600, 120) love.graphics.pop("all") self.gui.text:draw("Fin de la partie, vous avez remporté " .. (self.score*50 + self.pull*400) .. " points !", 85, 270, 1) self.gui.text:draw("Appuyez sur ENTREE pour recommencer", 120, 300, 1) end end function Game:keypressed(key, scancode, isrepeat) if not self.gameover then if self.current == self.step.TITLE then self.stage.title:keypressed(key, scancode, isrepeat) elseif self.current == self.step.HOUSE then self.stage.house:keypressed(key, scancode, isrepeat) elseif self.current == self.step.CREDIT then self.stage.credit:keypressed(key, scancode, isrepeat) end else if key == "return" or key == "kpenter" then self.main:stop() self:init() end end end function Game:keyreleased(key) if not self.gameover then if self.current == self.step.TITLE then self.stage.title:keyreleased(key) elseif self.current == self.step.HOUSE then self.stage.house:keyreleased(key) elseif self.current == self.step.CREDIT then self.stage.credit:keyreleased(key) end end end function Game:runChrono(dt) if not self.gameover then local progress = self.timer:update(dt) if progress <= 0 then self.chrono = self.chrono - 1 if self.chrono <= 0 then self.gameover = true end end end end function Game:setStep(value) self.current = value end function Game:createBall(x, y) self.drop:play() table.insert(self.balls, Object:create('entity/ball', self, x, y)); end function Game:getBalls() return self.balls end function Game:getScore() return self.score end function Game:addScore(value) self.score = self.score + value end function Game:getPull() return self.pull end function Game:addPull(value) self.pull = self.pull + value end function Game:getConfig() return self.config end return Game
local TableUtil = require("sebaestschjin-tts.TableUtil") local XmlUiFactory = require("sebaestschjin-tts.xmlui.XmlUiFactory") local XmlUiElement = require("sebaestschjin-tts.xmlui.XmlUiElement") ---@class seb_XmlUi_Button : seb_XmlUi_Element ---@class seb_XmlUi_Button_Static ---@overload fun(element: tts__UIButtonElement): seb_XmlUi_Button local XmlUiButton = {} local Attributes = { colors = XmlUiFactory.AttributeType.colorBlock, textColor = XmlUiFactory.AttributeType.color, } ---@shape seb_XmlUi_ButtonAttributes : seb_XmlUi_Attributes ---@field text nil | string ---@field value nil | string ---@field textColor nil | seb_XmlUi_Color ---@field colors nil | seb_XmlUi_ColorBlock ---@field [any] nil @All other fields are invalid setmetatable(XmlUiButton, TableUtil.merge(getmetatable(XmlUiElement), { ---@param element tts__UIButtonElement __call = function(_, element) local self = --[[---@type seb_XmlUi_Button]] XmlUiElement(element) return self end })) XmlUiFactory.register("Button", XmlUiButton, Attributes) return XmlUiButton
---@class GameTooltipText : Font ---@class GameTooltipTextSmall : Font
#!/usr/bin/env lua -- design -- widget -- { -- -- required -- ['.'] = gui.Window; w = 10; h = 10; -- minw = 0; minh = 0; -- label = ''; -- font/size/color -- -- -- optional -- box = 'up'; -- decoration -- bg = color or image (tile) -- align = gui.North, gui.East, gui.West, gui.South -- gui.Grid -- + enda, mid, endb (cw) -- scale = 0; -- false/no, 0/scale, 1/center; 2/scroll-bar -- shortcut = ''; -- activate -- callback = { func, pdata, ... -- [''] = { func, pdata, ... } -- event : true for default act -- shift/control/alt -- mouse-left/mouse-right/mouse-middle -- }; -- sub = {}; -- sub/extended class -- -- {...}; -- sub-widget -- {...}; -- sub-widget -- } local class = require 'pool' local strfind, strsub, strmatch = string.find, string.sub, string.match local tpack, tunpack, tinsert = table.pack, table.unpack, table.insert local fl = require 'moonfltk' -- local (network:html) local common = { -- common/basic widget {{{ -- widget (sub) moonFLTK -- ├─ box (sub) -- ├─ button (sub) -- │   ├─ light_button -- │   │   ├─ check_button -- │   │   ├─ radio_light_button -- │   │   └─ round_button -- │   │       └─ radio_round_button -- │   ├─ radio_button -- │   ├─ repeat_button -- │   ├─ return_button -- │   └─ toggle_button -- ├─ chart -- ├─ clock_output -- │   └─ clock -- │       └─ round_clock -- ├─ group (sub) -- │   ├─ browser_ -- │   │   ├─ browser (sub) -- │   │   │   ├─ file_browser -- │   │   │   ├─ hold_browser -- │   │   │   ├─ multi_browser -- │   │   │   └─ select_browser -- │   │   └─ check_browser -- │   ├─ color_chooser -- │   ├─ help_view -- │   ├─ input_choice -- │   ├─ pack -- │   ├─ scroll -- │   ├─ spinner -- │   ├─ table (sub) -- │   │   └─ table_row (sub) -- │   ├─ tabs (sub) -- │   ├─ text_display -- │   │   └─ text_editor -- │   ├─ tile -- │   ├─ tree -- │   ├─ window (sub) -- │   │   ├─ double_window (sub) -- │   │   │   └─ overlay_window (sub) -- │   │   ├─ gl_window (sub) -- │   │   └─ single_window (sub) -- │   │       └─ menu_window (sub) -- │   └─ wizard -- ├─ input_ -- │   └─ input -- │       ├─ file_input -- │       ├─ float_input -- │       ├─ int_input -- │       ├─ multiline_input -- │       ├─ output -- │       │   └─ multiline_output -- │       └─ secret_input -- ├─ menu_ -- │   ├─ choice -- │   ├─ menu_bar -- │   └─ menu_button -- ├─ progress -- └─ valuator --     ├─ adjuster --     ├─ counter --     │   └─ simple_counter --     ├─ dial --     │   ├─ fill_dial --     │   └─ line_dial --     ├─ roller (sub) --     ├─ slider (sub) --     │   ├─ fill_slider --     │   ├─ hor_fill_slider --     │   ├─ hor_nice_slider --     │   ├─ hor_slider --     │   ├─ nice_slider --     │   ├─ scrollbar --     │   └─ value_slider --     │       └─ hor_value_slider --     ├─ value_input --     └─ value_output } -- }}} local gui = { -- {{{ sub = ' widget box button group browser table_row tabs '.. ' window double_window overlay_window gl_window '.. ' single_window menu_window roller slider '; BOLD = fl.BOLD; ITALIC = fl.ITALIC; } -- }}} gui.font = { -- {{{ -- 'FL_HELVETICA_BOLD_ITALIC'; -- gui.BOLD; -- gui.ITALIC; } -- }}} gui.color = { -- alias {{{ } -- }}} gui.widget = { -- alias {{{ } -- }}} gui.new = class { -- {{{ ['.'] = 'widget'; -- basic widget ['*'] = false; -- proxy -- align = false; -- when = false; -- shortcut = false; -- derived class method fltk -- position = function (o, x, y) o['*']:position(x, y) end; -- size = function (o, w, h) o['*']:size(w, h) end; -- resize = function (o, x, y, w, h) o['*']:resize(x, y, w, h) end; add = function (o, ...) end; insert = function (o, ...) end; redraw = function (o) o['*']:redraw() end; -- sub_draw = function (o, f) o['*']:override_draw(f) end; sub_handle = function (o, f) o['*']:override_handle(f) end; sub_hide = function (o, f) o['*']:override_hide(f) end; sub_resize = function (o, f) o['*']:override_resize(f) end; show = function (o, ...) o['*']:show(...) end; callback = function (o, t) -- setting callback/events {{{ local arg = {} -- replacing w/ proxy for i = 1, #t do arg[i] = type(t[i]) == 'table' and t[i]['*'] or t[i] end if type(arg[1]) == 'function' then o['*']:callback(tunpack(arg)) end end; -- }}} do_callback = function (o, ...) -- {{{ local arg = {} -- replacing w/ proxy for _, v in ipairs(tpack(...)) do tinsert(arg, type(v) == 'table' and v['*'] or v) end o['*']:do_callback(tunpack(arg)) end; -- }}} add = function (o, s) o['*']:add(s['*']) end; ['<'] = function (o, wgt) -- {{{ if type(wgt) ~= 'table' then error('Widget spec: '..tostring(wgt), 2) end local basic = (gui.widget[wgt['.']] or wgt['.']) -- sub/derived/extend class if wgt.sub and strfind(gui.sub, ' '..basic..' ') then basic = basic..'_sub' end local proxy = fl[basic](wgt.x or 0, wgt.y or 0, wgt.w or 100, wgt.h or 100, wgt.label or basic) o['.'], o['*'] = basic, proxy if wgt.labelfont then proxy:labelfont(wgt.labelfont) end if wgt.labelsize then proxy:labelsize(wgt.labelsize) end if wgt.labeltype then proxy:labeltype(wgt.labeltype) end if wgt.labelcolor then proxy:labelcolor(fl[gui.color[wgt.labelcolor] or wgt.labelcolor]) end -- if wgt.bg then proxy:color(fl[gui.color[wgt.bg] or wgt.bg]) end -- string:color, obj:image if wgt.box then proxy:box(wgt.box..' box') end -- if o.align then proxy.align(o.align) end -- sub if type(wgt.sub) == 'table' then if wgt.sub.draw then o:sub_draw(wgt.sub.draw) end if wgt.sub.handle then o:sub_handle(wgt.sub.handle) end if wgt.sub.hide then o:sub_hide(wgt.sub.hide) end if wgt.sub.resize then o:sub_resize(wgt.sub.resize) end end -- children widgets for i, g in ipairs(wgt) do o[i] = class:new(o, g) end -- if o.when then proxy.when(o.when) end -- if o.shortcut then proxy.shortcut(o.shortcut) end if type(wgt.act) == 'table' then o:callback(wgt.callback) end if #wgt > 0 then proxy:done() end -- if wgt.scale then proxy:resizable(proxy) end end; -- }}} { -- operator {{{ __add = function (o1, o2) -- dock o2 to o1 tinsert(o1.node, o2.node) return o1 end; __tostring = function (o) return '('..o['.']..':'..o.label..')' end; } -- }}} } -- }}} --[[ local wb = gui.new -- workbench { ['.'] = 'double_window'; w = 300; h = 500; label = arg[0]; { ['.'] = 'widget'; x = 10; y = 10; w = 280; h = 280; sub = true; } {} } name = { "X", "Y", "R", "start", "end", "rotate" } args = { 140, 140, 50, 0, 360, 0 } -- initial value wb[1]:sub_draw(function (wid) -- proxy local x, y, w, h = wid:xywh() fl.push_clip(x, y, w, h) -- double buffer? TODO fl.color(fl.DARK3) fl.rectf(x, y, w, h) fl.push_matrix() if args[6] ~= 0 then fl.translate(x+w/2, y+h/2) fl.rotate(args[6]) fl.translate(-(x+w/2), -(y+h/2)) end fl.color(fl.WHITE) fl.translate(x, y) fl.begin_complex_polygon() fl.arc(args[1], args[2], args[3], args[4], args[5]) fl.gap() fl.arc(140, 140, 20, 0, -360) fl.end_complex_polygon() fl.color(fl.RED) fl.begin_line() fl.arc(args[1], args[2], args[3], args[4], args[5]) fl.end_line() fl.pop_matrix() fl.pop_clip() end) y = 300 function slider_cb(slider, n) args[n] = slider:value() wb[1]:redraw() end { ['.'] = 'hor_value_slider'; w = 50, y = y, w = 240; h = 25, label = 'X'; v = { 0, 300}; } { ['.'] = 'hor_value_slider'; w = 50, y = y + 25, w = 240; h = 25, label = 'Y'; v = { 0, 300}; } { ['.'] = 'hor_value_slider'; w = 50, y = y + 50, w = 240; h = 25, label = 'R'; v = { 0, 300}; } { ['.'] = 'hor_value_slider'; w = 50, y = y + 100, w = 240; h = 25, label = 'start'; v = {-360, 360}; } { ['.'] = 'hor_value_slider'; w = 50, y = y + 125, w = 240; h = 25, label = 'end'; v = {-360, 360}; } { ['.'] = 'hor_value_slider'; w = 50, y = y + 150, w = 240; h = 25, label = 'rotate'; v = { 0, 360}; } { ['.'] = 'h_slider'; x = 50; y = 25; w = 240, h = 25; label = name[1]; what = { 0, 300}; act = {slider_cb, 1}; } { ['.'] = 'h_slider'; x = 50; y = 25; w = 240, h = 25; label = name[2]; what = { 0, 300}; act = {slider_cb, 2}; } { ['.'] = 'h_slider'; x = 50; y = 25; w = 240, h = 25; label = name[3]; what = { 0, 300}; act = {slider_cb, 3}; } { ['.'] = 'h_slider'; x = 50; y = 25; w = 240, h = 25; label = name[4]; what = {-360, 360}; act = {slider_cb, 4}; } { ['.'] = 'h_slider'; x = 50; y = 25; w = 240, h = 25; label = name[5]; what = {-360, 360}; act = {slider_cb, 5}; } { ['.'] = 'h_slider'; x = 50; y = 25; w = 240, h = 25; label = name[6]; what = { 0, 360}; act = {slider_cb, 6}; } for n=1,6 do local s = fl.hor_value_slider(50, y, 240, 25, name[n]) y = y + 25 if n < 4 then s:minimum(0) s:maximum(300) elseif n == 6 then s:minimum(0) s:maximum(360) else end s:minimum(what[1]) s:maximum(what[2]) s:step(what[3] or 1) s:value(args[n]) s:align('left') s:callback(slider_cb, n) end wb:show(arg[0], arg) return fl.run() -- menu widget { ['.'] = 'double_window'; { ['.'] = 'Window'; }; { ['.'] = 'Input'; }; { ['.'] = 'Input'; }; { ['.'] = 'Button'; }; { ['.'] = 'Return_Button'; }; { ['.'] = 'Button'; }; { ['.'] = 'menu_bar'; }; -- ['.'] = 'Menu_Item'; { "&File", 0, 0, 0, FL_SUBMENU }, { "&New File", 0, (Fl_Callback *)new_cb }, { "&Open File...", FL_COMMAND + 'o', (Fl_Callback *)open_cb }, { "&Insert File...", FL_COMMAND + 'i', (Fl_Callback *)insert_cb, 0, FL_MENU_DIVIDER }, { "&Save File", FL_COMMAND + 's', (Fl_Callback *)save_cb }, { "Save File &As...", FL_COMMAND + FL_SHIFT + 's', (Fl_Callback *)saveas_cb, 0, FL_MENU_DIVIDER }, { "New &View", FL_ALT + 'v', (Fl_Callback *)view_cb, 0 }, { "&Close View", FL_COMMAND + 'w', (Fl_Callback *)close_cb, 0, FL_MENU_DIVIDER }, { "E&xit", FL_COMMAND + 'q', (Fl_Callback *)quit_cb, 0 }, { 0 }, { "&Edit", 0, 0, 0, FL_SUBMENU }, { "&Undo", FL_COMMAND + 'z', (Fl_Callback *)undo_cb, 0, FL_MENU_DIVIDER }, { "Cu&t", FL_COMMAND + 'x', (Fl_Callback *)cut_cb }, { "&Copy", FL_COMMAND + 'c', (Fl_Callback *)copy_cb }, { "&Paste", FL_COMMAND + 'v', (Fl_Callback *)paste_cb }, { "&Delete", 0, (Fl_Callback *)delete_cb }, { 0 }, { "&Search", 0, 0, 0, FL_SUBMENU }, { "&Find...", FL_COMMAND + 'f', (Fl_Callback *)find_cb }, { "F&ind Again", FL_COMMAND + 'g', find2_cb }, { "&Replace...", FL_COMMAND + 'r', replace_cb }, { "Re&place Again", FL_COMMAND + 't', replace2_cb }, { 0 }, { 0 } }; --]] -- return gui -- vim: ts=4 sw=4 sts=4 et foldenable fdm=marker fmr={{{,}}} fdl=1
-- Game: https://roblox.com/games/4623386862 --[[ Bugs: 1. Spam Escape does not work. Note: 1. Not finished yet! 2. Some maps need special handling that I have not added yet, due to them requiring to do certain things before you can get the item, auto farm, etc. 3. Kill All Hazards may not have all of the hazards indexed! 4. I may or may not add Auto Farm, probably not. Things to add: Feature List: (Things listed with * are not working or not implemented yet fully) 1. Avoid the Item Obfuscation 2. Get a certain item 3. Auto Use Item - For example, uses the hammer on the main door automatically* 4. Remove All Hazards* 5. Kill Enemy Bots* 6. Spam Escape* 8. Noclip 9. Infinite Jump 10. Player ESP 11. WalkSpeed + JumpPower 12. Kill All Players (As Piggy or Traitor) ]] if getgenv().PiggyHax then return getgenv().PiggyHax end warn("PiggyHax Module Loading...") -- // Valiant ENV loadstring(game:HttpGetAsync("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Universal/ValiantENV.lua"))() -- // Vars local UserInputService = game.GetService(game, "UserInputService") local RenderStepped = RunService.RenderStepped local Stepped = RunService.Stepped local Heartbeat = RunService.Heartbeat local LocalPlayer = Players.LocalPlayer local PlayerGui = LocalPlayer:WaitForChild("PlayerGui") local Character = LocalPlayer.Character or LocalPlayer.CharacterAdded.Wait(LocalPlayer.CharacterAdded) local Humanoid = Character.WaitForChild(Character, "Humanoid") local CurrentCamera = Workspace.CurrentCamera local Mouse = LocalPlayer.GetMouse(LocalPlayer) local ItemFolder = Workspace:WaitForChild("ItemFolder") local GameFolder = Workspace:FindFirstChild("GameFolder") local NotificationHandler = loadstring(game:HttpGetAsync("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Universal/Notifications/Script.lua"))() getgenv().PiggyHax = { Notifications = true, AntiTrap = true, SpammingEscape = false, InfiniteJump = false, Noclip = false, KillAllInProgress = false, WalkSpeed = 50, JumpPower = 50, PlayerESP = loadstring(game:HttpGetAsync("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Universal/ESP/Player%20ESP.lua"))(), autoDoItemMapsOrder = { Forest = {"Wrench"} }, Binds = {toggleNoclip = Enum.KeyCode.F4}, CMDs = {}, Prefix = ":", } -- // Base MT Vars + Funs local mt = getrawmetatable(game) local backupnamecall = mt.__namecall local backupnewindex = mt.__newindex local backupindex = mt.__index setreadonly(mt, false) -- // Anti Obfuscation function antiObfuscation() LocalPlayer.PlayerGui.GameGUI.ChildAdded:Connect(function(child) wait() if child.Name == "Crouch" and child:FindFirstChild("DoorScript") then child.DoorScript:Destroy() print('Avoided Obfuscation!') end end) print('Initialised Anti Item Obfuscation') end antiObfuscation() PlayerGui.ChildAdded:Connect(antiObfuscation) -- // Functions function noRagFall() Humanoid:SetStateEnabled(Enum.HumanoidStateType.FallingDown, false) Humanoid:SetStateEnabled(Enum.HumanoidStateType.Ragdoll, false) end noRagFall() function PiggyHax.teleport(targetCFrame) if targetCFrame and typeof(targetCFrame) == 'CFrame' and Character and Character:FindFirstChild("HumanoidRootPart") then Character.HumanoidRootPart.CFrame = targetCFrame print('Teleported!') end end function PiggyHax.getBots() local allPlayers = {} local bots = {} for _,v in next, game:GetService("Players"):GetPlayers() do table.insert(allPlayers, v.Name) end for _,v in pairs(workspace:GetDescendants()) do if v:IsA("Humanoid") and not table.find(allPlayers, v.Parent.Name) and not table.find(bots, v.Parent) then table.insert(bots, v.Parent) end end return bots end function PiggyHax.inGame() return GameFolder.Phase.Value == "GameInProgress" end function PiggyHax.returnMap() for _,v in pairs(Workspace:GetChildren()) do if v:IsA("Model") and v:FindFirstChild("Events") then return v end end end function PiggyHax.returnItem(ItemName) for _,v in pairs(ItemFolder:GetChildren()) do if string.lower(v.Name) == string.lower(ItemName) then return v end end end function PiggyHax.returnAllItems() return ItemFolder:GetChildren() end function PiggyHax.autoDoItem(ItemName) -- // Basically goes to where the item belongs so the White Key goes to the Main Door and the Key Code goes to the Key Pad, etc. if ItemName and typeof(ItemName) == 'string' and PiggyHax.inGame() and PiggyHax.returnMap() and Character:FindFirstChild(ItemName) then local Map = PiggyHax.returnMap() for _,v in pairs(Map.Events:GetDescendants()) do local SpecialHandlingDone = false for a,x in pairs(PiggyHax.autoDoItemMaps) do if tostring(Map) == a and ItemName == x then -- Special Handling Here SpecialHandlingDone = true break end end if SpecialHandlingDone then break end if v.Name == "ToolRequired" and v.Value == ItemName then PiggyHax.teleport(v.Parent.CFrame) local Handle = Character:FindFirstChild(ItemName).Handle for i = 1, 10 do Humanoid.Jump = true firetouchinterest(Handle, v.Parent, 0) wait(0.1) firetouchinterest(Handle, v.Parent, 1) Humanoid.Jump = false end end break end end end function PiggyHax.retriveItem(ItemName, GoTo) if PiggyHax.returnItem(ItemName) then local Item = PiggyHax.returnItem(ItemName) if Item then local SavedPos = Character.PrimaryPart.CFrame function getItem() PiggyHax.teleport(Item.CFrame); wait(0.25) Item:FindFirstChildWhichIsA("ClickDetector").MaxActivationDistance = 15; wait(0.25) Item.Transparency = 0; wait(0.25) fireclickdetector(Item:FindFirstChildWhichIsA("ClickDetector"), 0); wait(0.5) if not GoTo then PiggyHax.teleport(SavedPos); wait(0.25) else PiggyHax.autoDoItem(ItemName) end end getItem() Humanoid:EquipTool(LocalPlayer.Backpack:FindFirstChild(ItemName)) wait(0.1) end if Character:FindFirstChild(ItemName) then NotificationHandler.newNotification('SUCCESS', 'Got '..ItemName.."!", 'Success') else NotificationHandler.newNotification('ERROR', ItemName.." does not exist, another player has this item already, or support to get this item on this map is not added yet. Note: This is case-sensitive!", 'Error') end end end function PiggyHax.returnEnemies() local Enemies = {} for _,plr in pairs(Players:GetPlayers()) do if plr.Character and (plr.Character:FindFirstChild("Enemy") and plr.Character.Enemy.Value) or (plr.Character:FindFirstChild("Traitor") and plr.Character.Traitor.Value) then table.insert(Enemies, plr) end end return Enemies end function PiggyHax.localPlayerPiggy() for _,plr in pairs(PiggyHax.returnEnemies()) do if plr == LocalPlayer then return true end end return false end function PiggyHax.killAll() if not PiggyHax.KillAllInProgress and PiggyHax.inGame() and PiggyHax.localPlayerPiggy() then PiggyHax.KillAllInProgress = true local nonKilled = Players:GetPlayers() local Connection = Players.PlayerAdded:Connect(function(player) if PiggyHax.KillAllInProgress then table.insert(nonKilled, player) end end) for i,plr in pairs(nonKilled) do repeat if plr and plr.Character and plr.Character.Humanoid.Health < 1 then if not firetouchinterest then PiggyHax.teleport(plr.Character.PrimaryPart.CFrame) end if firetouchinterest then firetouchinterest(Character.PrimaryPart, plr.Character.PrimaryPart, 0) firetouchinterest(Character.PrimaryPart, plr.Character.PrimaryPart, 1) end end until not plr or plr.Character or plr.Character.Humanoid.Health < 1 table.remove(nonKilled, i) end PiggyHax.KillAllInProgress = false Connection:Disconnect() NotificationHandler.newNotification('SUCCESS', 'Killed All!', 'Success') end end function PiggyHax.destroyAllHazards() if PiggyHax.inGame() then for _,v in pairs(ItemFolder:GetDescendants()) do if v:IsA("TouchTransmitter") then v:Destroy() end end for _,v in pairs(PiggyHax.returnMap().Events:GetChildren()) do if (v.Name == "LaserGate" and v:FindFirstChild("LaserTrigger")) or (v.Name == "SecuritySystem" and v:FindFirstChild("AlarmScanner")) or (v.Name == "FallTrigger") then v.LaserTrigger:Destroy() end end NotificationHandler.newNotification('SUCCESS', 'Removed all possible hazards!', 'Success') end end function PiggyHax.RemoveBots() if PiggyHax.inGame() and #PiggyHax.getBots() > 0 then for _,v in pairs(PiggyHax.getBots():GetDescendants()) do if v:IsA("TouchTransmitter") then v:Destroy() end end NotificationHandler.newNotification('SUCCESS', 'Removed Bots.', 'Success') end end function PiggyHax.toggleEscapeSpam() PiggyHax.SpammingEscape = not PiggyHax.SpammingEscape NotificationHandler.newNotification('SUCCESS', 'Toggle - Escape Spam: '..(PiggyHax.SpammingEscape and "Enabled!" or "Disabled!"), 'Success') return PiggyHax.Noclip end function PiggyHax.toggleInfiniteJump() PiggyHax.InfiniteJump = not PiggyHax.InfiniteJump NotificationHandler.newNotification('SUCCESS', 'Toggle - Infinite Jump: '..(PiggyHax.InfiniteJump and "Enabled!" or "Disabled!"), 'Success') return PiggyHax.InfiniteJump end -- // Anti Trap ItemFolder.ChildAdded:Connect(function(child) wait() if string.match(child.Name, "Trap") and PiggyHax.AntiTrap and not PiggyHax.localPlayerPiggy() then child:Destroy() end end) -- // Coroutines coroutine.wrap(function() while wait() do if PiggyHax.SpammingEscape and PiggyHax.inGame() then PiggyHax.teleport(PiggyHax.returnMap().Events.EscapeTrigger.CFrame) end end end)() -- // WalkSpeed + JumpPower Humanoid.WalkSpeed = PiggyHax["WalkSpeed"] Humanoid.JumpPower = PiggyHax["JumpPower"] mt.__newindex = newcclosure(function(t, k, v) if not checkcaller() and k == "WalkSpeed" or k == "JumpPower" and t == LocalPlayer.Character:FindFirstChildWhichIsA("Humanoid") then return backupnewindex(t, i, PiggyHax[i]) end return backupnewindex(t, k, v) end) -- // Anti Fall + Ragdoll LocalPlayer.CharacterAdded:Connect(noRagFall) -- // Infinite Jump UserInputService.JumpRequest:Connect(function() if PiggyHax.InfiniteJump then Character:ChangeState("Jumping") end end) -- // Noclip Stepped:Connect(function() if PiggyHax.Noclip then for _,v in pairs(Character:GetDescendants()) do if v:IsA("BasePart") and v.CanCollide then v.CanCollide = false end end end end) function PiggyHax.toggleNoclip() PiggyHax.Noclip = not PiggyHax.Noclip NotificationHandler.newNotification('SUCCESS', 'Toggle - Noclip: '..(PiggyHax.Noclip and "Enabled!" or "Disabled!"), 'Success') return PiggyHax.Noclip end -- // Bind Handling UserInputService.InputBegan:Connect(function(Key, GPE) for cmd, bind in pairs(PiggyHax.Binds) do if not GPE and Key.KeyCode == bind then PiggyHax[cmd]() end end end) -- // CMD Handler function addCMD(CommandName, ModuleName, Example, Description, Function) local CMDs = PiggyHax.CMDs CMDs[CommandName] = { ModuleName = ModuleName, Example = Example, Description = PiggyHax.Prefix..Description, Function = Function, } end LocalPlayer.Chatted:Connect(function(message) for i,v in pairs(PiggyHax.CMDs) do local Command = PiggyHax.Prefix..i if not message then message = "" end if v.Function and string.sub(message, 1, #Command) == Command then v.Function(message) end end end) -- // Commands function PiggyHax.startCommands() addCMD("getitem", "Farming", "getitem WhiteKey", "Gets the Item you want.", function(message) local splitString = string.split(message, " ") if splitString[2] and PiggyHax.returnItem(splitString[2]) then PiggyHax.retriveItem(splitString[2]) else if not splitString[2] then NotificationHandler.newNotification("ALERT", "Missing Argument #2!", "Alert") elseif splitString[2] and not PiggyHax.returnItem(splitString[2]) then NotificationHandler.newNotification("ALERT", splitString[2].." does not exist, another player has this item already, or support to get this item on this map is not added yet. Note: This Argument is case-sensitive!", "Alert") end end end) addCMD("autoitem", "Farming", "autoitem", "Automatically does the needed action to use the item specified.", function() local splitString = string.split(message, " ") if splitString[2] and PiggyHax.returnItem[splitString[2]] then PiggyHax.autoDoItem(splitString[2]) else if not splitString[2] then NotificationHandler.newNotification("ALERT", "Missing Argument #2!", "Alert") elseif splitString[2] and not PiggyHax.returnItem(splitString[2]) then NotificationHandler.newNotification("ALERT", splitString[2].." does not exist or another player has this item already. Note: This Argument is case-sensitive!", "Alert") end end end) addCMD("escapespam", "Farming", "escapespam", "Toggles Spamming the Escape", function() PiggyHax["toggleEscapeSpam"]() end) addCMD("removebots", "Game", "removebots", "Removes the bot ability to kill you.", function(message) PiggyHax["RemoveBots"]() end) addCMD("removehazards", "Game", "removehazards", "Removes all possible hazards that could kill you or give you away.", function(message) PiggyHax["destroyAllHazards"]() end) addCMD("killall", "Game", "killall", "Kills everyone, if you're Piggy/Traitor.", function(message) PiggyHax["killAll"]() end) addCMD("noclip", "Player", "noclip", "Toggles noclip.", function(message) PiggyHax["toggleNoclip"]() end) addCMD("infjump", "Player", "infjump", "Toggles Infinite Jump.", function(message) PiggyHax["toggleInfiniteJump"]() end) addCMD("ws", "Player", "ws 100", "Sets your WalkSpeed.", function(message) local splitString = string.split(message, " ") if splitString[2] and tonumber(splitString[2]) then Humanoid.WalkSpeed = tonumber(splitString[2]) PiggyHax["WalkSpeed"] = tonumber(splitString[2]) NotificationHandler.newNotification("SUCCESS", "Set WalkSpeed to "..splitString[2].."!", "Success") else if not splitString[2] then NotificationHandler.newNotification("ALERT", "Missing Argument #2!", "Alert") elseif splitString[2] and not tonumber(splitString[2]) then NotificationHandler.newNotification("ALERT", "Argument #2 is not a number!", "Alert") end end end) addCMD("jp", "Player", "jp 100", "Sets your JumpPower.", function(message) local splitString = string.split(message, " ") if splitString[2] and tonumber(splitString[2]) then Humanoid.JumpPower = tonumber(splitString[2]) PiggyHax["JumpPower"] = tonumber(splitString[2]) NotificationHandler.newNotification("SUCCESS", "Set JumpPower to "..splitString[2].."!", "Success") else if not splitString[2] then NotificationHandler.newNotification("ALERT", "Missing Argument #2!", "Alert") elseif splitString[2] and not tonumber(splitString[2]) then NotificationHandler.newNotification("ALERT", "Argument #2 is not a number!", "Alert") end end end) NotificationHandler.newNotification('SUCCESS', 'Commands Enabled!', 'Success') end NotificationHandler.newNotification('SUCCESS', 'PiggyHax Module Loaded!', 'Success') warn("PiggyHax Module Loaded!")
-- 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_underlord_firestorm_lua = class({}) -------------------------------------------------------------------------------- -- Classifications function modifier_underlord_firestorm_lua:IsHidden() return false end function modifier_underlord_firestorm_lua:IsDebuff() return true end function modifier_underlord_firestorm_lua:IsStunDebuff() return false end function modifier_underlord_firestorm_lua:IsPurgable() return true end -------------------------------------------------------------------------------- -- Initializations function modifier_underlord_firestorm_lua:OnCreated( kv ) -- references if not IsServer() then return end local interval = kv.interval self.damage_pct = kv.damage/100 -- precache damage self.damageTable = { victim = self:GetParent(), attacker = self:GetCaster(), -- damage = damage, damage_type = DAMAGE_TYPE_MAGICAL, ability = self:GetAbility(), --Optional. } -- ApplyDamage(damageTable) -- Start interval self:StartIntervalThink( interval ) end function modifier_underlord_firestorm_lua:OnRefresh( kv ) if not IsServer() then return end self.damage_pct = kv.damage/100 end function modifier_underlord_firestorm_lua:OnRemoved() end function modifier_underlord_firestorm_lua:OnDestroy() end -------------------------------------------------------------------------------- -- Interval Effects function modifier_underlord_firestorm_lua:OnIntervalThink() -- check health local damage = self:GetParent():GetMaxHealth() * self.damage_pct -- apply damage self.damageTable.damage = damage ApplyDamage( self.damageTable ) end -------------------------------------------------------------------------------- -- Graphics & Animations function modifier_underlord_firestorm_lua:GetEffectName() return "particles/units/heroes/heroes_underlord/abyssal_underlord_firestorm_wave_burn.vpcf" end function modifier_underlord_firestorm_lua:GetEffectAttachType() return PATTACH_ABSORIGIN_FOLLOW end
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by Administrator. --- DateTime: 2020/2/21 10:18 --- local iputils = require "resty.iputils" local protocols_with_subsystem = { http = "http", https = "http", tcp = "stream", tls = "stream" } local http_protocols = {} for p, s in pairs(protocols_with_subsystem) do if s == "http" then http_protocols[#http_protocols + 1] = p end end table.sort(http_protocols) local function validate_cidr_v4(ip) local _, err = iputils.parse_cidr(ip) -- It's an error only if the second variable is a string if type(err) == "string" then return nil, "invalid cidr range: " .. err end return true end local string_array = { type = "array", default = {}, elements = { type = "string" }, } local colon_string_array = { type = "array", default = {}, --elements = { type = "string", }, elements = { type = "string", custom_validator = validate_cidr_v4, }, } local one_of = { type = "string", default = "header", one_of = { "header", "cookie", 'args' } } local ip_canary_record = { type = "record", fields = { { range = colon_string_array }, { upstream = { type = "string" } }, }, } local uid_canary_record = { type = "record", fields = { { on = one_of }, { name = { type = "string", default = "uid" } }, { range = string_array }, { upstream = { type = "string" } }, } } local canary_on_record = { type = "record", fields = { { on = one_of }, { name = { type = "string", } }, { range = string_array }, { upstream = { type = "string" } }, } } return { name = "canary", fields = { --{ run_on = typedefs.run_on_first }, { protocols = { type = "set", required = true, default = http_protocols, elements = { type = "string", one_of = http_protocols }, } }, { config = { type = "record", fields = { { canary_upstream = { type = "string", len_min = 1, required = true }, }, { ip = ip_canary_record }, { uid = uid_canary_record }, { customize = canary_on_record }, }, }, }, }, }
TOOL.Category = "Poser" TOOL.Name = "#tool.inflator.name" TOOL.LeftClickAutomatic = true TOOL.RightClickAutomatic = true TOOL.RequiresTraceHit = true TOOL.Information = { { name = "left" }, { name = "right" }, { name = "reload" } } local ScaleYZ = { "ValveBiped.Bip01_L_UpperArm", "ValveBiped.Bip01_L_Forearm", "ValveBiped.Bip01_L_Thigh", "ValveBiped.Bip01_L_Calf", "ValveBiped.Bip01_R_UpperArm", "ValveBiped.Bip01_R_Forearm", "ValveBiped.Bip01_R_Thigh", "ValveBiped.Bip01_R_Calf", "ValveBiped.Bip01_Spine2", "ValveBiped.Bip01_Spine1", "ValveBiped.Bip01_Spine", "ValveBiped.Bip01_Spinebut", -- Vortigaunt "ValveBiped.spine4", "ValveBiped.spine3", "ValveBiped.spine2", "ValveBiped.spine1", "ValveBiped.hlp_ulna_R", "ValveBiped.hlp_ulna_L", "ValveBiped.arm1_L", "ValveBiped.arm1_R", "ValveBiped.arm2_L", "ValveBiped.arm2_R", "ValveBiped.leg_bone1_L", "ValveBiped.leg_bone1_R", "ValveBiped.leg_bone2_L", "ValveBiped.leg_bone2_R", "ValveBiped.leg_bone3_L", "ValveBiped.leg_bone3_R", -- Team Fortress 2 "bip_knee_L", "bip_knee_R", "bip_hip_R", "bip_hip_L", } local ScaleXZ = { "ValveBiped.Bip01_pelvis", -- Team Fortress 2 "bip_upperArm_L", "bip_upperArm_R", "bip_lowerArm_L", "bip_lowerArm_R", "bip_forearm_L", "bip_forearm_R", } local function GetNiceBoneScale( name, scale ) if ( table.HasValue( ScaleYZ, name ) || string.find( name:lower(), "leg" ) || string.find( name:lower(), "arm" ) ) then return Vector( 0, scale, scale ) end if ( table.HasValue( ScaleXZ, name ) ) then return Vector( scale, 0, scale ) end return Vector( scale, scale, scale ) end --Scale the specified bone by Scale local function ScaleBone( ent, bone, scale, type ) if ( !bone || CLIENT ) then return false end local physBone = ent:TranslateBoneToPhysBone( bone ) for i = 0, ent:GetBoneCount() do if ( ent:TranslateBoneToPhysBone( i ) != physBone ) then continue end -- Some bones are scaled only in certain directions (like legs don't scale on length) local v = GetNiceBoneScale( ent:GetBoneName( i ), scale ) * 0.1 local TargetScale = ent:GetManipulateBoneScale( i ) + v * 0.1 if ( TargetScale.x < 0 ) then TargetScale.x = 0 end if ( TargetScale.y < 0 ) then TargetScale.y = 0 end if ( TargetScale.z < 0 ) then TargetScale.z = 0 end ent:ManipulateBoneScale( i, TargetScale ) end end --Scale UP function TOOL:LeftClick( trace, scale ) if ( !IsValid( trace.Entity ) ) then return false end if ( !trace.Entity:IsNPC() && trace.Entity:GetClass() != "prop_ragdoll" /*&& !trace.Entity:IsPlayer()*/ ) then return false end local bone = trace.Entity:TranslatePhysBoneToBone( trace.PhysicsBone ) ScaleBone( trace.Entity, bone, scale or 1 ) self:GetWeapon():SetNextPrimaryFire( CurTime() + 0.01 ) local effectdata = EffectData() effectdata:SetOrigin( trace.HitPos ) util.Effect( "inflator_magic", effectdata ) return false end -- Scale DOWN function TOOL:RightClick( trace ) return self:LeftClick( trace, -1 ) end -- Reset scaling function TOOL:Reload( trace ) if ( !IsValid( trace.Entity ) ) then return false end if ( !trace.Entity:IsNPC() && trace.Entity:GetClass() != "prop_ragdoll" /*&& !trace.Entity:IsPlayer()*/ ) then return false end if ( CLIENT ) then return true end for i = 0, trace.Entity:GetBoneCount() do trace.Entity:ManipulateBoneScale( i, Vector( 1, 1, 1 ) ) end return true end function TOOL.BuildCPanel( CPanel ) CPanel:AddControl( "Header", { Description = "#tool.inflator.desc" } ) end
require("Framework.event.EventDispatcher") local super = EventDispatcher ---@class UnityLoader UnityLoader = class("Framework.loader.UnityLoader", super) function UnityLoader:ctor() end function UnityLoader:Load() end
local context = {} function context.new(headers) return { code = 200, mime = "text/plain", body = "", headers = headers, cookies = { get = function() local cookies = {} for header, cookie in headers:each() do if header == "cookie" then table.insert(cookies, kolba.cookie.parse(cookie)) end end return cookies end, set = function(key, value) headers:append("Set-Cookie", key .. "=" .. value) end } } end return context
modifier_siglos_disadvantage_silence = class({}) function modifier_siglos_disadvantage_silence:CheckState() return {[MODIFIER_STATE_SILENCED] = true} end function modifier_siglos_disadvantage_silence:OnCreated() if IsClient() then return end local hParent = self:GetParent() self.iParticle = ParticleManager:CreateParticle("particles/siglos/siglos_disadvantage_silence.vpcf", PATTACH_OVERHEAD_FOLLOW, hParent) ParticleManager:SetParticleControlEnt(self.iParticle, 1, hParent, PATTACH_ABSORIGIN_FOLLOW, 'follow_origin', hParent:GetOrigin(), true) end function modifier_siglos_disadvantage_silence:OnDestroy() if IsClient() then return end ParticleManager:DestroyParticle(self.iParticle, false) end function modifier_siglos_disadvantage_silence:IsPurgable() local hSpecial = self:GetCaster():FindAbilityByName("special_bonus_unique_siglos_2") if hSpecial and hSpecial:GetLevel() > 0 then return false else return true end end modifier_siglos_disadvantage_disarm = class({}) function modifier_siglos_disadvantage_disarm:CheckState() return {[MODIFIER_STATE_DISARMED] = true} end function modifier_siglos_disadvantage_disarm:OnCreated() if IsClient() then return end local hParent = self:GetParent() self.iParticle = ParticleManager:CreateParticle("particles/siglos/siglos_disadvantage_disarm.vpcf", PATTACH_OVERHEAD_FOLLOW, hParent) ParticleManager:SetParticleControlEnt(self.iParticle, 1, hParent, PATTACH_ABSORIGIN_FOLLOW, 'follow_origin', hParent:GetOrigin(), true) end function modifier_siglos_disadvantage_disarm:OnDestroy() if IsClient() then return end ParticleManager:DestroyParticle(self.iParticle, false) end function modifier_siglos_disadvantage_disarm:IsPurgable() local hSpecial = self:GetCaster():FindAbilityByName("special_bonus_unique_siglos_2") if hSpecial and hSpecial:GetLevel() > 0 then return false else return true end end modifier_siglos_reflect = class({}) function modifier_siglos_reflect:IsPurgable() return true end function modifier_siglos_reflect:OnCreated() if IsClient() then return end local hParent = self:GetParent() self.iParticle = ParticleManager:CreateParticle("particles/siglos/siglos_reflect.vpcf", PATTACH_CUSTOMORIGIN_FOLLOW, hParent) ParticleManager:SetParticleControlEnt(self.iParticle, 0, hParent, PATTACH_POINT_FOLLOW, "attach_hitloc", hParent:GetOrigin(), true) end function modifier_siglos_reflect:OnDestroy() if IsClient() then return end ParticleManager:DestroyParticle(self.iParticle, false) end function modifier_siglos_reflect:DeclareFunctions() return {MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_PHYSICAL, MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_MAGICAL, MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_PURE, MODIFIER_PROPERTY_TOOLTIP} end function modifier_siglos_reflect:OnTooltip() if not self.bFoundSpecial then self.hSpecial = Entities:First() while self.hSpecial and (self.hSpecial:GetName() ~= "special_bonus_unique_siglos_4" or self.hSpecial:GetCaster() ~= self:GetCaster()) do self.hSpecial = Entities:Next(self.hSpecial) end self.bFoundSpecial = true end if self.hSpecial then return self:GetAbility():GetSpecialValueFor("percentage_damage")+self.hSpecial:GetSpecialValueFor("value") else return self:GetAbility():GetSpecialValueFor("percentage_damage") end end function modifier_siglos_reflect:GetAbsoluteNoDamagePhysical(keys) if not keys.attacker or not keys.target or bit.band(keys.damage_flags, DOTA_DAMAGE_FLAG_REFLECTION) > 0 then return 1 end local iDamagePercentage = self:GetAbility():GetSpecialValueFor("percentage_damage") if keys.target:HasAbility("special_bonus_unique_siglos_4") then iDamagePercentage = iDamagePercentage+keys.target:FindAbilityByName("special_bonus_unique_siglos_4"):GetSpecialValueFor("value") end ApplyDamage({attacker = keys.target, damage = keys.original_damage*iDamagePercentage/100, damage_type = keys.damage_type, damage_flags = DOTA_DAMAGE_FLAG_REFLECTION+DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION, victim = keys.attacker, ability = self:GetAbility()}) local iParticle = ParticleManager:CreateParticle("particles/units/heroes/hero_spectre/spectre_dispersion.vpcf", PATTACH_CUSTOMORIGIN_FOLLOW, keys.target) ParticleManager:SetParticleControlEnt(iParticle, 0, keys.attacker, PATTACH_POINT_FOLLOW, "attach_hitloc", keys.attacker:GetOrigin(), true) ParticleManager:SetParticleControlEnt(iParticle, 1, keys.target, PATTACH_POINT_FOLLOW, "attach_hitloc", keys.target:GetOrigin(), true) return 1 end function modifier_siglos_reflect:GetAbsoluteNoDamageMagical() return 1 end function modifier_siglos_reflect:GetAbsoluteNoDamagePure() return 1 end modifier_siglos_disruption_aura = class({}) function modifier_siglos_disruption_aura:IsAura() return true end function modifier_siglos_disruption_aura:GetAuraRadius() return self:GetAbility():GetSpecialValueFor("aura_radius") end function modifier_siglos_disruption_aura:GetModifierAura() return "modifier_siglos_disruption_aura_target" end function modifier_siglos_disruption_aura:GetAuraSearchTeam() return DOTA_UNIT_TARGET_TEAM_ENEMY end function modifier_siglos_disruption_aura:GetAuraSearchType() return DOTA_UNIT_TARGET_BASIC+DOTA_UNIT_TARGET_HERO end function modifier_siglos_disruption_aura:IsHidden() return true end function modifier_siglos_disruption_aura:RemoveOnDeath() return false end function modifier_siglos_disruption_aura:IsPurgable() return false end modifier_siglos_disruption_aura_target = class({}) function modifier_siglos_disruption_aura_target:IsHidden() return false end function modifier_siglos_disruption_aura_target:DeclareFunctions() return {MODIFIER_PROPERTY_TOOLTIP} end function modifier_siglos_disruption_aura_target:OnTooltip() if not self.bFoundSpecial then self.hSpecial = Entities:First() while self.hSpecial and (self.hSpecial:GetName() ~= "special_bonus_unique_siglos_1" or self.hSpecial:GetCaster() ~= self:GetCaster()) do self.hSpecial = Entities:Next(self.hSpecial) end self.bFoundSpecial = true end if self.hSpecial then return self:GetAbility():GetSpecialValueFor("disruption_range")+self.hSpecial:GetSpecialValueFor("value") else return self:GetAbility():GetSpecialValueFor("disruption_range") end end modifier_siglos_mind_control = class({}) function modifier_siglos_mind_control:OnCreated() if IsClient() then return end local hParent = self:GetParent() local hCaster = self:GetCaster() self.iOwnerID = hParent:GetPlayerOwnerID() hParent.iTeam = hParent:GetTeam() hParent:SetOrigin(hParent:GetOrigin()+Vector(0,0,10000)) hParent:AddEffects(EF_NODRAW) end function modifier_siglos_mind_control:CheckState() return {[MODIFIER_STATE_NO_UNIT_COLLISION] = true, [MODIFIER_STATE_INVULNERABLE] = true, [MODIFIER_STATE_OUT_OF_GAME] = true, [MODIFIER_STATE_STUNNED] = true} end function modifier_siglos_mind_control:OnDestroy() if IsClient() then return end local hParent = self:GetParent() local hCaster = self:GetCaster() hParent:RemoveEffects(EF_NODRAW) hParent:SetOrigin(GetGroundPosition(hParent:GetOrigin(), hParent)) end modifier_siglos_mind_control_magic_immune = class({}) function modifier_siglos_mind_control_magic_immune:OnDestroy() if IsClient() then return end ParticleManager:DestroyParticle(self.iParticle, false) end function modifier_siglos_mind_control_magic_immune:IsPurgable() return false end function modifier_siglos_mind_control_magic_immune:IsHidden() return true end function modifier_siglos_mind_control_magic_immune:OnCreated() if IsClient() then return end self.iParticle = ParticleManager:CreateParticle("particles/items_fx/black_king_bar_avatar.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetParent()) end function modifier_siglos_mind_control_magic_immune:OnDestroy() if IsClient() then return end ParticleManager:DestroyParticle(self.iParticle, false) end function modifier_siglos_mind_control_magic_immune:CheckState() return {[MODIFIER_STATE_MAGIC_IMMUNE]=true} end function modifier_siglos_mind_control_magic_immune:GetStatusEffectName() return "particles/status_fx/status_effect_avatar.vpcf" end
data:extend({ --Crab { type = "capsule", name = "af-crab", icon = "__Advanced_Fishing__/graphics/fishes/crab.png", icon_size = 128, subgroup = "raw-material", stack_size = 100, capsule_action = { type = "use-on-self", attack_parameters = { type = "projectile", ammo_category = "capsule", cooldown = 30, range = 0, ammo_type = { category = "capsule", target_type = "position", action = { type = "direct", action_delivery = { type = "instant", target_effects = { type = "damage", damage = {type = "physical", amount = -160} } } } } } } }, --Salmon { type = "capsule", name = "af-salmon", icon = "__Advanced_Fishing__/graphics/fishes/salmon.png", icon_size = 128, subgroup = "raw-material", stack_size = 100, capsule_action = { type = "use-on-self", attack_parameters = { type = "projectile", ammo_category = "capsule", cooldown = 30, range = 0, ammo_type = { category = "capsule", target_type = "position", action = { type = "direct", action_delivery = { type = "instant", target_effects = { type = "damage", damage = {type = "physical", amount = -100} } } } } } } }, --Tropical { type = "capsule", name = "af-tropical", icon = "__Advanced_Fishing__/graphics/fishes/tropical.png", icon_size = 128, subgroup = "raw-material", stack_size = 100, capsule_action = { type = "use-on-self", attack_parameters = { type = "projectile", ammo_category = "capsule", cooldown = 30, range = 0, ammo_type = { category = "capsule", target_type = "position", action = { type = "direct", action_delivery = { type = "instant", target_effects = { type = "damage", damage = {type = "physical", amount = -120} } } } } } } }, --Squid { type = "capsule", name = "af-squid", icon = "__Advanced_Fishing__/graphics/fishes/squid.png", icon_size = 128, subgroup = "raw-material", stack_size = 100, capsule_action = { type = "use-on-self", attack_parameters = { type = "projectile", activation_type = "consume", ammo_category = "capsule", cooldown = 30, range = 0, ammo_type = { category = "capsule", target_type = "position", action = { type = "direct", action_delivery = { type = "instant", target_effects = { type = "damage", damage = {type = "physical", amount = -200} } } } } } } } })
if Server then -- sort always by distance first (increases the chance that we find a suitable source faster) function FindNewPowerConsumers(powerSource) -- allow passing of nil (to handle map change or unexpected destruction of some ojects) if not powerSource then return nil end local consumers = GetEntitiesWithMixin("PowerConsumer") -- there might not be any if alien versus alien if consumers and #consumers > 0 then --Shared.SortEntitiesByDistance(powerSource:GetOrigin(), consumers) local canPower = false local stopSearch = false for index, consumer in ipairs(consumers) do canPower, stopSearch = powerSource:GetCanPower(consumer) if canPower then powerSource:AddConsumer(consumer) consumer:SetPowerOn() consumer.powerSourceId = powerSource:GetId() end if stopSearch then break end end end end end
local propLeaderboard = script:GetCustomProperty("leaderboard") -- Signs local signs = {} local colors = {} local setupFinished = false math.randomseed(os.time()) function OnSignCreated(player) local playerPos = player:GetWorldPosition() local randomRot = math.ceil(math.random() * 360) local randomScale = math.random() + 0.6 local location = Vector3.New(playerPos.x, playerPos.y, -44.9) local rotation = Rotation.New(0, 90, randomRot) local scale = Vector3.New(randomScale, randomScale, randomScale) local signStorage = signs[player.name] local color = colors[player.name] or "#FFFFFF" if not signStorage then signStorage = {} end table.insert(signStorage, 1, {position = location, rotation = rotation, scale = scale, color = color}) signs[player.name] = signStorage while Events.BroadcastToAllPlayers("SignCreatedEvent", player.name, location, rotation, scale, color) == BroadcastEventResultCode.EXCEEDED_RATE_LIMIT do Task.Wait() end end Events.ConnectForPlayer("SignEvent", OnSignCreated) function OnPlayerJoined(player) -- Send all Signs to the player if setupFinished == false then print("Not ready yet") return end print("Sending signs to " .. player.name) for playerName, signStorage in pairs(signs) do print("Sending sign of " .. playerName) for i = 1, #signStorage do local sign = signStorage[i] while Events.BroadcastToPlayer(player, "SignCreatedEvent", playerName, sign.position, sign.rotation, sign.scale, sign.color) == BroadcastEventResultCode.EXCEEDED_RATE_LIMIT do print("Sign rate limit exceeded for " .. playerName .."'s sign. Trying again") Task.Wait(0.1) end end end end Game.playerJoinedEvent:Connect(function(player) Task.Wait(1) OnPlayerJoined(player) end) function OnPlayerLeave(player) -- Save PlayerSign to Leaderboard and Storage local playerSign = signs[player.name] if playerSign then Storage.SetPlayerData(player, playerSign) if (Leaderboards.HasLeaderboards()) then Leaderboards.SubmitPlayerScore(propLeaderboard, player, 1) end end end Game.playerLeftEvent:Connect(OnPlayerLeave) function ChangeColorEvent(player, color) colors[player.name] = color print("Color changed to " .. color .. " for " .. player.name) end Events.ConnectForPlayer("ColorSignEvent", ChangeColorEvent) function SendAll() if #Game.GetPlayers() > 0 then for playerName, signStorage in pairs(signs) do print("Sending sign of " .. playerName) for i = 1, #signStorage do local sign = signStorage[i] while Events.BroadcastToAllPlayers("SignCreatedEvent", playerName, sign.position, sign.rotation, sign.scale, sign.color) == BroadcastEventResultCode.EXCEEDED_RATE_LIMIT do print("Sign rate limit exceeded for " .. playerName .."'s sign. Trying again") Task.Wait(0.1) end end end end end -- StartUP function StartUp() print("Initializing Signs") while not Leaderboards.HasLeaderboards() do -- just keep checking until this until the Leaderboards are loaded Task.Wait(1) -- wait one second end local leaderboard = Leaderboards.GetLeaderboard(propLeaderboard, LeaderboardType.GLOBAL) for _, entry in ipairs(leaderboard) do local signStorage = Storage.GetOfflinePlayerData(entry.id) if signStorage then signs[entry.name] = signStorage end end setupFinished = true SendAll() print("Signs initialized") end StartUp()
local anim8 = require 'anim8' return function(ship) local pss = love.graphics.newImage('assets/player.png') local ess = love.graphics.newImage('assets/explosion.png') local gp = anim8.newGrid(16, 24, pss:getWidth(), pss:getHeight()) local ge = anim8.newGrid(16, 16, ess:getWidth(), ess:getHeight()) ship.name = 'player' ship.initialState = 'movingForward' ship.initialAnim = anim8.newAnimation(gp(3, '1-2'), 0.05) ship.initialSpritesheet = pss ship.initialOffset = {x = 0, y = 0} ship.events = { {name = 'moveForward', from = {'movingLeft', 'movingRight'}, to = 'movingForward', spritesheet = pss, anim = anim8.newAnimation(gp(3, '1-2'), 0.05), offset = {x=0, y=0}}, {name = 'moveLeft', from = {'movingForward', 'movingRight'}, to = 'movingLeft', spritesheet = pss, anim = anim8.newAnimation(gp(1, '1-2'), 0.05), offset = {x=0, y=0}}, {name = 'moveRight', from = {'movingForward', 'movingLeft'}, to = 'movingRight', spritesheet = pss, anim = anim8.newAnimation(gp(5, '1-2'), 0.05), offset = {x=0, y=0}}, {name = 'explode', from = {'movingForward', 'movingLeft', 'movingRight'}, to = 'exploding', spritesheet = ess, anim = anim8.newAnimation(ge('1-5', 1), 0.1, function(anim) anim:pause(); ship:destroy() end), offset = {x=0, y=0}}, {name = 'destroy', from = {'exploding'}, to = 'destroyed'}, } end
------------------------------------------------- -- Allows to store client specific settings in one place -- -- @author Pavel Makhov -- @copyright 2019 Pavel Makhov -------------------------------------------- local secrets = { -- Yandex.Translate API key - https://tech.yandex.com/translate/ translate_widget_api_key = os.getenv('AWW_TRANSLATE_API_KEY') or 'API_KEY', -- OpenWeatherMap API key - https://openweathermap.org/appid weather_widget_api_key = os.getenv('AWW_WEATHER_API_KEY') or 'API_KEY', weather_widget_city = os.getenv('AWW_WEATHER_CITY') or 'Montreal,ca', weather_widget_units = os.getenv('AWW_WEATHER_UNITS') or 'metric' -- for celsius, or 'imperial' for fahrenheit } return secrets
ENT.Type = "anim" ENT.Base = "base_gmodentity" ENT.PrintName = "Racing Platform" ENT.Author = "Owain Owjo" ENT.Category = "The XYZ Network Custom Stuff" ENT.RenderGroup = RENDERGROUP_BOTH ENT.Spawnable = true ENT.AdminSpawnable = true function ENT:Initialize() table.insert(XYZRacing.Platforms, self) end function ENT:OnRemove() table.RemoveByValue(XYZRacing.Platforms, self) end
function Update() ac = GetActorByName("Thing") if ac == nil then PrintText("Actor does not exist") end trans = ac:GetTransform() vc = trans:GetPosition() if Input():GetKey("right") == true then vc= vc + trans:Right() end if Input():GetKey("left") == true then vc= vc - trans:Right() end if Input():GetKey("up") == true then vc= vc + trans:Forward() end if Input():GetKey("down") == true then vc= vc - trans:Forward() end trans:SetPosition(vc) if Input():GetKey("d") == true then trans:Rotate(10.0,trans:Forward()*-1.0) end if Input():GetKey("a") == true then trans:Rotate(10.0,trans:Forward()) end if Input():GetKey("w") == true then trans:Rotate(10.0,trans:Right()) end if Input():GetKey("s") == true then trans:Rotate(10.0,trans:Right()*-1.0) end end
--iが0になると繰り返し終了 i=1000000 repeat print(i) i = i - 2 until i == 0