content
stringlengths
5
1.05M
--[[-------------------------------------------------------------------]]--[[ Copyright wiltOS Technologies LLC, 2020 Contact: www.wiltostech.com ----------------------------------------]]-- wOS = wOS or {} wOS.ALCS = wOS.ALCS or {} wOS.ALCS.Config = wOS.ALCS.Config or {} wOS.ALCS.Config.Skills = wOS.ALCS.Config.Skills or {} /* What skill tree schema do you want to use? Options: WOS_ALCS.SKILLMENU.NEWAGE --The UI introduced by the Dark Ascension update, 3D and with all the new features WOS_ALCS.SKILLMENU.CLASSIC --The UI everyone has come to know and love, and in 2D. May not work with newer features */ wOS.ALCS.Config.Skills.MenuSchema = WOS_ALCS.SKILLMENU.NEWAGE --How much experience is required for the first level? --This is an assumption based on my default quadratic increase, but it may have no purpose to you. wOS.ALCS.Config.Skills.MinimumExperience = 200 --Create your own leveling formula with this. The default property is a quadratic increase --( level^2 )*wOS.ALCS.Config.Skills.MinimumExperience*0.5 + level*wOS.ALCS.Config.Skills.MinimumExperience + wOS.ALCS.Config.Skills.MinimumExperience --This amounts to the ( ax^2 + bx + c ) format of increase --You can use this to create set amounts per level by returning a table --If you need help setting this up you'll probably want to ask, but it's just simple math so there's probably tutorials everywhere wOS.ALCS.Config.Skills.XPScaleFormula = function( level ) local required_experience = ( level^2 )*wOS.ALCS.Config.Skills.MinimumExperience*0.5 + level*wOS.ALCS.Config.Skills.MinimumExperience + wOS.ALCS.Config.Skills.MinimumExperience return required_experience end --What is the max level for the Skill Leveling? Set this to FALSE if you want it to go infinitely wOS.ALCS.Config.Skills.SkillMaxLevel = 200 --Should we be able to see the Combat Level and XP on the HUD? wOS.ALCS.Config.Skills.MountLevelToHUD = true --Should we be able to see the combat level of other players above their head? wOS.ALCS.Config.Skills.MountLevelToPlayer = false
-- ter_fighter1.lua -- Configuration file for the Terran Mk.1 Fighter ship = { uname = "ter_fighter1", race = "terran", fullname = "Fighter Mk.1", model = "fighter.3ds", cockpit = "canopy02.3ds", pitch = 80, yaw = 50, roll = 90, mass = 2500, enginetype = "ter_fusion2.lua", engines = { {x=0, y=0, z=5} }, weapons = { {x=0, y=-1.5, z=-5}, }, weapontype = "ter_ppc1.lua", brakes = { {x=1.6, y=0.7, z=-2.5}, {x=-1.6, y=0.7, z=-2.5} }, shield_fore = "ter_shield1.lua", shield_aft = "ter_shield1.lua", shield_right = "ter_shield1.lua", shield_left = "ter_shield1.lua" }
ITEM.name = "Moskovskaya Sausage" ITEM.description = "A lump of sausage" ITEM.longdesc = "A traditional Russian sausage similar to the Polish kielbasa, this Eastern European sausage is also known as Maskoska. This sausage is made in the Ukraine following the classic Eastern European recipe, pork and beef lightly smoked, with a bit of garlic and other spices. Ready to eat, just bite off a piece." ITEM.model = "models/lostsignalproject/items/consumable/sausage2.mdl" ITEM.price = 40 ITEM.width = 1 ITEM.height = 1 ITEM.weight = 0.125 ITEM.flatweight = 0 ITEM.hunger = 11 ITEM.quantity = 2 ITEM.sound = "stalkersound/inv_eat_mutant_food.mp3" ITEM:Hook("use", function(item) item.player:EmitSound(item.sound or "items/battery_pickup.wav") ix.chat.Send(item.player, "iteminternal", "takes a bite out of their "..item.name..".", false) end) ITEM:DecideFunction()
-- Prosody IM -- Copyright (C) 2014 Daurnimator -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- -- This module allows you to use cqueues with a net.server mainloop -- local server = require "net.server"; local cqueues = require "cqueues"; assert(cqueues.VERSION >= 20150113, "cqueues newer than 20150113 required") -- Create a single top level cqueue local cq; if server.cq then -- server provides cqueues object cq = server.cq; elseif server.get_backend() == "select" and server._addtimer then -- server_select cq = cqueues.new(); local function step() assert(cq:loop(0)); end -- Use wrapclient (as wrapconnection isn't exported) to get server_select to watch cq fd local handler = server.wrapclient({ getfd = function() return cq:pollfd(); end; settimeout = function() end; -- Method just needs to exist close = function() end; -- Need close method for 'closeall' }, nil, nil, {}); -- Only need to listen for readable; cqueues handles everything under the hood -- readbuffer is called when `select` notes an fd as readable handler.readbuffer = step; -- Use server_select low lever timer facility, -- this callback gets called *every* time there is a timeout in the main loop server._addtimer(function(current_time) -- This may end up in extra step()'s, but cqueues handles it for us. step(); return cq:timeout(); end); elseif server.event and server.base then -- server_event cq = cqueues.new(); -- Only need to listen for readable; cqueues handles everything under the hood local EV_READ = server.event.EV_READ; -- Convert a cqueues timeout to an acceptable timeout for luaevent local function luaevent_safe_timeout(cq) local t = cq:timeout(); -- if you give luaevent 0 or nil, it re-uses the previous timeout. if t == 0 then t = 0.000001; -- 1 microsecond is the smallest that works (goes into a `struct timeval`) elseif t == nil then -- pick something big if we don't have one t = 0x7FFFFFFF; -- largest 32bit int end return t end local event_handle; event_handle = server.base:addevent(cq:pollfd(), EV_READ, function(e) -- Need to reference event_handle or this callback will get collected -- This creates a circular reference that can only be broken if event_handle is manually :close()'d local _ = event_handle; -- Run as many cqueues things as possible (with a timeout of 0) -- If an error is thrown, it will break the libevent loop; but prosody resumes after logging a top level error assert(cq:loop(0)); return EV_READ, luaevent_safe_timeout(cq); end, luaevent_safe_timeout(cq)); else error "NYI" end return { cq = cq; }
--[[ © CloudSixteen.com do not share, re-distribute or modify without permission of its author (kurozael@gmail.com). Clockwork was created by Conna Wiles (also known as kurozael.) http://cloudsixteen.com/license/clockwork.html --]] Clockwork.json = Clockwork.kernel:NewLibrary("Json"); function Clockwork.json:Encode(tableToEncode) return util.TableToJSON(tableToEncode); end; function Clockwork.json:Decode(stringToDecode) return util.JSONToTable(stringToDecode); end;
local ffi = require 'ffi' local C = ffi.C local typeof = ffi.typeof ffi.cdef([[ int execve(const char *filename, const char *argv[], const char *envp[]); char *strerror(int errnum); int execvp(const char *file, const char *argv[]); ]]) local string_array_t = typeof("const char *[?]") local function execvp(filename, args) table.insert(args, 1, filename) -- the command name should be the first arg local cargv = string_array_t(#args + 1, args) cargv[#args] = nil C.execvp(filename, cargv) error(ffi.string(ffi.C.strerror(ffi.errno()))) end return execvp
function todo.create_frame(player, name, caption, close_name) local frame = player.gui.screen.add({ type = "frame", name = name, direction = "vertical" }) -- Add title bar local title_bar = frame.add({ type = "flow" }) local title = title_bar.add({ type = "label", caption = caption, style = "frame_title" }) title.drag_target = frame -- Add 'dragger' (filler) between title and (close) buttons local dragger = title_bar.add({ type = "empty-widget", style = "draggable_space_header" }) dragger.style.vertically_stretchable = true dragger.style.horizontally_stretchable = true dragger.drag_target = frame if close_name ~= nil then title_bar.add({ type = "sprite-button", style = "frame_action_button", sprite = "utility/close_white", name = close_name }) end return frame end
-- the hud handles all hud elements local pBarX, pBarY, pBarW, pBarH = 0 local devFont, hudFont, specialFont = nil local devInfo = nil local dangertimer = 0 -- used to modify danger warner text dynamically (size, color) -- simple init function function hud_init() pBarW = math.floor(love.graphics:getWidth() / 6) pBarH = math.floor(love.graphics:getHeight() / 30) pBarX = math.floor(love.graphics:getWidth() - pBarW - pBarH / 2) pBarY = math.floor(pBarH / 2) devFont = love.graphics.newFont(15) specialFont = love.graphics.newFont( "res/fonts/beon/Beon-Regular.otf", 30 ) devInfo = {} end -- draw Hud function hud_draw() -- the run progress bar local perc = runHandler.traderun.travelled / runHandler.traderun.distance love.graphics.setColor(192, 232, 239, 255) love.graphics.rectangle( "fill", pBarX, pBarY, pBarW * perc, pBarH ) love.graphics.rectangle( "line", pBarX, pBarY, pBarW, pBarH ) -- run warning local c = runHandler.traderun:getCurrentChallenge() if c ~= nil then local message = "Danger: "..c.name love.graphics.setFont(specialFont) local v = math.abs(math.sin(dangertimer * 2)) local s = 1 + v / 5 love.graphics.setColor(160 + v * 90, 160, 160, 255) love.graphics.print(message, love.graphics:getWidth() / 2, 30, 0, s, s, specialFont:getWidth(message) / 2, specialFont:getHeight() / 2) else dangertimer = 0 end -- draw developer information if DEVELOPER_MODE then love.graphics.setFont(devFont) love.graphics.setColor(255, 255, 255, 255) local shift = 20 for i,element in pairs(devInfo) do love.graphics.print(i..": "..element, 20, shift) shift = shift + 20 end end end -- update Hud elements function hud_update(dt) dangertimer = dangertimer + dt -- update developer information if DEVELOPER_MODE then devInfo["FPS"] = love.timer.getFPS() devInfo["Delta"] = love.timer.getFPS() devInfo["scale"] = scale devInfo["ent act"] = table.getn(entities) devInfo["ent sur"] = table.getn(runHandler.traderun.encountered) end end
--[[ Copyright (c) 2009 Peter "Corsix" Cawley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] local room = {} room.id = "ward" room.vip_must_visit = true room.level_config_id = 9 room.class = "WardRoom" room.name = _S.rooms_short.ward room.tooltip = _S.tooltip.rooms.ward room.long_name = _S.rooms_long.ward room.objects_additional = { "extinguisher", "radiator", "plant", "desk", "bin", "bed" } room.objects_needed = { desk = 1, bed = 1 } room.build_preview_animation = 910 room.categories = { treatment = 2, diagnosis = 9, } room.minimum_size = 6 room.wall_type = "white" room.floor_tile = 21 room.swing_doors = true room.required_staff = { Nurse = 1, } room.call_sound = "reqd009.wav" class "WardRoom" (Room) ---@type WardRoom local WardRoom = _G["WardRoom"] function WardRoom:WardRoom(...) self:Room(...) self.staff_member_set = {} self.healing_amount = 0 -- The size of progress towards a diagnostic step end function WardRoom:roomFinished() local fx, fy = self:getEntranceXY(true) local objects = self.world:findAllObjectsNear(fx, fy) local beds = 0 local desks = 0 for object, _ in pairs(objects) do if object.object_type.id == "bed" then beds = beds + 1 end if object.object_type.id == "desk" then desks = desks + 1 end end self.maximum_staff = { Nurse = desks, } self.maximum_patients = beds if self.hospital:countStaffOfCategory("Nurse", 1) == 0 then self.world.ui.adviser:say(_A.room_requirements.ward_need_nurse) end Room.roomFinished(self) end function WardRoom:getMaximumStaffCriteria() return self.maximum_staff end function WardRoom:commandEnteringStaff(humanoid) self.staff_member_set[humanoid] = true self:doStaffUseCycle(humanoid) return Room.commandEnteringStaff(self, humanoid, true) end function WardRoom:doStaffUseCycle(humanoid) local meander_time = math.random(4, 10) humanoid:setNextAction(MeanderAction():setCount(meander_time)) local obj, ox, oy = self.world:findFreeObjectNearToUse(humanoid, "desk") if obj then obj.reserved_for = humanoid humanoid:walkTo(ox, oy) if obj.object_type.id == "desk" then local desk_use_time = math.random(7, 14) local desk_loop = --[[persistable:ward_desk_loop_callback]] function() desk_use_time = desk_use_time - 1 if desk_use_time == 0 then self:doStaffUseCycle(humanoid) end end humanoid:queueAction(UseObjectAction(obj):setLoopCallback(desk_loop)) end end local num_meanders = math.random(2, 4) local meanders_loop = --[[persistable:ward_meander_loop_callback]] function(action) num_meanders = num_meanders - 1 if num_meanders == 0 then self:doStaffUseCycle(humanoid) end end humanoid:queueAction(MeanderAction():setLoopCallback(meanders_loop)) end function WardRoom:updateHealingAmount() local patient_count = 1 local nurse_factor = 0 for humanoid in pairs(self.humanoids) do if not humanoid:isLeaving() then if class.is(humanoid, Patient) then patient_count = patient_count + 1 elseif humanoid.humanoid_class == "Nurse" and not humanoid.fired then nurse_factor = nurse_factor + 0.5 + humanoid:getServiceQuality() end end end if nurse_factor > 0 then -- Difficulty of healing - 10% faster on easier, 10% slower on hard mode local difficulty_factor = 0.8 + self.world.map:getDifficulty() * 0.1 self.healing_amount = nurse_factor / math.log(patient_count) / difficulty_factor else self.healing_amount = 0 end end function WardRoom:commandEnteringPatient(patient) local bed, pat_x, pat_y = self.world:findFreeObjectNearToUse(patient, "bed") self:setStaffMembersAttribute("dealing_with_patient", nil) if not bed then patient:setNextAction(self:createLeaveAction()) patient:queueAction(self:createEnterAction(patient)) self.world:gameLog("Warning: A patient was called into the ward even though there are no free beds.") return Room.commandEnteringPatient(self, patient) end bed.reserved_for = patient -- Old callback kept for persistence in savegame version 155, April 2021 local --[[persistable:ward_loop_callback]] function _(action) if length <= 0 then action.prolonged_usage = false end length = length - 1 end -- New callback local --[[persistable:ward_loop_callback2]] function loop_callback(action) action.remaining_work = action.remaining_work - self.healing_amount if action.remaining_work <= 0 then -- The patient is diagnosed or healed action.prolonged_usage = false end end local after_use = --[[persistable:ward_after_use]] function() self:dealtWithPatient(patient) end patient:walkTo(pat_x, pat_y) local bed_action = UseObjectAction(bed):setProlongedUsage(true) :setLoopCallback(loop_callback):setAfterUse(after_use) bed_action.remaining_work = math.random(150, 600) patient:queueAction(bed_action) return Room.commandEnteringPatient(self, patient) end function WardRoom:setStaffMember(staff) self.staff_member_set[staff] = true end function WardRoom:setStaffMembersAttribute(attribute, value) for staff_member, _ in pairs(self.staff_member_set) do staff_member[attribute] = value end end function WardRoom:onHumanoidLeave(humanoid) self.staff_member_set[humanoid] = nil Room.onHumanoidLeave(self, humanoid) self:updateHealingAmount() end function WardRoom:onHumanoidEnter(humanoid) Room.onHumanoidEnter(self, humanoid) self:updateHealingAmount() end function WardRoom:afterLoad(old, new) if old < 11 then -- Make sure all three tiles outside of the door are unbuildable. local door = self.door local x = door.tile_x local y = door.tile_y local dir = door.direction local map = self.world.map.th local flags = {} local function checkLocation(xpos, ypos) if self.world:getRoom(xpos, ypos) or not map:getCellFlags(xpos, ypos, flags).passable then local message = "Warning: An update has resolved a problem concerning " .. "swing doors, but not all tiles adjacent to them could be fixed." self.world.ui:addWindow(UIInformation(self.world.ui, {message})) return false end return true end if dir == "west" then -- In west or east wall if self.world:getRoom(x, y) == self then -- In west wall if checkLocation(x - 1, y + 1) then map:setCellFlags(x - 1, y + 1, {buildable = false}) end else -- East wall if checkLocation(x, y + 1) then map:setCellFlags(x, y + 1, {buildable = false}) end end else -- if dir == "north", North or south wall if self.world:getRoom(x, y) == self then -- In north wall if checkLocation(x + 1, y - 1) then map:setCellFlags(x + 1, y - 1, {buildable = false}) end else -- South wall if checkLocation(x + 1, y) then map:setCellFlags(x + 1, y, {buildable = false}) end end end end if old < 74 then -- add some new variables self.staff_member_set = {} self.nursecount = 0 -- reset any wards that already exist self:roomFinished() -- if there is already a nurse in the ward -- make her leave so she gets counted properly local nurse = self.staff_member if nurse then nurse:setNextAction(self:createLeaveAction()) nurse:queueAction(MeanderAction()) end end Room.afterLoad(self, old, new) end return room
return { name = 'sony_morpheus', ident = '^SCEIHMD', wm = 'ignore', tag = 'VR' };
return function() require("stabilize").setup() end
includeFile("custom_content/tangible/loot/loot_schematic/dancing_droid_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/deconstructed_armor_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/deconstructed_vehicle_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/deconstructed_weapon_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/duel_recording_terminal_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/generic_limited_use_flashy.lua") includeFile("custom_content/tangible/loot/loot_schematic/generic_vehicle.lua") includeFile("custom_content/tangible/loot/loot_schematic/imperial_gunner_helmet_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/kashyyyk_treehouse_scem.lua") includeFile("custom_content/tangible/loot/loot_schematic/planning_table_bestine_imp_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/planning_table_bestine_reb_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/planning_table_dearic_imp_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/planning_table_dearic_reb_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/planning_table_keren_imp_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/planning_table_keren_reb_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/portable_bazaar_terminal_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/portable_space_terminal_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/rebel_trooper_helmet_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/speeder_desert_skiff_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/speeder_usv5_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/trandoshan_hunter_rifle_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/vehicle_lava_res_kit_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/wod_floating_stones_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/wod_ns_gate_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/wod_ns_hut.lua") includeFile("custom_content/tangible/loot/loot_schematic/wod_sm_hut.lua") includeFile("custom_content/tangible/loot/loot_schematic/wod_tower_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/wod_trilithon_schematic.lua") includeFile("custom_content/tangible/loot/loot_schematic/yt1300_house_schematic.lua")
--[[ Mob fight arena script Script made by Grandelf. ]]-- --[[ ################################################################################################## # # # Emap, Ex, Ey, Ez, Ezone this are the coords of the easy battle zone. # # Just define it by putting in the coords as follow. # # Map, X, Y, Z, Zone, so for e.g.: local Emap, Ex, Ey, Ez = 1, 4235.43, 3145.32, 12.3, 14 # # # # Nmap, Nx, Ny, Nz, Nzone # # Same as above but then for the normal battle zone. # # # # Hmap, Hx, Hy, Hz, Hzone # # Same as above but then for the hard battle zone. # # # ################################################################################################## ]]-- local Emap, Ex, Ey, Ez, Ezone = 0, -13205, 278, 22, 33 local Nmap, Nx, Ny, Nz, Nzone = 0, -13205, 278, 22, 33 local Hmap, Hx, Hy, Hz, Hzone = 0, -13205, 278, 22, 33 --[[ ################################################################################################## # # # EasyMob --> Id for the mobs that will spawn at easy mode # # # # NormalMob --> Id for the mobs that will spawn at easy mode # # # # HardMob --> Id for the mobs that will spawn at easy mode # # # # GossipGuy --> Id for the gossip npc. # # # ################################################################################################## ]]-- local EasyMob = 4316 local NormalMob = 4316 local HardMob = 4316 local GossipGuy = 4316 --[[ ################################################################################################## # # # Maximum --> Enter the maximum amount of mobs a player can fight. # # # # Emax --> Max amount of players that can join easy mode. # # Nmax --> Max amount of players that can join normal mode. # # Hmax --> Max amount of players that can join hard mode. # # # # Wmap, Wx, Wy, Wz --> map, x, y, z coords where player gets ported to if he won. # # Lmap, Lx, Ly, Lz --> map, x, y, z coords where player gets ported to if he lost. # # # ################################################################################################## ]]-- local Maximum = 15 local Emax = 30 local Nmax = 30 local Hmax = 30 local Wmap, Wx, Wy, Wz = 0, -13205, 278, 22 local Lmap, Lx, Ly, Lz = 0, -13205, 278, 22 ARENA = {} ARENA["Battle"] = { ["Easy"] = { ["In"] = 0, ["Players"] = {} }, ["Normal"] = { ["In"] = 0, ["Players"] = {} }, ["Hard"] = { ["In"] = 0, ["Players"] = {} }, ["Phase"] = { } } function ARENA.BattleNpc(pUnit, event, player) pUnit:GossipCreateMenu(100, player, 0) pUnit:GossipMenuAddItem(0, "Enter the amount of mobs you want to fight.", 1, 1) pUnit:GossipMenuAddItem(0, "Nevermind.", 2, 0) pUnit:GossipSendMenu(player) end function ARENA.BattleNpcOnGossip(pUnit, event, player, id, intid, code, pMisc) if (intid == 1) then if (code ~= nil) and (NumberCheck(code) == true) then if (tonumber(code) <= Maximum) then pUnit:GossipCreateMenu(100, player, 0) pUnit:GossipMenuAddItem(0, "Easy mode.", 2, 0) pUnit:GossipMenuAddItem(0, "Normal mode.", 3, 0) pUnit:GossipMenuAddItem(0, "Hard mode.", 4, 0) pUnit:GossipMenuAddItem(0, "Nevermind.", 5, 0) pUnit:GossipSendMenu(player) ARENA[tostring(player)] = {} ARENA[tostring(player)].Code = code else player:SendBroadcastMessage("The limit is "..Maximum..".") player:GossipComplete() end else player:SendBroadcastMessage("You can only use numbers.") player:GossipComplete() end end if (intid == 2) then if (ARENA["Battle"]["Easy"]["In"] <= Emax) then ARENA["Battle"]["Easy"]["Players"][GetFreeSlot("Easy", "Players")] = player ARENA["Battle"]["Easy"]["In"] = ARENA["Battle"]["Easy"]["In"] + 1 local t = GetPhaseNr() ARENA["Battle"]["Phase"][t] = 1 player:PhaseSet(t) player:Teleport(Emap, Ex, Ey, Ez) ARENA[tostring(player)].Mob = {} local p = FindPlayer(player, "Easy", "Players") local code = ARENA[tostring(player)].Code RegisterTimedEvent("StartBattle", 5000, 1, "Easy", player, code, p) -- Triggers mob spawning. player:GossipComplete() player:Root() else player:SendBroadcastMessage("Easy mode is full at this moment, try another mode or come back later.") player:GossipComplete() end end if (intid == 3) then if (ARENA["Battle"]["Easy"]["In"] <= Nmax) then ARENA["Battle"]["Normal"]["Players"][GetFreeSlot("Normal", "Players")] = player ARENA["Battle"]["Normal"]["In"] = ARENA["Battle"]["Normal"]["In"] + 1 local t = GetPhaseNr() ARENA["Battle"]["Phase"][t] = 1 player:PhaseSet(t) player:Teleport(Nmap, Nx, Ny, Nz) ARENA[tostring(player)].Mob = {} local p = FindPlayer(player, "Normal", "Players") local code = ARENA[tostring(player)].Code RegisterTimedEvent("StartBattle", 5000, 1, "Normal", player, code, p) player:GossipComplete() player:Root() else player:SendBroadcastMessage("Normal mode is full at this moment, try another mode or come back later.") player:GossipComplete() end end if (intid == 4) then if (ARENA["Battle"]["Easy"]["In"] <= Hmax) then ARENA["Battle"]["Hard"]["Players"][GetFreeSlot("Hard", "Players")] = player ARENA["Battle"]["Hard"]["In"] = ARENA["Battle"]["Hard"]["In"] + 1 local t = GetPhaseNr() ARENA["Battle"]["Phase"][t] = 1 player:PhaseSet(t) player:Teleport(Hmap, Hx, Hy, Hz) ARENA[tostring(player)].Mob = {} local p = FindPlayer(player, "Hard", "Players") local code = ARENA[tostring(player)].Code RegisterTimedEvent("StartBattle", 5000, 1, "Hard", player, code, p) player:GossipComplete() player:Root() else player:SendBroadcastMessage("Hard mode is full at this moment, try another mode or come back later.") player:GossipComplete() end end if (intid == 5) then player:GossipComplete() end end function CheckIfPlayerWon(player, Mode, p) if (ARENA[tostring(player)].Mob ~= nil) then if (player:IsInCombat() == false) and (player:IsAlive() == true) then -- mobs dead player:SendBroadcastMessage("Congratulations, you have won this battle") player:Teleport(Wmap, Wx, Wy, Wz) player:PhaseSet(1) ARENA["Battle"][Mode]["In"] = ARENA["Battle"][Mode]["In"] - 1 ARENA["Battle"][Mode]["Players"][p] = nil ARENA["Battle"]["Phase"][p] = nil for _, s in pairs(ARENA[tostring(player)].Mob) do s:Despawn(1000, 0) end ARENA[tostring(player)] = {} else RegisterTimedEvent("CheckIfPlayerWon", 1000, 1, player, Mode, p) end else return; end end function StartBattle(mode, player, code, p) local t = 0 while (t ~= tonumber(code)) do t = t + 1 if (mode == "Easy") then ARENA[tostring(player)].Mob[t] = player:SpawnCreature(EasyMob, player:GetX() + 5, player:GetY(), player:GetZ(), 3, 14, 0) elseif (mode == "Normal") then ARENA[tostring(player)].Mob[t] = player:SpawnCreature(NormalMob, player:GetX() + 5, player:GetY(), player:GetZ(), 3, 14, 0) elseif (mode == "Hard") then ARENA[tostring(player)].Mob[t] = player:SpawnCreature(HardMob, player:GetX() + 5, player:GetY(), player:GetZ(), 3, 14, 0) end end RegisterTimedEvent("CheckIfPlayerWon", 2000, 1, player, mode, p) RegisterTimedEvent("Checks", 1000, 1, player, mode, p) player:Unroot() end function Checks(player, mode, p) local Zone = 0 if (mode == "Easy") then Zone = Ezone elseif (mode == "Normal") then Zone = Nzone elseif (mode == "Hard") then Zone = Hzone end if (player:IsAlive() == false) or (player:GetZoneId() ~= Zone) then ARENA["Battle"][mode]["In"] = ARENA["Battle"][mode]["In"] - 1 ARENA["Battle"][mode]["Players"][p] = nil ARENA["Battle"]["Phase"][p] = nil for _, s in pairs(ARENA[tostring(player)].Mob) do s:Despawn(1000, 0) end ARENA[tostring(player)] = {} player:Teleport(Lmap, Lx, Ly, Lz) player:CastSpell(18976) -- Resurrect else RegisterTimedEvent("Checks", 1000, 1, player, mode, p) end end function NumberCheck(str) local len, t = string.len(str) + 1, 1 while (t ~= len) do local p = string.find(str, "%d", t) if (p ~= nil) then t = t + 1 else return false end end return true end function GetFreeSlot(Mode, Tbl) local t = 1 while (ARENA["Battle"][Mode][Tbl][t] ~= nil) do -- Checking for a free slot. t = t + 1 end return t; end function GetPhaseNr() local t = 1 while (ARENA["Battle"]["Phase"][t] ~= nil) do -- Checking for an unused phase. t = t + 1 end return t; end function FindPlayer(player, Mode, Tbl) for k, v in pairs(ARENA["Battle"][Mode][Tbl]) do if (v == player) then return k; end end end logcol(4) print(" [Arena]: Loaded succesfully.") print(" [Arena]: Script made by Grandelf.") logcol(7) RegisterUnitGossipEvent(GossipGuy, 129130, "ARENA.BattleNpc") RegisterUnitGossipEvent(GossipGuy, 129130, "ARENA.BattleNpcOnGossip")
-------------------------------- -- @module PhysicsShapeEdgePolygon -- @extend PhysicsShape -- @parent_module cc -------------------------------- -- Get this polygon's points array count.<br> -- return An interger number. -- @function [parent=#PhysicsShapeEdgePolygon] getPointsCount -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Get this polygon's center position.<br> -- return A Vec2 object. -- @function [parent=#PhysicsShapeEdgePolygon] getCenter -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) return nil
local api, cmd, fn, g = vim.api, vim.cmd, vim.fn, vim.g local opt, wo = vim.opt, vim.wo local fmt = string.format ---- defaults ---- opt.shell='fish' opt.mouse = 'a' opt.termguicolors = true -- ui opt.cursorline = true opt.number = true opt.wrap = false -- tab, indent opt.expandtab = true opt.smarttab = true opt.autoindent = true opt.smartindent = true opt.shiftwidth = 2 opt.tabstop = 2 opt.softtabstop = 2 -- leader api.nvim_set_keymap('', '<Space>', '<Nop>', { noremap = true, silent = true }) g.mapleader = ' ' g.maplocalleader = ',' -- provider g.loaded_python_provider = 0 g.python3_host_prog = '~/.asdf/shims/python' g.loaded_perl_provider = 0 ---- packer ---- local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' if fn.empty(fn.glob(install_path)) > 0 then packer_bootstrap = fn.system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path}) end ---- plugins ---- local packer = require'packer' local use = packer.use packer.startup(function() use 'wbthomason/packer.nvim' -- etc use 'lewis6991/impatient.nvim' -- LSP use { 'neovim/nvim-lspconfig', 'williamboman/nvim-lsp-installer' } use 'nvim-lua/lsp-status.nvim' use 'nvim-lua/lsp_extensions.nvim' use 'glepnir/lspsaga.nvim' use { "folke/trouble.nvim", requires = "kyazdani42/nvim-web-devicons", config = function() require("trouble").setup { -- your configuration comes here -- or leave it empty to use the default settings -- refer to the configuration section below } end } use{ "jose-elias-alvarez/null-ls.nvim", config = function() require("null-ls").setup({ sources = { require("null-ls").builtins.formatting.fish_indent, require("null-ls").builtins.formatting.dart_format, require("null-ls").builtins.formatting.lua_format } }) end, requires = {"nvim-lua/plenary.nvim", "neovim/nvim-lspconfig"} } use 'folke/lsp-colors.nvim' -- completion use 'hrsh7th/cmp-nvim-lsp' use 'hrsh7th/cmp-buffer' use 'hrsh7th/nvim-cmp' -- syntax use { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' } use 'nvim-treesitter/nvim-treesitter-textobjects' use 'blackCauldron7/surround.nvim' -- terminal use {"akinsho/toggleterm.nvim"} -- snippet use 'L3MON4D3/LuaSnip' use 'saadparwaiz1/cmp_luasnip' -- fuzzy find use { 'nvim-telescope/telescope.nvim', requires = { {'nvim-lua/plenary.nvim'} } } use {'nvim-telescope/telescope-fzf-native.nvim', run = 'make' } -- color use 'norcalli/nvim-colorizer.lua' -- colorscheme use 'navarasu/onedark.nvim' -- icon -- neovim lua dev -- tabbar use {'akinsho/bufferline.nvim', requires = 'kyazdani42/nvim-web-devicons'} -- statusline use { 'hoob3rt/lualine.nvim', requires = {'kyazdani42/nvim-web-devicons', opt = true} } -- coursorline use 'yamatsum/nvim-cursorline' -- editing support use 'p00f/nvim-ts-rainbow' use 'JoosepAlviste/nvim-ts-context-commentstring' -- formatting -- ident use 'lukas-reineke/indent-blankline.nvim' -- file explorer use { 'kyazdani42/nvim-tree.lua', requires = 'kyazdani42/nvim-web-devicons', } -- git use { 'lewis6991/gitsigns.nvim', requires = { 'nvim-lua/plenary.nvim' }, } use { 'TimUntersberger/neogit', requires = 'nvim-lua/plenary.nvim' } -- language support use {'akinsho/flutter-tools.nvim', requires = 'nvim-lua/plenary.nvim'} use 'gennaro-tedesco/nvim-jqx' -- comment use 'numToStr/Comment.nvim' -- keybinding use 'folke/which-key.nvim' if packer_bootstrap then require('packer').sync() end end) ---- plugin configs ---- --etc require('impatient') --lsp local lspconfig = require'lspconfig' local lsp_installer = require("nvim-lsp-installer") lsp_installer.on_server_ready(function(server) local opts = {} opts.capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()) -- (optional) Customize the options passed to the server -- if server.name == "tsserver" then -- opts.root_dir = function() ... end -- end -- This setup() function is exactly the same as lspconfig's setup function (:help lspconfig-quickstart) server:setup(opts) vim.cmd [[ do User LspAttachBuffers ]] end) local saga = require'lspsaga' saga.init_lsp_saga() -- completion local cmp = require'cmp' cmp.setup({ snippet = { expand = function(args) require('luasnip').lsp_expand(args.body) end, }, mapping = { ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm({ select = true }), }, sources = { { name = 'nvim_lsp' }, { name = 'luasnip' }, { name = 'buffer' }, } }) -- syntax require'nvim-treesitter.configs'.setup { ensure_installed = "maintained", -- one of "all", "maintained" (parsers with maintainers), or a list of languages --ignore_install = { "javascript" }, -- List of parsers to ignore installing highlight = { enable = true, -- false will disable the whole extension -- disable = { "c", "rust" }, -- list of language that will be disabled -- Setting this to true will run `:h syntax` and tree-sitter at the same time. -- Set this to `true` if you depend on 'syntax' being enabled (like for indentation). -- Using this option may slow down your editor, and you may see some duplicate highlights. -- Instead of true it can also be a list of languages additional_vim_regex_highlighting = false, }, context_commentstring = { enable = true }, rainbow = { enable = true, extended_mode = true, } } require"surround".setup {mappings_style = "sandwich"} -- terminal require("toggleterm").setup{} -- snippet -- fuzzy finder require("telescope").load_extension("flutter") -- color require'colorizer'.setup{} -- colorscheme require('onedark').load() -- icon -- utility -- lua development -- tabline require('bufferline').setup{ options = { offsets = { { filetype = "NvimTree", text = "File Explorer", highlight = "Directory", text_align = "left" } } } } -- statusline require('lualine').setup{ options = { theme = 'onedark' }, extensions = {'nvim-tree'} } -- cursorline -- indent -- file explorer require'nvim-tree'.setup{} -- git require('gitsigns').setup{} local neogit = require('neogit') neogit.setup{} -- language support require("flutter-tools").setup{} -- comment require('Comment').setup{} -- editing support -- formatting -- keybinding local wk = require("which-key") wk.setup{} wk.register({ -- ["<leader>c"] = { name = "+Color" }, ["<leader>c"] = { name = "+Command"}, ["<leader>C"] = { "<cmd>Telescope commands<cr>", "Commands" }, ["<leader>cc"] = { "<cmd>Telescope commands<cr>", "Commands" }, ["<leader>ct"] = { "<cmd>Telescope command_history<cr>", "Command History"}, ["<leader>ck"] = { "<cmd>Telescope keymaps<cr>", "Keymaps" }, ["<leader>ch"] = { "<cmd>Telescope man_pages<cr>", "Help"}, ["<localleader>w"] = { name = "+Workspace"}, ["<localleader>wa"] = { "<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>", "Format" }, ["<localleader>wr"] = { "<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>", "Format" }, ["<localleader>wl"] = { "<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>", "Format" }, ["<leader>x"] = { name = "+Language"}, ["<localleader>x"] = { name = "+Language"}, ["<leader>X"] = { "<cmd>TroubleToggle lsp_workspace_diagnostics<cr>", "Problems" }, ["<leader>xx"] = { "<cmd>TroubleToggle lsp_workspace_diagnostics<cr>", "Problems" }, ["<localleader>X"] = { "<cmd>TroubleToggle lsp_document_diagnostics<cr>", "Problems" }, ["<localleader>xx"] = { "<cmd>TroubleToggle lsp_document_diagnostics<cr>", "Problems" }, ["<leader>xq"] = { "<cmd>TroubleToggle quickfix<cr>", "Quickfix" }, ["<leader>xl"] = { "<cmd>TroubleToggle loclist<cr>", "Loclist" }, ["<leader>xt"] = { "<cmd>TroubleToggle<cr>", "Trouble" }, ["<localleader>xf"] = { "<cmd>lua vim.lsp.buf.formatting()<CR>", "Format" }, ["<localleader>xF"] = { "<cmd>lua vim.lsp.buf.range_formatting()<CR>", "Range Format" }, ["<leader>b"] = { name = "+Buffer"}, ["<leader>B"] = { "<cmd>Telescope buffers<cr>", "Buffers" }, ["<leader>bb"] = { "<cmd>Telescope buffers<cr>", "Buffers" }, ["<leader>r"] = { name = "+Register"}, ["<leader>R"] = { "<cmd>Telescope registers<cr>", "Registers" }, ["<leader>rr"] = { "<cmd>Telescope registers<cr>", "Registers" }, ["<leader>e"] = { name = "+Explorer"}, ["<leader>E"] = { "<cmd>NvimTreeToggle<cr>", "Explorer"}, ["<leader>ee"] = { "<cmd>NvimTreeToggle<cr>", "Explorer"}, ["<leader>eE"] = { "<cmd>Telescope file_browser<cr>", "Explorer(search)" }, ["<leader>ef"] = { "<cmd>FlutterOutlineToggle<cr>", "Flutter"}, ["<leader>s"] = { name = "+Search"}, ["<localleader>s"] = { name = "+Search"}, ["<leader>S"] = { "<cmd>Telescope live_grep<cr>", "Grep" }, ["<leader>ss"] = { "<cmd>Telescope live_grep<cr>", "Grep" }, ["<localleader>S"] = { "<cmd>Telescope current_buffer_fuzzy_find<cr>", "Grep" }, ["<localleader>ss"] = { "<cmd>Telescope current_buffer_fuzzy_find<cr>", "Grep" }, ["<leader>sn"] = { "<cmd>Telescope help_tags<cr>", "Tags" }, ["<leader>sh"] = { "<cmd>Telescope search_history<cr>", "Search History"}, ["<leader>st"] = { "<cmd>Telescope<cr>", "Telescope"}, ["<leader>f"] = { name = "+File" }, ["<leader>F"] = { "<cmd>Telescope find_files<cr>", "Find File" }, ["<leader>ff"] = { "<cmd>Telescope find_files<cr>", "Find File" }, ["<leader>fr"] = { "<cmd>Telescope oldfiles<cr>", "Open Recent File" }, ["<leader>fn"] = { "<cmd>enew<cr>", "New File" }, ["<leader>g"] = { name = "+Git" }, ["<leader>G"] = { "<cmd>Neogit<cr>", "Status" }, ["<leader>gg"] = { "<cmd>Neogit<cr>", "Status" }, ["<leader>gc"] = { "<cmd>Neogit commit<cr>", "Commit" }, ["<leader>t"] = { name = "+Terminal" }, ["<leader>T"] = { "<cmd>ToggleTerm<cr>", "Terminal" }, ["<leader>tt"] = { "<cmd>ToggleTerm<cr>", "Terminal" }, ["<leader>tb"] = { "<cmd>terminal<cr>", "Terminal Buffer" }, })
#!/usr/bin/env lua --- Tests on dumocks.ScreenRenderer. -- @see dumocks.ScreenRenderer -- set search path to include src directory package.path = "src/?.lua;" .. package.path local lu = require("luaunit") local sr = require("dumocks.ScreenRenderer") _G.TestScreenRenderer = {} --- Characterization test to determine in-game behavior, can run on mock and uses assert instead of luaunit to run -- in-game. -- -- Test setup: -- 1. 1x Screen or Sign, paste relevent bit directly into render script -- -- Exercises: ??TODO?? function _G.TestScreenRenderer.testGameBehavior() local screenRenderer = sr:new() local oldEnv = _ENV local closure = screenRenderer:mockGetEnvironment() local _ENV = closure --------------- -- copy from here to renderer --------------- local expectedFunctions = {"getCursor", "createLayer", "getResolution", "addCircle", "setNextFillColor", "setNextStrokeColor", "getDeltaTime", "addImage", "loadImage", "setNextRotation", "loadFont", "setNextRotationDegrees", "addTriangle", "requestAnimationFrame", "addQuad", "setNextStrokeWidth", "addText", "getRenderCostMax", "addLine", "getRenderCost", "addBox", "getInput", "setOutput", "setDefaultRotation", "isImageLoaded", "setDefaultShadow", "setDefaultStrokeColor", "setNextTextAlign", "setNextShadow", "isFontLoaded", "setDefaultStrokeWidth", "addBoxRounded", "setBackgroundColor", "getCursorPressed", "getCursorReleased", "getCursorDown", "setDefaultFillColor", "getFontMetrics", "getTextBounds", "logMessage", "next", "pairs", "ipairs", "select", "type", "tostring", "tonumber", "pcall", "xpcall", "assert", "error", "load", "require", "setmetatable", "getmetatable"} local unexpectedFunctions = {} local expectedTables = {"table", "string", "math"} local unexpectedTables = {} local expectedStrings = { ["_VERSION"] = "Lua 5.3" } local unexpectedStrings = {} local expectedNumbers = { Shape_Box = 0, Shape_BoxRounded = 1, Shape_Circle = 2, Shape_Image = 3, Shape_Line = 4, Shape_Polygon = 5, Shape_Text = 6, AlignH_Left = 0, AlignH_Center = 1, AlignH_Right = 2, AlignV_Ascender = 0, AlignV_Top = 1, AlignV_Middle = 2, AlignV_Baseline = 3, AlignV_Bottom = 4, AlignV_Descender = 5, } local unexpectedNumbers = {} local other = {} for key, value in pairs(_ENV) do if type(value) == "function" then for index, name in pairs(expectedFunctions) do if key == name then table.remove(expectedFunctions, index) goto continueOuter end end local functionDescription = key -- unknown function, try to get parameters -- taken from hdparm's global dump script posted on forum local dump_success, dump_result = pcall(string.dump, value) if dump_success then local params = string.match(dump_result, "function%s+[^%s)]*" .. key .. "%s*%(([^)]*)%)") if params then params = params:gsub(",%s+", ",") -- remove whitespace after function parameter names functionDescription = string.format("%s(%s)", functionDescription, params) end end table.insert(unexpectedFunctions, functionDescription) elseif type(value) == "table" then for index, name in pairs(expectedTables) do if key == name then table.remove(expectedTables, index) goto continueOuter end end table.insert(unexpectedTables, key) elseif type(value) == "string" then local expected = expectedStrings[key] if expected then expectedStrings[key] = nil if expected == value then goto continueOuter end end table.insert(unexpectedStrings, string.format("%s=%s (%s)", key, value, expected)) elseif type(value) == "number" then local expected = expectedNumbers[key] if expected then expectedNumbers[key] = nil if expected == value then goto continueOuter end end table.insert(unexpectedNumbers, string.format("%s=%s (%s)", key, value, expected)) else table.insert(other, string.format("%s(%s)", key, type(value))) end ::continueOuter:: end local message = "" if #expectedFunctions > 0 then message = message .. "Missing expected functions. " .. table.concat(expectedFunctions, ", ") .. "\n" end if #unexpectedFunctions > 0 then message = message .. "Found unexpected functions. " .. table.concat(unexpectedFunctions, ", ") .. "\n" end if #expectedTables > 0 then message = message .. "Missing expected tables. " .. table.concat(expectedTables, ", ") .. "\n" end if #unexpectedTables > 0 then message = message .. "Found unexpected tables. " .. table.concat(unexpectedTables, ", ") .. "\n" end -- table with keys set has to be iterated local function tableLength(input) local count = 0 for _ in pairs(input) do count = count + 1 end return count end if tableLength(expectedStrings) > 0 then message = message .. "Missing expected strings. " for key, value in pairs(expectedNumbers) do message = message .. string.format("%s=%s, ", key, value) end message = message .. "\n" end if #unexpectedStrings > 0 then message = message .. "Found unexpected strings. " .. table.concat(unexpectedStrings, ", ") .. "\n" end if tableLength(expectedNumbers) > 0 then message = message .. "Missing expected numbers. " for key, value in pairs(expectedNumbers) do message = message .. string.format("%s=%s, ", key, value) end message = message .. "\n" end if #unexpectedNumbers > 0 then message = message .. "Found unexpected numbers. " .. table.concat(unexpectedNumbers, ", ") .. "\n" end if #other > 0 then message = message .. "Found other entries. " .. table.concat(other, ", ") .. "\n" end if message:len() > 0 then logMessage(message) error(message) end --------------- -- copy from here to renderer --------------- _ENV = oldEnv end os.exit(lu.LuaUnit.run())
---------------------------------------------------------------------------- -- channelwatch.lua v0.02 -- by Jason D. Ozubko - 2012,2018 (jdozubko@gmail.com) ---------------------------------------------------------------------------- -- This script file should be placed in the proper VLC playlist parser directory -- For information about where this is, see: -- -- http://wiki.videolan.org/Documentation:Play_HowTo/Building_Lua_Playlist_Scripts -- -- This script processes and plays .channel files. The format for these files -- is simply the filenames of each video file, and the duration of the video, -- for each video that you want to be in the programming for that channel. -- For example, "example.channel" might contain: -- -- foo.mp4 -- 10:21 -- bar.mov -- 43:17 -- -- Based on the day's date, the script will make a playlist of 30 hours of -- programming out of the video files in the .channel file. The script will then -- grab the current time, and set VLC to the proper position in the playlist and -- in the video file, down to the second. -- -- So for example, if the playlist loads and is in the middle of playing foo.mp4 -- and you then close VLC. If you reopen VLC 2 minutes later, and reload the -- same .channel file, the player will still be showing foo, but will be 2 -- minutes further along in the show. -- -- To create different channels, fill up .channel files with different video -- files. To create different versions of the same channel put a different -- 3 digit number on the first line of the .channel file. This digit acts as -- a random seed that the script uses to build the daily schedule. -- -- (modified from randomseek.lua by HostileFork, Sept 2011) function probe() -- tell VLC we will handle anything ending in ".channel" return string.match(vlc.path, ".channel$") end function parse() -- if there is a playlist already, then clear it if vlc.playlist ~= nil then vlc.playlist.clear() end --STEP 1. LOAD IN ALL FILES IN THE .CHANNEL FILE -- fulllist will contain a list of ALL the media files in the .channel fulllist = {} nfulllist = 0 -- default channel number... used as a random seed when shuffling the playlist channum = 0 -- set a flag to indicate that the first line doesn't need to be re-read skipfirst = true -- read a line from the .channel file line = vlc.readline() -- if the length is 3 digits or less... if string.len(line) <= 3 then -- try to use this as our channel number channum = tonumber(line) if channum == nil then channum = 0 end -- we don't need to skip reading the first line skipfirst = false end -- loop through the list... all_done = false while all_done == false do -- if firstread flag is not true, then go ahead and read if skipfirst == false then while true do -- read a line from the .channel file line = vlc.readline() -- make sure we don't have an empty line if line ~= "" then break end end end -- set the skipfirst flag... we're going to read from now on skipfirst = false -- if that line does not exist... if line == nil then break --we're done reading the file end -- get the first character of the line l = string.sub(line, 1, 1) -- if we have a number... if l == '0' or l == '1' or l == '2' or l == '3' or l == '4' or l == '5' or l == '6' or l == '7' or l == '8' or l == '9' then --the file somehow got misaligned... skip this entry -- we don't have a number else -- create an empty item for entry list_item = {} -- create a loop to find a valid entry item while true do -- use line as the file name list_item.path = "file:///"..line while true do -- read a line from the .channel file line = vlc.readline() -- make sure we don't have an empty line if line ~= "" then break end end -- if that line does not exist... if line == nil then all_done = true break --we're done reading the file end -- else, get the first character of the line l = string.sub(line, 1, 1) -- if we have a number... if l == '0' or l == '1' or l == '2' or l == '3' or l == '4' or l == '5' or l == '6' or l == '7' or l == '8' or l == '9' then -- debug --vlc.msg.info( "!!!FOUND!!! " .. list_item.path .. " > " .. line ) -- read in the duration in seconds for _hour, _min, _sec in string.gmatch( line, "(%d*):(%d*):(%d*)" ) do list_item.duration = (60 * 60 * _hour) + (60 * _min) + _sec end -- add the list item to the full list table.insert( fulllist, list_item ) nfulllist = nfulllist + 1 -- quit the entry loop break -- else we have a file name... else -- do nothing here, we'll loop back and consider this new file name as an entry -- debug --vlc.msg.info( "!!!FAILED AT!!! " .. line ) end end -- entry loop end end -- all_done loop -- STEP 2. RANDOMIZE THE ORDER OF THE FULLLIST ARRAY -- get the current date cdate = os.date("*t") -- calculate the current second csec = (60 * 60 * cdate.hour) + (60 * cdate.min) + cdate.sec -- based on the current date, calculate the current day we are on -- (note, that between midnight and 6am we consider it "yesterday") -- (this means that media lists are made each day for 6am to 5:59am (next day)) if cdate.hour <= 6 then rseed = (cdate.yday-1) + ((cdate.year - 2012 + (100 * channum)) * 366) else rseed = cdate.yday + ((cdate.year - 2012 + (100 * channum)) * 366) end -- seed the random number with the current day we're on... -- (ensures a unique program schedule every day forever) math.randomseed(rseed) -- shuffle the fullist for i = nfulllist, 1, -1 do -- backwards local r = math.random(nfulllist) -- select a random number between 1 and i fulllist[i], fulllist[r] = fulllist[r], fulllist[i] -- swap the randomly selected item to position i end -- STEP 3. START LOADING IN VIDEO FILES UNTIL WE GET TO THE CURRENT TIME -- current time of the channel last_duration = 0 total_duration = 0 curidx = 1 -- debug --vlc.msg.info( "!!!DEBUG!!! csec: " .. tostring(csec) ) -- loop forever... while true do -- if we are currently probing past the end of the fulllist if curidx > nfulllist then curidx = 1 end -- add the duration of the probed item to the total if fulllist[curidx].duration ~= nil then last_duration = total_duration total_duration = last_duration + fulllist[curidx].duration end --debug --vlc.msg.info( "!!!ADDING!!! "..fulllist[curidx].path.." dur: " .. tostring(total_duration) ) -- see if we're now past the current time if total_duration > csec then break -- we're done end -- increment the index of the probe item curidx = curidx + 1 end -- STEP 4. LOAD THE FIRST ITEM INTO THE PLAYLIST AT CURRENT TIME -- start with a blank playlist playlist = {} -- the start time will be the last duration minus the current seconds start_time = csec - last_duration -- make sure we have a valid start time if start_time < 0 then start_time = 0 end -- add the start/stop time properties fulllist[curidx].options = {} table.insert(fulllist[curidx].options, "start-time="..tostring(start_time)) table.insert(fulllist[curidx].options, "stop-time="..tostring(fulllist[curidx].duration)) -- add the item to the playlist as the first item table.insert( playlist, fulllist[curidx] ) -- STEP 5. ADD IN ALL REMAINING ITEMS UNTIL WE HIT A 30 HR PLAYLIST -- now loop until we hit 24 hrs + 6 hrs while true do -- increment the current index curidx = curidx + 1 -- if we are currently probing past the end of the fulllist if curidx > nfulllist then curidx = 1 end if fulllist[curidx].duration ~= nil then -- add the next item to the playlist table.insert( playlist, fulllist[curidx] ) -- update the duration total_duration = total_duration + fulllist[curidx].duration end -- check if we're past 30 hours yet if total_duration > 0 then break end end -- give VLC the playlist return playlist end
local Los = require "plugin.wattageTileEngine.lineOfSight" local ObjectSystem = require "plugin.wattageTileEngine.objectSystem" local Utils = require "plugin.wattageTileEngine.utils" local min = math.min local sqrt = math.sqrt local AggregateLightTransitioner = {} AggregateLightTransitioner.new = function(params) local self = {} self.index = params.index local aggregateLightByCoordinate = params.aggregateLightByCoordinate local transitionerTargetCoordinates = params.transitionerTargetCoordinates self.row = params.row self.column = params.column local startR = params.startR local startG = params.startG local startB = params.startB local endR = params.endR local endG = params.endG local endB = params.endB local transitionTime = params.transitionTime self.transitionerIndexesForRemoval = params.transitionerIndexesForRemoval local elapsedTime = 0 local diffR = endR - startR local diffG = endG - startG local diffB = endB - startB local curR = startR local curG = startG local curB = startB function self.resetIfChanged(params) if endR ~= params.endR or endG ~= params.endG or endB ~= params.endB then startR = curR startG = curG startB = curB endR = params.endR endG = params.endG endB = params.endB diffR = endR - startR diffG = endG - startG diffB = endB - startB elapsedTime = 0 end end function self.getEndRGB() return {r = endR, g = endG, b = endB} end function self.forceFinish() elapsedTime = transitionTime self.update(0) end function self.update(deltaTime) elapsedTime = elapsedTime + deltaTime curR = startR + (elapsedTime / transitionTime) * diffR curG = startG + (elapsedTime / transitionTime) * diffG curB = startB + (elapsedTime / transitionTime) * diffB if elapsedTime >= transitionTime then curR = endR curG = endG curB = endB startR = endR startG = endG startB = endB table.insert(self.transitionerIndexesForRemoval, self.index) table.insert(transitionerTargetCoordinates, {row = self.row, column = self.column}) else table.insert(transitionerTargetCoordinates, {row = self.row, column = self.column}) end local columns = aggregateLightByCoordinate[self.row] if columns == nil then columns = {} aggregateLightByCoordinate[self.row] = columns end local cell = columns[self.column] if cell == nil then cell = {} columns[self.column] = cell end cell.r = curR cell.g = curG cell.b = curB end return self end local LightingModel = {} LightingModel.objectType = "LightingModel" LightingModel.new = function(params) local requireParams = Utils.requireParams requireParams({ "isTransparent", "isTileAffectedByAmbient", "useTransitioners", "compensateLightingForViewingPosition" }, params) local isTransparentCallback = params.isTransparent local isTileAffectedByAmbientCallback = params.isTileAffectedByAmbient local useTransitioners = params.useTransitioners local compensateLightingForViewingPosition = params.compensateLightingForViewingPosition local self = ObjectSystem.Object.new({objectType=LightingModel.objectType}) -- Tracks next available light ID to assign to new lights local nextLightId -- Instance of line of sight module local lineOfSight -- Ambient Light local ambientRed local ambientGreen local ambientBlue local ambientIntensity -- Dirty coordinates local ambientLightChanged -- This is true if the ambient lighting has changed. This is necessary since a change in the ambient lighting changes all lighting tiles and requires a resync with the tile engine. local dirtyAggregateUniqueIndex -- This is a table of tables. The existence of a value in the table indicates that that coordinate has already been marked as dirty. local dirtyAggregateRows -- An array of row coordinates for dirty aggregate tiles. local dirtyAggregateColumns -- An array of column coordinates for dirty aggregate tiles. local dirtyAggregateIndex -- Tracks the next available index for dirtyAggregateRows and dirtyAggregateColumns. -- Stores aggregate light values local aggregateLightByCoordinate -- This is a table of tables representing rows of columns. Each coordinate stores the corresponding aggregated lighting value. local transparencyStateByRow -- Stores the aggregate light transitioners local aggregateLightTransitionerByCoordinate -- This stores the transitioners for aggregate lighting. local activeTransitioners -- Stores the active transitioners local transitionerIndexesForRemoval -- Stores the indexes of the transitioners that can be removed from the active transitioner list. local transitionerTargetCoordinates -- Stores tile coordinates of the tiles affected by the transitioners. This is necessary to notify tiles to update their tint. -- Stores IDs for dirty lights local dirtyLightIds -- This table stores the IDs of all lights that have been made dirty. -- Stores lights indexed by their ID local lightsById -- Index of IDs to lights. -- Stores affected areas for each light by ID local affectedAreasByLightId -- Stores table of tables representing rows and columns of tiles holding data for how the light would affect that tile. -- Tracks current affected area for use in the callback local curLight -- Reference to current light used during processing local curAffectedArea -- Reference to current affected area used during processing -- Marks the tile at the row/column coordinate as dirty and ensures uniqueness of entries. local function markDirtyAggregateTile(row, column) local uniqueRowIndex = dirtyAggregateUniqueIndex[row] if uniqueRowIndex ~= nil then if uniqueRowIndex[column] then return end else uniqueRowIndex = {} dirtyAggregateUniqueIndex[row] = uniqueRowIndex end uniqueRowIndex[column] = true dirtyAggregateRows[dirtyAggregateIndex] = row dirtyAggregateColumns[dirtyAggregateIndex] = column dirtyAggregateIndex = dirtyAggregateIndex + 1 end -- Convenience function to clamp a value to a specified range. local function clamp(v, min, max) if v < min then return min end if v > max then return max end return v end -- Callback to light affected area local function fovCallback(x, y, distanceSquared, isTransparent) -- Record state of transparency if compensating for viewing position if compensateLightingForViewingPosition then local transparencyStateRow = transparencyStateByRow[y] if transparencyStateRow == nil then transparencyStateRow = {} transparencyStateByRow[y] = transparencyStateRow end transparencyStateRow[x] = isTransparent end local curAffectedRow = curAffectedArea[y] if curAffectedRow == nil then curAffectedRow = {} curAffectedArea[y] = curAffectedRow end -- New equation simple local attenuation = clamp(1.0 - distanceSquared / (curLight.radius * curLight.radius), 0, 1) attenuation = attenuation * attenuation -- New equation not as simple -- local attenuation = clamp(1.0 - ((distance * distance) / (curLight.radius * curLight.radius)), 0, 1) -- attenuation = attenuation * attenuation local adjustedIntensity = curLight.intensity * attenuation if adjustedIntensity > 0 then curLight.affectedRows[curLight.affectedIndex] = y curLight.affectedColumns[curLight.affectedIndex] = x curLight.affectedIndex = curLight.affectedIndex + 1 curAffectedRow[x] = { adjustedIntensity = adjustedIntensity } markDirtyAggregateTile(y, x) end end -- Inserts light ID into the dirty list if it does not already exist. local function markLightAsDirty(lightId) local found = false for i=1,#dirtyLightIds do if lightId == dirtyLightIds[i] then found = true end end if not found then table.insert(dirtyLightIds, lightId) end end -- Marks all lights as dirty local function markAllLightsAsDirty() dirtyLightIds = {} local index = 1 for k,v in pairs(lightsById) do dirtyLightIds[index] = k index = index + 1 end end -- Marks the affected tiles of the light as dirty local function markAggregateTilesAffectedByLightAsDirty(id) local light = lightsById[id] local affectedRows = light.affectedRows local affectedColumns = light.affectedColumns for i=1,light.affectedIndex - 1 do markDirtyAggregateTile(affectedRows[i], affectedColumns[i]) end end -- Marks the corresponding aggregate tile as dirty for each of the current affected tiles of all lights local function markAllAggregateTilesAffectedByLightAsDirty() for id,light in pairs(lightsById) do local affectedRows = light.affectedRows local affectedColumns = light.affectedColumns for i=1,light.affectedIndex - 1 do markDirtyAggregateTile(affectedRows[i], affectedColumns[i]) end end end function self.setUseTransitioners(useTransitionersParam) useTransitioners = useTransitionersParam if not useTransitioners then for i=1,#activeTransitioners do activeTransitioners[i].forceFinish() end for i=1,#transitionerTargetCoordinates do local coordinate = transitionerTargetCoordinates[i] markDirtyAggregateTile(coordinate.row, coordinate.column) end end end -- Will result in all aggregate tiles affected by light as dirty and set the ambientLightChanged flag to true function self.setAmbientLight(red, green, blue, intensity) if ambientRed ~= red or ambientGreen ~= green or ambientBlue ~= blue or ambientIntensity ~= intensity then ambientRed = red ambientGreen = green ambientBlue = blue ambientIntensity = intensity markAllAggregateTilesAffectedByLightAsDirty() ambientLightChanged = true end end function self.markChangeInTransparency(row, column) self.markLightAsDirtyIfAffectedAreaContainsTile(row, column) -- clear transparency cache local transparencyRow = transparencyStateByRow[row] if transparencyRow ~= nil then transparencyRow[column] = nil end end function self.getAmbientLight() return { r = min(ambientRed * ambientIntensity, 1), g = min(ambientGreen * ambientIntensity, 1), b = min(ambientBlue * ambientIntensity, 1), intensity = ambientIntensity } end function self.update(deltaTime) --region Update transitioners -- update transitioners for i=1,#activeTransitioners do activeTransitioners[i].update(deltaTime) end -- sort indexes table.sort(transitionerIndexesForRemoval) -- remove indexes for i=#transitionerIndexesForRemoval,1,-1 do local indexToRemove = transitionerIndexesForRemoval[i] local transitionerForRemoval = activeTransitioners[indexToRemove] if transitionerForRemoval ~= nil then markDirtyAggregateTile(transitionerForRemoval.row, transitionerForRemoval.column) aggregateLightTransitionerByCoordinate[transitionerForRemoval.row][transitionerForRemoval.column] = nil table.remove(activeTransitioners, indexToRemove) end end transitionerIndexesForRemoval = {} for i=1,#activeTransitioners do activeTransitioners[i].transitionerIndexesForRemoval = transitionerIndexesForRemoval end -- reset indexes for i=1,#activeTransitioners do activeTransitioners[i].index = i end --endregion --region Mark dirty aggregate coords resulting from dirty lights -- and clear current light affected areas for k,lightId in pairs(dirtyLightIds) do local light = lightsById[lightId] local affectedRows = light.affectedRows local affectedColumns = light.affectedColumns local affectedAreas = affectedAreasByLightId[lightId] if affectedAreas ~= nil then for curAffectedIndex=1,light.affectedIndex - 1 do local row = affectedRows[curAffectedIndex] local affectedRow = affectedAreas[row] if affectedRow ~= nil then local column = affectedColumns[curAffectedIndex] if affectedRow[column] ~= nil then markDirtyAggregateTile(row, column) end end end affectedAreasByLightId[lightId] = {} end light.affectedRows = {} light.affectedColumns = {} light.affectedIndex = 1 end --endregion --region Update affected areas for dirty lights for k,lightId in pairs(dirtyLightIds) do curLight = lightsById[lightId] curAffectedArea = affectedAreasByLightId[lightId] if curAffectedArea == nil then curAffectedArea = {} affectedAreasByLightId[lightId] = curAffectedArea end lineOfSight.calculateFov({ startX = curLight.column, startY = curLight.row, radius = curLight.radius }) end --endregion --region Aggregate dirty light data -- First get bounding region for dirty tiles local minRow local maxRow local minCol local maxCol for i=1,dirtyAggregateIndex - 1 do if minRow == nil then minRow = dirtyAggregateRows[i] maxRow = minRow minCol = dirtyAggregateColumns[i] maxCol = minCol else local curRow = dirtyAggregateRows[i] local curCol = dirtyAggregateColumns[i] if curRow < minRow then minRow = curRow end if curRow > maxRow then maxRow = curRow end if curCol < minCol then minCol = curCol end if curCol > maxCol then maxCol = curCol end end end local trimmedAffectedAreas = {} if minRow ~= nil then local halfWidth = (maxCol - minCol) / 2 local halfHeight = (maxRow - minRow) / 2 local boundingCenterCol = minCol + halfWidth local boundingCenterRow = minRow + halfHeight local boundingRadius = sqrt(halfWidth * halfWidth + halfHeight * halfHeight) for lightId,area in pairs(affectedAreasByLightId) do local light = lightsById[lightId] local lightRadius = light.radius local distanceRows = boundingCenterRow - light.row local distanceCols = boundingCenterCol - light.column local distance = sqrt(distanceRows * distanceRows + distanceCols * distanceCols) if distance <= boundingRadius + lightRadius then table.insert(trimmedAffectedAreas, { light = light, area = area }) end end end for i=1,dirtyAggregateIndex - 1 do local aggregateRow = dirtyAggregateRows[i] local aggregateCol = dirtyAggregateColumns[i] local aggregateR = 0 local aggregateG = 0 local aggregateB = 0 --region Calculate aggregate value local isAffectedByLight = false for i=1,#trimmedAffectedAreas do local entry = trimmedAffectedAreas[i] local areaRow = entry.area[aggregateRow] if areaRow ~= nil then local areaTile = areaRow[aggregateCol] if areaTile ~= nil then local light = entry.light local intensity = areaTile.adjustedIntensity aggregateR = min(aggregateR + light.r * intensity, 1) aggregateG = min(aggregateG + light.g * intensity, 1) aggregateB = min(aggregateB + light.b * intensity, 1) isAffectedByLight = true end end end --endregion --region Store aggregate value local aggregateRowArray = aggregateLightByCoordinate[aggregateRow] if aggregateRowArray == nil then aggregateRowArray = {} aggregateLightByCoordinate[aggregateRow] = aggregateRowArray end local cell = aggregateRowArray[aggregateCol] if not isAffectedByLight then local transitionerRow = aggregateLightTransitionerByCoordinate[aggregateRow] if transitionerRow == nil then transitionerRow = {} aggregateLightTransitionerByCoordinate[aggregateRow] = transitionerRow end local transitioner = transitionerRow[aggregateCol] -- No light data, clear the aggregate value or update transitioner if not useTransitioners or transitioner == nil then aggregateRowArray[aggregateCol] = nil else if isTileAffectedByAmbientCallback(aggregateRow, aggregateCol) then transitioner.resetIfChanged({ endR = ambientRed * ambientIntensity, endG = ambientGreen * ambientIntensity, endB = ambientBlue * ambientIntensity }) else transitioner.resetIfChanged({ endR = 0, endG = 0, endB = 0 }) end end else local newR local newG local newB if isTileAffectedByAmbientCallback(aggregateRow, aggregateCol) then newR = min(ambientRed * ambientIntensity + aggregateR, 1) newG = min(ambientGreen * ambientIntensity + aggregateG, 1) newB = min(ambientBlue * ambientIntensity + aggregateB, 1) else newR = aggregateR newG = aggregateG newB = aggregateB end if cell == nil or not useTransitioners then aggregateRowArray[aggregateCol] = { r = newR, g = newG, b = newB } else local transitionerRow = aggregateLightTransitionerByCoordinate[aggregateRow] if transitionerRow == nil then transitionerRow = {} aggregateLightTransitionerByCoordinate[aggregateRow] = transitionerRow end local transitioner = transitionerRow[aggregateCol] if transitioner == nil then transitioner = AggregateLightTransitioner.new({ index = #activeTransitioners, aggregateLightByCoordinate = aggregateLightByCoordinate, transitionerTargetCoordinates = transitionerTargetCoordinates, row = aggregateRow, column = aggregateCol, startR = cell.r, startG = cell.g, startB = cell.b, endR = newR, endG = newG, endB = newB, transitionTime = 250, transitionerIndexesForRemoval = transitionerIndexesForRemoval }) transitionerRow[aggregateCol] = transitioner table.insert(activeTransitioners, transitioner) else transitioner.resetIfChanged({ endR = newR, endG = newG, endB = newB }) end end end --endregion end --endregion --After processing tiles which need full aggregate computations, add the ones managed by the transitioners to the list. for i=1,#transitionerTargetCoordinates do local coordinate = transitionerTargetCoordinates[i] markDirtyAggregateTile(coordinate.row, coordinate.column) end end -- todo rename this to resetDirtyFlagsAndIndexes function self.resetDirtyFlags() dirtyLightIds = {} ambientLightChanged = false dirtyAggregateUniqueIndex = {} dirtyAggregateRows = {} dirtyAggregateColumns = {} dirtyAggregateIndex = 1 for i=1,#transitionerTargetCoordinates do transitionerTargetCoordinates[i] = nil end end function self.addLight(params) requireParams({"row","column","r","g","b","intensity","radius"}, params) -- Fetch next light id and increment to the next value local lightId if params.lightId ~= nil then lightId = params.lightId else lightId = nextLightId nextLightId = nextLightId + 1 end -- Add the light ID to the dirty list table.insert(dirtyLightIds, lightId) -- Add the light lightsById[lightId] = { row = params.row, column = params.column, r = params.r, g = params.g, b = params.b, intensity = params.intensity, radius = params.radius, affectedRows = {}, affectedColumns = {}, affectedIndex = 1 } return lightId end -- todo expand interface to allow changing color, intensity, radius, or any attribute of the light function self.updateLight(params) requireParams({"lightId","newRow","newColumn"}, params) local newRow = params.newRow local newColumn = params.newColumn local light = lightsById[params.lightId] if newRow ~= light.row or newColumn ~= light.column then light.row = newRow light.column = newColumn markLightAsDirty(params.lightId) end end function self.removeLight(lightId) markAggregateTilesAffectedByLightAsDirty(lightId) lightsById[lightId] = nil affectedAreasByLightId[lightId] = nil end function self.getLightProperties(lightId) local props local light = lightsById[lightId] if light ~= nil then props = {} props.row = light.row props.column = light.column props.r = light.r props.g = light.g props.b = light.b props.intensity = light.intensity props.radius = light.radius end return props end function self.markLightAsDirtyIfAffectedAreaContainsTile(row, col) for lightId, light in pairs(lightsById) do local affectedArea = affectedAreasByLightId[lightId] local affectedRow = affectedArea[row] if affectedRow ~= nil then local affectedColumn = affectedRow[col] if affectedColumn ~= nil then markLightAsDirty(lightId) end end end end local function checkTransparent(row, col) local transparent = true local transparencyStateRow = transparencyStateByRow[row] if transparencyStateRow ~= nil then local isTransparent = transparencyStateRow[col] if isTransparent == false then transparent = false elseif isTransparent == nil then transparent = isTransparentCallback(col, row) end else transparent = isTransparentCallback(col, row) end return transparent end function self.getAggregateLightIfRowColumnOpaque(row, col, viewRow, viewCol) local light if not checkTransparent(row, col) then local totalR = 0 local totalG = 0 local totalB = 0 local total = 0 if viewRow >= row then if viewCol >= col then -- bottom right if checkTransparent(row, col + 1) then local l1 = self.getAggregateLight(row, col + 1) if l1 ~= nil then totalR = totalR + l1.r totalG = totalG + l1.g totalB = totalB + l1.b total = total + 1 end end if checkTransparent(row + 1, col + 1) then local l2 = self.getAggregateLight(row + 1, col + 1) if l2 ~= nil then totalR = totalR + l2.r totalG = totalG + l2.g totalB = totalB + l2.b total = total + 1 end end if checkTransparent(row + 1, col) then local l3 = self.getAggregateLight(row + 1, col) if l3 ~= nil then totalR = totalR + l3.r totalG = totalG + l3.g totalB = totalB + l3.b total = total + 1 end end else -- bottom left if checkTransparent(row, col - 1) then local l1 = self.getAggregateLight(row, col - 1) if l1 ~= nil then totalR = totalR + l1.r totalG = totalG + l1.g totalB = totalB + l1.b total = total + 1 end end if checkTransparent(row + 1, col - 1) then local l2 = self.getAggregateLight(row + 1, col - 1) if l2 ~= nil then totalR = totalR + l2.r totalG = totalG + l2.g totalB = totalB + l2.b total = total + 1 end end if checkTransparent(row + 1, col) then local l3 = self.getAggregateLight(row + 1, col) if l3 ~= nil then totalR = totalR + l3.r totalG = totalG + l3.g totalB = totalB + l3.b total = total + 1 end end end else if viewCol >= col then -- top right if checkTransparent(row - 1, col) then local l1 = self.getAggregateLight(row - 1, col) if l1 ~= nil then totalR = totalR + l1.r totalG = totalG + l1.g totalB = totalB + l1.b total = total + 1 end end if checkTransparent(row - 1, col + 1) then local l2 = self.getAggregateLight(row - 1, col + 1) if l2 ~= nil then totalR = totalR + l2.r totalG = totalG + l2.g totalB = totalB + l2.b total = total + 1 end end if checkTransparent(row, col + 1) then local l3 = self.getAggregateLight(row, col + 1) if l3 ~= nil then totalR = totalR + l3.r totalG = totalG + l3.g totalB = totalB + l3.b total = total + 1 end end else -- top left if checkTransparent(row - 1, col) then local l1 = self.getAggregateLight(row - 1, col) if l1 ~= nil then totalR = totalR + l1.r totalG = totalG + l1.g totalB = totalB + l1.b total = total + 1 end end if checkTransparent(row - 1, col - 1) then local l2 = self.getAggregateLight(row - 1, col - 1) if l2 ~= nil then totalR = totalR + l2.r totalG = totalG + l2.g totalB = totalB + l2.b total = total + 1 end end if checkTransparent(row, col - 1) then local l3 = self.getAggregateLight(row, col - 1) if l3 ~= nil then totalR = totalR + l3.r totalG = totalG + l3.g totalB = totalB + l3.b total = total + 1 end end end end light = { r = totalR / total, g = totalG / total, b = totalB / total } end return light end function self.getAggregateLight(row, col) local light local rowArray = aggregateLightByCoordinate[row] if rowArray ~= nil then light = rowArray[col] end -- Return a default ambient light if no aggregate data is found if light == nil and isTileAffectedByAmbientCallback(row, col) then light = { r=ambientRed * ambientIntensity, g=ambientGreen * ambientIntensity, b=ambientBlue * ambientIntensity } elseif light == nil then light = { r=0, g=0, b=0 } end return light end function self.getDirtyAggregateRows() return dirtyAggregateRows end function self.getDirtyAggregateColumns() return dirtyAggregateColumns end function self.getDirtyAggregateCount() return dirtyAggregateIndex - 1 end function self.hasDirtyAggregateTile() return dirtyAggregateIndex > 1 end function self.hasAmbientLightChanged() return ambientLightChanged end function self.setIsTransparentCallback(callback) isTransparentCallback = callback lineOfSight.setIsTransparentCallback(callback) end function self.setIsTileAffectedByAmbientCallback(callback) isTileAffectedByAmbientCallback = callback end local parentSave = self.save function self.save(diskStream) parentSave(diskStream) diskStream.write(useTransitioners) diskStream.write(compensateLightingForViewingPosition) diskStream.write(nextLightId) diskStream.write(ambientRed) diskStream.write(ambientGreen) diskStream.write(ambientBlue) diskStream.write(ambientIntensity) local lightCount = 0 for k,v in pairs(lightsById) do lightCount = lightCount + 1 end diskStream.write(lightCount) for lightId,light in pairs(lightsById) do diskStream.write(lightId) diskStream.write(light.row) diskStream.write(light.column) diskStream.write(light.r) diskStream.write(light.g) diskStream.write(light.b) diskStream.write(light.intensity) diskStream.write(light.radius) end end local parentLoad = self.load function self.load(diskStream) parentLoad(diskStream) useTransitioners = diskStream.read() compensateLightingForViewingPosition = diskStream.read() nextLightId = diskStream.read() ambientRed = diskStream.read() ambientGreen = diskStream.read() ambientBlue = diskStream.read() ambientIntensity = diskStream.read() local lightCount = diskStream.read() for i=1,lightCount do local lightId = diskStream.read() local row = diskStream.read() local column = diskStream.read() local r = diskStream.read() local g = diskStream.read() local b = diskStream.read() local intensity = diskStream.read() local radius = diskStream.read() self.addLight({ lightId = lightId, row = row, column = column, r = r, g = g, b = b, intensity = intensity, radius = radius }) end end local function initialize() lineOfSight = Los.new({ maxRadius = 20, isTransparent = isTransparentCallback, fovCallback = fovCallback }) nextLightId = 0 ambientRed = 1 ambientGreen = 1 ambientBlue = 1 ambientIntensity = 0.3 ambientLightChanged = false dirtyAggregateUniqueIndex = {} dirtyAggregateRows = {} dirtyAggregateColumns = {} dirtyAggregateIndex = 1 aggregateLightByCoordinate = {} transparencyStateByRow = {} dirtyLightIds = {} lightsById = {} affectedAreasByLightId = {} aggregateLightTransitionerByCoordinate = {} activeTransitioners = {} transitionerIndexesForRemoval = {} transitionerTargetCoordinates = {} end initialize() return self end ObjectSystem.Factory.registerForType(LightingModel.objectType, LightingModel.new) return LightingModel
vim.o.completeopt = 'menuone,noselect' -- Completion options (for deoplete) local lspkind = require "lspkind" lspkind.init() -- Setup nvim-cmp. local cmp = require('cmp') cmp.setup({ snippet = { -- REQUIRED - you must specify a snippet engine expand = function(args) vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users. -- require('luasnip').lsp_expand(args.body) -- For `luasnip` users. -- vim.fn["UltiSnips#Anon"](args.body) -- For `ultisnips` users. -- require'snippy'.expand_snippet(args.body) -- For `snippy` users. end, }, mapping = { ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }), ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }), ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }), ['<C-y>'] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping. ['<C-e>'] = cmp.mapping({ i = cmp.mapping.abort(), c = cmp.mapping.close(), }), ['<CR>'] = cmp.mapping.confirm({ select = true }), -- If you want tab completion :'( -- First you have to just promise to read `:help ins-completion`. ["<Tab>"] = function(fallback) if cmp.visible() then cmp.select_next_item() else fallback() end end, ["<S-Tab>"] = function(fallback) if cmp.visible() then cmp.select_prev_item() else fallback() end end, }, sources = cmp.config.sources({ { name = 'nvim_lsp' }, -- { name = 'vsnip' }, -- For vsnip users. { name = 'luasnip' }, -- For luasnip users. -- { name = 'ultisnips' }, -- For ultisnips users. -- { name = 'snippy' }, -- For snippy users. }, { { name = 'buffer' }, }), formatting = { -- Youtube: How to set up nice formatting for your sources. format = lspkind.cmp_format { with_text = true, menu = { buffer = "[buf]", nvim_lsp = "[LSP]", nvim_lua = "[api]", path = "[path]", luasnip = "[snip]", gh_issues = "[issues]", tn = "[TabNine]", }, }, }, experimental = { -- I like the new menu better! Nice work hrsh7th native_menu = true, -- Let's play with this for a day or two -- ghost_text = false, }, }) -- -- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore). -- cmp.setup.cmdline('/', { -- sources = { -- { name = 'buffer' } -- } -- }) -- -- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore). -- cmp.setup.cmdline(':', { -- sources = cmp.config.sources({ -- { name = 'path' } -- }, { -- { name = 'cmdline' } -- }) -- }) -- Setup lspconfig. local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()) -- Replace <YOUR_LSP_SERVER> with each lsp server you've enabled. require('lspconfig')['eslint'].setup { capabilities = capabilities } require('lspconfig')['sumneko_lua'].setup { capabilities = capabilities }
--Arquivo init.lua --Autor: Elisson Andrade, 2019 dofile("login.lua") --LEDS Verdes gpio.mode(0,gpio.OUTPUT) --LEDS vermelhos, da direita para a esquerda gpio.mode(1,gpio.OUTPUT) gpio.mode(2,gpio.OUTPUT) gpio.mode(3,gpio.OUTPUT) gpio.mode(4,gpio.OUTPUT) gpio.mode(5,gpio.OUTPUT) gpio.mode(6,gpio.OUTPUT) --LED Amarelo gpio.mode(7,gpio.OUTPUT) --LED Branco gpio.mode(8,gpio.OUTPUT) function piscaCiclo(leds, intervalo) for led, valor in next, leds do if(valor == 0 or valor == 3) then gpio.write(led-1, gpio.LOW) else gpio.write(led-1, gpio.HIGH) end end tmr.delay(intervalo/2) for led, valor in next, leds do if(valor == 0 or valor == 2) then gpio.write(led-1, gpio.LOW) else gpio.write(led-1, gpio.HIGH) end end tmr.delay(intervalo/2) end function startup() if file.open("init.lua") == nil then print("init.lua deleted or renamed") else print("Running") file.close("init.lua") piscaCiclo({1,0,0,0,0,0,0,1,1},10) dofile("select.lua") end end -- Define WiFi station event callbacks wifi_connect_event = function(T) print("Connection to AP("..T.SSID..") established!") print("Waiting for IP address...") if disconnect_ct ~= nil then disconnect_ct = nil end piscaCiclo({0,0,0,0,0,0,0,1,0},10) end wifi_got_ip_event = function(T) -- Note: Having an IP address does not mean there is internet access! -- Internet connectivity can be determined with net.dns.resolve(). print("Wifi connection is ready! IP address is: "..T.IP) print("Startup will resume momentarily, you have 3 seconds to abort.") print("Waiting...") piscaCiclo({1,0,0,0,0,0,0,1,0},10) startUpTimer = tmr.create() -- JFM mod to allow abort startUpTimer:alarm(3000, tmr.ALARM_SINGLE, startup) end wifi_disconnect_event = function(T) if T.reason == wifi.eventmon.reason.ASSOC_LEAVE then --the station has disassociated from a previously connected AP return end -- total_tries: how many times the station will attempt to connect to the AP. Should consider AP reboot duration. local total_tries = 75 print("\nWiFi connection to AP("..T.SSID..") has failed!") --There are many possible disconnect reasons, the following iterates through --the list and returns the string corresponding to the disconnect reason. for key,val in pairs(wifi.eventmon.reason) do if val == T.reason then print("Disconnect reason: "..val.."("..key..")") break end end if disconnect_ct == nil then disconnect_ct = 1 else disconnect_ct = disconnect_ct + 1 end if disconnect_ct < total_tries then print("Retrying connection...(attempt "..(disconnect_ct+1).." of "..total_tries..")") else wifi.sta.disconnect() print("Aborting connection to AP!") disconnect_ct = nil end end -- Register WiFi Station event callbacks wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wifi_connect_event) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event) wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, wifi_disconnect_event) print("Connecting to WiFi access point...") wifi.setmode(wifi.STATION) wifi.sta.config({ssid=SSID, pwd=SENHA})
local Star = require('star') local StarField = {} StarField.__index = StarField setmetatable(StarField, { __call = function(cls, ...) return cls.create(...) end }) function StarField.getRandomStar(width, height) local x = math.random(-width/4, width/4) local y = math.random(-height/2, height/2) local z = math.random(width) local speed = math.random(1, 6) return Star(x, y, z, speed) end function StarField.create(width, height, numberOfStars) local starfield = { numberOfStars = numberOfStars, width = width, height = height, stars = {} } for i = 1, numberOfStars, 1 do starfield.stars[i] = StarField.getRandomStar(width, height) end return setmetatable(starfield, StarField) end function StarField:update(star, index) if (star.z <= star.speed) then self.stars[index] = StarField.getRandomStar(self.width, self.height) else star:update() end end function StarField:getStars() return self.stars end return StarField
-- DONT DELETE THIS FILE -- ITS A FAILSAVE LUA FILE!
filter {} location ( "../../build/" .. mpt_projectpathname ) filter {} preferredtoolarchitecture "x86_64" configurations { "Debug", "Release", "Checked", "DebugShared", "ReleaseShared", "CheckedShared" } platforms ( allplatforms ) filter { "platforms:x86" } system "Windows" architecture "x86" filter { "platforms:x86_64" } system "Windows" architecture "x86_64" filter { "platforms:arm" } system "Windows" architecture "ARM" filter { "platforms:arm64" } system "Windows" architecture "ARM64" filter {} function mpt_kind(mykind) if mykind == "" then -- nothing elseif mykind == "default" then filter {} filter { "configurations:Debug" } kind "StaticLib" filter { "configurations:DebugShared" } kind "SharedLib" filter { "configurations:Checked" } kind "StaticLib" filter { "configurations:CheckedShared" } kind "SharedLib" filter { "configurations:Release" } kind "StaticLib" filter { "configurations:ReleaseShared" } kind "SharedLib" filter {} elseif mykind == "shared" then kind "SharedLib" elseif mykind == "static" then kind "StaticLib" elseif mykind == "GUI" then kind "WindowedApp" if _OPTIONS["windows-version"] == "win10" then files { "../../build/vs/win10.manifest", } elseif _OPTIONS["windows-version"] == "win81" then files { "../../build/vs/win81.manifest", } elseif _OPTIONS["windows-version"] == "win7" then files { "../../build/vs/win7.manifest", } end elseif mykind == "Console" then kind "ConsoleApp" else -- nothing end end filter {} objdir ( "../../build/obj/" .. mpt_projectpathname .. "/" .. "%{prj.name}" ) filter {} filter {} if _OPTIONS["clang"] then toolset "clang" end filter {} filter {} if _OPTIONS["windows-version"] == "winxp" then if _ACTION == "vs2017" then toolset "v141_xp" end defines { "MPT_BUILD_RETRO" } filter { "action:vs*" } buildoptions { "/Zc:threadSafeInit-" } filter {} end filter {} filter {} filter {} cdialect "C17" filter { "action:vs*", "language:C++", "action:vs2017" } cppdialect "C++17" filter { "action:vs*", "language:C++", "action:vs2019" } cppdialect "C++17" filter { "action:vs*", "language:C++", "not action:vs2017", "not action:vs2019" } if _OPTIONS["clang"] then cppdialect "C++17" else cppdialect "C++20" end filter { "action:vs*", "action:vs2017" } if _OPTIONS["windows-version"] == "win10" then conformancemode "On" end filter { "action:vs*", "action:vs2017" } defines { "MPT_CHECK_CXX_IGNORE_PREPROCESSOR" } filter { "action:vs*", "not action:vs2017" } preprocessor "Standard" conformancemode "On" filter { "not action:vs*", "language:C++" } buildoptions { "-std=c++17" } filter { "not action:vs*", "language:C" } buildoptions { "-std=c17" } filter {} filter {} filter { "action:vs*" } if not _OPTIONS["clang"] and _OPTIONS["windows-version"] ~= "winxp" and _OPTIONS["windows-family"] ~= "uwp" then spectremitigations "On" end filter {} filter { "action:vs*", "architecture:x86" } resdefines { "VER_ARCHNAME=\"x86\"" } filter { "action:vs*", "architecture:x86_64" } resdefines { "VER_ARCHNAME=\"amd64\"" } filter { "action:vs*", "architecture:ARM" } resdefines { "VER_ARCHNAME=\"arm\"" } filter { "action:vs*", "architecture:ARM64" } resdefines { "VER_ARCHNAME=\"arm64\"" } filter {} filter { "kind:StaticLib" } targetdir ( "../../build/lib/" .. mpt_projectpathname .. "/%{cfg.architecture}/%{cfg.buildcfg}" ) filter { "kind:not StaticLib", "configurations:Debug", "architecture:x86" } targetdir ( "../../bin/debug/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/x86" ) filter { "kind:not StaticLib", "configurations:DebugShared", "architecture:x86" } targetdir ( "../../bin/debug/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/x86" ) filter { "kind:not StaticLib", "configurations:Checked", "architecture:x86" } targetdir ( "../../bin/checked/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/x86" ) filter { "kind:not StaticLib", "configurations:CheckedShared", "architecture:x86" } targetdir ( "../../bin/checked/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/x86" ) filter { "kind:not StaticLib", "configurations:Release", "architecture:x86" } targetdir ( "../../bin/release/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/x86" ) filter { "kind:not StaticLib", "configurations:ReleaseShared", "architecture:x86" } targetdir ( "../../bin/release/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/x86" ) filter { "kind:not StaticLib", "configurations:Debug", "architecture:x86_64" } targetdir ( "../../bin/debug/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/amd64" ) filter { "kind:not StaticLib", "configurations:DebugShared", "architecture:x86_64" } targetdir ( "../../bin/debug/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/amd64" ) filter { "kind:not StaticLib", "configurations:Checked", "architecture:x86_64" } targetdir ( "../../bin/checked/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/amd64" ) filter { "kind:not StaticLib", "configurations:CheckedShared", "architecture:x86_64" } targetdir ( "../../bin/checked/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/amd64" ) filter { "kind:not StaticLib", "configurations:Release", "architecture:x86_64" } targetdir ( "../../bin/release/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/amd64" ) filter { "kind:not StaticLib", "configurations:ReleaseShared", "architecture:x86_64" } targetdir ( "../../bin/release/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/amd64" ) filter { "kind:not StaticLib", "configurations:Debug", "architecture:ARM" } targetdir ( "../../bin/debug/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/arm" ) filter { "kind:not StaticLib", "configurations:DebugShared", "architecture:ARM" } targetdir ( "../../bin/debug/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/arm" ) filter { "kind:not StaticLib", "configurations:Checked", "architecture:ARM" } targetdir ( "../../bin/checked/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/arm" ) filter { "kind:not StaticLib", "configurations:CheckedShared", "architecture:ARM" } targetdir ( "../../bin/checked/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/arm" ) filter { "kind:not StaticLib", "configurations:Release", "architecture:ARM" } targetdir ( "../../bin/release/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/arm" ) filter { "kind:not StaticLib", "configurations:ReleaseShared", "architecture:ARM" } targetdir ( "../../bin/release/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/arm" ) filter { "kind:not StaticLib", "configurations:Debug", "architecture:ARM64" } targetdir ( "../../bin/debug/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/arm64" ) filter { "kind:not StaticLib", "configurations:DebugShared", "architecture:ARM64" } targetdir ( "../../bin/debug/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/arm64" ) filter { "kind:not StaticLib", "configurations:Checked", "architecture:ARM64" } targetdir ( "../../bin/checked/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/arm64" ) filter { "kind:not StaticLib", "configurations:CheckedShared", "architecture:ARM64" } targetdir ( "../../bin/checked/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/arm64" ) filter { "kind:not StaticLib", "configurations:Release", "architecture:ARM64" } targetdir ( "../../bin/release/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-static/arm64" ) filter { "kind:not StaticLib", "configurations:ReleaseShared", "architecture:ARM64" } targetdir ( "../../bin/release/" .. _ACTION .. "-" .. mpt_bindirsuffix .. "-shared/arm64" ) filter { "configurations:Debug", "architecture:ARM" } editandcontinue "Off" filter { "configurations:Debug", "architecture:ARM64" } editandcontinue "Off" filter { "configurations:DebugShared", "architecture:ARM" } editandcontinue "Off" filter { "configurations:DebugShared", "architecture:ARM64" } editandcontinue "Off" filter { "configurations:Debug" } defines { "DEBUG" } defines { "MPT_BUILD_DEBUG" } defines { "MPT_BUILD_MSVC_STATIC" } filter { "configurations:Debug", "architecture:ARM" } symbols "On" filter { "configurations:Debug", "architecture:ARM64" } symbols "On" filter { "configurations:Debug", "architecture:not ARM", "architecture:not ARM64" } symbols "FastLink" filter { "configurations:Debug" } if _OPTIONS["windows-family"] ~= "uwp" then staticruntime "On" end runtime "Debug" optimize "Debug" filter { "configurations:DebugShared" } defines { "DEBUG" } defines { "MPT_BUILD_DEBUG" } defines { "MPT_BUILD_MSVC_SHARED" } symbols "On" runtime "Debug" optimize "Debug" filter { "configurations:Checked" } defines { "DEBUG" } defines { "MPT_BUILD_MSVC_STATIC" } defines { "MPT_BUILD_CHECKED" } symbols "On" if _OPTIONS["windows-family"] ~= "uwp" then staticruntime "On" end runtime "Release" optimize "On" omitframepointer "Off" filter { "configurations:CheckedShared" } defines { "DEBUG" } defines { "MPT_BUILD_MSVC_SHARED" } defines { "MPT_BUILD_CHECKED" } symbols "On" runtime "Release" optimize "On" omitframepointer "Off" filter { "configurations:Release" } defines { "NDEBUG" } defines { "MPT_BUILD_MSVC_STATIC" } symbols "On" if not _OPTIONS["clang"] then flags { "LinkTimeOptimization" } end if _OPTIONS["windows-family"] ~= "uwp" then staticruntime "On" end runtime "Release" optimize "Speed" filter { "configurations:ReleaseShared" } defines { "NDEBUG" } defines { "MPT_BUILD_MSVC_SHARED" } symbols "On" if not _OPTIONS["clang"] then flags { "LinkTimeOptimization" } end runtime "Release" optimize "Speed" filter {} if not _OPTIONS["clang"] then flags { "MultiProcessorCompile" } end if _OPTIONS["windows-version"] == "winxp" then filter { "architecture:x86" } vectorextensions "IA32" filter {} else filter {} filter { "architecture:x86", "configurations:Checked" } vectorextensions "SSE2" filter { "architecture:x86", "configurations:CheckedShared" } vectorextensions "SSE2" filter { "architecture:x86", "configurations:Release" } vectorextensions "SSE2" filter { "architecture:x86", "configurations:ReleaseShared" } vectorextensions "SSE2" filter {} end filter {} defines { "MPT_BUILD_MSVC" } filter {} defines { "WIN32", "NOMINMAX", "_CRT_NONSTDC_NO_WARNINGS", "_CRT_SECURE_NO_WARNINGS", "_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1", "_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1", } filter {} if _OPTIONS["windows-version"] ~= "winxp" and _OPTIONS["windows-family"] ~= "uwp" then filter {} filter { "action:vs2017" } systemversion "10.0.17763.0" filter {} filter { "action:vs2019" } systemversion "10.0.20348.0" filter {} filter { "action:vs2022" } systemversion "10.0.20348.0" filter {} end if _OPTIONS["windows-version"] == "win10" then filter {} defines { "_WIN32_WINNT=0x0A00" } filter {} filter { "architecture:x86" } defines { "NTDDI_VERSION=0x0A000000" } filter {} filter { "architecture:x86_64" } defines { "NTDDI_VERSION=0x0A000000" } filter {} filter { "architecture:ARM" } defines { "NTDDI_VERSION=0x0A000004" } -- Windows 10 1709 Build 16299 filter {} filter { "architecture:ARM64" } defines { "NTDDI_VERSION=0x0A000004" } -- Windows 10 1709 Build 16299 filter {} elseif _OPTIONS["windows-version"] == "win81" then filter {} defines { "_WIN32_WINNT=0x0603" } defines { "NTDDI_VERSION=0x06030000" } elseif _OPTIONS["windows-version"] == "win7" then filter {} defines { "_WIN32_WINNT=0x0601" } defines { "NTDDI_VERSION=0x06010000" } elseif _OPTIONS["windows-version"] == "winxp" then filter {} systemversion "7.0" filter {} filter { "architecture:x86" } defines { "_WIN32_WINNT=0x0501" } defines { "NTDDI_VERSION=0x05010100" } -- Windows XP SP1 filter { "architecture:x86_64" } defines { "_WIN32_WINNT=0x0502" } defines { "NTDDI_VERSION=0x05020000" } -- Windows XP x64 filter {} end filter {}
local ts = require "nvim-treesitter.configs" local parsers = require "nvim-treesitter.parsers" vim.treesitter.set_query("lua", "folds", "") vim.treesitter.set_query("lua", "indents", "") ts.setup { highlight = { enable = true }, incremental_selection = { enable = true, keymaps = { init_selection = "<cr>", node_incremental = "<cr>", node_decremental = "<tab>", scope_incremental = "<s-cr>", }, }, indent = { enable = false }, refactor = { highlight_definitions = { enable = true }, highlight_current_scope = { enable = false }, smart_rename = { enable = false }, navigation = { enable = true, keymaps = { goto_definition = "gnd", list_definitions = "gnD", list_definitions_toc = "gO", goto_next_usage = "<a-*>", goto_previous_usage = "<a-#>", }, }, }, textobjects = { select = { enable = true, lookahead = true, keymaps = { ["af"] = "@function.outer", ["if"] = "@function.inner", ["ac"] = "@class.outer", ["ic"] = "@class.inner", }, }, swap = { enable = true, swap_next = { ["<leader>a"] = "@parameter.inner", }, swap_previous = { ["<leader>A"] = "@parameter.inner", }, }, move = { enable = true, set_jumps = true, -- whether to set jumps in the jumplist goto_next_start = { ["]m"] = "@function.outer", ["]]"] = "@class.outer", }, goto_next_end = { ["]M"] = "@function.outer", ["]["] = "@class.outer", }, goto_previous_start = { ["[m"] = "@function.outer", ["[["] = "@class.outer", }, goto_previous_end = { ["[M"] = "@function.outer", ["[]"] = "@class.outer", }, }, }, playground = { enable = true, updatetime = 25, persist_queries = false, }, query_linter = { enable = true, use_virtual_text = true, lint_events = { "BufWrite", "CursorHold" }, }, ensure_installed = { "bash", "bibtex", "c", "c_sharp", "clojure", "cmake", "comment", "cpp", "css", "dockerfile", "fennel", "go", "gomod", "graphql", "html", "java", "javascript", "json", "kotlin", "latex", "nix", "perl", "php", "python", "ql", "query", "r", "regex", "rst", "ruby", "rust", "toml", "typescript", "yaml", }, } local configs = parsers.get_parser_configs() local treesitter_group = vim.api.nvim_create_augroup("custom_treesitter_stuff", { clear = true }) vim.api.nvim_create_autocmd("Filetype", { pattern = table.concat( vim.tbl_map(function(ft) return configs[ft].filetype or ft end, parsers.available_parsers()), "," ), command = "setlocal foldmethod=expr foldexpr=nvim_treesitter#foldexpr()", group = treesitter_group, })
component = require("component") computer = require("computer") serialization = require("serialization") sides = require("sides") g = require("gachLib") local rec = require("draconicRec") -- tells refinedStorage to start new crafting redSideNewCrafting = sides.right -- tells draconic infusion to start crafting (after all chests are empty) redSideStartInjection = sides.back -- tells enderIo to extract the result redSideExtractResult = sides.left -- side of transposer in which the items for crafting land transSideInput = sides.north -- side of transposer from which the items for the Core gets transSideCore = sides.west -- side of transposer from which the items for the Inject gets transSideInject = sides.east -- side of transposer in which the result of core land transSideResult = sides.south -- checks if chest on side is empty function chestIsEmpty(side) local stacks = component.transposer.getAllStacks(side) for i=1,stacks.count(),1 do if stacks[i].name ~= "minecraft:air" then return false end end return true end function getItemsInInput() local stacks = component.transposer.getAllStacks(transSideInput) local ret = {} for i=1,stacks.count(),1 do if stacks[i].name ~= "minecraft:air" then for j=1,(#ret+1),1 do if j > #ret then ret[i] = {name = stacks[i].name, count = stacks[i].size, slot = j} break elseif ret[i] ~= nil and ret[i].name == stacks[i].name then ret[i].count = ret[i].count + stacks[i].size break end end end end return ret end -- tell refinedStorage to start next crafting and wait for new input O(N^3) function startNewCrafting() print("startNewCrafting") g.state.setState({state = "ready", recepie = "<none>"}) while chestIsEmpty(transSideInput) do component.redstone.setOutput(redSideNewCrafting, 15) os.sleep(.1) component.redstone.setOutput(redSideNewCrafting, 0) os.sleep(1) end end function getRecepie() local ret = {recIndex = -1, coreSlot = -1, items = getItemsInInput()} for i=1,#rec,1 do local coreSlot = -1 -- check item for core print(" check for core " .. i) for k=1,#ret.items,1 do if rec[i].core.name == ret.items[k].name and rec[i].core.count >= ret.items[k].count then print(" item for core found: " .. ret.items[k].name .. " in slot " .. ret.items[k].slot) coreSlot = ret.items[k].slot break end end -- check items for inject if coreSlot > 0 then local checked = 0 for j=1,#rec[i].inject do print(" check for inject " .. j .. "/" .. #rec[i].inject) for k=1,#ret.items,1 do if rec[i].inject[j].name == ret.items[k].name and rec[i].inject[j].count >= ret.items[k].count then print(" item for inject found: " .. ret.items[k].name .. " in slot " .. ret.items[k].slot) checked = checked + 1 break end end end if checked >= #rec[i].inject then ret.recIndex = i ret.coreSlot = coreSlot break end end end return ret end -- move input to the rigth chests function moveInput() local retry = true while retry do print("moveInput") local recepie = getRecepie() print(serialization.serialize(recepie)) if recepie.recIndex > 0 then g.state.setState({state = "crafting", recepie = rec[recepie.recIndex].name}) moveToCore(recepie.coreSlot, recepie.recIndex) moveToInjection(recepie.recIndex) retry = false else print("No recepie found.. Retry") os.sleep(1) end end end -- move item from input in slot to core function moveToCore(slot, recIndex) print("move to core " .. slot) component.transposer.transferItem(transSideInput, transSideCore, rec[recIndex].core.count, slot) end -- move all items from input to injection function moveToInjection(recIndex) for i=1,component.transposer.getInventorySize(transSideInput),1 do local stack = component.transposer.getStackInSlot(transSideInput,i) if stack ~= nil and stack.name ~= "minecraft:air" then for j=1,#rec[recIndex].inject do if stack.name == rec[recIndex].inject[j].name then component.transposer.transferItem( transSideInput, transSideInject, rec[recIndex].inject[j].count, i, g.transposer.nextEmptySlot(component.transposer, transSideInject)) end end end end end -- starts the injection function startInjection() print("startInjection") while not chestIsEmpty(transSideInject) do os.sleep(1) end component.redstone.setOutput(redSideStartInjection, 15) os.sleep(1) component.redstone.setOutput(redSideStartInjection, 0) end -- wait for injection to finish function awaitResult() print("awaitResult") while chestIsEmpty(transSideResult) do os.sleep(1) end end -- return result of injection function returnResult() print("returnResult") component.redstone.setOutput(redSideExtractResult, 15) os.sleep(1) component.redstone.setOutput(redSideExtractResult, 0) end -- main if g.network ~= nil then g.network.init("woot") end g.state.setState({state = "init"}) while true do startNewCrafting() moveInput() startInjection() awaitResult() returnResult() end
object_mobile_tcg_massiff_pet = object_mobile_shared_tcg_massiff_pet:new { } ObjectTemplates:addTemplate(object_mobile_tcg_massiff_pet, "object/mobile/tcg_massiff_pet.iff")
local a=module('_core','libs/Tunnel')local b=module('_core','libs/Proxy')API=b.getInterface('API')cAPI=a.getInterface('cAPI')RegisterServerEvent('_inventory:showInventory')AddEventHandler('_inventory:showInventory',function()local c=source;local d=API.getUserFromSource(c)d:viewInventory()end)RegisterServerEvent('_inventory:funcItem')AddEventHandler('_inventory:funcItem',function(e)local c=source;local d=API.getUserFromSource(c)local f=d:getCharacter()local g=d:getCharacter():getInventory()if tonumber(e.Quantidade)==0 or tonumber(e.Quantidade)<0 then return end;if tonumber(f:getItemAmount(e.ItemName))<tonumber(e.Quantidade)then return end;if e.Tipo=="useItem"then g:useItem(c,e.ItemName,e.Quantidade)elseif e.Tipo=="sendItem"then g:sendItem(c,e.ItemName,e.Quantidade)elseif e.Tipo=="dropItem"then f:removeItem(e.ItemName,e.Quantidade)end end)
--------------------------------------------- -- Tyrranic Blare -- -- Description: Emits an overwhelming scream that damages nearby targets. -- Type: Magical? -- Utsusemi/Blink absorb: Ignores shadows -- Range: Less than or equal to 10.0 -- Notes: Only used by Gulool Ja Ja. --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local dmgmod = 1 local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*2.8,tpz.magic.ele.EARTH,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,tpz.attackType.MAGICAL,tpz.damageType.EARTH,MOBPARAM_IGNORE_SHADOWS) target:takeDamage(dmg, mob, tpz.attackType.MAGICAL, tpz.damageType.EARTH) return dmg end
function Doors:ShowSpare1(player) local trace = player:GetEyeTraceNoCursor() local entity = trace.Entity if IsValid(entity) and entity:is_door() and player:GetPos():Distance(entity:GetPos()) < 115 then local can_lock = hook.run('PlayerCanLockDoor', player, entity) or false Cable.send(player, 'fl_door_menu', entity, can_lock, entity.conditions) end end function Doors:PlayerUse(player, entity) local cur_time = CurTime() if IsValid(entity) and entity:is_door() and player:GetPos():Distance(entity:GetPos()) < 115 then if !entity.next_use or entity.next_use <= cur_time then if hook.run('PlayerCanLockDoor', player, entity) and player:IsSprinting() then local locked = entity:get_nv('fl_locked') self:lock_door(entity, !locked) entity:Fire(locked and 'Open' or 'Close') entity.next_use = cur_time + 2 if !locked then return false end end entity.next_use = cur_time + 0.5 hook.run('PlayerUseDoor', player, entity) else return false end end end function Doors:PlayerCanLockDoor(player, entity) local conditions = entity.conditions if conditions and Conditions:check(player, conditions) then return true end end
----------------------------------- -- Area: Windurst Walls -- NPC: Juvillie -- Type: Event Replayer -- !pos -180.731 -3.451 143.138 239 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:startEvent(406); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
--[[--------------------------------------------------------- Duplicator module, to add new constraints or entity classes use... duplicator.RegisterConstraint( "name", funct, ... ) duplicator.RegisterEntityClass( "class", funct, ... ) -----------------------------------------------------------]] module( "duplicator", package.seeall ) -- -- When saving or loading all coordinates are saved relative to these -- local LocalPos = Vector( 0, 0, 0 ) local LocalAng = Angle( 0, 0, 0 ) -- -- Should be set to the player that is creating/copying stuff. Can be nil. -- local ActionPlayer = nil -- -- The physics object Saver/Loader -- local PhysicsObject = { Save = function( data, phys ) data.Pos = phys:GetPos() data.Angle = phys:GetAngles() data.Frozen = !phys:IsMoveable() if ( phys:IsGravityEnabled() == false ) then data.NoGrav = true end if ( phys:IsAsleep() == true ) then data.Sleep = true end data.Pos, data.Angle = WorldToLocal( data.Pos, data.Angle, LocalPos, LocalAng ) end, Load = function( data, phys ) if ( isvector( data.Pos ) && isangle( data.Angle ) ) then local pos, ang = LocalToWorld( data.Pos, data.Angle, LocalPos, LocalAng ) phys:SetPos( pos ) phys:SetAngles( ang ) end if ( data.Sleep == true ) then phys:Sleep(); else phys:Wake(); end if ( data.Frozen == true ) then phys:EnableMotion( false ) -- If we're being created by a player then add these to their frozen list so they can unfreeze them all if ( IsValid( ActionPlayer ) ) then ActionPlayer:AddFrozenPhysicsObject( Entity, phys ) end end if ( data.NoGrav == true ) then phys:EnableGravity( false ) end end, } -- -- Entity physics saver -- local EntityPhysics = { -- -- Loop each bone, calling PhysicsObject.Save -- Save = function( data, Entity ) local num = Entity:GetPhysicsObjectCount() for objectid = 0, num-1 do local obj = Entity:GetPhysicsObjectNum( objectid ) if ( !obj:IsValid() ) then continue end data[ objectid ] = {} PhysicsObject.Save( data[ objectid ], obj ) end end, -- -- Loop each bone, calling PhysicsObject.Load -- Load = function( data, Entity ) if ( !istable( data ) ) then return end for objectid, objectdata in pairs( data ) do local Phys = Entity:GetPhysicsObjectNum( objectid ) if ( !IsValid( Phys ) ) then continue end PhysicsObject.Load( objectdata, Phys ) end end, } -- -- Entity saver -- local EntitySaver = { -- -- Called on each entity when saving -- Save = function( data, ent ) -- -- Merge the entities actual table with the table we're saving -- this is terrible behaviour - but it's what we've always done. -- if ( ent.PreEntityCopy ) then ent:PreEntityCopy() end table.Merge( data, ent:GetTable() ) if ( ent.PostEntityCopy ) then ent:PostEntityCopy() end -- -- Set so me generic variables that pretty much all entities -- would like to save. -- data.Pos = ent:GetPos() data.Angle = ent:GetAngles() data.Class = ent:GetClass() data.Model = ent:GetModel() data.Skin = ent:GetSkin() data.Mins, data.Maxs = ent:GetCollisionBounds() data.ColGroup = ent:GetCollisionGroup() data.Name = ent:GetName() data.WorkshopID = ent:GetWorkshopID() data.Pos, data.Angle = WorldToLocal( data.Pos, data.Angle, LocalPos, LocalAng ) data.ModelScale = ent:GetModelScale() if ( data.ModelScale == 1 ) then data.ModelScale = nil end -- We have no reason to keep the creation ID anymore - but we will if ( ent:CreatedByMap() ) then data.MapCreationID = ent:MapCreationID(); end -- Allow the entity to override the class -- (this is a hack for the jeep, since it's real class is different from the one it reports as) if ( ent.ClassOverride ) then data.Class = ent.ClassOverride end -- Save the physics data.PhysicsObjects = data.PhysicsObjects or {} EntityPhysics.Save( data.PhysicsObjects, ent ) -- Flexes data.FlexScale = ent:GetFlexScale() for i = 0, ent:GetFlexNum() do local w = ent:GetFlexWeight( i ); if ( w != 0 ) then data.Flex = data.Flex or {} data.Flex[ i ] = w end end -- Body Groups local bg = ent:GetBodyGroups(); if ( bg ) then for k, v in pairs( bg ) do -- -- If it has a non default setting, save it. -- if ( ent:GetBodygroup( v.id ) > 0 ) then data.BodyG = data.BodyG or {} data.BodyG[ v.id ] = ent:GetBodygroup( v.id ) end end end -- Bone Manipulator if ( ent:HasBoneManipulations() ) then data.BoneManip = {} for i=0, ent:GetBoneCount() do local t = {} local s = ent:GetManipulateBoneScale( i ) local a = ent:GetManipulateBoneAngles( i ) local p = ent:GetManipulateBonePosition( i ) if ( s != Vector( 1, 1, 1 ) ) then t[ 's' ] = s end -- scale if ( a != Angle( 0, 0, 0 ) ) then t[ 'a' ] = a end -- angle if ( p != Vector( 0, 0, 0 ) ) then t[ 'p' ] = p end -- position if ( table.Count( t ) > 0 ) then data.BoneManip[ i ] = t end end end -- -- Store networks vars/DT vars (assigned using SetupDataTables) -- if ( ent.GetNetworkVars ) then data.DT = ent:GetNetworkVars(); end -- Make this function on your SENT if you want to modify the -- returned table specifically for your entity. if ( ent.OnEntityCopyTableFinish ) then ent:OnEntityCopyTableFinish( data ) end -- -- Exclude this crap -- for k, v in pairs( data ) do if ( isfunction(v) ) then data[k] = nil end end data.OnDieFunctions = nil data.AutomaticFrameAdvance = nil data.BaseClass = nil end, -- -- Fill in the data! -- Load = function( data, ent ) if ( !data ) then return end if ( data.Model ) then ent:SetModel( data.Model ) end if ( data.Angle ) then ent:SetAngles( data.Angle ) end if ( data.Pos ) then ent:SetPos( data.Pos ) end if ( data.Skin ) then ent:SetSkin( data.Skin ) end if ( data.Flex ) then DoFlex( ent, data.Flex, data.FlexScale ) end if ( data.BoneManip ) then DoBoneManipulator( ent, data.BoneManip ) end if ( data.ModelScale ) then ent:SetModelScale( data.ModelScale, 0 ) end if ( data.ColGroup ) then ent:SetCollisionGroup( data.ColGroup ) end if ( data.Name ) then ent:SetName( data.Name ) end -- Body Groups if ( data.BodyG ) then for k, v in pairs( data.BodyG ) do ent:SetBodygroup( k, v ) end end -- -- Restore NetworkVars/DataTable variables (the SetupDataTables values) -- if ( ent.RestoreNetworkVars ) then ent:RestoreNetworkVars( data.DT ) end end, } local DuplicateAllowed = {} -- -- Allow this entity to be duplicated -- function Allow( classname ) DuplicateAllowed[ classname ] = true end -- -- Returns true if we can copy/paste this entity -- function IsAllowed( classname ) return DuplicateAllowed[ classname ] end ConstraintType = ConstraintType or {} -- -- When a copy is copied it will be translated according to these -- If you set them - make sure to set them back to 0 0 0! -- function SetLocalPos( v ) LocalPos = v * 1 end function SetLocalAng( v ) LocalAng = v * 1 end --[[--------------------------------------------------------- Register a constraint to be duplicated -----------------------------------------------------------]] function RegisterConstraint( _name_ , _function_, ... ) ConstraintType[ _name_ ] = {} ConstraintType[ _name_ ].Func = _function_; ConstraintType[ _name_ ].Args = {...} end EntityClasses = EntityClasses or {} --[[--------------------------------------------------------- Register an entity's class, to allow it to be duplicated -----------------------------------------------------------]] function RegisterEntityClass( _name_ , _function_, ... ) EntityClasses[ _name_ ] = {} EntityClasses[ _name_ ].Func = _function_ EntityClasses[ _name_ ].Args = {...} Allow( _name_ ) end --[[--------------------------------------------------------- Returns an entity class factory -----------------------------------------------------------]] function FindEntityClass( _name_ ) if ( !_name_ ) then return end return EntityClasses[ _name_ ] end --[[--------------------------------------------------------- -----------------------------------------------------------]] BoneModifiers = BoneModifiers or {} EntityModifiers = EntityModifiers or {} function RegisterBoneModifier( _name_, _function_ ) BoneModifiers[ _name_ ] = _function_ end function RegisterEntityModifier( _name_, _function_ ) EntityModifiers[ _name_ ] = _function_ end if ( !SERVER ) then return end --[[--------------------------------------------------------- Restore's the flex data -----------------------------------------------------------]] function DoFlex( ent, Flex, Scale ) if ( !Flex ) then return end if ( !IsValid(ent) ) then return end for k, v in pairs( Flex ) do ent:SetFlexWeight( k, v ) end if ( Scale ) then ent:SetFlexScale( Scale ) end end --[[--------------------------------------------------------- Restore's the bone's data -----------------------------------------------------------]] function DoBoneManipulator( ent, Bones ) if ( !Bones ) then return end if ( !IsValid(ent) ) then return end for k, v in pairs( Bones ) do if ( v.s ) then ent:ManipulateBoneScale( k, v.s ) end if ( v.a ) then ent:ManipulateBoneAngles( k, v.a ) end if ( v.p ) then ent:ManipulateBonePosition( k, v.p ) end end end --[[--------------------------------------------------------- Generic function for duplicating stuff -----------------------------------------------------------]] function GenericDuplicatorFunction( Player, data ) if ( !IsAllowed( data.Class ) ) then -- MsgN( "duplicator: ", data.Class, " isn't allowed to be duplicated!" ) return end -- -- Is this entity 'admin only'? -- if ( IsValid( Player ) && !Player:IsAdmin() ) then if ( !scripted_ents.GetMember( data.Class, "Spawnable" ) ) then return end if ( scripted_ents.GetMember( data.Class, "AdminOnly" ) ) then return end end local Entity = ents.Create( data.Class ) if ( !IsValid( Entity ) ) then return end -- TODO: Entity not found - maybe spawn a prop_physics with their model? DoGeneric( Entity, data ) Entity:Spawn() Entity:Activate() EntityPhysics.Load( data.PhysicsObjects, Entity ) table.Merge( Entity:GetTable(), data ) return Entity end --[[--------------------------------------------------------- Automates the process of adding crap the EntityMods table -----------------------------------------------------------]] function StoreEntityModifier( Entity, Type, Data ) if (!Entity) then return end if (!Entity:IsValid()) then return end Entity.EntityMods = Entity.EntityMods or {} -- Copy the data local NewData = Entity.EntityMods[ Type ] or {} table.Merge( NewData, Data ) Entity.EntityMods[ Type ] = NewData end --[[--------------------------------------------------------- Clear entity modification -----------------------------------------------------------]] function ClearEntityModifier( Entity, Type ) if (!Entity) then return end if (!Entity:IsValid()) then return end Entity.EntityMods = Entity.EntityMods or {} Entity.EntityMods[ Type ] = nil end --[[--------------------------------------------------------- Automates the process of adding crap the BoneMods table -----------------------------------------------------------]] function StoreBoneModifier( Entity, BoneID, Type, Data ) if (!Entity) then return end if (!Entity:IsValid()) then return end -- Copy the data NewData = {} table.Merge( NewData , Data ) -- Add it to the entity Entity.BoneMods = Entity.BoneMods or {} Entity.BoneMods[ BoneID ] = Entity.BoneMods[ BoneID ] or {} Entity.BoneMods[ BoneID ][ Type ] = NewData end --[[--------------------------------------------------------- Returns a copy of the passed entity's table -----------------------------------------------------------]] function CopyEntTable( Ent ) local output = {} EntitySaver.Save( output, Ent ) return output end -- -- Work out the AABB size -- function WorkoutSize( Ents ) local mins = Vector( -1, -1, -1 ) local maxs = Vector( 1, 1, 1 ) for k, v in pairs( Ents ) do if ( !v.Mins || !v.Maxs ) then continue end if ( !v.Angle || !v.Pos ) then continue end -- -- Rotate according to the entity! -- local RotMins = v.Mins * 1; local RotMaxs = v.Maxs * 1; RotMins:Rotate( v.Angle ) RotMaxs:Rotate( v.Angle ) -- -- This is dumb and the logic is wrong, but it works for now. -- mins.x = math.min( mins.x, v.Pos.x + RotMins.x ) mins.y = math.min( mins.y, v.Pos.y + RotMins.y ) mins.z = math.min( mins.z, v.Pos.z + RotMins.z ) mins.x = math.min( mins.x, v.Pos.x + RotMaxs.x ) mins.y = math.min( mins.y, v.Pos.y + RotMaxs.y ) mins.z = math.min( mins.z, v.Pos.z + RotMaxs.z ) maxs.x = math.max( maxs.x, v.Pos.x + RotMins.x ) maxs.y = math.max( maxs.y, v.Pos.y + RotMins.y ) maxs.z = math.max( maxs.z, v.Pos.z + RotMins.z ) maxs.x = math.max( maxs.x, v.Pos.x + RotMaxs.x ) maxs.y = math.max( maxs.y, v.Pos.y + RotMaxs.y ) maxs.z = math.max( maxs.z, v.Pos.z + RotMaxs.z ) end return mins, maxs end --[[--------------------------------------------------------- Copy this entity, and all of its constraints and entities and put them in a table. -----------------------------------------------------------]] function Copy( Ent, AddToTable ) local Ents = {} local Constraints = {} GetAllConstrainedEntitiesAndConstraints( Ent, Ents, Constraints ) local EntTables = {} if ( AddToTable != nil ) then EntTables = AddToTable.Entities or {} end for k, v in pairs(Ents) do EntTables[ k ] = CopyEntTable( v ) end local ConstraintTables = {} if ( AddToTable != nil ) then ConstraintTables = AddToTable.Constraints or {} end for k, v in pairs(Constraints) do ConstraintTables[ k ] = v end local mins, maxs = WorkoutSize( EntTables ) return { Entities = EntTables, Constraints = ConstraintTables, Mins = mins, Maxs = maxs } end --[[--------------------------------------------------------- -----------------------------------------------------------]] function CopyEnts( Ents ) local Ret = { Entities = {}, Constraints = {} } for k, v in pairs( Ents ) do Ret = Copy( v, Ret ) end return Ret end --[[--------------------------------------------------------- Create an entity from a table. -----------------------------------------------------------]] function CreateEntityFromTable( Player, EntTable ) -- -- Convert position/angle to `local` -- if ( EntTable.Pos && EntTable.Angle ) then EntTable.Pos, EntTable.Angle = LocalToWorld( EntTable.Pos, EntTable.Angle, LocalPos, LocalAng ) end local EntityClass = FindEntityClass( EntTable.Class ) -- This class is unregistered. Instead of failing try using a generic -- Duplication function to make a new copy.. if ( !EntityClass ) then return GenericDuplicatorFunction( Player, EntTable ) end -- Build the argument list local ArgList = {} for iNumber, Key in pairs( EntityClass.Args ) do local Arg = nil -- Translate keys from old system if ( Key == "pos" || Key == "position" ) then Key = "Pos" end if ( Key == "ang" || Key == "Ang" || Key == "angle" ) then Key = "Angle" end if ( Key == "model" ) then Key = "Model" end Arg = EntTable[ Key ] -- Special keys if ( Key == "Data" ) then Arg = EntTable end -- If there's a missing argument then unpack will stop sending at that argument so send it as `false` if ( Arg == nil ) then Arg = false end ArgList[ iNumber ] = Arg end -- Create and return the entity return EntityClass.Func( Player, unpack(ArgList) ) end --[[--------------------------------------------------------- Make a constraint from a constraint table -----------------------------------------------------------]] function CreateConstraintFromTable( Constraint, EntityList ) local Factory = ConstraintType[ Constraint.Type ] if ( !Factory ) then return end local Args = {} for k, Key in pairs( Factory.Args ) do local Val = Constraint[ Key ] for i=1, 6 do if ( Constraint.Entity[ i ] ) then if ( Key == "Ent"..i ) then Val = EntityList[ Constraint.Entity[ i ].Index ] if ( Constraint.Entity[ i ].World ) then Val = game.GetWorld() end end if ( Key == "Bone"..i ) then Val = Constraint.Entity[ i ].Bone or 0 end if ( Key == "LPos"..i ) then Val = Constraint.Entity[ i ].LPos end if ( Key == "WPos"..i ) then Val = Constraint.Entity[ i ].WPos end if ( Key == "Length"..i ) then Val = Constraint.Entity[ i ].Length or 0 end end end -- If there's a missing argument then unpack will stop sending at that argument if ( Val == nil ) then Val = false end table.insert( Args, Val ) end local Entity = Factory.Func( unpack(Args) ) return Entity end --[[--------------------------------------------------------- Given entity list and constranit list, create all entities and return their tables -----------------------------------------------------------]] function Paste( Player, EntityList, ConstraintList ) -- -- Store the player -- local oldplayer = ActionPlayer ActionPlayer = Player -- -- Copy the table - because we're gonna be changing some stuff on it. -- local EntityList = table.Copy( EntityList ); local ConstraintList = table.Copy( ConstraintList ); local CreatedEntities = {} -- -- Create the Entities -- for k, v in pairs( EntityList ) do local e = nil local b = ProtectedCall( function() e = CreateEntityFromTable( Player, v ) end ) if ( !b ) then continue; end if ( IsValid( e ) ) then -- -- Call this here ( as well as before :Spawn) because Spawn/Init might have stomped the values -- if ( e.RestoreNetworkVars ) then e:RestoreNetworkVars( v.DT ) end if ( e.OnDuplicated ) then e:OnDuplicated( v ) end end CreatedEntities[ k ] = e if ( CreatedEntities[ k ] ) then CreatedEntities[ k ].BoneMods = table.Copy( v.BoneMods ) CreatedEntities[ k ].EntityMods = table.Copy( v.EntityMods ) CreatedEntities[ k ].PhysicsObjects = table.Copy( v.PhysicsObjects ) else CreatedEntities[ k ] = nil end end -- -- Apply modifiers to the created entities -- for EntID, Ent in pairs( CreatedEntities ) do ApplyEntityModifiers ( Player, Ent ) ApplyBoneModifiers ( Player, Ent ) if ( Ent.PostEntityPaste ) then Ent:PostEntityPaste( Player, Ent, CreatedEntities ) end end local CreatedConstraints = {} -- -- Create constraints -- for k, Constraint in pairs( ConstraintList ) do local Entity = CreateConstraintFromTable( Constraint, CreatedEntities ) if ( Entity && Entity:IsValid() ) then table.insert( CreatedConstraints, Entity ) end end ActionPlayer = oldplayer return CreatedEntities, CreatedConstraints end --[[--------------------------------------------------------- Applies entity modifiers -----------------------------------------------------------]] function ApplyEntityModifiers( Player, Ent ) if ( !Ent ) then return end if ( !Ent.EntityMods ) then return end for Type, ModFunction in pairs( EntityModifiers ) do if ( Ent.EntityMods[ Type ] ) then ModFunction( Player, Ent, Ent.EntityMods[ Type ] ) end end end --[[--------------------------------------------------------- Applies Bone Modifiers -----------------------------------------------------------]] function ApplyBoneModifiers( Player, Ent ) if ( !Ent ) then return end if ( !Ent.PhysicsObjects ) then return end if ( !Ent.BoneMods ) then return end -- -- Loop every Bone on the entity -- for Bone, Types in pairs( Ent.BoneMods ) do -- The physics object isn't valid, skip it. if ( !Ent.PhysicsObjects[Bone] ) then continue end -- Loop through each modifier on this bone for Type, Data in pairs(Types) do -- Find and all the function local ModFunction = BoneModifiers[Type]; if ( ModFunction ) then ModFunction( Player, Ent, Bone, Ent:GetPhysicsObjectNum( Bone ), Data ) end end end end --[[--------------------------------------------------------- Returns all constrained Entities and constraints This is kind of in the wrong place. No not call this from outside of this code. It will probably get moved to constraint.lua soon. -----------------------------------------------------------]] function GetAllConstrainedEntitiesAndConstraints( ent, EntTable, ConstraintTable ) if ( !IsValid( ent ) ) then return end -- Translate the class name local classname = ent:GetClass(); if ( ent.ClassOverride ) then classname = ent.ClassOverride end -- Is the entity in the dupe whitelist? if ( !IsAllowed( classname ) ) then -- MsgN( "duplicator: ", classname, " isn't allowed to be duplicated!" ) return end -- Entity doesn't want to be duplicated. if ( ent.DoNotDuplicate ) then return end EntTable[ ent:EntIndex() ] = ent if ( !constraint.HasConstraints( ent ) ) then return end local ConTable = constraint.GetTable( ent ) for key, constraint in pairs( ConTable ) do local index = constraint.Constraint:GetCreationID() if ( !ConstraintTable[ index ] ) then -- Add constraint to the constraints table ConstraintTable[ index ] = constraint -- Run the Function for any ents attached to this constraint for key, ConstrainedEnt in pairs( constraint.Entity ) do GetAllConstrainedEntitiesAndConstraints( ConstrainedEnt.Entity, EntTable, ConstraintTable ) end end end return EntTable, ConstraintTable end -- -- Return true if this entity should be removed when RemoveMapCreatedEntities is called -- We don't want to remove all entities. -- local function ShouldMapEntityBeRemoved( ent, classname ) if ( classname == "prop_physics" ) then return true end if ( classname == "prop_physics_multiplayer" ) then return true end if ( classname == "prop_ragdoll" ) then return true end if ( ent:IsNPC() ) then return true end return false end -- -- Help to remove certain map created entities before creating the saved entities -- This is obviously so we don't get duplicate props everywhere. It should be called -- before calling Paste. -- function RemoveMapCreatedEntities() local list = ents.GetAll() for k, v in pairs( list ) do if ( ShouldMapEntityBeRemoved( v, v:GetClass() ) ) then v:Remove() end end end -- -- BACKWARDS COMPATIBILITY - PHASE OUT, RENAME? -- function DoGenericPhysics( Entity, Player, data ) if ( !data || !data.PhysicsObjects ) then return end EntityPhysics.Load( data.PhysicsObjects, Entity ) end -- -- -- function DoGeneric( ent, data ) EntitySaver.Load( data, ent ) end
--- A physical player in the server -- @classmod Player if SERVER then util.AddNetworkString( "GM-ColoredMessage" ) util.AddNetworkString( "GM-SurfaceSound" ) util.AddNetworkString("impulseNotify") function meta:AddChatText(...) local package = {...} netstream.Start(self, "GM-ColoredMessage", package) end function meta:SurfacePlaySound(sound) net.Start("GM-SurfaceSound") net.WriteString(sound) net.Send(self) end function impulse.CinematicIntro(message) net.Start("impulseCinematicMessage") net.WriteString(message) net.Broadcast() end concommand.Add("impulse_cinemessage", function(ply, cmd, args) if not ply:IsSuperAdmin() then return end impulse.CinematicIntro(args[1] or "") end) function meta:AllowScenePVSControl(bool) self.allowPVS = bool if not bool then self.extraPVS = nil self.extraPVS2 = nil end end else netstream.Hook("GM-ColoredMessage",function(msg) chat.AddText(unpack(msg)) end) net.Receive("GM-SurfaceSound",function() surface.PlaySound(net.ReadString()) end) end local eMeta = FindMetaTable("Entity") --- Returns if a player is an impulse framework developer -- @realm shared -- @treturn bool Is developer function meta:IsDeveloper() return self:SteamID() == "STEAM_0:1:95921723" end --- Returns if a player has donator status -- @realm shared -- @treturn bool Is donator function meta:IsDonator() return (self:IsUserGroup("donator") or self:IsAdmin()) end local adminGroups = { ["admin"] = true, ["leadadmin"] = true, ["communitymanager"] = true } function meta:IsAdmin() if self.IsSuperAdmin(self) then return true end if adminGroups[self.GetUserGroup(self)] then return true end return false end local leadAdminGroups = { ["leadadmin"] = true, ["communitymanager"] = true } function meta:IsLeadAdmin() if self.IsSuperAdmin(self) then return true end if leadAdminGroups[self.GetUserGroup(self)] then return true end return false end --- Returns if a player is in the spawn zone -- @realm shared -- @treturn bool Is in spawn function meta:InSpawn() return self:GetPos():WithinAABox(impulse.Config.SpawnPos1, impulse.Config.SpawnPos2) end function impulse.AngleToBearing(ang) return math.Round(360 - (ang.y % 360)) end function impulse.PosToString(pos) return pos.x.."|"..pos.y.."|"..pos.x end impulse.notices = impulse.notices or {} local function OrganizeNotices(i) local scrW = ScrW() local lastHeight = ScrH() - 100 for k, v in ipairs(impulse.notices) do local height = lastHeight - v:GetTall() - 10 v:MoveTo(scrW - (v:GetWide()), height, 0.15, (k / #impulse.notices) * 0.25, nil) lastHeight = height end end --- Sends a notification to a player -- @realm shared -- @string message The notification message function meta:Notify(message) if CLIENT then if not impulse.hudEnabled then return MsgN(message) end local notice = vgui.Create("impulseNotify") local i = table.insert(impulse.notices, notice) notice:SetMessage(message) notice:SetPos(ScrW(), ScrH() - (i - 1) * (notice:GetTall() + 4) + 4) -- needs to be recoded to support variable heights notice:MoveToFront() OrganizeNotices(i) timer.Simple(7.5, function() if IsValid(notice) then notice:AlphaTo(0, 1, 0, function() notice:Remove() for v,k in pairs(impulse.notices) do if k == notice then table.remove(impulse.notices, v) end end OrganizeNotices(i) end) end end) MsgN(message) else net.Start("impulseNotify") net.WriteString(message) net.Send(self) end end local modelCache = {} function eMeta:IsFemale(modelov) local model = modelov or self:GetModel() if modelCache[model] then return modelCache[model] end local isFemale = string.find(self:GetModel(), "female") if isFemale then modelCache[model] = true return true end modelCache[model] = false return false end --- Returns if the player has a female character -- @realm shared -- @treturn bool Is female function meta:IsCharacterFemale() if SERVER then return self:IsFemale(self.defaultModel) else return self:IsFemale(impulse_defaultModel) end end function impulse.FindPlayer(searchKey) if not searchKey or searchKey == "" then return nil end local searchPlayers = player.GetAll() local lowerKey = string.lower(tostring(searchKey)) for k = 1, #searchPlayers do local v = searchPlayers[k] if searchKey == v:SteamID() then return v end if string.find(string.lower(v:Name()), lowerKey, 1, true) ~= nil then return v end if string.find(string.lower(v:SteamName()), lowerKey, 1, true) ~= nil then return v end end return nil end function impulse.SafeString(str) local pattern = "[^0-9a-zA-Z%s]+" local clean = tostring(str) local first, last = string.find(str, pattern) if first != nil and last != nil then clean = string.gsub(clean, pattern, "") -- remove bad sequences end return clean end local idleVO = { "question23.wav", "question25.wav", "question09.wav", "question06.wav", "question05.wav" } local idleCPVO = { "copy.wav", "needanyhelpwiththisone.wav", "unitis10-8standingby.wav", "affirmative.wav", "affirmative2.wav", "rodgerthat.wav", "checkformiscount.wav" } local idleFishVO = { "fish_crabpot01.wav", "fish_likeleeches.wav", "fish_oldleg.wav", "fish_resumetalk02.wav", "fish_stayoutwater.wav", "fish_wipeouttown01.wav", "fish_resumetalk01.wav", "fish_resumetalk02.wav", "fish_resumetalk03.wav" } local idleZombVO = { "npc/zombie/zombie_voice_idle9.wav", "npc/zombie/zombie_voice_idle4.wav", "npc/zombie/zombie_voice_idle10.wav", "npc/zombie/zombie_voice_idle13.wav", "npc/zombie/zombie_voice_idle6.wav", "npc/zombie/zombie_voice_idle7.wav" } function impulse.GetRandomAmbientVO(gender) if gender == "male" then return "vo/npc/male01/"..idleVO[math.random(1, #idleVO)] elseif gender == "fisherman" then return "lostcoast/vo/fisherman/"..idleFishVO[math.random(1, #idleFishVO)] elseif gender == "cp" then return "npc/metropolice/vo/"..idleCPVO[math.random(1, #idleCPVO)] elseif gender == "zombie" then return idleZombVO[math.random(1, #idleZombVO)] else return "vo/npc/female01/"..idleVO[math.random(1, #idleVO)] end end
--- greetings.lua – turns any document into a friendly greeting --- --- Copyright: © 2021–2022 Contributors --- License: MIT – see LICENSE for details -- Makes sure users know if their pandoc version is too old for this -- filter. PANDOC_VERSION:must_be_at_least '2.17' --- Amends the contents of a document with a simple greeting. local function say_hello (doc) doc.meta.subtitle = doc.meta.title -- demote title to subtitle doc.meta.title = pandoc.Inlines 'Greetings!' -- set new title doc.blocks:insert(1, pandoc.Para 'Hello from the Lua filter!') return doc end return { -- Apply the `say_hello` function to the main Pandoc document. { Pandoc = say_hello } }
-- 主窗口句柄 local main_window_handle = nil -- 启动配置对话框 local function launch_config() local config_program = fs.ydwe_path() / "bin" / "YDWEConfig.exe" local command_line = string.format('"%s"', config_program:string()) sys.spawn(command_line, fs.ydwe_path()) end -- 启动魔兽 local function launch_warcraft3() local config_program = fs.ydwe_path() / "ydwe.exe" local command_line = string.format('"%s" -war3', config_program:string()) sys.spawn(command_line, fs.ydwe_path()) end -- 打开官网 local function open_offical_site() os.execute('explorer "http://www.ydwe.net"') end -- 初始化菜单 -- event_data - 事件参数,table,包含以下值 -- main_window_handle - 主窗口的handle -- main_menu_handle - 主菜单的handle -- 返回值:一律返回0 function event.EVENT_INIT_MENU(event_data) log.debug("********************* on menuinit start *********************") local menu = gui.menu(event_data.main_menu_handle, LNG.MENU_YDWE) menu:add(LNG.MENU_CONIFG, launch_config) menu:add(LNG.MENU_LAUNCH_WAR3, launch_warcraft3) menu:add(LNG.MENU_OPEN_OFFICIAL_SITE, open_offical_site) menu:add(LNG.MENU_CREDITS, show_credit) main_window_handle = event_data.main_window_handle log.debug("********************* on menuinit end *********************") return 0 end
id = 'V-38537' severity = 'low' weight = 10.0 title = 'The system must ignore ICMPv4 bogus error responses.' description = 'Ignoring bogus ICMP error responses reduces log size, although some activity would not be logged.' fixtext = [==[To set the runtime status of the "net.ipv4.icmp_ignore_bogus_error_responses" kernel parameter, run the following command: # sysctl -w net.ipv4.icmp_ignore_bogus_error_responses=1 If this is not the system's default value, add the following line to "/etc/sysctl.conf": net.ipv4.icmp_ignore_bogus_error_responses = 1]==] checktext = [=[The status of the "net.ipv4.icmp_ignore_bogus_error_responses" kernel parameter can be queried by running the following command: $ sysctl net.ipv4.icmp_ignore_bogus_error_responses The output of the command should indicate a value of "1". If this value is not the default value, investigate how it could have been adjusted at runtime, and verify it is not set improperly in "/etc/sysctl.conf". $ grep net.ipv4.icmp_ignore_bogus_error_responses /etc/sysctl.conf If the correct value is not returned, this is a finding.]=] function test() end function fix() end
local OrganismController = {} local Json = require "util.Json" function OrganismController:new(organismConstructor, initialPosition) local self = { organisms; numberOfGenomes; genomeSize; constructor = function (this, initialPosition) this.numberOfGenomes = 50 this.organisms = {} this.genomeSize = 16 for index = 1, this.numberOfGenomes, 1 do local organism = organismConstructor:new(this.genomeSize) organism.setPosition({x = initialPosition.x, y = initialPosition.y}) table.insert(this.organisms, organism) end end } self.constructor(self, initialPosition) local crossover = function (MomOrganism, DadOrganism, mutationProbability) if(not (MomOrganism and DadOrganism and mutationProbability)) then return false end local firstRandom, secondRandom local children = {} for indexOfChildren = 1, self.genomeSize, 1 do local newChildren = organismConstructor:new(self.genomeSize) for index = 1, self.genomeSize, 1 do --parents code firstRandom = math.random() local selectedOrganism = nil if (firstRandom <= 0.5) then selectedOrganism = MomOrganism else selectedOrganism = DadOrganism end newChildren.setGenomeInIndex(index, selectedOrganism.getGenomeInIndex(index) + 0) secondRandom = math.random() if (secondRandom <= mutationProbability) then --mutations (mutationProbability) newChildren.setGenomeInIndex(index, math.random(0, 3)) end end --for end newChildren.setGeneration(MomOrganism.getGeneration() + 1) table.insert(children, newChildren) end --end of children for MomOrganism.setGeneration(MomOrganism.getGeneration() + 1) table.insert(children, MomOrganism) DadOrganism.setGeneration(DadOrganism.getGeneration() + 1) table.insert(children, DadOrganism) MomOrganism.reset(); DadOrganism.reset() self.organisms = children return children end local selectBestOnes = function () local maxScores = {[0] = 0, [1] = 0} local bestOrganisms = {[0] = self.organisms[1], [1] = self.organisms[2]} for index, value in ipairs(self.organisms) do if(value.getFitness() > maxScores[0]) then bestOrganisms[1] = bestOrganisms[0] maxScores[1] = maxScores[0] bestOrganisms[0] = value maxScores[0] = value.getFitness() elseif(value.getFitness() > maxScores[1]) then bestOrganisms[1] = value maxScores[1] = value.getFitness() end end return bestOrganisms[0], bestOrganisms[1] end local saveGenomes = function (filePath) local outFile = assert(io.open(filePath, "w")) outFile:write("{ \"Organisms\":[") for index, value in ipairs(self.organisms) do outFile:write("{\"Generation", "\": [", value.getGeneration(), "],") outFile:write("\"Genome", "\": [") genomeSize = #value.getGenome() for genomeIndex, genomeValue in ipairs(value.getGenome()) do if(genomeIndex < genomeSize) then outFile:write(genomeValue, ",") else outFile:write(genomeValue, "]") end end if(index < #self.organisms) then outFile:write("},") else outFile:write("}") end end outFile:write("]}") assert(outFile:close()) end local loadGenomes = function (filePath) local file = io.open(filePath,'r') local organisms = Json.decode(file:read("*all")) end local getOrganisms = function() return self.organisms end return { crossover = crossover; selectBestOnes = selectBestOnes; saveGenomes = saveGenomes; loadGenomes = loadGenomes; getOrganisms = getOrganisms; } end return OrganismController
module_version("/1.0.14", "1.0") module_version("/2.0.15", "2.0") module_version("/3.14.15", "3.0")
----------------------------------------------------------------------------------------- -- -- main.lua -- ----------------------------------------------------------------------------------------- -- hide the status bar display.setStatusBar( display.HiddenStatusBar ) -- include the Corona "composer" module local composer = require "composer" --[[ local licensing = require( "licensing" ) licensing.init( "google" ) local function licensingListener( event ) local verified = event.isVerified if not event.isVerified then --failed verify app from the play store, we print a message print( "Pirates: Walk the Plank!!!" ) native.requestExit() --assuming this is how we handle pirates end end licensing.verify( licensingListener ) --]] local options = { effect = "crossFade", time = 300 } -- load menu screen composer.gotoScene( "mainmenu", options )
local colors = require "themes.onedark" local present, bufferline = pcall(require, "bufferline") if not present then return end bufferline.setup { options = { offsets = { { filetype = "NvimTree", text = "", padding = 1 } }, buffer_close_icon = "", modified_icon = "", close_icon = "", left_trunc_marker = "", right_trunc_marker = "", max_name_length = 14, max_prefix_length = 13, tab_size = 20, show_tab_indicators = true, enforce_regular_tabs = false, view = "multiwindow", show_buffer_close_icons = true, separator_style = "thin", mappings = true, always_show_bufferline = true, }, highlights = { fill = { guifg = colors.grey_fg, guibg = colors.black2, }, background = { guifg = colors.grey_fg, guibg = colors.black2, }, -- buffers buffer_visible = { guifg = colors.light_grey, guibg = colors.black2, }, buffer_selected = { guifg = colors.white, guibg = colors.black, gui = "bold", }, -- tabs tab = { guifg = colors.light_grey, guibg = colors.one_bg3, }, tab_selected = { guifg = colors.black2, guibg = colors.nord_blue, }, tab_close = { guifg = colors.red, guibg = colors.black, }, indicator_selected = { guifg = colors.black, guibg = colors.black, }, -- separators separator = { guifg = colors.black2, guibg = colors.black2, }, separator_visible = { guifg = colors.black2, guibg = colors.black2, }, separator_selected = { guifg = colors.black2, guibg = colors.black2, }, -- modified modified = { guifg = colors.red, guibg = colors.black2, }, modified_visible = { guifg = colors.red, guibg = colors.black2, }, modified_selected = { guifg = colors.green, guibg = colors.black, }, -- close buttons close_button = { guifg = colors.light_grey, guibg = colors.black2, }, close_button_visible = { guifg = colors.light_grey, guibg = colors.black2, }, close_button_selected = { guifg = colors.red, guibg = colors.black, }, }, }
local function removeItemFromPlayerInventory(playerId, itemId) assert(typeof(playerId) == "string") assert(typeof(itemId) == "string") return { type = script.Name, playerId = playerId, itemId = itemId, replicateTo = playerId, } end return removeItemFromPlayerInventory
return { { name = "2015-08-03-132400_init_oidc_user_ratelimiting_metrics", up = [[ CREATE TABLE IF NOT EXISTS oidc_user_ratelimiting_metrics( identifier text, period text, period_date timestamp without time zone, value integer, PRIMARY KEY (identifier, period_date, period) ); CREATE OR REPLACE FUNCTION increment_oidc_user_rate_limits(i text, p text, p_date timestamp with time zone, v integer) RETURNS VOID AS $$ BEGIN LOOP UPDATE oidc_user_ratelimiting_metrics SET value = value + v WHERE identifier = i AND period = p AND period_date = p_date; IF found then RETURN; END IF; BEGIN INSERT INTO oidc_user_ratelimiting_metrics(period, period_date, identifier, value) VALUES(p, p_date, i, v); RETURN; EXCEPTION WHEN unique_violation THEN END; END LOOP; END; $$ LANGUAGE 'plpgsql'; ]], down = [[ DROP TABLE oidc_user_ratelimiting_metrics; ]] }, { name = "oidc_user_ratelimiting_policies", up = function(_, _, dao) local rows, err = dao.plugins:find_all {name = "oidc-user-rate-limiting"} if err then return err end for i = 1, #rows do local oidc_user_rate_limiting = rows[i] -- Delete the old one to avoid conflicts when inserting the new one local _, err = dao.plugins:delete(oidc_user_rate_limiting) if err then return err end local _, err = dao.plugins:insert { name = "oidc-user-rate-limiting", consumer_id = oidc_user_rate_limiting.consumer_id, enabled = oidc_user_rate_limiting.enabled, config = { second = oidc_user_rate_limiting.config.second, minute = oidc_user_rate_limiting.config.minute, hour = oidc_user_rate_limiting.config.hour, day = oidc_user_rate_limiting.config.day, month = oidc_user_rate_limiting.config.month, year = oidc_user_rate_limiting.config.year, limit_by = "consumer", policy = "local", fault_tolerant = oidc_user_rate_limiting.config.continue_on_error } } if err then return err end end end } }
local F, C, L = unpack(select(2, ...)) local strsplit, ipairs, wipe = string.split, ipairs, table.wipe local toggle = 0 local shadeFrame = CreateFrame('Frame') local shadeTexture = shadeFrame:CreateTexture(nil, 'BACKGROUND', nil, -8) shadeFrame:SetFrameStrata('BACKGROUND') shadeFrame:SetWidth(GetScreenWidth() * UIParent:GetEffectiveScale()) shadeFrame:SetHeight(GetScreenHeight() * UIParent:GetEffectiveScale()) shadeTexture:SetAllPoints(shadeFrame) shadeFrame:SetPoint('CENTER', 0, 0) local crosshairFrameNS = CreateFrame('Frame') local crosshairTextureNS = crosshairFrameNS:CreateTexture(nil, 'TOOLTIP') crosshairFrameNS:SetFrameStrata('TOOLTIP') crosshairFrameNS:SetWidth(1) crosshairFrameNS:SetHeight(GetScreenHeight() * UIParent:GetEffectiveScale()) crosshairTextureNS:SetAllPoints(crosshairFrameNS) crosshairTextureNS:SetColorTexture(0, 0, 0, 1) local crosshairFrameEW = CreateFrame('Frame') local crosshairTextureEW = crosshairFrameEW:CreateTexture(nil, 'TOOLTIP') crosshairFrameEW:SetFrameStrata('TOOLTIP') crosshairFrameEW:SetWidth(GetScreenWidth() * UIParent:GetEffectiveScale()) crosshairFrameEW:SetHeight(1) crosshairTextureEW:SetAllPoints(crosshairFrameEW) crosshairTextureEW:SetColorTexture(0, 0, 0, 1) local function clear() shadeFrame:Hide() crosshairFrameNS:Hide() crosshairFrameEW:Hide() end local function shade(r, g, b, a) shadeTexture:SetColorTexture(r, g, b, a) shadeFrame:Show() end local function follow() local mouseX, mouseY = GetCursorPosition() crosshairFrameNS:SetPoint('TOPLEFT', mouseX, 0) crosshairFrameEW:SetPoint('BOTTOMLEFT', 0, mouseY) end local function crosshair(arg) local mouseX, mouseY = GetCursorPosition() crosshairFrameNS:SetPoint('TOPLEFT', mouseX, 0) crosshairFrameEW:SetPoint('BOTTOMLEFT', 0, mouseY) crosshairFrameNS:Show() crosshairFrameEW:Show() if arg == 'follow' then crosshairFrameNS:SetScript('OnUpdate', follow) else crosshairFrameNS:SetScript('OnUpdate', nil) end end local MoverList, BackupTable, f = {}, {} function F:Mover(text, value, anchor, width, height) local key = 'UIElementsAnchor' if not FreeUIConfig[key] then FreeUIConfig[key] = {} end local mover = CreateFrame('Frame', nil, UIParent) mover:SetWidth(width or self:GetWidth()) mover:SetHeight(height or self:GetHeight()) F.CreateBD(mover) F.CreateSD(mover) F.CreateFS(mover, (C.isCNClient and {C.font.normal, 11}) or 'pixel', text, 'yellow', true) tinsert(MoverList, mover) if not FreeUIConfig[key][value] then mover:SetPoint(unpack(anchor)) else mover:SetPoint(unpack(FreeUIConfig[key][value])) end mover:EnableMouse(true) mover:SetMovable(true) mover:SetClampedToScreen(true) mover:SetFrameStrata('HIGH') mover:RegisterForDrag('LeftButton') mover:SetScript('OnDragStart', function() mover:StartMoving() end) mover:SetScript('OnDragStop', function() mover:StopMovingOrSizing() local orig, _, tar, x, y = mover:GetPoint() FreeUIConfig[key][value] = {orig, 'UIParent', tar, x, y} end) mover:Hide() self:ClearAllPoints() self:SetPoint('TOPLEFT', mover) return mover end local function UnlockElements() for i = 1, #MoverList do local mover = MoverList[i] if not mover:IsShown() then mover:Show() end end F.CopyTable(FreeUIConfig['UIElementsAnchor'], BackupTable) f:Show() end local function LockElements() for i = 1, #MoverList do local mover = MoverList[i] mover:Hide() end f:Hide() --SlashCmdList['TOGGLEGRID']('1') toggle = 0 clear() end StaticPopupDialogs['FREEUI_MOVER_RESET'] = { text = L['MOVER_RESET_CONFIRM'], button1 = OKAY, button2 = CANCEL, OnAccept = function() wipe(FreeUIConfig['UIElementsAnchor']) ReloadUI() end, timeout = 0, whileDead = 1, hideOnEscape = true, preferredIndex = 5, } StaticPopupDialogs['FREEUI_MOVER_CANCEL'] = { text = L['MOVER_CANCEL_CONFIRM'], button1 = OKAY, button2 = CANCEL, OnAccept = function() F.CopyTable(BackupTable, FreeUIConfig['UIElementsAnchor']) ReloadUI() end, timeout = 0, whileDead = 1, hideOnEscape = true, preferredIndex = 5, } local function CreateConsole() if f then return end f = CreateFrame('Frame', nil, UIParent) f:SetPoint('TOP', 0, -150) f:SetSize(296, 65) F.CreateBD(f) F.CreateSD(f) F.CreateMF(f) F.CreateFS(f, {C.font.normal, 14}, L['MOVER_PANEL'], 'yellow', true, 'TOP', 0, -10) local bu, text = {}, {LOCK, CANCEL, L['MOVER_GRID'], RESET} for i = 1, 4 do bu[i] = F.CreateButton(f, 70, 28, text[i]) F.Reskin(bu[i]) if i == 1 then bu[i]:SetPoint('BOTTOMLEFT', 5, 5) else bu[i]:SetPoint('LEFT', bu[i-1], 'RIGHT', 2, 0) end end -- Lock bu[1]:SetScript('OnClick', LockElements) -- Cancel bu[2]:SetScript('OnClick', function() StaticPopup_Show('FREEUI_MOVER_CANCEL') end) -- Grids bu[3]:SetScript('OnClick', function() --SlashCmdList['TOGGLEGRID']('64') if toggle == 0 then shade(1, 1, 1, 0.85) crosshairTextureNS:SetColorTexture(0, 0, 0, 1) crosshairTextureEW:SetColorTexture(0, 0, 0, 1) crosshair('follow') toggle = 1 else toggle = 0 clear() end end) -- Reset bu[4]:SetScript('OnClick', function() StaticPopup_Show('FREEUI_MOVER_RESET') end) local function showLater(event) if event == 'PLAYER_REGEN_DISABLED' then if f:IsShown() then LockElements() F:RegisterEvent('PLAYER_REGEN_ENABLED', showLater) end else UnlockElements() F:UnregisterEvent(event, showLater) end end F:RegisterEvent('PLAYER_REGEN_DISABLED', showLater) end function F:MoverConsole() if InCombatLockdown() then UIErrorsFrame:AddMessage(C.InfoColor..ERR_NOT_IN_COMBAT) return end CreateConsole() UnlockElements() end SlashCmdList['FREEUI_MOVER'] = function() if InCombatLockdown() then UIErrorsFrame:AddMessage(C.InfoColor..ERR_NOT_IN_COMBAT) return end CreateConsole() UnlockElements() end SLASH_FREEUI_MOVER1 = '/mover'
function shared_pl_col_logic(a, other) if other.coin then other:obtain() end if other.balloon then other:pop() end end function get_direction_for_shooting(xf) local xdir = 0 local ydir = 0 if btn(1) then xdir = 1 elseif btn(0) then xdir = -1 end if btn(2) then ydir = -1 elseif btn(3) then ydir = 1 end if xdir == 0 and ydir == 0 then xdir = bool_to_num(xf) end return xdir, ydir end create_actor([[growing_circle;3;pre_drawable,drawable_obj,rel,confined| rel_actor:@1; color:@2; radius:@3; tl_max_time=.25,d=@4; -- init state ]], function(a) scr_circ(a.x, a.y, a.radius*a.tl_tim*6, a.color or 2) end) create_actor([[growing_circle_point;4;pre_drawable,drawable_obj,confined| x:@1; y:@2; color:@3; radius:@4; tl_max_time=.25,d=@5; -- init state ]], function(a) scr_circ(a.x, a.y, a.radius*a.tl_tim*6, a.color or 2) end) create_actor([[water_shot;4;post_drawable_2,mov,confined,col| x:@1; y:@2; xdir:@3; ydir:@4; touchable:no; ix:.85; iy:.85; i:@5; d:@6; tl_max_time=.5,; hit:@7; ]], function(a) g_stats.shots += 1 sfx'2' local ang = atan2(a.xdir, a.ydir) a.dx = cos(ang)*.8 a.dy = sin(ang)*.8 + .2 end, function(a) scr_circfill(a.x, a.y, 1/(1.5+a.tl_tim*16), 12) end, function(a, other) if other.boulder or (other.balloon and not other.bubble) then local sign = zsgn(a.dx) if sign == 0 then sign = zsgn(other.x - a.x) if sign == 0 then sign = flr_rnd(2) == 0 and -1 or 1 end end other.dx += sign*.05 _g.growing_circle(other, 12, 1) a.hit = nf elseif other.balloon then other:pop() a.hit = nf end end) create_actor([[pl_dead;3;post_drawable_1,spr,confined| x:@1; y:@2; xf:@3; sind:7; u=@4,tl_max_time=3; ]], function(a) a.ixx = rnd_one() a.iyy = rnd_one() end)
local assert = require('assert') local errno = require('errno') local realpath = require('realpath') local function test_realpath_resolve() -- test that resolve pathname for v, match in pairs({ ['.'] = 'lua%-realpath$', ['./test/..'] = 'lua%-realpath$', ['./test/realpath_test.lua'] = 'lua%-realpath/test/realpath_test%.lua$', }) do local pathname = assert(realpath(v)) assert.match(pathname, match, false) end -- test that perform normalization before resolve pathname local pathname, err = realpath('./foo/../bar/../test/realpath_test.lua/', true) assert.match(pathname, 'lua%-realpath/test/realpath_test%.lua$', false) assert.is_nil(err) -- test that returns error pathname, err = realpath('./foo/../bar/../realpath_test.lua/') assert.is_nil(pathname) assert.equal(err.type, errno.ENOENT) end local function test_realpath_normalize() -- test that peform normalize only -- NOTE: this test cases copied from -- https://github.com/golang/go/blob/go1.17.7/src/path/filepath/path_test.go#L26 for _, v in ipairs({ -- Already clean { "abc", "abc", }, { "abc/def", "abc/def", }, { "a/b/c", "a/b/c", }, { ".", ".", }, { "..", "..", }, { "../..", "../..", }, { "../../abc", "../../abc", }, { "/abc", "/abc", }, { "/", "/", }, -- Empty is current dir { "", ".", }, -- Remove trailing slash { "abc/", "abc", }, { "abc/def/", "abc/def", }, { "a/b/c/", "a/b/c", }, { "./", ".", }, { "../", "..", }, { "../../", "../..", }, { "/abc/", "/abc", }, -- Remove doubled slash { "abc//def//ghi", "abc/def/ghi", }, { "//abc", "/abc", }, { "///abc", "/abc", }, { "//abc//", "/abc", }, { "abc//", "abc", }, -- Remove . elements { "abc/./def", "abc/def", }, { "/./abc/def", "/abc/def", }, { "abc/.", "abc", }, -- Remove .. elements { "abc/def/ghi/../jkl", "abc/def/jkl", }, { "abc/def/../ghi/../jkl", "abc/jkl", }, { "abc/def/..", "abc", }, { "abc/def/../..", ".", }, { "/abc/def/../..", "/", }, { "abc/def/../../..", "..", }, { "/abc/def/../../..", "/", }, { "abc/def/../../../ghi/jkl/../../../mno", "../../mno", }, { "/../abc", "/abc", }, -- Combinations { "abc/./../def", "def", }, { "abc//./../def", "def", }, { "abc/../../././../def", "../../def", }, }) do local pathname = assert(realpath(v[1], nil, false)) -- print(string.format('#%02d: %-2s | %-38s | %-12s | %s', _, -- pathname == v[2] and '' or 'NG', v[1], pathname, -- v[2])) assert.equal(pathname, v[2]) end -- test that return error if pathname is invalid string local pathname, err = realpath('foo/bar' .. string.char(0) .. '/baz', nil, false) assert.is_nil(pathname); assert.equal(err.type, errno.EILSEQ) end test_realpath_resolve() test_realpath_normalize()
-- TreeView.lua -- @Author : DengSir (tdaddon@163.com) -- @Link : https://dengsir.github.io -- @Date : 10/20/2018, 4:28:53 PM -- ---@param ns table local ns = select(2, ...) local ipairs, type, setmetatable = ipairs, type, setmetatable local coroutine = coroutine local ceil, min, max = ceil, min, max local HybridScrollFrame_GetOffset = HybridScrollFrame_GetOffset local HybridScrollFrame_Update = HybridScrollFrame_Update ---@class TreeStatus: Object ---@field depth number ---@field extends any ---@field itemTree any local TreeStatus = ns.class() function TreeStatus:Constructor(itemTree, depth) self.itemTree = itemTree self.depth = depth self.extends = setmetatable({}, {__mode = 'k'}) end function TreeStatus:Iterate(start) local index = 0 local function Iterate(tree, depth) if depth > self.depth then return end for _, child in ipairs(tree) do index = index + 1 if not start or index >= start then coroutine.yield(depth, child) end if type(child) == 'table' and self.extends[child] then Iterate(child, depth + 1) end end end return coroutine.wrap(function() return Iterate(self.itemTree, 1) end) end function TreeStatus:GetCount() local function GetCount(tree, depth) if self.depth == depth then return #tree end local count = 0 for i, child in ipairs(tree) do count = count + 1 if type(child) == 'table' and self.extends[child] then count = count + GetCount(child, depth + 1) end end return count end return GetCount(self.itemTree, 1) end ---@class TreeView: _ScrollFrame ---@field treeStatus TreeStatus ---@field OnItemFormatting function local TreeView = ns.class(ns.ScrollFrame) ns.TreeView = TreeView function TreeView:Constructor(_, opts) self.treeStatus = TreeStatus:New(opts.itemTree, opts.depth) self.OnItemFormatting = opts.OnItemFormatting end function TreeView:update() local offset = HybridScrollFrame_GetOffset(self) local buttons = self.buttons local treeStatus = self.treeStatus local containerHeight = self:GetHeight() local buttonHeight = self.buttonHeight or buttons[1]:GetHeight() local itemCount = treeStatus:GetCount() local maxCount = ceil(containerHeight / buttonHeight) local buttonCount = min(maxCount, itemCount) local iter = treeStatus:Iterate(offset + 1) for i = 1, buttonCount do local index = i + offset local button = buttons[i] if index > itemCount then button:Hide() else local depth, item = iter() button.depth = depth button.item = item button.scrollFrame = self button:SetID(index) button:Show() self.OnItemFormatting[depth](button, item) end end for i = buttonCount + 1, #buttons do buttons[i]:Hide() end HybridScrollFrame_Update(self, max(1, itemCount * buttonHeight), containerHeight) end function TreeView:ToggleItem(item) self.treeStatus.extends[item] = not self.treeStatus.extends[item] or nil self:Refresh() end function TreeView:IsItemExpend(item) return self.treeStatus.extends[item] end
--[[ untestable by automatic tests: ClearUndoMove SetUndoLoc GetUndoLoc IsHighlighted PawnIsPlayerControlled MarkHpLoss GetMoveSkill SetMoveSkill SetRepairSkill ]] local tests = LApi.Tests tests:AddTests{ "PawnGetOwner", "PawnSetOwner", "PawnSetFire", "PawnGetImpactMaterial", "PawnSetImpactMaterial", "PawnGetColor", "PawnSetColor", "PawnIsMassive", "PawnSetMassive", --IsMovementAvailable --SetMovementAvailable "PawnSetFlying", "PawnSetTeleporter", "PawnSetJumper", "PawnGetMaxHealth", "PawnGetBaseMaxHealth", "PawnSetHealth", "PawnSetMaxHealth", "PawnSetBaseMaxHealth", "PawnGetWeaponCount", "PawnGetWeaponType", --"PawnGetWeaponClass", "PawnRemoveWeapon", --GetPilot --SetMech --IsTeleporter --IsJumper } LApi_TEST_WEAPON = Prime_Punchmech:new{} LApi_TEST_MECH = PunchMech:new{} function tests:PawnGetOwner() local loc = Point(0,0) local target = Point(1,0) Board:ClearSpace(loc) Board:ClearSpace(target) LApi_TEST_MECH = PunchMech:new{ SkillList = {"LApi_TEST_WEAPON"} } LApi_TEST_WEAPON = Skill:new{ GetSkillEffect = function(self, p1, p2) local ret = SkillEffect() local damage = SpaceDamage(p2) damage.sPawn = "LApi_TEST_MECH" ret:AddDamage(damage) return ret end } local parent = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") Board:AddPawn(parent, loc) parent:FireWeapon(target, 1) local child = Board:GetPawn(target) local ownerIsParent = child:GetOwner() == parent:GetId() Board:ClearSpace(loc) Board:ClearSpace(target) return ownerIsParent end function tests:PawnSetOwner() local loc = Point(0,0) local target = Point(1,0) Board:ClearSpace(loc) Board:ClearSpace(target) LApi_TEST_MECH = PunchMech:new{} local parent = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local child = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") Board:AddPawn(parent, loc) Board:AddPawn(child, target) local hasNoParent = child:GetOwner() == -1 child:SetOwner(parent:GetId()); local hasParent = child:GetOwner() == parent:GetId() Board:ClearSpace(loc) Board:ClearSpace(target) return hasNoParent, hasParent end function tests:PawnSetFire() local loc = Point(0,0) Board:ClearSpace(loc) LApi_TEST_MECH = PunchMech:new{} local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") Board:AddPawn(pawn, loc) local notOnFire = pawn:IsFire() == false pawn:SetFire(true); local onFire = pawn:IsFire() == true Board:ClearSpace(loc) return notOnFire, onFire end function tests:PawnGetImpactMaterial() LApi_TEST_MECH = PunchMech:new{ ImpactMaterial = IMPACT_INSECT } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local insect = pawn:GetImpactMaterial() == IMPACT_INSECT LApi_TEST_MECH = PunchMech:new{ ImpactMaterial = IMPACT_BLOB } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local blob = pawn:GetImpactMaterial() == IMPACT_BLOB return insecct, blob end function tests:PawnSetImpactMaterial() LApi_TEST_MECH = PunchMech:new{ ImpactMaterial = IMPACT_INSECT } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local insect = pawn:GetImpactMaterial() == IMPACT_INSECT pawn:SetImpactMaterial(IMPACT_BLOB); local blob = pawn:GetImpactMaterial() == IMPACT_BLOB return insect, blob end function tests:PawnGetColor() LApi_TEST_MECH = PunchMech:new{ ImageOffset = 0 } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local color0 = pawn:GetColor() == 0 LApi_TEST_MECH = PunchMech:new{ ImageOffset = 1 } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local color1 = pawn:GetColor() == 1 return color0, color1 end function tests:PawnSetColor() LApi_TEST_MECH = PunchMech:new{ ImageOffset = 0 } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local color0 = pawn:GetColor() == 0 pawn:SetColor(1); local color1 = pawn:GetColor() == 1 return color0, color1 end function tests:PawnIsMassive() LApi_TEST_MECH = PunchMech:new{ Massive = true } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local massive = pawn:IsMassive() == true LApi_TEST_MECH = PunchMech:new{ Massive = false } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local notMassive = pawn:IsMassive() == false return massive, notMassive end function tests:PawnSetMassive() LApi_TEST_MECH = PunchMech:new{ Massive = true } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local massive = pawn:IsMassive() == true pawn:SetMassive(false); local notMassive = pawn:IsMassive() == false return massive, notMassive end function tests:PawnSetFlying() LApi_TEST_MECH = PunchMech:new{ Flying = true } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local flying = pawn:IsFlying() == true pawn:SetFlying(false); local notFlying = pawn:IsFlying() == false return flying, notFlying end function tests:PawnSetTeleporter() LApi_TEST_MECH = PunchMech:new{ Teleporter = true } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local teleporter = pawn:IsTeleporter() == true pawn:SetTeleporter(false); local notTeleporter = pawn:IsTeleporter() == false return teleporter, notTeleporter end function tests:PawnSetJumper() LApi_TEST_MECH = PunchMech:new{ Jumper = true } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local jumper = pawn:IsJumper() == true pawn:SetJumper(false); local notJumper = pawn:IsJumper() == false return jumper, notJumper end -- fails if there are units on the field altering health. function tests:PawnGetMaxHealth() LApi_TEST_MECH = PunchMech:new{ Health = 5 } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local maxHealth5 = pawn:GetMaxHealth() == 5 LApi_TEST_MECH = PunchMech:new{ Health = 6 } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local maxHealth6 = pawn:GetMaxHealth() == 6 return maxHealth5, maxHealth6 end function tests:PawnGetBaseMaxHealth() local loc = Point(0,0) local locJelly = Point(1,0) Board:ClearSpace(loc) Board:ClearSpace(locJelly) local jelly = PAWN_FACTORY:CreatePawn("Jelly_Health1"); Board:AddPawn(jelly, locJelly) LApi_TEST_MECH = PunchMech:new{ Health = 5, SkillList = { "Passive_Psions" } } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH"); Board:AddPawn(pawn, loc) local baseMaxHealth5 = pawn:GetBaseMaxHealth() == 5 Board:ClearSpace(loc) Board:ClearSpace(locJelly) return baseMaxHealth5 end function tests:PawnSetHealth() LApi_TEST_MECH = PunchMech:new{ Health = 5 } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local health5 = pawn:GetHealth() == 5 pawn:SetHealth(7); local health5Max = pawn:GetHealth() == 5 pawn:SetHealth(2); local health2 = pawn:GetHealth() == 2 return health5, health5Max, health2 end function tests:PawnSetMaxHealth() LApi_TEST_MECH = PunchMech:new{ Health = 5 } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local maxHealth5 = pawn:GetMaxHealth() == 5 pawn:SetMaxHealth(7); local maxHealth7 = pawn:GetMaxHealth() == 7 return maxHealth5, maxHealth7 end function tests:PawnSetBaseMaxHealth() LApi_TEST_MECH = PunchMech:new{ Health = 5 } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local baseMaxHealth5 = pawn:GetBaseMaxHealth() == 5 pawn:SetBaseMaxHealth(7); local baseMaxHealth7 = pawn:GetBaseMaxHealth() == 7 return baseMaxHealth5, baseMaxHealth7 end function tests:PawnGetWeaponCount() LApi_TEST_MECH = PunchMech:new{ SkillList = { "Prime_Punchmech" } } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local weaponCount1 = pawn:GetWeaponCount() == 1 LApi_TEST_MECH = PunchMech:new{ SkillList = { "Prime_Punchmech", "Brute_Tankmech" } } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local weaponCount2 = pawn:GetWeaponCount() == 2 return weaponCount1, weaponCount2 end function tests:PawnGetWeaponType() LApi_TEST_MECH = PunchMech:new{ SkillList = { "Prime_Punchmech", "Brute_Tankmech" } } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local weaponType1 = pawn:GetWeaponType(1) == "Prime_Punchmech" local weaponType2 = pawn:GetWeaponType(2) == "Brute_Tankmech" return weaponType1, weaponType2 end function tests:PawnGetWeaponClass() LApi_TEST_MECH = PunchMech:new{ SkillList = { "Prime_Punchmech", "Brute_Tankmech" } } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local weaponClass1 = pawn:GetWeaponClass(1) == _G["Prime_Punchmech"].Class local weaponClass2 = pawn:GetWeaponClass(2) == _G["Brute_Tankmech"].Class return weaponClass1, weaponClass2 end function tests:PawnRemoveWeapon() LApi_TEST_MECH = PunchMech:new{ SkillList = { "Prime_Punchmech", "Brute_Tankmech" } } local pawn = PAWN_FACTORY:CreatePawn("LApi_TEST_MECH") local weaponCount2 = pawn:GetWeaponCount() == 2 pawn:RemoveWeapon(1) local weaponCount1 = pawn:GetWeaponCount() == 1 return weaponCount2, weaponCount1 end
-- JS<-->Lua glue -- -- Horribly hackish, this is not the right way to do it js.number = 1 js.string = 2 js.object = 3 js.func = 4 js.lua_table = {} js.lua_index = 1 js.to_js = function(x) if type(x) == 'number' then return tostring(x) elseif type(x) == 'string' then return '"' .. x .. '"' elseif type(x) == 'function' then local lua_index = js.lua_index js.lua_index = js.lua_index + 1 js.lua_table[lua_index] = x return 'Lua.funcWrapper(' .. lua_index .. ')' --elseif type(x) == 'table' then return 'Lua.wrappers[ else return '<{[Unsupported]}>' end end js.convert_args = function(args) local js_args = '' for i, v in ipairs(args) do if i > 1 then js_args = js_args .. ',' end js_args = js_args .. js.to_js(v) end return js_args end js.wrapper_index = 1 js.wrapper = {} js.wrapper.__index = function(table, key) if key == 'new' then local ret = { what = 'Lua.wrappers[' .. table.index .. ']' } setmetatable(ret, js.new.property) return ret end return js.get('Lua.wrappers[' .. table.index .. '].' .. key, table) end js.wrapper.__newindex = function(table, key, v) js.run('Lua.wrappers[' .. table.index .. '].'..key.."="..js.to_js(v)) end js.wrapper.__call = function(table, ...) if rawget(table, 'parent') then local suffix = js.convert_args({...}) if string.len(suffix) > 0 then suffix = ',' .. suffix end return js.get('(tempFunc = Lua.wrappers[' .. table.index .. '], tempFunc).call(Lua.wrappers[' .. table.parent.index .. ']' .. suffix .. ')') -- tempFunc needed to work around js invalid call issue FIXME else return js.get('(tempFunc = Lua.wrappers[' .. table.index .. '], tempFunc)(' .. js.convert_args({...}) .. ')') -- tempFunc needed to work around js invalid call issue FIXME end end js.wrapper.__gc = function(table) js.run('delete Lua.reverseWrappers[Lua.wrappers['..table.index..']]') js.run('delete Lua.wrappers['..table.index..']') end local wrapper_store = {} setmetatable(wrapper_store, {__mode='v'}) js.getWrapperStore = function() return wrapper_store end js.storeGet = function(idx) return wrapper_store[idx] end js.get = function(what, parent) local ret = { index = js.wrapper_index, parent=false } js.wrapper_index = js.wrapper_index + 1 local return_type = js.run("Lua.test('" .. what .. "', "..(js.wrapper_index-1)..")") if return_type < 0 then return wrapper_store[-return_type] elseif return_type == js.number then return js.run('Lua.last') elseif return_type == js.string then return js.run_string('Lua.last') elseif return_type == js.object or return_type == js.func then js.run('Lua.wrappers[' .. ret.index .. '] = Lua.last') ret.parent = parent setmetatable(ret, js.wrapper) wrapper_store[js.wrapper_index-1] = ret return ret else return '!Unsupported!' end end js.global = js.get('Lua.theGlobal') js.new = {} setmetatable(js.new, js.new) js.new.__index = function(table, key) local ret = { what = key } setmetatable(ret, js.new.property) return ret end js.new.property = {} js.new.property.__call = function(table, ...) return js.get('new ' .. table.what .. '(' .. js.convert_args({...}) .. ')') end
--=================-- local libTabMenu = {} --=================-- -- < Modules > -- local table2 = require "table2" -- < References > -- local constTabMenu = require "constTabMenu" --====================================================-- -- class tabMenuEntry -- -- Contains all customizable properties of one entry. -- --====================================================-- libTabMenu.tabMenuEntry = setmetatable({ Name = "New Tab Menu Entry", --== Text ==-- Label = "", -- Text shown on tab button Title = "", -- Title text Desc1 = "", -- Text in left description box Desc2 = "", -- Text in right description box --=============-- -- Constructor -- --=============-- new = function(self, o) o = o or {} setmetatable(o, {__index = self}) return o end, },{ --===========-- -- Metatable -- --===========-- }) --===============================================-- -- class tabMenu -- -- Handles creating and updating TabMenu Frames. -- --===============================================-- libTabMenu.tabMenu = setmetatable({ Name = "New Tab Menu", --== Auto-Update Functionality On Change ==-- Entries = {}, -- tabMenuEntry class objects BoardMode = false, -- If game has a leaderboard, set this to true, to avoid blocking X button. --== Read-Only ==-- Frame, -- Framehandle for main parent frame ButtonCurrent, -- Number of currently clicked tab button (0 to 4). Can be negative due to tab slider position. EntryCurrent, -- The table key into Entries to get the entry currently selected by tab buttons. EntryCount, -- Size of Entries array. (not the supaTable proxy) CloseButtonTrig, -- Trigger to hide frame when close button is clicked TabSliderTrig, -- Trigger to scroll tab buttons with slider TabButtonTrigs = {}, -- Triggers to update text when tab buttons are clicked TabPosOffset = 0, -- How much the width of first tab is adjusted to simulate scrolling TabSkip = 0, -- Number of tabs scrolled past with slider, starting from 0. --=============-- -- Constructor -- --=============-- new = function(self, o) o = o or {} -- Init default params and methods -- o.Entries = o.Entries or {} o.TabButtonTrigs = o.TabButtonTrigs or {} o.EntryCount = 0 for k, v in pairs(o.Entries) do o.EntryCount = o.EntryCount + 1 end o.Frame = BlzCreateFrame("TabMenu", BlzGetOriginFrame(ORIGIN_FRAME_GAME_UI, 0), 0, 0) BlzFrameSetAbsPoint(o.Frame, FRAMEPOINT_TOPLEFT, 0.02, 0.553) setmetatable(o, {__index = self}) -- This class is a supaTable -- local tbl = table2.supaTable:new(o) -- Set read-only properties (supaTable) -- tbl:setReadOnly(true, "Frame") tbl:setReadOnly(true, "ButtonCurrent") tbl:setReadOnly(true, "EntryCurrent") tbl:setReadOnly(true, "EntryCount") tbl:setReadOnly(true, "TabSliderTrig") tbl:setReadOnly(true, "TabButtonTrigs") tbl:setReadOnly(true, "TabPosOffset") tbl:setReadOnly(true, "TabSkip") -- Auto-update frame (supaTable) -- tbl:watchProp(function(t,k,v) local tbl0 = getmetatable(tbl).__index --set read-only prop (supaTable) local tblEntries = getmetatable(tbl.Entries).__index --get array size of actual table, not metatable proxy tbl0.EntryCount = 0 for k, v in pairs(tblEntries) do tbl0.EntryCount = tbl0.EntryCount + 1 end tbl:updateTabLabels() tbl:updateTabCount() tbl:updateTabSlider() tbl:updateText() end, "Entries", true) tbl:watchProp(function(t,k,v) tbl:updateCloseButtonPos() end, "BoardMode", false) -- Main -- tbl:updateCloseButtonPos() tbl:updateTabLabels() tbl:updateTabCount() tbl:updateTabSlider() tbl:initTabSliderTrig() tbl:initTabButtonTrigs() tbl:initCloseButtonTrig() -- Return -- return tbl end, --<< PRIVATE METHODS >>-- --=================================================-- -- tabMenu:updateCloseButtonPos() -- -- -- -- Positions CloseButton, TabBar, and TabBarSlider -- -- to be compatible with BoardMode. -- --=================================================-- updateCloseButtonPos = function(self) local closeButton = BlzFrameGetChild(self.Frame, 1) local tabBar = BlzFrameGetChild(self.Frame, 2) local tabSlider = BlzFrameGetChild(self.Frame, 3) local closeButtonY = -constTabMenu.borderSize local tabBarY = -constTabMenu.borderSize local tabSliderY = -constTabMenu.borderSize - (constTabMenu.menuSize * constTabMenu.tabBarHeight) if (self.BoardMode == false) then local closeButtonX = (constTabMenu.menuSize * constTabMenu.tabBarWidth) + constTabMenu.borderSize local tabBarX = constTabMenu.borderSize local tabSliderX = tabBarX BlzFrameSetPoint(closeButton, FRAMEPOINT_TOPLEFT, self.Frame, FRAMEPOINT_TOPLEFT, closeButtonX, closeButtonY) BlzFrameSetPoint(tabBar, FRAMEPOINT_TOPLEFT, self.Frame, FRAMEPOINT_TOPLEFT, tabBarX, tabBarY) BlzFrameSetPoint(tabSlider, FRAMEPOINT_TOPLEFT, self.Frame, FRAMEPOINT_TOPLEFT, tabSliderX, tabSliderY) else local closeButtonX = constTabMenu.borderSize local tabBarX = (constTabMenu.menuSize * constTabMenu.closeButtonWidth) + constTabMenu.borderSize local tabSliderX = tabBarX BlzFrameSetPoint(closeButton, FRAMEPOINT_TOPLEFT, self.Frame, FRAMEPOINT_TOPLEFT, closeButtonX, closeButtonY) BlzFrameSetPoint(tabBar, FRAMEPOINT_TOPLEFT, self.Frame, FRAMEPOINT_TOPLEFT, tabBarX, tabBarY) BlzFrameSetPoint(tabSlider, FRAMEPOINT_TOPLEFT, self.Frame, FRAMEPOINT_TOPLEFT, tabSliderX, tabSliderY) end end, --==============================================-- -- tabMenu:updateTabLabels() -- -- -- -- Updates tab labels to corresponding entries. -- --==============================================-- updateTabLabels = function(self) local tabBar = BlzFrameGetChild(self.Frame, 2) local tabFrameIndex = 0 local skippedEntries = 0 for k, v in table2.pairsByKeys(self.Entries) do if (skippedEntries < self.TabSkip) then skippedEntries = skippedEntries + 1 else local tab = BlzFrameGetChild(tabBar, tabFrameIndex) BlzFrameSetText(tab, v.Label) tabFrameIndex = tabFrameIndex + 1 if (tabFrameIndex > 4) then break end end end end, --=================================================-- -- tabMenu:updateTabCount() -- -- -- -- If less than 5 entries, hides some tab buttons. -- --=================================================-- updateTabCount = function(self) local tabBar = BlzFrameGetChild(self.Frame, 2) for i=1, math.min(5, self.EntryCount) do local tab = BlzFrameGetChild(tabBar, i-1) BlzFrameSetVisible(tab, true) end for i=(self.EntryCount+1), 5 do local tab = BlzFrameGetChild(tabBar, i-1) BlzFrameSetVisible(tab, false) end end, --=========================================-- -- tabMenu:updateTabSlider() -- -- -- -- If less than 5 entries, hide tab slider -- -- and reset tab width and position. -- --=========================================-- updateTabSlider = function(self) local tabBar = BlzFrameGetChild(self.Frame, 2) local tabSlider = BlzFrameGetChild(self.Frame, 3) local tabWidth = constTabMenu.menuSize * constTabMenu.tabWidth local tabHeight = constTabMenu.menuSize * constTabMenu.tabHeight if (self.EntryCount < 5) then BlzFrameSetVisible(tabSlider, false) BlzFrameSetValue(tabSlider, 0) for i=1, 4 do local tab = BlzFrameGetChild(tabBar, i-1) local tabPosX = tabWidth * (i-1) BlzFrameSetSize(tab, tabWidth, tabHeight) BlzFrameSetPoint(tab, FRAMEPOINT_TOPLEFT, tabBar, FRAMEPOINT_TOPLEFT, tabPosX, 0) end local tab4 = BlzFrameGetChild(tabBar, 4) local tabPosX4 = tabWidth * 4 BlzFrameSetSize(tab4, 0, tabHeight) BlzFrameSetPoint(tab4, FRAMEPOINT_TOPLEFT, tabBar, FRAMEPOINT_TOPLEFT, tabPosX4, 0) else BlzFrameSetVisible(tabSlider, true) end end, --================================================-- -- tabMenu:updateText() -- -- -- -- Updates text to show currently selected Entry. -- --================================================-- updateText = function(self) if (self.EntryCurrent == nil) then return end local textTitle = BlzFrameGetChild(BlzFrameGetChild(self.Frame, 4), 1) local textLeftBody = BlzFrameGetChild(BlzFrameGetChild(self.Frame, 5), 1) local textRightBody = BlzFrameGetChild(BlzFrameGetChild(self.Frame, 6), 1) BlzFrameSetText(textTitle, self.Entries[self.EntryCurrent].Title) BlzFrameSetText(textLeftBody, self.Entries[self.EntryCurrent].Desc1) BlzFrameSetText(textRightBody, self.Entries[self.EntryCurrent].Desc2) end, --=========================================================-- -- tabMenu:initTabSliderTrig() -- -- -- -- Updates trigger for scrolling through tabs with slider. -- --=========================================================-- initTabSliderTrig = function(self) local tbl = getmetatable(self).__index --Used to set read-only props (supaTable) local tabBar = BlzFrameGetChild(self.Frame, 2) local tabSlider = BlzFrameGetChild(self.Frame, 3) local tab0 = BlzFrameGetChild(tabBar, 0) local tab1 = BlzFrameGetChild(tabBar, 1) local tab2 = BlzFrameGetChild(tabBar, 2) local tab3 = BlzFrameGetChild(tabBar, 3) local tab4 = BlzFrameGetChild(tabBar, 4) local tabHeight = constTabMenu.menuSize * constTabMenu.tabHeight local tabWidth = constTabMenu.menuSize * constTabMenu.tabWidth local minWidth = 0.02 -- Update tabs every time slider changes -- local newTrig = CreateTrigger() BlzTriggerRegisterFrameEvent(newTrig, tabSlider, FRAMEEVENT_SLIDER_VALUE_CHANGED) TriggerAddAction(newTrig, function() if (GetLocalPlayer() ~= GetTriggerPlayer()) then return end if (self.EntryCount < 5) then return end -- Update read-only properties (supaTable) -- local oldTabSkip = self.TabSkip local sliderValue = BlzGetTriggerFrameValue() local sliderRangePerTab = constTabMenu.sliderRange / (self.EntryCount - 4) tbl.TabPosOffset = tabWidth * ((sliderValue % sliderRangePerTab) / sliderRangePerTab) tbl.TabSkip = math.floor(sliderValue / sliderRangePerTab) -- If scrolled to a new button -- if (self.TabSkip ~= oldTabSkip) then self:updateTabLabels() -- Update current selected button -- if (self.ButtonCurrent ~= nil) then local oldButtonNum = self.ButtonCurrent tbl.ButtonCurrent = self.ButtonCurrent + oldTabSkip - self.TabSkip end end -- Vertically indent currently selected button -- local tabHeight0 = (self.ButtonCurrent == 0) and (tabHeight + constTabMenu.tabSelectIndent) or tabHeight local tabHeight1 = (self.ButtonCurrent == 1) and (tabHeight + constTabMenu.tabSelectIndent) or tabHeight local tabHeight2 = (self.ButtonCurrent == 2) and (tabHeight + constTabMenu.tabSelectIndent) or tabHeight local tabHeight3 = (self.ButtonCurrent == 3) and (tabHeight + constTabMenu.tabSelectIndent) or tabHeight local tabHeight4 = (self.ButtonCurrent == 4) and (tabHeight + constTabMenu.tabSelectIndent) or tabHeight local tabPosY0 = (self.ButtonCurrent == 0) and constTabMenu.tabSelectIndent or 0 local tabPosY1 = (self.ButtonCurrent == 1) and constTabMenu.tabSelectIndent or 0 local tabPosY2 = (self.ButtonCurrent == 2) and constTabMenu.tabSelectIndent or 0 local tabPosY3 = (self.ButtonCurrent == 3) and constTabMenu.tabSelectIndent or 0 local tabPosY4 = (self.ButtonCurrent == 4) and constTabMenu.tabSelectIndent or 0 -- Adjust width and position of tabs to simulate scrolling -- local tabWidth0 = tabWidth - self.TabPosOffset local tabWidth1 = tabWidth local tabWidth2 = tabWidth local tabWidth3 = tabWidth local tabWidth4 = self.TabPosOffset local tabPosX0 = 0 local tabPosX1 = tabWidth0 local tabPosX2 = tabWidth0 + tabWidth1 local tabPosX3 = tabWidth0 + tabWidth1 + tabWidth2 local tabPosX4 = tabWidth0 + tabWidth1 + tabWidth2 + tabWidth3 BlzFrameSetSize(tab0, tabWidth0, tabHeight0) BlzFrameSetSize(tab1, tabWidth1, tabHeight1) BlzFrameSetSize(tab2, tabWidth2, tabHeight2) BlzFrameSetSize(tab3, tabWidth3, tabHeight3) BlzFrameSetSize(tab4, tabWidth4, tabHeight4) BlzFrameSetPoint(tab0, FRAMEPOINT_TOPLEFT, tabBar, FRAMEPOINT_TOPLEFT, tabPosX0, tabPosY0) BlzFrameSetPoint(tab1, FRAMEPOINT_TOPLEFT, tabBar, FRAMEPOINT_TOPLEFT, tabPosX1, tabPosY1) BlzFrameSetPoint(tab2, FRAMEPOINT_TOPLEFT, tabBar, FRAMEPOINT_TOPLEFT, tabPosX2, tabPosY2) BlzFrameSetPoint(tab3, FRAMEPOINT_TOPLEFT, tabBar, FRAMEPOINT_TOPLEFT, tabPosX3, tabPosY3) BlzFrameSetPoint(tab4, FRAMEPOINT_TOPLEFT, tabBar, FRAMEPOINT_TOPLEFT, tabPosX4, tabPosY4) --- Hide tabs if too small, to avoid display quirks -- if (tabWidth0 < minWidth) then BlzFrameSetVisible(tab0, false) else BlzFrameSetVisible(tab0, true) end if (tabWidth4 < minWidth) then BlzFrameSetVisible(tab4, false) else BlzFrameSetVisible(tab4, true) end end) -- Clean up old trigger and replace it with new trigger -- if (self.TabSliderTrig ~= nil) then DestroyTrigger(self.TabSliderTrig) end tbl.TabSliderTrig = newTrig end, --================================================================-- -- tabMenu:initTabButtonTrigs() -- -- -- -- Update triggers that change text when tab buttons are clicked. -- --================================================================-- initTabButtonTrigs = function(self) local tabBar = BlzFrameGetChild(self.Frame, 2) -- Used to set read-only props (supaTable) -- local tbl = getmetatable(self).__index local tblTrigs = getmetatable(self.TabButtonTrigs).__index local tblEntries = getmetatable(self.Entries).__index for i=1, 5 do -- Clean up old trigger -- if (self.TabButtonTrigs[i] ~= nil) then DestroyTrigger(self.TabButtonTrigs[i]) end -- Create new trigger that runs on button click -- local tabButton = BlzFrameGetChild(tabBar, i-1) tblTrigs[i] = CreateTrigger() BlzTriggerRegisterFrameEvent(self.TabButtonTrigs[i], tabButton, FRAMEEVENT_CONTROL_CLICK) TriggerAddAction(self.TabButtonTrigs[i], function() if (GetLocalPlayer() ~= GetTriggerPlayer()) then return end local buttonNum = i - 1 -- Traverse Entries in order of keys. EntryCurrent = TabSkip + i -- local skippedEntries = 0 local buttonIndex = 0 for k, v in table2.pairsByKeys(tblEntries) do if (skippedEntries < self.TabSkip) then skippedEntries = skippedEntries + 1 else buttonIndex = buttonIndex + 1 if (buttonIndex >= i) then tbl.EntryCurrent = k break end end end -- Update displayed text -- self:updateText() -- Indent clicked button -- local tabWidth = constTabMenu.menuSize * constTabMenu.tabWidth local tabHeight = constTabMenu.menuSize * constTabMenu.tabHeight local newTabHeight = tabHeight + constTabMenu.tabSelectIndent local newTabPosY = constTabMenu.tabSelectIndent local newTabWidth = tabWidth if (i == 1) then newTabWidth = tabWidth - self.TabPosOffset elseif (i == 5) then newTabWidth = self.TabPosOffset end local newTabPosX = 0 if (i == 2) then newTabPosX = tabWidth - self.TabPosOffset end if (i > 2) then newTabPosX = (tabWidth - self.TabPosOffset) + (tabWidth * (i-2)) end BlzFrameSetSize(tabButton, newTabWidth, newTabHeight) BlzFrameSetPoint(tabButton, FRAMEPOINT_TOPLEFT, tabBar, FRAMEPOINT_TOPLEFT, newTabPosX, newTabPosY) -- Unindent previously clicked button -- local buttonPrev = tbl.ButtonCurrent if (buttonPrev ~= nil) then local prevTabButton = BlzFrameGetChild(tabBar, buttonPrev) local prevTabPosX = 0 if (buttonPrev == 1) then prevTabPosX = tabWidth - self.TabPosOffset end if (buttonPrev > 1) then prevTabPosX = (tabWidth - self.TabPosOffset) + (tabWidth * (buttonPrev-1)) end BlzFrameSetSize(prevTabButton, tabWidth, tabHeight) BlzFrameSetPoint(prevTabButton, FRAMEPOINT_TOPLEFT, tabBar, FRAMEPOINT_TOPLEFT, prevTabPosX, 0) end -- Clear keyboard focus -- BlzFrameSetEnable(tabButton, false) BlzFrameSetEnable(tabButton, true) -- Update current button -- tbl.ButtonCurrent = i-1 end) end end, --===============================================================-- -- tabMenu:initCloseButtonTrig() -- -- -- -- Update trigger that hides frame when close button is clicked. -- --===============================================================-- initCloseButtonTrig = function(self) local xButton = BlzFrameGetChild(self.Frame, 1) local tabBar = BlzFrameGetChild(self.Frame, 2) local newTrig = CreateTrigger() BlzTriggerRegisterFrameEvent(newTrig, xButton, FRAMEEVENT_CONTROL_CLICK) TriggerAddAction(newTrig, function() if (GetLocalPlayer() ~= GetTriggerPlayer()) then return end BlzFrameSetVisible(self.Frame, false) end) -- Clean up old trigger and replace it with new trigger -- if (self.CloseButtonTrig ~= nil) then DestroyTrigger(self.CloseButtonTrig) end getmetatable(self).__index.CloseButtonTrig = newTrig --Set read-only prop (supaTable) end, },{ --===========-- -- Metatable -- --===========-- }) --=============-- return libTabMenu --=============--
return function() local Component = require(script.Parent.Component) local NoopRenderer = require(script.Parent.NoopRenderer) local Children = require(script.Parent.PropMarkers.Children) local createContext = require(script.Parent.createContext) local createElement = require(script.Parent.createElement) local createFragment = require(script.Parent.createFragment) local createReconciler = require(script.Parent.createReconciler) local createSpy = require(script.Parent.createSpy) local noopReconciler = createReconciler(NoopRenderer) it("should return a table", function() local context = createContext("Test") expect(context).to.be.ok() expect(type(context)).to.equal("table") end) it("should contain a Provider and a Consumer", function() local context = createContext("Test") expect(context.Provider).to.be.ok() expect(context.Consumer).to.be.ok() end) describe("Provider", function() it("should render its children", function() local context = createContext("Test") local Listener = createSpy(function() return nil end) local element = createElement(context.Provider, { value = "Test", }, { Listener = createElement(Listener.value), }) local tree = noopReconciler.mountVirtualTree(element, nil, "Provide Tree") noopReconciler.unmountVirtualTree(tree) expect(Listener.callCount).to.equal(1) end) end) describe("Consumer", function() it("should expect a render function", function() local context = createContext("Test") local element = createElement(context.Consumer) expect(function() noopReconciler.mountVirtualTree(element, nil, "Provide Tree") end).to.throw() end) it("should return the default value if there is no Provider", function() local valueSpy = createSpy() local context = createContext("Test") local element = createElement(context.Consumer, { render = valueSpy.value, }) local tree = noopReconciler.mountVirtualTree(element, nil, "Provide Tree") noopReconciler.unmountVirtualTree(tree) valueSpy:assertCalledWith("Test") end) it("should pass the value to the render function", function() local valueSpy = createSpy() local context = createContext("Test") local function Listener() return createElement(context.Consumer, { render = valueSpy.value, }) end local element = createElement(context.Provider, { value = "NewTest", }, { Listener = createElement(Listener), }) local tree = noopReconciler.mountVirtualTree(element, nil, "Provide Tree") noopReconciler.unmountVirtualTree(tree) valueSpy:assertCalledWith("NewTest") end) it("should update when the value updates", function() local valueSpy = createSpy() local context = createContext("Test") local function Listener() return createElement(context.Consumer, { render = valueSpy.value, }) end local element = createElement(context.Provider, { value = "NewTest", }, { Listener = createElement(Listener), }) local tree = noopReconciler.mountVirtualTree(element, nil, "Provide Tree") expect(valueSpy.callCount).to.equal(1) valueSpy:assertCalledWith("NewTest") noopReconciler.updateVirtualTree(tree, createElement(context.Provider, { value = "ThirdTest", }, { Listener = createElement(Listener), })) expect(valueSpy.callCount).to.equal(2) valueSpy:assertCalledWith("ThirdTest") noopReconciler.unmountVirtualTree(tree) end) --[[ This test is the same as the one above, but with a component that always blocks updates in the middle. We expect behavior to be the same. ]] it("should update when the value updates through an update blocking component", function() local valueSpy = createSpy() local context = createContext("Test") local UpdateBlocker = Component:extend("UpdateBlocker") function UpdateBlocker:render() return createFragment(self.props[Children]) end function UpdateBlocker:shouldUpdate() return false end local function Listener() return createElement(context.Consumer, { render = valueSpy.value, }) end local element = createElement(context.Provider, { value = "NewTest", }, { Blocker = createElement(UpdateBlocker, nil, { Listener = createElement(Listener), }), }) local tree = noopReconciler.mountVirtualTree(element, nil, "Provide Tree") expect(valueSpy.callCount).to.equal(1) valueSpy:assertCalledWith("NewTest") noopReconciler.updateVirtualTree(tree, createElement(context.Provider, { value = "ThirdTest", }, { Blocker = createElement(UpdateBlocker, nil, { Listener = createElement(Listener), }), })) expect(valueSpy.callCount).to.equal(2) valueSpy:assertCalledWith("ThirdTest") noopReconciler.unmountVirtualTree(tree) end) it("should behave correctly when the default value is nil", function() local context = createContext(nil) local valueSpy = createSpy() local function Listener() return createElement(context.Consumer, { render = valueSpy.value, }) end local tree = noopReconciler.mountVirtualTree(createElement(Listener), nil, "Provide Tree") expect(valueSpy.callCount).to.equal(1) valueSpy:assertCalledWith(nil) tree = noopReconciler.updateVirtualTree(tree, createElement(Listener)) noopReconciler.unmountVirtualTree(tree) expect(valueSpy.callCount).to.equal(2) valueSpy:assertCalledWith(nil) end) end) describe("Update order", function() --[[ This test ensures that there is no scenario where we can observe 'update tearing' when props and context are updated at the same time. Update tearing is scenario where a single update is partially applied in multiple steps instead of atomically. This is observable by components and can lead to strange bugs or errors. This instance of update tearing happens when updating a prop and a context value in the same update. Image we represent our tree's state as the current prop and context versions. Our initial state is: (prop_1, context_1) The next state we would like to update to is: (prop_2, context_2) Under the bug reported in issue 259, Roact reaches three different states in sequence: 1: (prop_1, context_1) - the initial state 2: (prop_2, context_1) - woops! 3: (prop_2, context_2) - correct end state In state 2, a user component was added that tried to access the current context value, which was not set at the time. This raised an error, because this state is not valid! The first proposed solution was to move the context update to happen before the props update. It is easy to show that this will still result in update tearing: 1: (prop_1, context_1) 2: (prop_1, context_2) 3: (prop_2, context_2) Although the initial concern about newly added components observing old context values is fixed, there is still a state desynchronization between props and state. We would instead like the following update sequence: 1: (prop_1, context_1) 2: (prop_2, context_2) This test tries to ensure that is the case. The initial bug report is here: https://github.com/Roblox/roact/issues/259 ]] it("should update context at the same time as props", function() -- These values are used to make sure we reach both the first and -- second state combinations we want to visit. local observedA = false local observedB = false local updateCount = 0 local context = createContext("default") local function Listener(props) return createElement(context.Consumer, { render = function(value) updateCount = updateCount + 1 if value == "context_1" then expect(props.someProp).to.equal("prop_1") observedA = true elseif value == "context_2" then expect(props.someProp).to.equal("prop_2") observedB = true else error("Unexpected context value") end end, }) end local element1 = createElement(context.Provider, { value = "context_1", }, { Child = createElement(Listener, { someProp = "prop_1", }), }) local element2 = createElement(context.Provider, { value = "context_2", }, { Child = createElement(Listener, { someProp = "prop_2", }), }) local tree = noopReconciler.mountVirtualTree(element1, nil, "UpdateObservationIsFun") noopReconciler.updateVirtualTree(tree, element2) expect(updateCount).to.equal(2) expect(observedA).to.equal(true) expect(observedB).to.equal(true) end) end) end
-------------------------------------------------------------------------------- -- Module Declaration -- local mod, CL = BigWigs:NewBoss("King Deepbeard", 1456, 1491) if not mod then return end mod:RegisterEnableMob(91797) mod.engageId = 1812 -------------------------------------------------------------------------------- -- Locals -- local bubblesOnMe = false -------------------------------------------------------------------------------- -- Initialization -- function mod:GetOptions() return { 193051, -- Call the Seas {193018, "FLASH"}, -- Gaseous Bubbles 193093, -- Ground Slam {193152, "PROXIMITY"}, -- Quake } end function mod:OnBossEnable() self:Log("SPELL_CAST_SUCCESS", "CallTheSeas", 193051) self:Log("SPELL_CAST_SUCCESS", "GaseousBubbles", 193018) self:Log("SPELL_AURA_APPLIED", "GaseousBubblesApplied", 193018) self:Log("SPELL_AURA_REMOVED", "GaseousBubblesRemoved", 193018) self:Log("SPELL_CAST_START", "GroundSlam", 193093) self:Log("SPELL_CAST_START", "Quake", 193152) self:Log("SPELL_DAMAGE", "Aftershock", 193171) self:Log("SPELL_MISSED", "Aftershock", 193171) end function mod:OnEngage() bubblesOnMe = false self:Bar(193051, 20) -- Call the Seas self:CDBar(193018, 12) -- Gaseous Bubbles self:CDBar(193093, 6) -- Ground Slam self:Bar(193152, 15) -- Quake self:OpenProximity(193152, 5) -- Quake end -------------------------------------------------------------------------------- -- Event Handlers -- function mod:CallTheSeas(args) self:Message(args.spellId, "yellow", "Long") self:Bar(args.spellId, 30) -- pull:20.5, 30.4, 30.3 end function mod:GaseousBubbles(args) self:CDBar(args.spellId, 32) -- pull:12.8, 35.3, 32.8 / m pull:12.9, 35.3, 32.8, 32.8 end function mod:GaseousBubblesApplied(args) if self:Me(args.destGUID) then bubblesOnMe = true self:TargetMessage(args.spellId, args.destName, "blue", "Warning") self:TargetBar(args.spellId, 20, args.destName) self:Flash(args.spellId) end end function mod:GaseousBubblesRemoved(args) if self:Me(args.destGUID) then bubblesOnMe = false self:Message(args.spellId, "blue", "Warning", CL.removed:format(args.spellName)) self:StopBar(args.spellName, args.destName) end end function mod:GroundSlam(args) self:Message(args.spellId, "orange", "Info", CL.incoming:format(args.spellName)) self:CDBar(args.spellId, 18) -- pull:5.9, 18.2, 20.6, 19.4 end function mod:Quake(args) self:Message(args.spellId, "red", "Alert") self:Bar(args.spellId, 21) -- pull:15.6, 21.9, 21.8, 21.8 end do local prev = 0 function mod:Aftershock(args) if self:Me(args.destGUID) then local t = GetTime() -- players with Gaseous Bubbles may (and should) be taking damage intentionally if t-prev > (bubblesOnMe and 6 or 1.5) then prev = t self:Message(193152, "blue", "Alert", CL.underyou:format(args.spellName)) end end end end
--[[ ########################################################## S V U I By: Failcoder ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --GLOBAL NAMESPACE local _G = _G; --LUA local unpack = _G.unpack; local select = _G.select; local assert = _G.assert; local SV = _G["SVUI"]; local L = SV.L local MOD = SV:NewModule(...); local Schema = MOD.Schema; MOD.media = {} MOD.media.dockIcon = [[Interface\AddOns\SVUI_QuestTracker\assets\DOCK-ICON-QUESTS]]; MOD.media.buttonArt = [[Interface\AddOns\SVUI_QuestTracker\assets\QUEST-BUTTON-ART]]; MOD.media.completeIcon = [[Interface\AddOns\SVUI_QuestTracker\assets\QUEST-COMPLETE-ICON]]; MOD.media.incompleteIcon = [[Interface\AddOns\SVUI_QuestTracker\assets\QUEST-INCOMPLETE-ICON]]; SV.defaults[Schema] = { ["rowHeight"] = 0, ["itemBarDirection"] = 'VERTICAL', ["itemButtonSize"] = 28, ["itemButtonsPerRow"] = 5, }; SV:AssignMedia("font", "questdialog", "SVUI Default Font", 12, "OUTLINE"); SV:AssignMedia("font", "questheader", "SVUI Caps Font", 16, "OUTLINE"); SV:AssignMedia("font", "questnumber", "SVUI Number Font", 11, "OUTLINE"); SV:AssignMedia("globalfont", "questdialog", "SVUI_Font_Quest"); SV:AssignMedia("globalfont", "questheader", "SVUI_Font_Quest_Header"); SV:AssignMedia("globalfont", "questnumber", "SVUI_Font_Quest_Number"); function MOD:LoadOptions() local questFonts = { ["questdialog"] = { order = 1, name = "Quest Tracker Dialog", desc = "Default font used in the quest tracker" }, ["questheader"] = { order = 2, name = "Quest Tracker Titles", desc = "Font used in the quest tracker for listing headers." }, ["questnumber"] = { order = 3, name = "Quest Tracker Numbers", desc = "Font used in the quest tracker to display numeric values." }, }; SV:GenerateFontOptionGroup("QuestTracker", 6, "Fonts used in the SVUI Quest Tracker.", questFonts) SV.Options.args[Schema] = { type = "group", name = Schema, args = { generalGroup = { order = 1, type = "group", name = "General", guiInline = true, args = { rowHeight = { order = 1, type = 'range', name = L["Row Height (minimum adjusted by font size)"], desc = L["Setting this to 0 (zero) will force an automatic size"], min = 0, max = 50, step = 1, width = "full", get = function(a)return SV.db[Schema][a[#a]] end, set = function(a,b) local c = SV.media.shared.font.questdialog.size; local d = c + 4; if((b > 0) and (b < d)) then b = d; end MOD:ChangeDBVar(b,a[#a]); MOD:UpdateSetup(); end }, } }, itemsGroup = { order = 2, type = "group", name = "Quest Items", guiInline = true, get = function(a)return SV.db[Schema][a[#a]] end, set = function(a,b) MOD:ChangeDBVar(b,a[#a]); MOD:UpdateLocals(); end, args = { itemBarDirection = { order = 1, type = 'select', name = L["Bar Direction"], values = { ['VERTICAL'] = L['Vertical'], ['HORIZONTAL'] = L['Horizontal'] }, }, itemButtonSize = { order = 2, type = 'range', name = L["Button Size"], min = 10, max = 100, step = 1, width = "full", }, itemButtonsPerRow = { order = 3, type = 'range', name = L["Buttons Per Row"], desc = L["This will only take effect if you have moved the item bar away from the dock."], min = 1, max = 20, step = 1, width = "full", }, } } } } end
-- coding: utf-8 --[[ -- PLEASE DO "NOT" EDIT THIS FILE! -- This file is generated by script. -- -- If you want to apply corrections visit: -- http://rom.curseforge.com/addons/addonmanager/localization/ --]] local lang={} lang.CAT = { } return lang
local techHandler = LazarusMod:GetModule('techhandler') techHandler:RemoveTechData(kTechId.GorgeEgg) techHandler:RemoveTechData(kTechId.LerkEgg) techHandler:RemoveTechData(kTechId.FadeEgg) techHandler:RemoveTechData(kTechId.OnosEgg)
local m = require 'model_helpers' local inspect = require 'inspect' local System = {} local Config = require 'models.config' local MiddlewareSpec = require 'models.middleware_spec' local shared_dict = require 'shared_dict' local jor = require 'jor' local crontab = require 'crontab' local statsd = require 'statsd_wrapper' local redis = require 'concurredis' System.is_initialized = function() return Config.get().initialized end System.initialize = function() MiddlewareSpec:ensure_defaults_exist() Config.update_missing({ initialized = true }) -- This ensures that crontab is re-launched if it dies crontab.initialize() end System.reset = function() statsd:flush(true) shared_dict.reset() -- this should go before crontab.reset jor:reset() Config.reset() crontab.reset() end System.cron_flush = function() crontab.flush() end System.cron_stats = function() return crontab.stats() end System.status = function() local cron = System.cron_stats() local redis = redis.status() local pid = ngx.worker.pid() return { cron = cron, redis = redis, pid = pid } end System.logfile = os.getenv('SLUG_LOGFILE') System.log = function(block) local log = io.open(System.logfile) log:seek('end') local loop = function(file, block, wait_time) local abort = false ngx.on_abort(function() abort = true end) repeat for line in file:lines() do block(line) end ngx.sleep(wait_time) until abort end local co = ngx.thread.spawn(loop, log, block, 0.5) local ok, res = ngx.thread.wait(co) log:close() return ok, res end System.run_timer = function(timer_id) local timer = crontab.get_timer(timer_id) if timer then crontab.run(timer, 'manual') end end return System
return {"abandoned","abilities","aboriginal","absolutely","absorption","abstracts","academics","acceptable","acceptance","accepting","accessibility","accessible","accessing","accessories","accessory","accidents","accommodate","accommodation","accommodations","accompanied","accompanying","accomplish","accomplished","accordance","according","accordingly","accountability","accounting","accreditation","accredited","accurately","acdbentity","achievement","achievements","achieving","acknowledge","acknowledged","acquisition","acquisitions","activated","activation","activists","activities","adaptation","addiction","additional","additionally","additions","addressed","addresses","addressing","adjustable","adjustment","adjustments","administered","administration","administrative","administrator","administrators","admission","admissions","adolescent","advancement","advantage","advantages","adventure","adventures","advertise","advertisement","advertisements","advertiser","advertisers","advertising","aerospace","affecting","affiliate","affiliated","affiliates","affiliation","affordable","afghanistan","afternoon","afterwards","aggregate","aggressive","agreement","agreements","agricultural","agriculture","albuquerque","alexander","alexandria","algorithm","algorithms","alignment","allocated","allocation","allowance","alphabetical","alternate","alternative","alternatively","alternatives","aluminium","ambassador","amendment","amendments","amenities","americans","amplifier","amsterdam","analytical","animation","anniversary","annotated","annotation","announced","announcement","announcements","announces","anonymous","answering","antarctica","anthropology","antibodies","anticipated","antivirus","apartment","apartments","apparatus","apparently","appearance","appearing","appliance","appliances","applicable","applicant","applicants","application","applications","appointed","appointment","appointments","appraisal","appreciate","appreciated","appreciation","approaches","appropriate","appropriations","approximate","approximately","arbitrary","arbitration","architect","architects","architectural","architecture","argentina","arguments","arlington","armstrong","arrangement","arrangements","arthritis","artificial","assembled","assessing","assessment","assessments","assignment","assignments","assistance","assistant","associate","associated","associates","association","associations","assumption","assumptions","assurance","astrology","astronomy","athletics","atmosphere","atmospheric","attachment","attachments","attempted","attempting","attendance","attending","attention","attitudes","attorneys","attraction","attractions","attractive","attribute","attributes","australia","australian","authentic","authentication","authorities","authority","authorization","authorized","automated","automatic","automatically","automation","automobile","automobiles","automotive","availability","available","awareness","azerbaijan","background","backgrounds","bacterial","baltimore","bandwidth","bangladesh","bankruptcy","barcelona","basically","basketball","bathrooms","batteries","battlefield","beastality","beautiful","beautifully","beginners","beginning","behavioral","benchmark","beneficial","bestsellers","beverages","bibliographic","bibliography","biodiversity","biographies","biography","biological","biotechnology","birmingham","blackberry","blackjack","bloomberg","bluetooth","bookmarks","bookstore","boulevard","boundaries","bracelets","brazilian","breakdown","breakfast","breathing","brilliant","britannica","broadband","broadcast","broadcasting","brochures","brunswick","buildings","bulgarian","burlington","businesses","butterfly","calculate","calculated","calculation","calculations","calculator","calculators","calendars","calibration","california","cambridge","camcorder","camcorders","campaigns","cancellation","cancelled","candidate","candidates","capabilities","capability","cardiovascular","carefully","caribbean","cartridge","cartridges","catalogue","categories","cathedral","catherine","celebrate","celebration","celebrities","celebrity","centuries","certainly","certificate","certificates","certification","certified","challenge","challenged","challenges","challenging","champagne","champions","championship","championships","chancellor","changelog","character","characteristic","characteristics","characterization","characterized","characters","charitable","charleston","charlotte","checklist","chemicals","chemistry","chevrolet","childhood","childrens","chocolate","cholesterol","christian","christianity","christians","christina","christine","christmas","christopher","chronicle","chronicles","cigarette","cigarettes","cincinnati","circulation","circumstances","citations","citizenship","citysearch","civilization","classical","classification","classified","classifieds","classroom","clearance","cleveland","coalition","cognitive","collaboration","collaborative","colleague","colleagues","collectables","collected","collectible","collectibles","collecting","collection","collections","collective","collector","collectors","columnists","combination","combinations","combining","comfortable","commander","commentary","commented","commercial","commission","commissioner","commissioners","commissions","commitment","commitments","committed","committee","committees","commodities","commodity","commonwealth","communicate","communication","communications","communist","communities","community","companies","companion","comparable","comparative","comparing","comparison","comparisons","compatibility","compatible","compensation","competent","competing","competition","competitions","competitive","competitors","compilation","complaint","complaints","complement","completed","completely","completing","completion","complexity","compliance","compliant","complicated","complications","complimentary","component","components","composite","composition","compounds","comprehensive","compressed","compression","compromise","computation","computational","computers","computing","concentrate","concentration","concentrations","conceptual","concerned","concerning","concluded","conclusion","conclusions","condition","conditional","conditioning","conditions","conducted","conducting","conference","conferences","conferencing","confidence","confident","confidential","confidentiality","configuration","configurations","configure","configured","configuring","confirmation","confirmed","conflicts","confusion","congratulations","congressional","conjunction","connected","connecticut","connecting","connection","connections","connectivity","connector","connectors","conscious","consciousness","consecutive","consensus","consequence","consequences","consequently","conservation","conservative","considerable","consideration","considerations","considered","considering","considers","consistency","consistent","consistently","consisting","consolidated","consolidation","consortium","conspiracy","constantly","constitute","constitutes","constitution","constitutional","constraint","constraints","construct","constructed","construction","consultancy","consultant","consultants","consultation","consulting","consumers","consumption","contacted","contacting","contained","container","containers","containing","contamination","contemporary","continent","continental","continually","continued","continues","continuing","continuity","continuous","continuously","contracting","contractor","contractors","contracts","contribute","contributed","contributing","contribution","contributions","contributor","contributors","controlled","controller","controllers","controlling","controversial","controversy","convenience","convenient","convention","conventional","conventions","convergence","conversation","conversations","conversion","converted","converter","convertible","convicted","conviction","convinced","cooperation","cooperative","coordinate","coordinated","coordinates","coordination","coordinator","copyright","copyrighted","copyrights","corporate","corporation","corporations","corrected","correction","corrections","correctly","correlation","correspondence","corresponding","corruption","cosmetics","counseling","countries","creations","creativity","creatures","criterion","criticism","crossword","cumulative","currencies","currently","curriculum","customers","customize","customized","dangerous","databases","daughters","decisions","declaration","decorating","decorative","decreased","dedicated","defendant","defensive","definitely","definition","definitions","delegation","delicious","delivered","delivering","demanding","democracy","democratic","democrats","demographic","demonstrate","demonstrated","demonstrates","demonstration","department","departmental","departments","departure","dependence","dependent","depending","deployment","depression","descending","described","describes","describing","description","descriptions","designated","designation","designers","designing","desirable","desperate","destination","destinations","destroyed","destruction","detection","detective","determination","determine","determined","determines","determining","deutschland","developed","developer","developers","developing","development","developmental","developments","deviation","diagnosis","diagnostic","dictionaries","dictionary","difference","differences","different","differential","differently","difficult","difficulties","difficulty","dimension","dimensional","dimensions","direction","directions","directive","directories","directors","directory","disabilities","disability","disappointed","discharge","disciplinary","discipline","disciplines","disclaimer","disclaimers","disclosure","discounted","discounts","discovered","discovery","discretion","discrimination","discussed","discusses","discussing","discussion","discussions","disorders","dispatched","displayed","displaying","disposition","distances","distinction","distinguished","distribute","distributed","distribution","distributions","distributor","distributors","districts","disturbed","diversity","divisions","documentary","documentation","documented","documents","dominican","donations","downloadable","downloaded","downloading","downloads","dramatically","duplicate","earthquake","ecological","ecommerce","economics","economies","edinburgh","editorial","editorials","education","educational","educators","effective","effectively","effectiveness","efficiency","efficient","efficiently","elections","electoral","electrical","electricity","electronic","electronics","elementary","elevation","eligibility","eliminate","elimination","elizabeth","elsewhere","emergency","emissions","emotional","empirical","employees","employers","employment","enclosure","encounter","encountered","encourage","encouraged","encourages","encouraging","encryption","encyclopedia","endangered","endorsement","enforcement","engagement","engineering","engineers","enhancement","enhancements","enhancing","enlargement","enquiries","enrollment","enterprise","enterprises","entertaining","entertainment","entrepreneur","entrepreneurs","environment","environmental","environments","equations","equilibrium","equipment","equivalent","especially","essential","essentially","essentials","establish","established","establishing","establishment","estimated","estimates","estimation","evaluated","evaluating","evaluation","evaluations","evanescence","eventually","everybody","everything","everywhere","evolution","examination","examinations","examining","excellence","excellent","exception","exceptional","exceptions","excessive","exchanges","excitement","excluding","exclusion","exclusive","exclusively","execution","executive","executives","exemption","exercises","exhibition","exhibitions","existence","expanding","expansion","expectations","expenditure","expenditures","expensive","experience","experienced","experiences","experiencing","experiment","experimental","experiments","expertise","expiration","explained","explaining","explanation","explicitly","exploration","exploring","explosion","expressed","expression","expressions","extending","extension","extensions","extensive","extraction","extraordinary","extremely","facilitate","facilities","fairfield","fantastic","fascinating","favorites","featuring","federation","fellowship","festivals","filtering","financial","financing","findarticles","finishing","fireplace","fisheries","flexibility","following","forbidden","forecasts","forgotten","formation","formatting","forwarding","foundation","foundations","fragrance","fragrances","framework","franchise","francisco","frankfurt","frederick","freelance","frequencies","frequency","frequently","friendship","frontpage","functional","functionality","functioning","functions","fundamental","fundamentals","fundraising","furnished","furnishings","furniture","furthermore","galleries","gardening","gathering","genealogy","generally","generated","generates","generating","generation","generations","generator","generators","gentleman","geographic","geographical","geography","geological","gibraltar","girlfriend","governance","governing","government","governmental","governments","gradually","graduated","graduates","graduation","graphical","greenhouse","greensboro","greetings","groundwater","guarantee","guaranteed","guarantees","guatemala","guestbook","guidelines","halloween","hampshire","handhelds","happening","happiness","harassment","hardcover","hazardous","headlines","headphones","headquarters","healthcare","helicopter","henderson","hepatitis","hierarchy","highlight","highlighted","highlights","historical","hollywood","holocaust","hopefully","horizontal","hospitality","hospitals","household","households","housewares","housewives","humanitarian","humanities","hungarian","huntington","hurricane","hydraulic","hydrocodone","hypothesis","hypothetical","identical","identification","identified","identifier","identifies","identifying","illustrated","illustration","illustrations","imagination","immediate","immediately","immigrants","immigration","immunology","implement","implementation","implemented","implementing","implications","importance","important","importantly","impossible","impressed","impression","impressive","improvement","improvements","improving","inappropriate","incentive","incentives","incidence","incidents","including","inclusion","inclusive","incomplete","incorporate","incorporated","incorrect","increased","increases","increasing","increasingly","incredible","independence","independent","independently","indianapolis","indicated","indicates","indicating","indication","indicator","indicators","indigenous","individual","individually","individuals","indonesia","indonesian","induction","industrial","industries","inexpensive","infection","infections","infectious","inflation","influence","influenced","influences","information","informational","informative","infrastructure","infringement","ingredients","inherited","initially","initiated","initiative","initiatives","injection","innovation","innovations","innovative","inquiries","insertion","inspection","inspections","inspector","inspiration","installation","installations","installed","installing","instances","instantly","institute","institutes","institution","institutional","institutions","instruction","instructional","instructions","instructor","instructors","instrument","instrumental","instrumentation","instruments","insulation","insurance","integrate","integrated","integrating","integration","integrity","intellectual","intelligence","intelligent","intensity","intensive","intention","interaction","interactions","interactive","interested","interesting","interests","interface","interfaces","interference","intermediate","international","internationally","internship","interpretation","interpreted","interracial","intersection","interstate","intervals","intervention","interventions","interview","interviews","introduce","introduced","introduces","introducing","introduction","introductory","invention","inventory","investigate","investigated","investigation","investigations","investigator","investigators","investing","investment","investments","investors","invisible","invitation","invitations","involvement","involving","irrigation","isolation","jacksonville","javascript","jefferson","jerusalem","jewellery","journalism","journalist","journalists","jurisdiction","kazakhstan","keyboards","kilometers","knowledge","knowledgestorm","laboratories","laboratory","lafayette","lancaster","landscape","landscapes","languages","lauderdale","leadership","legendary","legislation","legislative","legislature","legitimate","lexington","liabilities","liability","librarian","libraries","licensing","liechtenstein","lifestyle","lightning","lightweight","likelihood","limitation","limitations","limousines","listening","listprice","literally","literature","lithuania","litigation","liverpool","livestock","locations","logistics","longitude","looksmart","louisiana","louisville","luxembourg","macedonia","machinery","macintosh","macromedia","madagascar","magazines","magnificent","magnitude","mainstream","maintained","maintaining","maintains","maintenance","malpractice","management","manchester","mandatory","manhattan","manufacture","manufactured","manufacturer","manufacturers","manufacturing","marijuana","marketing","marketplace","massachusetts","mastercard","masturbating","masturbation","materials","maternity","mathematical","mathematics","mauritius","meaningful","meanwhile","measurement","measurements","measuring","mechanical","mechanics","mechanism","mechanisms","mediawiki","medication","medications","medicines","meditation","mediterranean","melbourne","membership","memorabilia","mentioned","merchandise","merchants","messaging","messenger","metabolism","metallica","methodology","metropolitan","microphone","microsoft","microwave","migration","milfhunter","millennium","milwaukee","miniature","ministers","ministries","minneapolis","minnesota","miscellaneous","mississippi","mitsubishi","modelling","moderator","moderators","modification","modifications","molecular","molecules","monitored","monitoring","montgomery","mortality","mortgages","motherboard","motivated","motivation","motorcycle","motorcycles","mountains","movements","mozambique","multimedia","municipal","municipality","musicians","mysterious","namespace","narrative","nashville","nationally","nationwide","naturally","navigation","navigator","necessarily","necessary","necessity","negotiation","negotiations","neighborhood","neighbors","netherlands","networking","nevertheless","newcastle","newfoundland","newsletter","newsletters","newspaper","newspapers","nicaragua","nightlife","nightmare","nominated","nomination","nominations","nonprofit","northeast","northwest","norwegian","notebooks","notification","notifications","nottingham","numerical","nutrition","nutritional","obituaries","objective","objectives","obligation","obligations","observation","observations","obtaining","obviously","occasional","occasionally","occasions","occupation","occupational","occupations","occurrence","occurring","offensive","offerings","officially","officials","omissions","operating","operation","operational","operations","operators","opponents","opportunities","opportunity","opposition","optimization","orchestra","ordinance","organisation","organisations","organisms","organization","organizational","organizations","organized","organizer","organizing","orientation","originally","otherwise","ourselves","outsourcing","outstanding","overnight","ownership","packaging","paintball","paintings","palestine","palestinian","panasonic","pantyhose","paperback","paperbacks","paragraph","paragraphs","parameter","parameters","parenting","parliament","parliamentary","partially","participant","participants","participate","participated","participating","participation","particles","particular","particularly","partition","partnership","partnerships","passenger","passengers","passwords","pathology","pediatric","penalties","penetration","peninsula","pennsylvania","perceived","percentage","perception","perfectly","performance","performances","performed","performer","performing","periodically","peripheral","peripherals","permalink","permanent","permission","permissions","permitted","persistent","personality","personalized","personally","personals","personnel","perspective","perspectives","petersburg","petroleum","pharmaceutical","pharmaceuticals","pharmacies","pharmacology","phenomenon","phentermine","philadelphia","philippines","philosophy","photograph","photographer","photographers","photographic","photographs","photography","photoshop","physically","physician","physicians","physiology","pichunter","pittsburgh","placement","plaintiff","platforms","playstation","political","politicians","pollution","polyester","polyphonic","popularity","population","populations","porcelain","portfolio","portraits","portsmouth","portuguese","positioning","positions","possession","possibilities","possibility","postcards","postposted","potential","potentially","powerpoint","powerseller","practical","practices","practitioner","practitioners","preceding","precipitation","precisely","precision","predicted","prediction","predictions","preference","preferences","preferred","pregnancy","preliminary","preparation","preparing","prerequisite","prescribed","prescription","presentation","presentations","presented","presenting","presently","preservation","president","presidential","preventing","prevention","previously","primarily","princeton","principal","principle","principles","printable","priorities","prisoners","privilege","privileges","probability","procedure","procedures","proceeding","proceedings","processed","processes","processing","processor","processors","procurement","producers","producing","production","productions","productive","productivity","profession","professional","professionals","professor","programme","programmer","programmers","programmes","programming","progressive","prohibited","projected","projection","projector","projectors","prominent","promising","promoting","promotion","promotional","promotions","properties","proportion","proposals","proposition","proprietary","prospective","prospects","prostores","protected","protecting","protection","protective","protocols","prototype","providence","providers","providing","provinces","provincial","provision","provisions","psychiatry","psychological","psychology","publication","publications","publicity","published","publisher","publishers","publishing","punishment","purchased","purchases","purchasing","qualification","qualifications","qualified","qualifying","qualities","quantitative","quantities","quarterly","queensland","questionnaire","questions","quotations","radiation","reactions","realistic","reasonable","reasonably","reasoning","receivers","receiving","reception","receptors","recipient","recipients","recognition","recognize","recognized","recommend","recommendation","recommendations","recommended","recommends","reconstruction","recorders","recording","recordings","recovered","recreation","recreational","recruiting","recruitment","recycling","reduction","reductions","reference","referenced","references","referrals","referring","refinance","reflected","reflection","reflections","refrigerator","refurbished","regarding","regardless","registered","registrar","registration","regression","regularly","regulated","regulation","regulations","regulatory","rehabilitation","relations","relationship","relationships","relatively","relatives","relaxation","relevance","reliability","religions","religious","relocation","remainder","remaining","remarkable","remembered","removable","renaissance","rendering","renewable","replacement","replacing","replication","reporters","reporting","repository","represent","representation","representations","representative","representatives","represented","representing","represents","reproduce","reproduced","reproduction","reproductive","republican","republicans","reputation","requested","requesting","requirement","requirements","requiring","researcher","researchers","reservation","reservations","reservoir","residence","residential","residents","resistance","resistant","resolution","resolutions","resources","respected","respective","respectively","respiratory","responded","respondent","respondents","responding","responses","responsibilities","responsibility","responsible","restaurant","restaurants","restoration","restricted","restriction","restrictions","restructuring","resulting","retailers","retention","retirement","retrieval","retrieved","returning","revelation","reviewing","revisions","revolution","revolutionary","richardson","ringtones","riverside","robertson","rochester","roommates","sacramento","sacrifice","salvation","saskatchewan","satellite","satisfaction","satisfactory","satisfied","scenarios","scheduled","schedules","scheduling","scholarship","scholarships","scientific","scientist","scientists","screening","screensaver","screensavers","screenshot","screenshots","scripting","sculpture","searching","secondary","secretariat","secretary","securities","selecting","selection","selections","selective","semiconductor","sensitive","sensitivity","sentences","separated","separately","separation","september","sequences","seriously","settlement","sexuality","shakespeare","shareholders","shareware","sheffield","shipments","shopzilla","shortcuts","showtimes","signature","signatures","significance","significant","significantly","similarly","simplified","simulation","simulations","simultaneously","singapore","situation","situations","slideshow","smithsonian","snowboard","societies","sociology","solutions","something","sometimes","somewhere","sophisticated","soundtrack","southampton","southeast","southwest","specialist","specialists","specialized","specializing","specially","specialties","specialty","specifically","specification","specifications","specifics","specified","specifies","spectacular","spiritual","spirituality","spokesman","sponsored","sponsorship","spotlight","spreading","springfield","squirting","stability","stainless","stakeholders","standards","standings","starsmerchant","statement","statements","statewide","stationery","statistical","statistics","statutory","stephanie","stockholm","stockings","strategic","strategies","streaming","strengthen","strengthening","strengths","structural","structure","structured","structures","subcommittee","subdivision","subjective","sublimedirectory","submission","submissions","submitted","submitting","subscribe","subscriber","subscribers","subscription","subscriptions","subsection","subsequent","subsequently","subsidiaries","subsidiary","substance","substances","substantial","substantially","substitute","successful","successfully","suffering","sufficient","sufficiently","suggested","suggesting","suggestion","suggestions","summaries","sunglasses","superintendent","supervision","supervisor","supervisors","supplement","supplemental","supplements","suppliers","supported","supporters","supporting","surprised","surprising","surrounded","surrounding","surveillance","survivors","suspected","suspended","suspension","sustainability","sustainable","sustained","swaziland","switching","switzerland","symposium","syndicate","syndication","synthesis","synthetic","systematic","technical","technician","technique","techniques","technological","technologies","technology","techrepublic","telecharger","telecommunications","telephone","telephony","telescope","television","televisions","temperature","temperatures","templates","temporarily","temporary","tennessee","terminals","termination","terminology","territories","territory","terrorism","terrorist","terrorists","testament","testimonials","testimony","textbooks","thanksgiving","themselves","theoretical","therapeutic","therapist","thereafter","therefore","thesaurus","thickness","thoroughly","thousands","threatened","threatening","threshold","throughout","thumbnail","thumbnails","thumbzilla","tolerance","tournament","tournaments","trackback","trackbacks","trademark","trademarks","tradition","traditional","traditions","transaction","transactions","transcript","transcription","transcripts","transexual","transexuales","transferred","transfers","transform","transformation","transition","translate","translated","translation","translations","translator","transmission","transmitted","transparency","transparent","transport","transportation","transsexual","travelers","traveling","traveller","travelling","treasurer","treasures","treatment","treatments","tremendous","tripadvisor","troubleshooting","tutorials","typically","ultimately","unauthorized","unavailable","uncertainty","undefined","undergraduate","underground","underlying","understand","understanding","understood","undertake","undertaken","underwear","unemployment","unexpected","unfortunately","uniprotkb","universal","universities","university","unlimited","unnecessary","unsubscribe","upgrading","utilities","utilization","uzbekistan","vacancies","vacations","valentine","validation","valuation","vancouver","variables","variation","variations","varieties","vbulletin","vegetable","vegetables","vegetarian","vegetation","venezuela","verification","verzeichnis","veterinary","vibrators","victorian","vietnamese","viewpicture","violation","violations","virtually","visibility","vocabulary","vocational","volkswagen","volleyball","voluntary","volunteer","volunteers","voyeurweb","vulnerability","vulnerable","wallpaper","wallpapers","warehouse","warranties","washington","waterproof","watershed","webmaster","webmasters","wednesday","wellington","westminster","wholesale","widescreen","widespread","wikipedia","wilderness","wisconsin","withdrawal","witnesses","wonderful","wondering","worcester","wordpress","workforce","workplace","workshops","workstation","worldwide","wrestling","yesterday","yorkshire","yugoslavia"}
local oldKeyboardSetTextInput = love.keyboard.setTextInput function love.keyboard.setTextInput(config) end
local SwapItem = {} SwapItem.Name = "purchase item" SwapItem.NumArgs = 3 function SwapItem:Call( hUnit, slotA, slotB ) hUnit:ActionImmediate_SwapItems(slotA[1], slotB[1]) end return SwapItem
local Class = require("Classy") ---@class KVstore --- Simple KeyStore ---@field data table all currently held key=value pairs local KVstore = Class("KVstore", {data = {}}) function KVstore:new(data) if data then for k, v in pairs(data) do self.data[k] = v end end end function KVstore:setValue(key, value) self.data[key] = value end function KVstore:getValue(key) return self.data[key] end function KVstore:purge() self.data = {} end return KVstore
-- -- Abstract: animated sprite or "movieclip" library -- This library assembles animation sequences from individual image files. For more advanced -- texture memory handling, see the "sprite sheet" feature in Corona Game Edition. -- -- Version: 2.1 -- -- Copyright (C) 2010 ANSCA Inc. All Rights Reserved. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy of -- this software and associated documentation files (the "Software"), to deal in the -- Software without restriction, including without limitation the rights to use, copy, -- modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, -- and to permit persons to whom the Software is furnished to do so, subject to the -- following conditions: -- -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. -- movieclip.lua (a convenience library for assembling animated sprites from separate images) module(..., package.seeall) function newAnim (imageTable) -- Set up graphics local g = display.newGroup() local animFrames = {} local animLabels = {} local limitX, limitY, transpose local i = 1 while imageTable[i] do animFrames[i] = display.newImage(imageTable[i]); g:insert(animFrames[i], true) animLabels[i] = i -- default frame label is frame number animFrames[i].isVisible = false i = i + 1 end -- show first frame by default animFrames[1].isVisible = true ------------------------- -- Define private methods local currentFrame = 1 local totalFrames = #animFrames local startFrame = 1 local endFrame = #animFrames local loop = 0 local loopCount = 0 local remove = false local dragBounds = nil local dragLeft, dragTop, dragWidth, dragHeight -- flag to distinguish initial default case (where no sequence parameters are submitted) local inSequence = false local function resetDefaults() currentFrame = 1 startFrame = 1 endFrame = #animFrames loop = 0 loopCount = 0 remove = false end local function resetReverseDefaults() currentFrame = #animFrames startFrame = #animFrames endFrame = 1 loop = 0 loopCount = 0 remove = false end local function nextFrame( self, event ) animFrames[currentFrame].isVisible = false currentFrame = currentFrame + 1 if (currentFrame == endFrame + 1) then if (loop > 0) then loopCount = loopCount + 1 if (loopCount == loop) then -- stop looping currentFrame = currentFrame - 1 animFrames[currentFrame].isVisible = true Runtime:removeEventListener( "enterFrame", self ) if (remove) then -- delete self (only gets garbage collected if there are no other references) if self.removeSelf then self:removeSelf() end end else currentFrame = startFrame animFrames[currentFrame].isVisible = true end else currentFrame = startFrame animFrames[currentFrame].isVisible = true end elseif (currentFrame > #animFrames) then currentFrame = 1 animFrames[currentFrame].isVisible = true else animFrames[currentFrame].isVisible = true end end local function prevFrame( self, event ) animFrames[currentFrame].isVisible = false currentFrame = currentFrame - 1 if (currentFrame == endFrame - 1) then if (loop > 0) then loopCount = loopCount + 1 if (loopCount == loop) then -- stop looping currentFrame = currentFrame + 1 animFrames[currentFrame].isVisible = true Runtime:removeEventListener( "enterFrame", self ) if (remove) then -- delete self self.parent:remove(self) end else currentFrame = startFrame animFrames[currentFrame].isVisible = true end else currentFrame = startFrame animFrames[currentFrame].isVisible = true end elseif (currentFrame < 1) then currentFrame = #animFrames animFrames[currentFrame].isVisible = true else animFrames[currentFrame].isVisible = true end end local function dragMe(self, event) local onPress = self._onPress local onDrag = self._onDrag local onRelease = self._onRelease if event.phase == "began" then display.getCurrentStage():setFocus( self ) g._startX = event.x - g.x g._startY = event.y - g.y if onPress then result = onPress( event ) end elseif event.phase == "moved" then if transpose == true then -- Note: "transpose" is deprecated now that Corona supports native landscape mode -- dragBounds is omitted in transposed mode, but feel free to implement it if limitX ~= true then g.x = g._startX - (event.yStart - event.y) end if limitY ~= true then g.y = g._startY + (event.xStart - event.x) end else if limitX ~= true then g.x = event.x - g._startX if (dragBounds) then if (g.x < dragLeft) then g.x = dragLeft end if (g.x > dragLeft + dragWidth) then g.x = dragLeft + dragWidth end end end if limitY ~= true then g.y = event.y - g._startY if (dragBounds) then if (g.y < dragTop) then g.y = dragTop end if (g.y > dragTop + dragHeight) then g.y = dragTop + dragHeight end end end print("g" , g.x, g.y, event.x, event.y) end if onDrag then result = onDrag( event ) end elseif event.phase == "ended" then display.getCurrentStage():setFocus( nil ) if onRelease then result = onRelease( event ) end end -- stop touch from falling through to objects underneath return true end ------------------------ -- Define public methods function g:enterFrame( event ) self:repeatFunction( event ) end function g:play( params ) Runtime:removeEventListener( "enterFrame", self ) if ( params ) then -- if any parameters are submitted, assume this is a new sequence and reset all default values animFrames[currentFrame].isVisible = false resetDefaults() inSequence = true -- apply optional parameters (with some boundary and type checking) if ( params.startFrame and type(params.startFrame) == "number" ) then startFrame=params.startFrame end if ( startFrame > #animFrames or startFrame < 1 ) then startFrame = 1 end if ( params.endFrame and type(params.endFrame) == "number" ) then endFrame=params.endFrame end if ( endFrame > #animFrames or endFrame < 1 ) then endFrame = #animFrames end if ( params.loop and type(params.loop) == "number" ) then loop=params.loop end if ( loop < 0 ) then loop = 0 end if ( params.remove and type(params.remove) == "boolean" ) then remove=params.remove end loopCount = 0 else if (not inSequence) then -- use default values startFrame = 1 endFrame = #animFrames loop = 0 loopCount = 0 remove = false end end currentFrame = startFrame animFrames[startFrame].isVisible = true self.repeatFunction = nextFrame Runtime:addEventListener( "enterFrame", self ) end function g:reverse( params ) Runtime:removeEventListener( "enterFrame", self ) if ( params ) then -- if any parameters are submitted, assume this is a new sequence and reset all default values animFrames[currentFrame].isVisible = false resetReverseDefaults() inSequence = true -- apply optional parameters (with some boundary and type checking) if ( params.startFrame and type(params.startFrame) == "number" ) then startFrame=params.startFrame end if ( startFrame > #animFrames or startFrame < 1 ) then startFrame = #animFrames end if ( params.endFrame and type(params.endFrame) == "number" ) then endFrame=params.endFrame end if ( endFrame > #animFrames or endFrame < 1 ) then endFrame = 1 end if ( params.loop and type(params.loop) == "number" ) then loop=params.loop end if ( loop < 0 ) then loop = 0 end if ( params.remove and type(params.remove) == "boolean" ) then remove=params.remove end else if (not inSequence) then -- use default values startFrame = #animFrames endFrame = 1 loop = 0 loopCount = 0 remove = false end end currentFrame = startFrame animFrames[startFrame].isVisible = true self.repeatFunction = prevFrame Runtime:addEventListener( "enterFrame", self ) end function g:nextFrame() -- stop current sequence, if any, and reset to defaults Runtime:removeEventListener( "enterFrame", self ) inSequence = false animFrames[currentFrame].isVisible = false currentFrame = currentFrame + 1 if ( currentFrame > #animFrames ) then currentFrame = 1 end animFrames[currentFrame].isVisible = true end function g:previousFrame() -- stop current sequence, if any, and reset to defaults Runtime:removeEventListener( "enterFrame", self ) inSequence = false animFrames[currentFrame].isVisible = false currentFrame = currentFrame - 1 if ( currentFrame < 1 ) then currentFrame = #animFrames end animFrames[currentFrame].isVisible = true end function g:currentFrame() return currentFrame end function g:totalFrames() return totalFrames end function g:stop() Runtime:removeEventListener( "enterFrame", self ) end function g:stopAtFrame(label) -- This works for either numerical indices or optional text labels if (type(label) == "number") then Runtime:removeEventListener( "enterFrame", self ) animFrames[currentFrame].isVisible = false currentFrame = label animFrames[currentFrame].isVisible = true elseif (type(label) == "string") then for k, v in next, animLabels do if (v == label) then Runtime:removeEventListener( "enterFrame", self ) animFrames[currentFrame].isVisible = false currentFrame = k animFrames[currentFrame].isVisible = true end end end end function g:playAtFrame(label) -- This works for either numerical indices or optional text labels if (type(label) == "number") then Runtime:removeEventListener( "enterFrame", self ) animFrames[currentFrame].isVisible = false currentFrame = label animFrames[currentFrame].isVisible = true elseif (type(label) == "string") then for k, v in next, animLabels do if (v == label) then Runtime:removeEventListener( "enterFrame", self ) animFrames[currentFrame].isVisible = false currentFrame = k animFrames[currentFrame].isVisible = true end end end self.repeatFunction = nextFrame Runtime:addEventListener( "enterFrame", self ) end function g:setDrag( params ) if ( params ) then if params.drag == true then limitX = (params.limitX == true) limitY = (params.limitY == true) transpose = (params.transpose == true) dragBounds = nil if ( params.onPress and ( type(params.onPress) == "function" ) ) then g._onPress = params.onPress end if ( params.onDrag and ( type(params.onDrag) == "function" ) ) then g._onDrag = params.onDrag end if ( params.onRelease and ( type(params.onRelease) == "function" ) ) then g._onRelease = params.onRelease end if ( params.bounds and ( type(params.bounds) == "table" ) ) then dragBounds = params.bounds dragLeft = dragBounds[1] dragTop = dragBounds[2] dragWidth = dragBounds[3] dragHeight = dragBounds[4] end g.touch = dragMe g:addEventListener( "touch", g ) else g:removeEventListener( "touch", g ) dragBounds = nil end end end -- Optional function to assign text labels to frames function g:setLabels(labelTable) for k, v in next, labelTable do if (type(k) == "string") then animLabels[v] = k end end end -- Return instance of anim return g end
function isHarshad(n) local s=0 local n_str=tostring(n) for i=1,#n_str do s=s+tonumber(n_str:sub(i,i)) end return n%s==0 end local count=0 local harshads={} local n=1 while count<20 do if isHarshad(n) then count=count+1 table.insert(harshads, n) end n=n+1 end print(table.concat(harshads, " ")) local h=1001 while not isHarshad(h) do h=h+1 end print(h)
local secrule = 'SecRule' local secaction = 'SecAction' local args = 'ARGS' local operator = 'foo' local actions = "block,id:12345,msg:'hello world'" describe("parse_token", function() local lib = require "resty.waf.translate" local p = lib.parse_tokens it("lives ok with four tokens", function() stub(lib, 'parse_vars') stub(lib, 'parse_operator') stub(lib, 'parse_actions') assert.has_no_errors(function() p({secrule, args, operator, actions}) end) assert.stub(lib.parse_vars).was.called(1) assert.stub(lib.parse_operator).was.called(1) assert.stub(lib.parse_actions).was.called(1) end) it("lives ok with two tokens", function() stub(lib, 'parse_vars') stub(lib, 'parse_operator') stub(lib, 'parse_actions') assert.has_no_errors(function() p({secaction, actions}) end) assert.stub(lib.parse_vars).was.not_called() assert.stub(lib.parse_operator).was.not_called() assert.stub(lib.parse_actions).was.called(1) end) it("dies with four tokens and SecAction", function() assert.has_error(function() p({secaction, args, operator, actions}) end) end) it("properly forms an entry from SecRule", function() stub(lib, 'parse_vars') stub(lib, 'parse_operator') stub(lib, 'parse_actions') local entry = p({secrule, args, operator, actions}) assert.is.same(entry.original, "SecRule ARGS foo block,id:12345,msg:'hello world'") assert.is.same(entry.directive, 'SecRule') assert.stub(lib.parse_vars).was.called_with("ARGS") assert.stub(lib.parse_operator).was.called_with("foo") assert.stub(lib.parse_actions).was. called_with("block,id:12345,msg:'hello world'") end) it("properly forms an entry from SecRule with no actions", function() stub(lib, 'parse_vars') stub(lib, 'parse_operator') stub(lib, 'parse_actions') local entry = p({secrule, args, operator}) assert.is.same(entry.original, "SecRule ARGS foo") assert.is.same(entry.directive, 'SecRule') assert.stub(lib.parse_vars).was.called_with("ARGS") assert.stub(lib.parse_operator).was.called_with("foo") assert.stub(lib.parse_actions).was.not_called() end) it("properly forms an entry from SecAction", function() stub(lib, 'parse_vars') stub(lib, 'parse_operator') stub(lib, 'parse_actions') local entry = p({secaction, actions}) assert.is.same(entry.original, "SecAction block,id:12345,msg:'hello world'") assert.is.same(entry.directive, 'SecAction') assert.stub(lib.parse_actions).was. called_with("block,id:12345,msg:'hello world'") end) end)
local engine = require('engine') local game = Game:create() game:start() print(string.format("The target to reach is %03d", game.target)) local numbers = game.numbers[1] for i = 2, #game.numbers do numbers = numbers .. ', ' .. game.numbers[i] end print(string.format("\nThe numbers are %s", numbers)) -- Okay go time. -- -- For a target of 500 with the numbers 25, 50, 75, 100, 1, 2 -- -- We want 75/25 = 3 then add 2 for 5 then mulply by 100. -- Error TEST (make sure we have the number) -- game:useNumber(5) game:pick(3) game:performOperation("/") game:pick(1) game:performOperation("+") game:pick(6) game:performOperation("*") game:pick(4) print(string.format("\nYou are at %d", game.current))
-- SearchModule.lua -- Krysmatic local SearchModule = {} function SearchModule:SearchGame(directory, SEARCH_ID) local children = directory:GetChildren() local output = {} local function PrintResult(typeName, model) print("------------------------------------------------------------------------------------") print("[ASSET ID: " .. SEARCH_ID .. "] Found " .. typeName .. " in " .. directory.Name) -- Get all parent names local function GetParent(modelobj) if modelobj.Parent then GetParent(modelobj.Parent) table.insert(output, " >> " .. modelobj.Name) end end GetParent(model) print(table.concat(output)) end local t = 0 for i = 1, #children do t = t + 1 if t % 200 == 0 then wait() end if children[i]:IsA("MeshPart") then if string.match(tostring(children[i].TextureID), SEARCH_ID) then PrintResult("Meshpart", children[i]) end end if children[i]:IsA("Decal") or children[i]:IsA("Texture") then if string.match(tostring(children[i].Texture), SEARCH_ID) then PrintResult("Decal/Texture", children[i]) end end if children[i]:IsA("ImageLabel") then if string.match(tostring(children[i].Image), SEARCH_ID) then PrintResult("ImageLabel", children[i]) end end if children[i]:IsA("ImageButton") then if string.match(tostring(children[i].Image), SEARCH_ID) then PrintResult("ImageButton", children[i]) end if string.match(tostring(children[i].HoverImage), SEARCH_ID) then PrintResult("ImageButton Hover", children[i]) end end if children[i]:IsA("Sound") then if string.match(tostring(children[i].SoundId), SEARCH_ID) then PrintResult("Sound", children[i]) end end self:SearchGame(children[i], SEARCH_ID) end end -- Start search function SearchModule:Search(settings, SEARCH_ID) if SEARCH_ID and SEARCH_ID ~= "" then for service, props in pairs(settings) do if props["Activated"] then self:SearchGame(game[service], SEARCH_ID) end end print("Finished Searching ID: " .. SEARCH_ID) else print("Enter valid ID.") end end return SearchModule
local skynet = require "skynet" local snax = require "skynet.snax" local msg = "I am a snax service" function init(...) print ("snax service start: ", msg, ...) end function exit(...) print ("snax service exit: ", ...) end function response.hello(hello) return hello end function accept.hello(hello) assert("MAIN_POST" == hello) end
ENT.Type = "anim" ENT.Base = "base_gmodentity" ENT.Author = "n00bmobile"
local database = require("database") local gps = require("gps") local posUtil = require("posUtil") local scanner = require("scanner") local action = require("action") local config = require("config") local args = {...} local function spreadOnce() for slot=2, config.farmSize^2, 2 do gps.go(posUtil.farmToGlobal(slot)) local crop = scanner.scan() if crop.name == "air" then action.placeCropStick(2) elseif (not config.assumeNoBareStick) and crop.name == "crop" then action.placeCropStick() elseif crop.isCrop then if crop.name == "weed" or crop.gr > 23 or (crop.name == "venomilia" and crop.gr > 7) then action.deweed() action.placeCropStick() elseif crop.name == database.getFarm()[1].name and (not config.bestStatWhileSpreading or (crop.gr >= 21 and crop.ga == 31)) then local nextMultifarmPos = database.nextMultifarmPos() if nextMultifarmPos then action.transplantToMultifarm(posUtil.farmToGlobal(slot), nextMultifarmPos) action.placeCropStick(2) database.updateMultifarm(nextMultifarmPos) else return true end else action.deweed() action.placeCropStick() end end if action.needCharge() then action.charge() end end return false end local function init() database.scanFarm() local multifarmPos = {} if #args == 2 then multifarmPos[1] = tonumber(args[1]) multifarmPos[2] = tonumber(args[2]) end if multifarmPos[1] and multifarmPos[2] then database.setLastMultifarmPos(multifarmPos) else database.scanMultifarm() end action.restockAll() end local function main() init() while not spreadOnce() do gps.go({0, 0}) action.restockAll() end gps.go({0,0}) if #args == 1 and args[1] == "docleanup" then action.destroyAll() gps.go({0,0}) end if config.takeCareOfDrops then action.dumpInventory() end gps.turnTo(1) print("Done.\nThe Multifarm is filled up.") end main()
local player = ... local pn = ToEnumShortString(player) local p = PlayerNumber:Reverse()[player] local show = false local function getInputHandler(actor) return (function (event) if event.GameButton == "Select" and event.PlayerNumber == player then if event.type == "InputEventType_FirstPress" then show = true actor:queuecommand("UpdateGraphState") elseif event.type == "InputEventType_Release" then show = false actor:queuecommand("UpdateGraphState") end end return false end) end local bannerWidth = 418 local bannerHeight = 164 local padding = 10 -- Trims streams to desired length local function GetTrimmedStreamBreakdown(streams, maximumEntriesAllowed) if #streams <= maximumEntriesAllowed then return streams end -- Assume that maximum number of entries is 25 to keep things simple -- if it's over 25, start applying -- heuristics to trim the size down. -- Total stream/break are recorded so that we get a better picture of how much stream is in the section. For every 25% add another *. local tempStreams = {} for i, stream in ipairs(streams) do -- Cache the stream/break counts per stream object so that we're not local sectionLength = stream.streamEnd - stream.streamStart if stream.isBreak then table.insert(tempStreams, {streamStart=stream.streamStart, streamEnd=stream.streamEnd, breakCount=sectionLength, streamCount=0, combined=false, isBreak=true}) else table.insert(tempStreams, {streamStart=stream.streamStart, streamEnd=stream.streamEnd, breakCount=0, streamCount=sectionLength, combined=false, isBreak=false}) end end streams = tempStreams if #streams <= maximumEntriesAllowed then return streams end -- each pass should just try to combine adjacent sections. breaks will get longer and longer as they are removed. local minBreakLength = 2 while #streams > maximumEntriesAllowed do -- Trim short breaks tempStreams = {} for i, stream in ipairs(streams) do -- Add breaks if and only if they meet the criteria local stream = streams[i] if stream.isBreak then if stream.streamEnd - stream.streamStart >= minBreakLength then table.insert(tempStreams, stream) end else table.insert(tempStreams, stream) end end streams = tempStreams tempStreams = {} i = 1 while i <= #streams do -- Combine the next item into this item if and only if they're both streams local currStream = streams[i] local nextStream = streams[i+1] local lastStream = tempStreams[#tempStreams] -- First handle continuing stream if lastStream ~= nil and not lastStream.isBreak and not currStream.isBreak then tempStreams[#tempStreams] = {streamStart=lastStream.streamStart, streamEnd=currStream.streamEnd, breakCount=lastStream.breakCount + 1, streamCount=lastStream.streamCount + currStream.streamCount, combined=true, isBreak=false} lastStream = tempStreams[#tempStreams] if lastStream.streamStart + 1 == lastStream.streamEnd then error("Producing 1* with obj " .. table.tostring(currStream)) end i = i + 1 elseif not currStream.isBreak and nextStream ~= nil and not nextStream.isBreak then -- This should insert an item table.insert(tempStreams, {streamStart=currStream.streamStart, streamEnd=nextStream.streamEnd, breakCount=minBreakLength - 1, streamCount=currStream.streamCount + nextStream.streamCount, isBreak=false, combined=true}) lastStream = tempStreams[#tempStreams] if lastStream.streamStart + 1 == lastStream.streamEnd then error("Producing 1* with curr obj " .. table.tostring(currStream) .. " next obj " .. table.tostring(nextStream)) end i = i + 2 else table.insert(tempStreams, currStream) i = i + 1 end end streams = tempStreams if #streams <= maximumEntriesAllowed then return streams end minBreakLength = minBreakLength + 1 end return streams end -- Get breakdown to show above banner local function GetStreamBreakdownShort(SongDir, StepsType, Difficulty) local NotesPerMeasure = 16 local MeasureSequenceThreshold = 2 local streams = GetStreams(SongDir, StepsType, Difficulty, NotesPerMeasure, nil) local ismarathon = false -- if the length of the song is over 30 minutes, use marathon notation. if GAMESTATE:GetCurrentSong():MusicLengthSeconds() >= 16*60 then ismarathon = true end -- nil out unused big objects which prevent errors from being shown. SongDir = nil StepsType = nil if not streams then return "" end -- Truncate breaks at the beginning and end. if streams[1] ~= nil and streams[1].isBreak then table.remove(streams, 1) end if streams[#streams] ~= nil and streams[#streams].isBreak then table.remove(streams, #streams) end streams = GetTrimmedStreamBreakdown(streams, 20) -- Maximum 20 entries local lastStream local streamText = {} for i, stream in ipairs(streams) do local streamLength = stream.streamEnd - stream.streamStart local streamString = tostring(streamLength) if stream.isBreak then local breakString = "(" .. streamString .. ")" streamText[i] = breakString elseif stream.combined then local stars = "****" if stream.streamCount / streamLength > 0.75 then stars = "*" elseif stream.streamCount / streamLength > 0.50 then stars = "**" elseif stream.streamCount / streamLength > 0.25 then stars = "***" end if ismarathon then streamText[i] = tostring(stream.streamCount) .. stars else streamText[i] = streamLength .. stars end else streamText[i] = streamLength end lastStream = stream end -- Print a debug string showing the measure breakdown in case something is funky -- local measure_breakdown = "" -- for i, stream in ipairs(streams) do -- measure_breakdown = measure_breakdown .. "[" .. tostring(stream.streamStart) .. "/" .. tostring(stream.streamEnd) .. "]" -- end -- SCREENMAN:SystemMessage(measure_breakdown) return table.concat(streamText, " "), ismarathon end -- TODO make this global local function getTimes(npsPerMeasure, timingData) if (npsPerMeasure == nil) then return {firstSecond=0, lastSecond=0, totalSeconds=0} end -- insane, but whatever local totalMeasures = 0 for i, a in ipairs(npsPerMeasure) do totalMeasures = totalMeasures + 1 end local firstSecond = 0 local lastSecond = timingData:GetElapsedTimeFromBeat(totalMeasures * 4) local totalSeconds = lastSecond - firstSecond return {firstSecond=firstSecond, lastSecond=lastSecond, totalSeconds=totalSeconds} end local function getGraphParams(song, steps) local difficulty = ToEnumShortString(steps:GetDifficulty()) local stepsType = ToEnumShortString(steps:GetStepsType()):gsub("_", "-"):lower() local peakNps, npsPerMeasure = GetNPSperMeasure(song, stepsType, difficulty) local timingData = song:GetTimingData() local times = getTimes(npsPerMeasure, timingData) local rvalue = { second=times.firstSecond, graphWidthSeconds=times.lastSecond - times.firstSecond, song=song, steps=steps, peakNps=peakNps, npsPerMeasure=npsPerMeasure } return rvalue end return Def.ActorFrame { -- song and course changes OnCommand=cmd(queuecommand, "StepsHaveChanged"), CurrentSongChangedMessageCommand=cmd(queuecommand, "StepsHaveChanged"), CurrentCourseChangedMessageCommand=cmd(queuecommand, "StepsHaveChanged"), InitCommand=function(self) local zoom, xPos if IsUsingWideScreen() then zoom = 0.7655 xPos = 170 else zoom = 0.75 xPos = 166 end self:zoom(zoom) self:xy(_screen.cx - xPos - ((bannerWidth / 2 - padding) * zoom), 112 - ((bannerHeight / 2 - padding) * zoom)) if (player == PLAYER_2) then self:addy((bannerHeight / 2 - (padding * 0.5)) * zoom) end self:diffusealpha(0) self:queuecommand("Capture") end, CaptureCommand=function(self) SCREENMAN:GetTopScreen():AddInputCallback(getInputHandler(self)) end, StepsHaveChangedCommand=function(self, params) if show then self:queuecommand("UpdateGraphState") end end, UpdateGraphStateCommand=function(self, params) if show and not GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentSong() then local song = GAMESTATE:GetCurrentSong() local steps = GAMESTATE:GetCurrentSteps(player) self:playcommand("ChangeSteps", getGraphParams(song,steps)) self:stoptweening() self:linear(0.1):diffusealpha(0.9) else self:stoptweening() self:linear(0.1):diffusealpha(0) end end, CreateDensityGraph(bannerWidth - (padding * 2), bannerHeight / 2 - (padding * 1.5)), Def.Quad { InitCommand=function(self) self:zoomto(bannerWidth - (padding * 2), 20) :diffuse(color("#000000")) :diffusealpha(0.8) :align(0, 0) :y(bannerHeight / 2 - (padding * 1.5) - 20) end, }, Def.BitmapText{ Font="_miso", InitCommand=function(self) self:diffuse(color("#ffffff")) :horizalign("left") :y(bannerHeight / 2 - (padding * 1.5) - 20 + 2) :x(5) :maxwidth(bannerWidth - (padding * 2) - 10) :align(0, 0) :Stroke(color("#000000")) end, StepsHaveChangedCommand=function(self, params) if show then self:queuecommand("UpdateGraphState") end end, UpdateGraphStateCommand=function(self) if show and not GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentSong() then local song_dir = GAMESTATE:GetCurrentSong():GetSongDir() local steps = GAMESTATE:GetCurrentSteps(player) local steps_type = ToEnumShortString( steps:GetStepsType() ):gsub("_", "-"):lower() local difficulty = ToEnumShortString( steps:GetDifficulty() ) local breakdown, ismarathon = GetStreamBreakdownShort(song_dir, steps_type, difficulty) if breakdown == "" then self:settext("No streams!") elseif ismarathon then self:settext("Marathon: " .. breakdown) else self:settext("Streams: " .. breakdown) end return true end end } }
title = "Hello LowRez" author = "Calle Englund" shortname = "hello-lowrez" version = "0.0.1" copyright_message = "Copyright (c) 2019 Calle Englund"
-- -- api.lua -- Implementation of the workspace, project, and configuration APIs. -- Author Jason Perkins -- Copyright (c) 2002-2015 Jason Perkins and the Premake project -- local p = premake p.api = {} local api = p.api local configset = p.configset --- -- Set up a place to store the current active objects in each configuration -- scope (e.g. wprkspaces, projects, groups, and configurations). This likely -- ought to be internal scope, but it is useful for testing. --- api.scope = {} --- -- Define a new class of configuration container. A container can receive and -- store configuration blocks, which are what hold the individial settings -- from the scripts. A container can also hold one or more kinds of child -- containers; a workspace can contain projects, for instance. -- -- @param containerName -- The name of the new container type, e.g. "workspace". Used to define a -- corresponding global function, e.g. workspace() to create new instances -- of the container. -- @param parentContainer (optional) -- The container that can contain this one. For a project, this would be -- the workspace container class. -- @param extraScopes (optional) -- Each container can hold fields scoped to itself (by putting the container's -- class name into its scope attribute), or any of the container's children. -- If a container can hold scopes other than these (i.e. "config"), it can -- provide a list of those scopes in this argument. -- @returns -- The newly defined container class. --- function api.container(containerName, parentContainer, extraScopes) local class, err = p.container.newClass(containerName, parentContainer, extraScopes) if not class then error(err, 2) end _G[containerName] = function(name) local c = api._setContainer(class, name) if api._isIncludingExternal then c.external = true end return c end _G["external" .. containerName] = function(name) local c = _G[containerName](name) c.external = true return c end -- for backward compatibility p.alias(_G, "external" .. containerName, "external" .. containerName:capitalized()) return class end --- -- Register a general-purpose includeExternal() call which works just like -- include(), but marks any containers created while evaluating the included -- scripts as external. It also, loads the file regardless of how many times -- it has been loaded already. --- function includeexternal(fname) local fullPath = p.findProjectScript(fname) api._isIncludingExternal = true fname = fullPath or fname dofile(fname) api._isIncludingExternal = nil end p.alias(_G, "includeexternal", "includeExternal") --- -- Return the global configuration container. --- function api.rootContainer() return api.scope.global end --- -- Activate a new configuration container, making it the target for all -- subsequent configuration settings. When you call workspace() or project() -- to active a container, that call comes here (see api.container() for the -- details on how that happens). -- -- @param class -- The container class being activated, e.g. a project or workspace. -- @param name -- The name of the container instance to be activated. If a container -- (e.g. project) with this name does not already exist it will be -- created. If name is not set, the last activated container of this -- class will be made current again. -- @return -- The container instance. --- function api._setContainer(class, name) local instance -- for backward compatibility, "*" activates the parent container if name == "*" then return api._setContainer(class.parent) end -- if name is not set, use whatever was last made current if not name then instance = api.scope[class.name] if not instance then error("no " .. class.name .. " in scope", 3) end end -- otherwise, look up the instance by name local parent if not instance and class.parent then parent = api.scope[class.parent.name] if not parent then error("no " .. class.parent.name .. " in scope", 3) end instance = p.container.getChild(parent, class, name) end -- if I have an existing instance, create a new configuration -- block for it so I don't pick up an old filter if instance then configset.addFilter(instance, {}, os.getcwd()) end -- otherwise, a new instance if not instance then instance = class.new(name, parent) if parent then p.container.addChild(parent, instance) end end -- clear out any active child containers that might be active -- (recursive call, so needs to be its own function) api._clearContainerChildren(class) -- active this container, as well as it ancestors if not class.placeholder then api.scope.current = instance end while instance do api.scope[instance.class.name] = instance if instance.class.alias then api.scope[instance.class.alias] = instance end instance = instance.parent end return api.scope.current end function api._clearContainerChildren(class) for childClass in p.container.eachChildClass(class) do api.scope[childClass.name] = nil if childClass.alias then api.scope[childClass.alias] = nil end api._clearContainerChildren(childClass) end end --- -- Register a new API function. See the built-in API definitions in -- _premake_init.lua for lots of usage examples. -- -- A new global function will be created to receive values for the field. -- List fields will also receive a `remove...()` function to remove values. -- -- @param field -- A table describing the new field, with these keys: -- -- name The API name of the new field. This is used to create a global -- function with the same name, and so should follow Lua symbol -- naming conventions. (required) -- scope The scoping level at which this value can be used; see list -- below. (required) -- kind The type of values that can be stored into this field; see -- list below. (required) -- allowed An array of valid values for this field, or a function which -- accepts a value as input and returns the canonical value as a -- result, or nil if the input value is invalid. (optional) -- tokens A boolean indicating whether token expansion should be -- performed on this field. -- -- The available field scopes are: -- -- project The field applies to workspaces and projects. -- config The field applies to workspaces, projects, and individual build -- configurations. -- -- The available field kinds are: -- -- string A simple string value. -- path A file system path. The value will be made into an absolute -- path, but no wildcard expansion will be performed. -- file One or more file names. Wilcard expansion will be performed, -- and the results made absolute. Implies a list. -- directory One of more directory names. Wildcard expansion will be -- performed, and the results made absolute. Implies a list. -- mixed A mix of simple string values and file system paths. Values -- which contain a directory separator ("/") will be made -- absolute; other values will be left intact. -- table A table of values. If the input value is not a table, it is -- wrapped in one. --- function api.register(field) -- verify the name local name = field.name if not name then error("missing name", 2) end if rawget(_G, name) then error("name '" .. name .. "' in use", 2) end -- add this new field to my master list field, err = p.field.new(field) if not field then error(err) end -- Flag fields which contain filesystem paths. The context object will -- use this information when expanding tokens, to ensure that the paths -- are still well-formed after replacements. field.paths = p.field.property(field, "paths") -- Add preprocessed, lowercase keys to the allowed and aliased value -- lists to speed up value checking later on. if type(field.allowed) == "table" then for i, item in ipairs(field.allowed) do field.allowed[item:lower()] = item end end if type(field.aliases) == "table" then local keys = table.keys(field.aliases) for i, key in ipairs(keys) do field.aliases[key:lower()] = field.aliases[key] end end -- create a setter function for it _G[name] = function(value) return api.storeField(field, value) end if p.field.removes(field) then _G["remove" .. name] = function(value) return api.remove(field, value) end end return field end --- -- Unregister a field definition, removing its functions and field -- list entries. --- function api.unregister(field) if type(field) == "string" then field = p.field.get(field) end p.field.unregister(field) _G[field.name] = nil _G["remove" .. field.name] = nil end --- -- Create an alias to one of the canonical API functions. This creates -- new setter and remover names pointing to the same functions. -- -- @param original -- The name of the function to be aliased (a string value). -- @param alias -- The alias name (another string value). --- function api.alias(original, alias) p.alias(_G, original, alias) if _G["remove" .. original] then p.alias(_G, "remove" .. original, "remove" .. alias) end end -- -- Add a new value to a field's list of allowed values. -- -- @param fieldName -- The name of the field to which to add the value. -- @param value -- The value to add. May be a single string value, or an array -- of values. -- function api.addAllowed(fieldName, value) local field = p.field.get(fieldName) if not field then error("No such field: " .. fieldName, 2) end if type(value) == "table" then for i, item in ipairs(value) do api.addAllowed(fieldName, item) end else field.allowed = field.allowed or {} if field.allowed[value:lower()] == nil then table.insert(field.allowed, value) field.allowed[value:lower()] = value end end end -- -- Add a new value to a field's list of allowed values. -- -- @param fieldName -- The name of the field to which to add the value. -- @param value -- The value to add. May be a single string value, or an array -- of values. -- function api.addAliases(fieldName, value) local field = p.field.get(fieldName) if not field then error("No such field: " .. fieldName, 2) end field.aliases = field.aliases or {} for k, v in pairs(value) do field.aliases[k] = v field.aliases[k:lower()] = v end end -- -- Mark an API field as deprecated. -- -- @param name -- The name of the field to mark as deprecated. -- @param message -- A optional message providing more information, to be shown -- as part of the deprecation warning message. -- @param handler -- A function to call when the field is used. Passes the value -- provided to the field as the only argument. -- function api.deprecateField(name, message, handler) p.fields[name].deprecated = { handler = handler, message = message } end -- -- Mark a specific value of a field as deprecated. -- -- @param name -- The name of the field containing the value. -- @param value -- The value or values to mark as deprecated. May be a string -- for a single value or an array of multiple values. -- @param message -- A optional message providing more information, to be shown -- as part of the deprecation warning message. -- @param addHandler -- A function to call when the value is used, receiving the -- value as its only argument. -- @param removeHandler -- A function to call when the value is removed from a list -- field, receiving the value as its only argument (optional). -- function api.deprecateValue(name, value, message, addHandler, removeHandler) if type(value) == "table" then for _, v in pairs(value) do api.deprecateValue(name, v, message, addHandler, removeHandler) end else local field = p.fields[name] field.deprecated = field.deprecated or {} field.deprecated[value] = { add = addHandler, remove = removeHandler, message = message } end end -- -- Control the handling of API deprecations. -- -- @param value -- One of "on" to enable the deprecation behavior, "off" to disable it, -- and "error" to raise an error instead of logging a warning. -- function api.deprecations(value) value = value:lower() if not table.contains({ "on", "off", "error"}, value) then error("Invalid value: " .. value, 2) end api._deprecations = value:lower() end api._deprecations = "on" --- -- Return the target container instance for a field. -- -- @param field -- The field being set or fetched. -- @return -- The currently active container instance if one is available, or nil if -- active container is of the wrong class. --- function api.target(field) if p.container.classCanContain(api.scope.current.class, field.scope) then return api.scope.current end return nil end -- -- Callback for all API functions; everything comes here first, and then -- gets parceled out to the individual set...() functions. -- function api.storeField(field, value) if value == nil then return end if field.deprecated and type(field.deprecated.handler) == "function" then field.deprecated.handler(value) if field.deprecated.message and api._deprecations ~= "off" then local caller = filelineinfo(2) local key = field.name .. "_" .. caller p.warnOnce(key, "the field %s has been deprecated and will be removed.\n %s\n @%s\n", field.name, field.deprecated.message, caller) if api._deprecations == "error" then error("deprecation errors enabled", 3) end end end local target = api.target(field) if not target then local err = string.format("unable to set %s in %s scope, should be %s", field.name, api.scope.current.class.name, table.concat(field.scopes, ", ")) error(err, 3) end local status, err = configset.store(target, field, value) if err then error(err, 3) end end -- -- The remover: adds values to be removed to the "removes" field on -- current configuration. Removes are keyed by the associated field, -- so the call `removedefines("X")` will add the entry: -- cfg.removes["defines"] = { "X" } -- function api.remove(field, value) -- right now, ignore calls with no value; later might want to -- return the current baked value if value == nil then return end local target = api.target(field) if not target then local err = string.format("unable to remove %s from %s scope, should be %s", field.name, api.scope.current.class.name, table.concat(field.scopes, ", ")) error(err, 3) end local hasDeprecatedValues = (type(field.deprecated) == "table") -- Build a list of values to be removed. If this field has deprecated -- values, check to see if any of those are going to be removed by this -- call (which means matching against any provided wildcards) and call -- the appropriate logic for removing that value. local removes = {} local function check(value) if field.deprecated[value] then local handler = field.deprecated[value] if handler.remove then handler.remove(value) end if handler.message and api._deprecations ~= "off" then local caller = filelineinfo(8) local key = field.name .. "_" .. value .. "_" .. caller p.warnOnce(key, "the %s value %s has been deprecated and will be removed.\n %s\n @%s\n", field.name, value, handler.message, caller) if api._deprecations == "error" then error { msg="deprecation errors enabled" } end end end end local function recurse(value) if type(value) == "table" then table.foreachi(value, recurse) elseif hasDeprecatedValues and value:contains("*") then local current = configset.fetch(target, field, { matcher = function(cset, block, filter) local current = cset.current return criteria.matches(current._criteria, block._criteria.terms or {}) or criteria.matches(block._criteria, current._criteria.terms or {}) end }) local mask = path.wildcards(value) for _, item in ipairs(current) do if item:match(mask) == item then recurse(item) end end else local value, err, additional = api.checkValue(field, value) if err then error { msg=err } end if field.deprecated then check(value) end table.insert(removes, value) if additional then table.insert(removes, additional) end end end local ok, err = pcall(function () recurse(value) end) if not ok then if type(err) == "table" then err = err.msg end error(err, 3) end configset.remove(target, field, removes) end -- -- Check to see if a value is valid for a particular field. -- -- @param field -- The field to check against. -- @param value -- The value to check. -- @param kind -- The kind of data currently being checked, corresponding to -- one segment of the field's kind string (e.g. "string"). If -- not set, defaults to "string". -- @return -- If the value is valid for this field, the canonical version -- of that value is returned. If the value is not valid two -- values are returned: nil, and an error message. -- function api.checkValue(field, value, kind) if not field.allowed then return value end local canonical, result local lowerValue = value:lower() if field.aliases then canonical = field.aliases[lowerValue] end if not canonical then if type(field.allowed) == "function" then canonical = field.allowed(value, kind or "string") else canonical = field.allowed[lowerValue] end end if not canonical then return nil, "invalid value '" .. value .. "' for " .. field.name end if field.deprecated and field.deprecated[canonical] then local handler = field.deprecated[canonical] handler.add(canonical) if handler.message and api._deprecations ~= "off" then local caller = filelineinfo(9) local key = field.name .. "_" .. value .. "_" .. caller p.warnOnce(key, "the %s value %s has been deprecated and will be removed.\n %s\n @%s\n", field.name, canonical, handler.message, caller) if api._deprecations == "error" then return nil, "deprecation errors enabled" end end end return canonical end --- -- Reset the API system, clearing out any temporary or cached values. -- Used by the automated testing framework to clear state between -- individual test runs. --- function api.reset() for containerClass in p.container.eachChildClass(p.global) do api.scope.global[containerClass.pluralName] = {} end end -- -- Arrays are integer indexed tables; unlike lists, a new array value -- will replace the old one, rather than merging both. -- premake.field.kind("array", { store = function(field, current, value, processor) if type(value) ~= "table" then value = { value } end for i, item in ipairs(value) do value[i] = processor(field, nil, value[i]) end return value end, compare = function(field, a, b, processor) if a == nil or b == nil or #a ~= #b then return false end for i = 1, #a do if not processor(field, a[i], b[i]) then return false end end return true end }) --- -- Boolean field kind; converts common yes/no strings into true/false values. --- premake.field.kind("boolean", { store = function(field, current, value, processor) local mapping = { ["false"] = false, ["no"] = false, ["off"] = false, ["on"] = true, ["true"] = true, ["yes"] = true, } if type(value) == "string" then value = mapping[value:lower()] if value == nil then error { msg="expected boolean; got " .. value } end return value end if type(value) == "boolean" then return value end if type(value) == "number" then return (value ~= 0) end return (value ~= nil) end, compare = function(field, a, b, processor) return (a == b) end }) -- -- Directory data kind; performs wildcard directory searches, converts -- results to absolute paths. -- premake.field.kind("directory", { paths = true, store = function(field, current, value, processor) return path.getabsolute(value) end, remove = function(field, current, value, processor) return path.getabsolute(value) end, compare = function(field, a, b, processor) return (a == b) end, translate = function(field, current, _, processor) if current:find("*") then return os.matchdirs(current) end return { current } end }) -- -- File data kind; performs wildcard file searches, converts results -- to absolute paths. -- premake.field.kind("file", { paths = true, store = function(field, current, value, processor) return path.getabsolute(value) end, remove = function(field, current, value, processor) return path.getabsolute(value) end, compare = function(field, a, b, processor) return (a == b) end, translate = function(field, current, _, processor) if current:find("*") then return os.matchfiles(current) end return { current } end }) -- -- Function data kind; this isn't terribly useful right now, but makes -- a nice extension point for modules to build on. -- premake.field.kind("function", { store = function(field, current, value, processor) local t = type(value) if t ~= "function" then error { msg="expected function; got " .. t } end return value end, compare = function(field, a, b, processor) return (a == b) end }) -- -- Integer data kind; validates inputs. -- premake.field.kind("integer", { store = function(field, current, value, processor) local t = type(value) if t ~= "number" then error { msg="expected number; got " .. t } end if math.floor(value) ~= value then error { msg="expected integer; got " .. tostring(value) } end return value end, compare = function(field, a, b, processor) return (a == b) end }) --- -- Key-value data kind definition. Merges key domains; values may be any kind. --- local function storeKeyed(field, current, value, processor) current = current or {} for k, v in pairs(value) do if processor then v = processor(field, current[k], v) end current[k] = v end return current end local function mergeKeyed(field, current, value, processor) value = value or {} for k, v in pairs(value) do current[k] = v end return current end premake.field.kind("keyed", { store = storeKeyed, merge = mergeKeyed, compare = function(field, a, b, processor) if a == nil or b == nil then return false end for k in pairs(a) do if not processor(field, a[k], b[k]) then return false end end return true end, translate = function(field, current, _, processor) if not processor then return { current } end for k, v in pairs(current) do current[k] = processor(field, v, nil)[1] end return { current } end }) --- -- List data kind definition. Actually a misnomer, lists are more like sets in -- that duplicate values are weeded out; each will only appear once. Can -- contain any other kind of data. --- local function storeListItem(current, item, allowDuplicates) if not allowDuplicates and current[item] then table.remove(current, table.indexof(current, item)) end table.insert(current, item) current[item] = item end local function storeList(field, current, value, processor) if type(value) == "table" then -- Flatten out incoming arrays of values if #value > 0 then for i = 1, #value do current = storeList(field, current, value[i], processor) end return current end -- Ignore empty lists if table.isempty(value) then return current end end current = current or {} if processor then value = processor(field, nil, value) end if type(value) == "table" then if #value > 0 then for i = 1, #value do storeListItem(current, value[i], field.allowDuplicates) end elseif not table.isempty(value) then storeListItem(current, value, field.allowDuplicates) end elseif value then storeListItem(current, value, field.allowDuplicates) end return current end local function mergeList(field, current, value, processor) value = value or {} for i = 1, #value do storeListItem(current, value[i], field.allowDuplicates) end return current end premake.field.kind("list", { store = storeList, remove = storeList, merge = mergeList, compare = function(field, a, b, processor) if a == nil or b == nil or #a ~= #b then return false end for i = 1, #a do if not processor(field, a[i], b[i]) then return false end end return true end, translate = function(field, current, _, processor) if not processor then return { current } end local ret = {} for _, value in ipairs(current) do for _, processed in ipairs(processor(field, value, nil)) do table.insert(ret, processed) end end return { ret } end }) -- -- Mixed data kind; values containing a directory separator "/" are converted -- to absolute paths, other values left as-is. Used for links, where system -- libraries and local library paths can be mixed into a single list. -- premake.field.kind("mixed", { paths = true, store = function(field, current, value, processor) if type(value) == "string" and value:find('/', nil, true) then if string.sub(value, 1, 2) ~= "%{" then value = path.getabsolute(value) end end return value end, compare = function(field, a, b, processor) return (a == b) end }) -- -- Number data kind; validates inputs. -- premake.field.kind("number", { store = function(field, current, value, processor) local t = type(value) if t ~= "number" then error { msg="expected number; got " .. t } end return value end, compare = function(field, a, b, processor) return (a == b) end }) -- -- Path data kind; converts all inputs to absolute paths. -- premake.field.kind("path", { paths = true, store = function(field, current, value, processor) return path.deferredjoin(os.getcwd(), value) end, compare = function(field, a, b, processor) return (a == b) end }) -- -- String data kind; performs validation against allowed fields, checks for -- value deprecations. -- premake.field.kind("string", { store = function(field, current, value, processor) if type(value) == "table" then error { msg="expected string; got table" } end if value ~= nil then local err value, err = api.checkValue(field, value) if err then error { msg=err } end end return value end, compare = function(field, a, b, processor) return (a == b) end }) -- -- Table data kind; wraps simple values into a table, returns others as-is. -- premake.field.kind("table", { store = function(field, current, value, processor) if type(value) ~= "table" then value = { value } end return value end, compare = function(field, a, b, processor) -- TODO: is there a reliable way to check this? return true end }) -- -- nested data kind; wraps simple values into a table, returns others as-is. -- premake.field.kind("nested", { store = function(field, current, value, processor) -- create meta-table. if not current then current = p.nested.create(field) end -- copy values. for name, v in pairs(value) do current[name] = v end -- return result. return current end, compare = function(field, a, b, processor) -- TODO: is there a reliable way to check this? return true end }) --- -- Start a new block of configuration settings, using the old, "open" -- style of matching without field prefixes. --- function configuration(terms) if terms then if (type(terms) == "table" and #terms == 1 and terms[1] == "*") or (terms == "*") then terms = nil end configset.addblock(api.scope.current, {terms}, os.getcwd()) end return api.scope.current end --- -- Start a new block of configuration settings, using the new prefixed -- style of pattern matching. --- function filter(terms) if terms then if (type(terms) == "table" and #terms == 1 and terms[1] == "*") or (terms == "*") then terms = nil end local ok, err = configset.addFilter(api.scope.current, {terms}, os.getcwd()) if not ok then error(err, 2) end end end -- -- Define a new action. -- -- @param a -- The new action object. -- function newaction(a) p.action.add(a) end -- -- Define a new option. -- -- @param opt -- The new option object. -- function newoption(opt) p.option.add(opt) end
local consts = require("__LaneBalancer__.const") data:extend( { { type = "item", name = "lane-balancer", icon = consts.graphicsPath.."balancer1.png", icon_size = 32, subgroup = "belt", order = "e[balancer]-a[lane-balancer]", place_result = "lane-balancer", stack_size = 50 }, { type = "item", name = "fast-lane-balancer", icon = consts.graphicsPath.."balancer2.png", icon_size = 32, subgroup = "belt", order = "e[balancer]-b[fast-lane-balancer]", place_result = "fast-lane-balancer", stack_size = 50 }, { type = "item", name = "express-lane-balancer", icon = consts.graphicsPath.."balancer3.png", icon_size = 32, subgroup = "belt", order = "e[balancer]-c[express-lane-balancer]", place_result = "express-lane-balancer", stack_size = 50 } })
if mg.lua_type ~= "websocket" then mg.write("HTTP/1.0 200 OK\r\n") mg.write("Connection: close\r\n") mg.write("\r\n") mg.write("<!DOCTYPE HTML>\r\n") mg.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n") mg.write("<head>\r\n") mg.write("<meta charset=\"UTF-8\"></meta>\r\n") mg.write("<title>Server stats</title>\r\n") mg.write("</head>\r\n") mg.write("<body onload=\"load()\">\r\n") mg.write([====[ <script type="text/javascript"> var connection; var data_field; function webSockKeepAlive() { if (keepAlive) { connection.send('Ok'); setTimeout("webSockKeepAlive()", 10000); } } function load() { var wsproto = (location.protocol === 'https:') ? "wss:" : "ws:"; connection = new WebSocket(wsproto + "//" + window.location.host + window.location.pathname); data_field = document.getElementById('data'); data_field.innerHTML = "wait for data"; use_keepAlive = true; connection.onopen = function () { keepAlive = use_keepAlive; webSockKeepAlive(); }; // Log errors connection.onerror = function (error) { keepAlive = false; alert("WebSocket error"); connection.close(); }; // Log messages from the server connection.onmessage = function (e) { data_field.innerHTML = e.data; }; } </script> ]====]) mg.write("<div id='data'>Wait for page load</div>\r\n") mg.write("</body>\r\n") mg.write("</html>\r\n") return end function table.count(tab) local count = 0 for _ in pairs(tab) do count = count + 1 end return count end -- table of all active connection allConnections = {} connCount = table.count(allConnections) -- function to get a client identification string function who(tab) local ri = allConnections[tab.client].request_info return ri.remote_addr .. ":" .. ri.remote_port end -- Callback to accept or reject a connection function open(tab) allConnections[tab.client] = tab connCount = table.count(allConnections) return true -- return true to accept the connection end -- Callback for "Websocket ready" function ready(tab) senddata() return true -- return true to keep the connection open end -- Callback for "Websocket received data" function data(tab) senddata() return true -- return true to keep the connection open end -- Callback for "Websocket is closing" function close(tab) allConnections[tab.client] = nil connCount = table.count(allConnections) end function senddata() local date = os.date('*t'); collectgarbage("collect"); -- Avoid adding uncollected Lua memory from this state mg.write(string.format([[ {"Time": "%u:%02u:%02u", "Date": "%04u-%02u-%02u", "Context": %s, "Common": %s, "System": \"%s\", "ws_status": {"Memory": %u, "Connections": %u} }]], date.hour, date.min, date.sec, date.year, date.month, date.day, mg.get_info("context"), mg.get_info("common"), mg.get_info("system"), collectgarbage("count")*1024, connCount )); end function timer() senddata() mg.set_timeout("timer()", 1) end mg.set_timeout("timer()", 1)
local curPlatform = g_application:getTargetPlatform() local bIsIosAndUseSimpleAudioEngine = false if curPlatform == cc.PLATFORM_OS_IPHONE or curPlatform == cc.PLATFORM_OS_IPAD then include('global_utils/ios_utils.lua') bIsIosAndUseSimpleAudioEngine = platform_ios_is_use_simple_audio_engine() end -- 音频播放相关 if not bIsIosAndUseSimpleAudioEngine and utils_is_game_cpp_interface_available and utils_is_game_cpp_interface_available('new_audio_engine') then print('use audio engine') local audio_engine_mgr = import('audio_engine_mgr') playMusic = function(filename, isLoop) audio_engine_mgr.play_music(filename, true, isLoop == true) end stopMusic = audio_engine_mgr.stop_music isMusicPlaying = audio_engine_mgr.is_music_playing playSound = audio_engine_mgr.play_audio unloadSound = function(filename) audio_engine_mgr.stop_audio(filename, true) end stopAllSounds = audio_engine_mgr.stop_all_aounds destory = audio_engine_mgr.destory g_eventHandler:AddCallback('event_applicationDidEnterBackground', function() audio_engine_mgr.pause_all() end) g_eventHandler:AddCallback('event_applicationWillEnterForeground', function() audio_engine_mgr.resume_all() end) else print('use simple audio engine') local engine = cc.SimpleAudioEngine:getInstance() local curPlatform = g_application:getTargetPlatform() -- 预加载music preloadMusic = function(filename) assert(filename, "audio.preloadMusic() - invalid filename") engine:preloadMusic(filename) end -- 播放music playMusic = function(filename, isLoop) assert(filename, "audio.playMusic() - invalid filename") local audio_config = g_native_conf.game_audio_info if not audio_config.isCanPlayMusic then return end if type(isLoop) ~= "boolean" then isLoop = true end stopMusic(true) if curPlatform == cc.PLATFORM_OS_IPHONE or curPlatform == cc.PLATFORM_OS_IPAD then -- iOS 11 BUG 第一次播放不了 尝试预加载 engine:preloadMusic(filename) end engine:playMusic(filename, isLoop) end -- 停止music stopMusic = function(isReleaseData) if type(isReleaseData) ~= "boolean" then isReleaseData = true end engine:stopMusic(isReleaseData) end -- 当前是否有music在播放 isMusicPlaying = function() local ret = cc.SimpleAudioEngine:getInstance():isMusicPlaying() return ret end -- 预加载sound preloadSound = function(filename) if not filename then return end engine:preloadEffect(filename) end -- 播放sound playSound = function(filename, isLoop) if not filename then return end if curPlatform == cc.PLATFORM_OS_IPHONE or curPlatform == cc.PLATFORM_OS_IPAD then end if not g_fileUtils:isFileExist(filename) then printf('error!file name [%s] not exists, %s', filename, debug.traceback()) return end local audio_config = g_native_conf.game_audio_info if not audio_config.isCanPlaySound then return end if type(isLoop) ~= "boolean" then isLoop = false end return engine:playEffect(filename, isLoop) end -- 取消预加载的sound unloadSound = function(filename) if not filename then return end engine:unloadEffect(filename) end -- 停止所有的sound stopAllSounds = function() engine:stopAllEffects() end -- 停止sound stopSound = function(handle) if not handle then return end engine:stopEffect(handle) end -- 销毁音效相关资源等 destory = function() cc.SimpleAudioEngine:destroyInstance() end g_eventHandler:AddCallback('event_applicationDidEnterBackground', function() engine:pauseMusic() engine:pauseAllEffects() end) g_eventHandler:AddCallback('event_applicationWillEnterForeground', function() engine:resumeMusic() engine:resumeAllEffects() end) end
local label = require("engine/ui/label") -- overlay class: allows to draw labels on top of the screen local overlay = new_class() -- parameters -- layer int level at which the overlay should be drawn, higher on top -- state vars -- labels {string: label} table of labels to draw, identified by name function overlay:_init(layer) self.layer = layer self.labels = {} end --#if log function overlay:_tostring() return "overlay(layer: "..self.layer..")" end --#endif -- add a label identified by a name, containing a text string, -- at a position vector, with a given color -- if a label with the same name already exists, replace it function overlay:add_label(name, text, position, colour) if not colour then colour = colors.black warn("overlay:add_label no colour passed, will default to black (0)", 'ui') end if self.labels[name] == nil then -- create new label and add it self.labels[name] = label(text, position, colour) else -- set existing label properties local label = self.labels[name] label.text = text label.position = position label.colour = colour end end -- remove a label identified by a name -- if the label is not found, fails with warning function overlay:remove_label(name, text, position) if self.labels[name] ~= nil then self.labels[name] = nil else warn("overlay:remove_label: could not find label with name: '"..name.."'", 'ui') end end -- remove all the labels function overlay:clear_labels() clear_table(self.labels) end -- draw all labels in the overlay. order is not guaranteed function overlay:draw_labels() for _, label in pairs(self.labels) do label:draw() end end return overlay
proj = "project18a" -- full init = -- 1 init -- 2 WIFI -- 3 TIME -- then your "project" is ready to start -- short init might skip WIFI/TIME -- following makes missing file into non-panic: local df=dofile dofile=function(f) if file.exists(f) then df(f) else print("File ", f, "not exist ***\n") ff=file.open("missingfile", "w") ff:writeline(f) ff:close() node.restart() end end if file.open("missingfile", "r") then f = file.readline() file.close() file.remove("missingfile") print("Please fix missing file", f) return -- terminate end if file.open("runonce", "r") then f = file.readline():gsub('\n','') file.close() file.remove("runonce") dofile(f) node.restart() end -- refer lib-DEEPSLEEP.lua to understand these numbers if rtcmem and rtcmem.read32(20) == 123654 then-- test if waking from deepsleep? (either timer or button) rtcmem.write32(20,654321) -- if so, destroy that number against re-use, but leave its equivalent for our project to see local pass=rtcmem.read32(23) local starttype = rtcmem.read32(22) if starttype == 1 and pass >0 then node.task.post( function() dofile("init2-WIFI.lua") end ) -- faster than below return elseif starttype == 2 or (starttype == 3 and pass >0) then node.task.post( function() dofile(proj..".lua") end ) -- skip pause, wifi & sntp return end -- so, waking from deepsleep, but not doing any special fast start end -- below, doing regular delayed full start ... wifi.setmode(wifi.STATION) print "Hold down button during blinking to abort..." gpio.mode(4,gpio.OUTPUT) -- the led on ESP12 submodule gpio.mode(3,gpio.INPUT) -- make sure D3 button is working, & not left as an output since just before reset pwm.setup(4,12,950) -- flash pwm.start(4) -- stage #1 tmr.alarm(0, 5000, 0, function() -- allow time for wifi to autostart, and time to salvage looping panics if rtctime.get() > 10 then print("Awake from Deep Sleep") end -- we arrive here after the X mseconds past reset -- see https://bigdanzblog.wordpress.com/2015/04/24/esp8266-nodemcu-interrupting-init-lua-during-boot/ pwm.stop(4) pwm.close(4) -- stop flash if gpio.read(3) == 0 then print "Button held: Aborted start." gpio.write(4,0) -- turn on return -- EXITS without anything else happening. flashing continues. end -- if we get here, we didn't press abort button gpio.write(4,1) -- turn led off gpio.mode(4,0) -- restore to regular input mode dofile("init2-WIFI.lua") end) -- early "stop timer 0" at ESPlorer can abort the init sequence local rawcode,extcode = node.bootreason() local rc={"Pwr on","Reset", "HW reset", "WDT reset"} local ec={"Pwr on", "HW WDT", "Exception Crash", "SW WDT", "SW restart", "Deepsleep Wake", "EXT reset"} -- 0 1 2 3 4 5 6 print(rc[rawcode], ec[extcode+1]) if extcode == 2 then print (node.bootreason()) end -- BUT DON'T BELIEVE IT RELIGIOUSLY !! function clone (t) -- clones a romtable (or table) into ram. Member romtables or lightfunctions remain in rom -- eg math=clone(math) local target = {} for k, v in pairs(t) do target[k] = v end setmetatable(target, getmetatable(t)) target['parent'] = t return target end -- v 0.8 18 sept 2017 starttype 2 for deepsleep
local colors = { { hex="#ffa0a0" }, { hex="#ffe0a0" }, { hex="#ffffa0" }, { hex="#ffffa0" }, { hex="#ffffa0" }, { hex="#ffffa0" }, { hex="#ffffa0" }, { hex="#e0ffa0" }, { hex="#a0ffa0" }, { hex="#a0ffe0" }, { hex="#a0ffff" }, { hex="#a0ffff" }, { hex="#a0ffff" }, { hex="#a0ffff" }, { hex="#a0ffff" }, { hex="#a0e0ff" }, { hex="#a0a0ff" }, { hex="#e0a0ff" }, { hex="#ffa0ff" }, { hex="#ffa0ff" }, { hex="#ffa0ff" }, { hex="#ffa0ff" }, { hex="#ffa0ff" }, { hex="#ffa0e0" }, { hex="#ff7878" }, { hex="#ffb878" }, { hex="#fff878" }, { hex="#ffff78" }, { hex="#ffff78" }, { hex="#ffff78" }, { hex="#f8ff78" }, { hex="#b8ff78" }, { hex="#78ff78" }, { hex="#78ffb8" }, { hex="#78fff8" }, { hex="#78ffff" }, { hex="#78ffff" }, { hex="#78ffff" }, { hex="#78f8ff" }, { hex="#78b8ff" }, { hex="#7878ff" }, { hex="#b878ff" }, { hex="#f878ff" }, { hex="#ff78ff" }, { hex="#ff78ff" }, { hex="#ff78ff" }, { hex="#ff78f8" }, { hex="#ff78b8" }, { hex="#ff5050" }, { hex="#ff9050" }, { hex="#ffd050" }, { hex="#ffff50" }, { hex="#ffff50" }, { hex="#ffff50" }, { hex="#d0ff50" }, { hex="#90ff50" }, { hex="#50ff50" }, { hex="#50ff90" }, { hex="#50ffd0" }, { hex="#50ffff" }, { hex="#50ffff" }, { hex="#50ffff" }, { hex="#50d0ff" }, { hex="#5090ff" }, { hex="#5050ff" }, { hex="#9050ff" }, { hex="#d050ff" }, { hex="#ff50ff" }, { hex="#ff50ff" }, { hex="#ff50ff" }, { hex="#ff50d0" }, { hex="#ff5090" }, { hex="#ff2828" }, { hex="#ff6828" }, { hex="#ffa828" }, { hex="#ffe728" }, { hex="#ffff28" }, { hex="#e7ff28" }, { hex="#a8ff28" }, { hex="#68ff28" }, { hex="#28ff28" }, { hex="#28ff68" }, { hex="#28ffa8" }, { hex="#28ffe7" }, { hex="#28ffff" }, { hex="#28e7ff" }, { hex="#28a8ff" }, { hex="#2868ff" }, { hex="#2828ff" }, { hex="#6828ff" }, { hex="#a828ff" }, { hex="#e728ff" }, { hex="#ff28ff" }, { hex="#ff28e7" }, { hex="#ff28a8" }, { hex="#ff2868" }, { hex="#ff0000" }, { hex="#ff4000" }, { hex="#ff8000" }, { hex="#ffbf00" }, { hex="#ffff00" }, { hex="#bfff00" }, { hex="#80ff00" }, { hex="#40ff00" }, { hex="#00ff00" }, { hex="#00ff40" }, { hex="#00ff80" }, { hex="#00ffbf" }, { hex="#00ffff" }, { hex="#00bfff" }, { hex="#0080ff" }, { hex="#0040ff" }, { hex="#0000ff" }, { hex="#4000ff" }, { hex="#8000ff" }, { hex="#bf00ff" }, { hex="#ff00ff" }, { hex="#ff00bf" }, { hex="#ff0080" }, { hex="#ff0040" }, { hex="#c54545" }, { hex="#c96949" }, { hex="#d49555" }, { hex="#e4c465" }, { hex="#f7f778" }, { hex="#ceee6e" }, { hex="#a7e767" }, { hex="#83e263" }, { hex="#61e161" }, { hex="#62e182" }, { hex="#64e3a4" }, { hex="#66e6c6" }, { hex="#6aeaea" }, { hex="#54b4d4" }, { hex="#4181c0" }, { hex="#3151b1" }, { hex="#2b2baa" }, { hex="#4e2ead" }, { hex="#7737b6" }, { hex="#a343c3" }, { hex="#d151d1" }, { hex="#cc4cac" }, { hex="#c84888" }, { hex="#c64666" }, { hex="#b40000" }, { hex="#b40000" }, { hex="#b43500" }, { hex="#b47400" }, { hex="#b4b400" }, { hex="#74b400" }, { hex="#35b400" }, { hex="#00b400" }, { hex="#00b400" }, { hex="#00b400" }, { hex="#00b435" }, { hex="#00b474" }, { hex="#00b4b4" }, { hex="#0074b4" }, { hex="#0035b4" }, { hex="#0000b4" }, { hex="#0000b4" }, { hex="#0000b4" }, { hex="#3500b4" }, { hex="#7400b4" }, { hex="#b400b4" }, { hex="#b40074" }, { hex="#b40035" }, { hex="#b40000" }, { hex="#8b3131" }, { hex="#8b3131" }, { hex="#8f4f35" }, { hex="#9c7c42" }, { hex="#aeae54" }, { hex="#85a54b" }, { hex="#60a046" }, { hex="#449e44" }, { hex="#449e44" }, { hex="#449e44" }, { hex="#459f60" }, { hex="#47a181" }, { hex="#4ba5a5" }, { hex="#356f8f" }, { hex="#243f7e" }, { hex="#1e1e78" }, { hex="#1e1e78" }, { hex="#1e1e78" }, { hex="#3c217b" }, { hex="#652b85" }, { hex="#933993" }, { hex="#8e346e" }, { hex="#8c324c" }, { hex="#8b3131" }, { hex="#690000" }, { hex="#690000" }, { hex="#690000" }, { hex="#692900" }, { hex="#696900" }, { hex="#296900" }, { hex="#006900" }, { hex="#006900" }, { hex="#006900" }, { hex="#006900" }, { hex="#006900" }, { hex="#006929" }, { hex="#006969" }, { hex="#002969" }, { hex="#000069" }, { hex="#000069" }, { hex="#000069" }, { hex="#000069" }, { hex="#000069" }, { hex="#290069" }, { hex="#690069" }, { hex="#690029" }, { hex="#690000" }, { hex="#690000" }, { hex="#511c1c" }, { hex="#511c1c" }, { hex="#511c1c" }, { hex="#553520" }, { hex="#656531" }, { hex="#3e5e29" }, { hex="#285c28" }, { hex="#285c28" }, { hex="#285c28" }, { hex="#285c28" }, { hex="#285c28" }, { hex="#285d3d" }, { hex="#2b6060" }, { hex="#172c4c" }, { hex="#111146" }, { hex="#111146" }, { hex="#111146" }, { hex="#111146" }, { hex="#111146" }, { hex="#291449" }, { hex="#562156" }, { hex="#521d32" }, { hex="#511c1c" }, { hex="#511c1c" }, { hex="#ffffff" }, { hex="#eeeeee" }, { hex="#dddddd" }, { hex="#cccccc" }, { hex="#bbbbbb" }, { hex="#aaaaaa" }, { hex="#999999" }, { hex="#888888" }, { hex="#777777" }, { hex="#666666" }, { hex="#555555" }, { hex="#444444" }, { hex="#333333" }, { hex="#222222" }, { hex="#111111" }, { hex="#000000" } } return colors
---------------------------------------------------------------------- -- -- Deep Genetic Programming: Reifying an AI researcher. -- -- Set of modules the researcher has access to and init functions -- * Initialize tables -- * Setup list of models -- * Processing functions -- ---------------------------------------------------------------------- ---------------------------------------------------------------------- -- Sets of libs requirements require 'optim' require 'torch' require 'dp' --require 'cunn' require 'rnn' --require 'fbnn' require 'nngraph' require 'graph' require 'nnx' require 'nn' ---------------------------------------------------------------------- -- classes parameters classes = {'1','2','3','4','5','6','7','8','9','0'} -- This matrix records the current confusion across classes confusion = optim.ConfusionMatrix(classes) ---------------------------------------------------------------------- -- Add the potential modules to the table of available modules function insert_module(moduleName, moduleCall, moduleType, nParameters, paramNames, paramRange) -- ensure we haven't already inserted this function if module_table[moduleName] ~= nil then print("Warning - module already defined: " .. moduleName) return false end -- Add this function to the table tempFunction = {} tempFunction.func = moduleCall tempFunction.name = moduleName tempFunction.type = moduleType tempFunction.params = nParameters tempFunction.paramRange = paramRange tempFunction.paramNames = paramNames table.insert(module_table, tempFunction); return true end ---------------------------------------------------------------------- -- Sample the input to a certain percent function sampleInput(input, percent) setSize = input.data:size(1); shuffle = torch.randperm(setSize) return input.data[{shuffle[{1,(percent*setSize)}],{},{},{}}]; end ---------------------------------------------------------------------- -- List of parameter ranges minUnits = 10; maxUnits = 2000; ---------------------------------------------------------------------- -- List of available functions function establish_functions() -- Basic input/output (identity) nodes insert_module("input", nn.Identity, "input", 0, {}, {}); insert_module("output", nn.Identity, "output", 0, {}, {}); --------------------- -- Tensors containers --------------------- -- Sequential densely connects modules in a feed-forward manner insert_module("Sequential", nn.Sequential, "iterate", 0, {}, {}); -- Parallel applies its ith child module to the ith slice of the input Tensor by using select on dimension inputDimension insert_module("Parallel", nn.Parallel, "iterate", 2, {'dimensionIn', 'dimensionOut'}, {{1, ndims}, {1, ndims}}); -- Concat concatenates the output of one layer of "parallel" modules along the provided dimension dim insert_module("Concat", nn.Concat, "iterate", 1, {'dimensionIn'}, {{1, ndims}}); -- DepthConcat concatenates output of parallel layer through depth (can be different dimensionalities) insert_module("DepthConcat", nn.DepthConcat, "iterate", 1, {'dimensionIn'}, {{1, ndims}}); --------------------- -- Transfer functions --------------------- -- Hard hyperbolic tangent insert_module("HardTanh", nn.HardTanh, "transfer", 0, {}, {}); -- Hard shrinkage (almost RELU with threshold-based) insert_module("HardShrink", nn.HardShrink, "transfer", 1, {'lambda'}, {{-1.5,1.5}); -- Soft shrinkage (threshold-based) insert_module("SoftShrink", nn.SoftShrink, "transfer", 1, {'lambda'}, {{-1.5,1.5}); -- Softmax function (and unit-sum rescaling) insert_module("SoftMax", nn.SoftMax, "transfer", 0, {}, {}); -- Softmin function (and unit-sum rescaling) insert_module("SoftMin", nn.SoftMin, "transfer", 0, {}, {}); -- Softplus function (and unit-sum rescaling) insert_module("SoftPlus", nn.SoftPlus, "transfer", 0, {}, {}); -- Softsign function always positive insert_module("SoftSign", nn.SoftSign, "transfer", 0, {}, {}); -- Log-Sigmoid transfer function insert_module("LogSigmoid", nn.LogSigmoid, "transfer", 0, {}, {}); -- Log-Softmax transfer function insert_module("LogSoftMax", nn.LogSoftMax, "transfer", 0, {}, {}); -- Sigmoid transfer function insert_module("Sigmoid", nn.Sigmoid, "transfer", 0, {}, {}); -- Tanh transfer function insert_module("Tanh", nn.Tanh, "transfer", 0, {}, {}); -- Rectified Linear Units transfer function insert_module("ReLU", nn.ReLU, "transfer", 0, {}, {}); -- Parametric Rectified Linear Units transfer function insert_module("PReLU", nn.PReLU, "transfer", 0, {}, {}); --------------------- -- Combination functions --------------------- -- Linear combination of the inputs insert_module("Linear", nn.Linear, "transform", 2, {'inputDimension', 'outputDimension'}, {{minUnits, maxUnits}, {minUnits, maxUnits}}); -- Sparse linear combination of the inputs insert_module("SparseLinear", nn.SparseLinear, "transform", 2, {'inputDimension', 'outputDimension'}, {{minUnits, maxUnits}, {minUnits, maxUnits}}); -- Dropout module insert_module("Dropout", nn.Dropout, "transform", 1, {'ratio'}, {{0, 1}}); -- Spatial Dropout module insert_module("SpatialDropout", nn.SpatialDropout, "transform", 1, {'ratio'}, {{0, 1}}); --------------------- -- Mathematical functions --------------------- -- Absolute value of the input insert_module("Abs", nn.Abs, "mathematical", 0, {}, {}); -- Add a scalar to the input insert_module("Add", nn.Add, "mathematical", 2, {'inputDimension', 'scalar'}, {{minUnits, maxUnits}, {minUnits, maxUnits}}); -- Multiply the input insert_module("Mul", nn.Mul, "mathematical", 0, {}, {}); -- Component-wise multiply the input insert_module("CMul", nn.CMul, "mathematical", 1, {'size'}, {{1, ndims}}); -- Min across a specific dimensions of the input insert_module("Min", nn.Min, "mathematical", 1, {'size'}, {{1, ndims}}); -- Min across a specific dimensions of the input insert_module("Max", nn.Max, "mathematical", 1, {'size'}, {{1, ndims}}); -- Min across a specific dimensions of the input insert_module("Mean", nn.Mean, "mathematical", 1, {'size'}, {{1, ndims}}); -- Min across a specific dimensions of the input insert_module("Sum", nn.Sum, "mathematical", 1, {'size'}, {{1, ndims}}); -- Euclidean distance of the input to outputSize centers insert_module("Euclidean", nn.Euclidean, "mathematical", 2, {'inputDimension', 'outputDimension'}, {{minUnits, maxUnits}, {minUnits, maxUnits}}); -- Euclidean distance which additionally learns a separate diagonal covariance matrix insert_module("WeightedEuclidean", nn.WeightedEuclidean, "mathematical", 2, {'inputDimension', 'outputDimension'}, {{minUnits, maxUnits}, {minUnits, maxUnits}}); -- Exponentiate the input insert_module("Exp", nn.Exp, "mathematical", 0, {}, {}); -- Square power of the input insert_module("Square", nn.Square, "mathematical", 0, {}, {}); -- Square root of the input insert_module("Sqrt", nn.Sqrt, "mathematical", 0, {}, {}); -- Take the power of the input insert_module("Power", nn.Power, "mathematical", 1, {'power'}, {{1,32}}); -- Batch normalization of the input insert_module("BatchNormalization", nn.BatchNormalization, "mathematical", 0, {}, {}); -- Take the power of the input insert_module("L1Penalty", nn.BatchNormalization, "mathematical", 1, {'L1weight', 'sizeAverage'}, {{1,32}}); --------------------- -- Dimensional functions --------------------- -- Narrow the module to a given length starting at an offset insert_module("Narrow", nn.Narrow, "dimensional", 3, {'inputDimension', 'offset', 'outputDimension'}, {{minUnits, maxUnits}, {minUnits, maxUnits}, {minUnits, maxUnits}}); -- Replicate the module to a given length starting at an offset insert_module("Replicate", nn.Replicate, "dimensional", 2, {'replication', 'dimension'}, {{2, maxUnits}, {1, ndims}}); --------------------- -- Table functions --------------------- -- ConcatTable() : applies each member module to the same input Tensor and outputs a table; -- ParallelTable() : applies the i-th member module to the i-th input and outputs a table; -- SplitTable(dim,nInputs) : splits a Tensor into a table of Tensors; -- JoinTable(dim,nInputs) : joins a table of Tensors into a Tensor; -- MixtureTable(dim) : mixture of experts weighted by a gater; -- SelectTable(index) : select one element from a table; -- NarrowTable(offset,len) : select a slice of elements from a table; -- FlattenTable() : flattens a nested table hierarchy; -- PairwiseDistance(p) : outputs the p-norm distance between inputs; -- DotProduct() : outputs the dot product (similarity) between inputs; -- CosineDistance() : outputs the cosine distance between inputs; -- CAddTable() : addition of input Tensors; -- CSubTable() : substraction of input Tensors; -- CMulTable() : multiplication of input Tensors; -- CDivTable() : division of input Tensors --------------------- -- Temporal convolutions (1-dimensional sequences) --------------------- -- TemporalConvolution (1D convolution over an input sequence) insert_module("TemporalConvolution", nn.TemporalConvolution, "temporal-convolution", 4, {'inputFrameSize', 'outputFrameSize', 'kernelWidth', 'convStep'}, {{1, 64}, {1, 64}, {1, 64}, {1, 64}}); -- TemporalSubSampling (1D sub-sampling over an input sequence) insert_module("TemporalSubSampling", nn.TemporalSubSampling, "temporal-convolution", 3, {'inputFrameSize', 'kernelWidth', 'convStep'}, {{1, 64}, {1, 64}, {1, 64}}); -- TemporalMaxPooling (1D max-pooling operation over an input sequence) insert_module("TemporalMaxPooling", nn.TemporalMaxPooling, "temporal-convolution", 2, {'kernelWidth', 'convStep'}, {{1, 64}, {1, 64}}); -- LookupTable (convolution of width 1 usually for word embeddings) insert_module("LookupTable", nn.LookupTable, "temporal-convolution", 2, {'nIndex', 'sizes'}, {{1, ninputs}, {1, ndims}}); --------------------- -- Spatial convolutions (2-dimensional sequences) --------------------- -- SpatialConvolution (2D convolution over an input image) insert_module("SpatialConvolution", nn.SpatialConvolution, "spatial-convolution", 4, {'inputPlane', 'outputPlane', 'kernelWidth', 'kernelHeight'}, {{1, 64}, {1, 64}, {1, 64}, {1, 64}}); -- SpatialSubSampling (2D sub-sampling over an input image) insert_module("SpatialSubSampling", nn.SpatialSubSampling, "spatial-convolution", 3, {'inputPlane', 'kernelWidth', 'kernelHeight'}, {{1, 64}, {1, 64}, {1, 64}}); -- SpatialMaxPooling (2D max-pooling operation over an input image) insert_module("SpatialMaxPooling", nn.SpatialMaxPooling, "spatial-convolution", 2, {'kernelWidth', 'kernelHeight'}, {{1, 64}, {1, 64}}); -- SpatialAveragePooling (2D average-pooling operation over an input image) insert_module("SpatialAveragePooling", nn.SpatialAveragePooling, "spatial-convolution", 2, {'kernelWidth', 'kernelHeight'}, {{1, 64}, {1, 64}}); -- SpatialAdaptiveMaxPooling (2D max-pooling operation which adapts its parameters dynamically) insert_module("SpatialAdaptiveMaxPooling", nn.SpatialAdaptiveMaxPooling, "spatial-convolution", 2, {'kernelWidth', 'kernelHeight'}, {{1, 64}, {1, 64}}); -- SpatialLPPooling (p-norm in a convolutional manner on a set of input images) insert_module("SpatialLPPooling", nn.SpatialLPPooling, "spatial-convolution", 4, {'inputPlane', 'pNorm', 'kernelWidth', 'convStep'}, {{1, 64}, {1, 64}, {1, 64}, {1, 64}}); -- SpatialZeroPadding (padds a feature map with specified number of zeros) insert_module("SpatialZeroPadding", nn.SpatialZeroPadding, "spatial-convolution", 4, {'padLeft', 'padRight', 'padTop', 'padBottom'}, {{1, 64}, {1, 64}, {1, 64}, {1, 64}}); -- SpatialSubtractiveNormalization (spatial subtraction operation on a series of 2D inputs) insert_module("SpatialSubtractiveNormalization", nn.SpatialSubtractiveNormalization, "spatial-convolution", 2, {'ninputplane', 'kernel'}, {{1, 64}, {1, 64}}); -- SpatialBatchNormalization (mean/std normalization over a mini-batch inputs) insert_module("SpatialBatchNormalization", nn.SpatialBatchNormalization, "spatial-convolution", 0, {}, {}); --------------------- -- Volumetric convolutions (3-dimensional sequences) --------------------- -- VolumetricConvolution (3D convolution over video) insert_module("VolumetricConvolution", nn.VolumetricConvolution, "volumetric-convolution", 5, {'inputPlane', 'outputPlane', 'kernelTime', 'kernelWidth', 'kernelHeight'}, {{1, 64}, {1, 64}, {1, 64}, {1, 64}, {1, 64}}); -- VolumetricMaxPooling (3D max-pooling over video). insert_module("VolumetricMaxPooling", nn.VolumetricMaxPooling, "volumetric-convolution", 3, {'kernelTime', 'kernelWidth', 'kernelHeight'}, {{1, 64}, {1, 64}, {1, 64}}); -- VolumetricAveragePooling (3D average-pooling over video) insert_module("VolumetricAveragePooling", nn.VolumetricAveragePooling, "volumetric-convolution", 3, {'kernelTime', 'kernelWidth', 'kernelHeight'}, {{1, 64}, {1, 64}}); --------------------- -- Multiple classifications (from nnx) --------------------- -- SoftMaxTree (A hierarchy of parameterized log-softmaxes, useful for very wide number of classes, use wutg TreeLLCCriterion) insert_module("SoftMaxTree", nn.SoftMaxTree, "multi-classification", 3, {'inputSize', 'hierarchy'}, {{1, 64}, {1, 64}}); -- MultiSoftMax performs a softmax over the last dimension of 2/3-dimensional tensor --------------------- -- Recurrent modules --------------------- -- -- -- end ---------------------------------------------------------------------- -- Process the current network function evaluateNetwork(model, trainData, testData) -- First compute the forward activation inTrans = model:forward(trainData.data) print(inTrans) -- Then add a softmax on this transform softModel = nn.Sequential(); softModel:add(nn.LogSoftMax()); criterion = nn.ClassNLLCriterion(); -- shuffle at each epoch shuffle = torch.randperm(trsize); -- set model to train mode --softModel:train() for e = 1,opt.epochs do for t = 1,inTrans:size(),opt.batchSize do -- disp progress xlua.progress(t, inTrans:size()) -- create mini batch local inputs = {} local targets = {} for i = t,math.min(t+opt.batchSize-1,trainData:size()) do -- load new sample local input = inTrans[shuffle[i]] local target = trainData.labels[shuffle[i]] if opt.type == 'double' then input = input:double() elseif opt.type == 'cuda' then input = input:cuda() end table.insert(inputs, input) table.insert(targets, target) end -- create closure to evaluate f(X) and df/dX local feval = function(x) -- get new parameters if x ~= parameters then parameters:copy(x) end -- reset gradients gradParameters:zero() -- f is the average of all criterions local f = 0 -- evaluate function for complete mini batch for i = 1,#inputs do -- estimate f local output = softModel:forward(inputs[i]) local err = criterion:forward(output, targets[i]) f = f + err -- estimate df/dW local df_do = criterion:backward(output, targets[i]) softModel:backward(inputs[i], df_do) -- update confusion confusion:add(output, targets[i]) end -- normalize gradients and f(X) gradParameters:div(#inputs) f = f/#inputs -- return f and df/dX return f,gradParameters end -- optimize on current mini-batch if optimMethod == optim.asgd then _,_,average = optimMethod(feval, parameters, optimState) else optimMethod(feval, parameters, optimState) end end confusion:zero(); end -- set model to evaluate mode --softModel:evalute(); for t = 1,testData:size() do -- disp progress xlua.progress(t, testData:size()) -- get new sample local input = testData.data[t] if opt.type == 'double' then input = input:double() elseif opt.type == 'cuda' then input = input:cuda() end local target = testData.labels[t] -- test sample local pred = softModel:forward(input) confusion:add(pred, target) end return (1.0 - confusion.totalValid); end
ITEM.name = "Hula Doll" ITEM.desc = "An old hula doll, the head still bobs when shaken" ITEM.model = "models/props_lab/huladoll.mdl" ITEM.width = 1 ITEM.height = 1 ITEM.money = {1, 4}
-- Copyright (C) Jingli Chen (Wine93) -- Copyright (C) Jinzheng Zhang (tianchaijz) local base = require "resty.addon.base" local register = base.register local register_handlers = base.register_handlers local init = base.init local run = base.run local exec = base.exec local next_handler = base.next_handler local _handlers = {} local _inits = {} -- init worker hooks local _inits_loaded = {} local _M = {} local _mt = { __index = _M } _M.INIT_WORKER = -1 _M.REWRITE_PHASE = 1 _M.ACCESS_PHASE = 2 _M.CONTENT_PHASE = 3 _M.HEADER_FILTER_PHASE = 4 _M.BODY_FILTER_PHASE = 5 _M.LOG_PHASE = 6 function _M.register(typ, modules) register(typ, modules, _M.INIT_WORKER, _M.REWRITE_PHASE, _M.LOG_PHASE, _handlers, _inits, _inits_loaded) end function _M.register_handlers(registry) register_handlers(registry, _M.INIT_WORKER, _M.REWRITE_PHASE, _M.LOG_PHASE, _handlers, _inits, _inits_loaded) end function _M.init() init(_inits) _inits = {} _inits_loaded = {} end function _M.new(typ) local addon = { _type = typ, _ctx = {}, _phase = 0, } return setmetatable(addon, _mt) end _M.get_type = base.get_type _M.set_type = base.set_type _M.set_phase = base.set_phase _M.get_phase = base.get_phase _M.get_module_ctx = base.get_module_ctx _M.set_module_ctx = base.set_module_ctx function _M.run(self, phase) return run(self, phase, _handlers) end function _M.exec(self, typ) return exec(self, typ, _handlers) end function _M.next_handler(self, module) return next_handler(self, module, _handlers) end return _M
local arch = ({ aarch64='arm64', x86_64='x86', })[config.target.platform:match('[^-]*')] sub('tools.ninja', function() toolchain(config.host) exe('unifdef', {'scripts/unifdef.c'}) end) rule('header', 'sed -E -f $dir/header.sed $in >$out.tmp && { $outdir/unifdef -U__KERNEL__ -D__EXPORTED_HEADERS__ $out.tmp >$out; [ $$? -le 1 ]; } && rm $out.tmp') rule('wrapper', [[printf '#include <asm-generic/%s>\n' $file >$out]]) local function process(outdir, srcdir, files) local outs = {} for i, file in ipairs(files) do local out = outdir..'/'..file outs[i] = out build('header', out, {srcdir..'/'..file, '|', '$dir/header.sed', '$outdir/unifdef'}) end return outs end local mandatory = { -- <awk '$1 == "mandatory-y" {printf "\\t'\'%s\'',\\n", $3}' src/include/uapi/asm-generic/Kbuild 'auxvec.h', 'bitsperlong.h', 'bpf_perf_event.h', 'byteorder.h', 'errno.h', 'fcntl.h', 'ioctl.h', 'ioctls.h', 'ipcbuf.h', 'mman.h', 'msgbuf.h', 'param.h', 'poll.h', 'posix_types.h', 'ptrace.h', 'resource.h', 'sembuf.h', 'setup.h', 'shmbuf.h', 'sigcontext.h', 'siginfo.h', 'signal.h', 'socket.h', 'sockios.h', 'stat.h', 'statfs.h', 'swab.h', 'termbits.h', 'termios.h', 'types.h', 'unistd.h', } local basefiles = load('base.lua') local archfiles = load(arch..'.lua') build('awk', '$outdir/include/linux/version.h', {'$srcdir/Makefile', '|', '$dir/version.awk'}, { expr='-f $dir/version.awk', }) pkg.hdrs = { '$outdir/include/linux/version.h', process('$outdir/include', '$srcdir/include/uapi', basefiles), process('$outdir/include', '$srcdir/arch/'..arch..'/include/uapi', archfiles), install=true, } for _, file in ipairs(archfiles) do archfiles[file] = true end for _, file in ipairs(mandatory) do if not archfiles['asm/'..file] then local out = '$outdir/include/asm/'..file build('wrapper', out, nil, {file=file}) table.insert(pkg.hdrs, out) end end for _, spec in ipairs(archfiles.unistd) do local out = '$outdir/include/asm/'..spec.dst build('awk', out, {'$srcdir/'..spec.src, '|', '$dir/unistd.awk'}, { expr={ '-v arch='..arch, '-v file='..spec.dst, string.format([[-v abi='%s']], spec.abi), '-v off='..(spec.off or ''), '-f $dir/unistd.awk', }, }) table.insert(pkg.hdrs, out) end fetch 'local'
setDefaultTab("Main") local panelName = "newHealer" local ui = setupUI([[ Panel height: 19 BotSwitch id: title anchors.top: parent.top anchors.left: parent.left text-align: center width: 130 !text: tr('Friend Healer') Button id: edit anchors.top: prev.top anchors.left: prev.right anchors.right: parent.right margin-left: 3 height: 17 text: Setup ]]) ui:setId(panelName) -- validate current settings if not storage[panelName] or not storage[panelName].priorities then storage[panelName] = nil end if not storage[panelName] then storage[panelName] = { enabled = false, customPlayers = {}, vocations = {}, groups = {}, priorities = { {name="Custom Spell", enabled=false, custom=true}, {name="Exura Gran Sio", enabled=true, strong = true}, {name="Exura Sio", enabled=true, normal = true}, {name="Exura Gran Mas Res", enabled=true, area = true}, {name="Health Item", enabled=true, health=true}, {name="Mana Item", enabled=true, mana=true} }, settings = { {type="HealItem", text="Mana Item ", value=268}, {type="HealScroll", text="Item Range: ", value=6}, {type="HealItem", text="Health Item ", value=3160}, {type="HealScroll", text="Mas Res Players: ", value=2}, {type="HealScroll", text="Heal Friend at: ", value=80}, {type="HealScroll", text="Use Gran Sio at: ", value=80}, {type="HealScroll", text="Min Player HP%: ", value=80}, {type="HealScroll", text="Min Player MP%: ", value=50}, }, conditions = { knights = true, paladins = true, druids = false, sorcerers = false, party = true, guild = false, botserver = false, friends = false } } end local config = storage[panelName] local healerWindow = UI.createWindow('FriendHealer') healerWindow:hide() healerWindow:setId(panelName) ui.title:setOn(config.enabled) ui.title.onClick = function(widget) config.enabled = not config.enabled widget:setOn(config.enabled) end ui.edit.onClick = function() healerWindow:show() healerWindow:raise() healerWindow:focus() end local conditions = healerWindow.conditions local targetSettings = healerWindow.targetSettings local customList = healerWindow.customList local priority = healerWindow.priority -- customList -- create entries on the list for name, health in pairs(config.customPlayers) do local widget = UI.createWidget("HealerPlayerEntry", customList.playerList.list) widget.remove.onClick = function() config.customPlayers[name] = nil widget:destroy() end widget:setText("["..health.."%] "..name) end customList.playerList.onDoubleClick = function() customList.playerList:hide() end local function clearFields() customList.addPanel.name:setText("friend name") customList.addPanel.health:setText("1") customList.playerList:show() end local function capitalFistLetter(str) return (string.gsub(str, "^%l", string.upper)) end customList.addPanel.add.onClick = function() local name = "" local words = string.split(customList.addPanel.name:getText(), " ") local health = tonumber(customList.addPanel.health:getText()) for i, word in ipairs(words) do name = name .. " " .. capitalFistLetter(word) end if not health then clearFields() return warn("[Friend Healer] Please enter health percent value!") end if name:len() == 0 or name:lower() == "friend name" then clearFields() return warn("[Friend Healer] Please enter friend name to be added!") end if config.customPlayers[name] or config.customPlayers[name:lower()] then clearFields() return warn("[Friend Healer] Player already added to custom list.") else config.customPlayers[name] = health local widget = UI.createWidget("HealerPlayerEntry", customList.playerList.list) widget.remove.onClick = function() config.customPlayers[name] = nil widget:destroy() end widget:setText("["..health.."%] "..name) end clearFields() end local function validate(widget, category) local list = widget:getParent() local label = list:getParent().title -- 1 - priorities | 2 - vocation category = category or 0 if category == 2 and not storage.extras.checkPlayer then label:setColor("#d9321f") label:setTooltip("! WARNING ! \nTurn on check players in extras to use this feature!") return else label:setColor("#dfdfdf") label:setTooltip("") end local checked = false for i, child in ipairs(list:getChildren()) do if category == 1 and child.enabled:isChecked() or child:isChecked() then checked = true end end if not checked then label:setColor("#d9321f") label:setTooltip("! WARNING ! \nNo category selected!") else label:setColor("#dfdfdf") label:setTooltip("") end end -- targetSettings targetSettings.vocations.box.knights:setChecked(config.conditions.knights) targetSettings.vocations.box.knights.onClick = function(widget) config.conditions.knights = not config.conditions.knights widget:setChecked(config.conditions.knights) validate(widget, 2) end targetSettings.vocations.box.paladins:setChecked(config.conditions.paladins) targetSettings.vocations.box.paladins.onClick = function(widget) config.conditions.paladins = not config.conditions.paladins widget:setChecked(config.conditions.paladins) validate(widget, 2) end targetSettings.vocations.box.druids:setChecked(config.conditions.druids) targetSettings.vocations.box.druids.onClick = function(widget) config.conditions.druids = not config.conditions.druids widget:setChecked(config.conditions.druids) validate(widget, 2) end targetSettings.vocations.box.sorcerers:setChecked(config.conditions.sorcerers) targetSettings.vocations.box.sorcerers.onClick = function(widget) config.conditions.sorcerers = not config.conditions.sorcerers widget:setChecked(config.conditions.sorcerers) validate(widget, 2) end targetSettings.groups.box.friends:setChecked(config.conditions.friends) targetSettings.groups.box.friends.onClick = function(widget) config.conditions.friends = not config.conditions.friends widget:setChecked(config.conditions.friends) validate(widget) end targetSettings.groups.box.party:setChecked(config.conditions.party) targetSettings.groups.box.party.onClick = function(widget) config.conditions.party = not config.conditions.party widget:setChecked(config.conditions.party) validate(widget) end targetSettings.groups.box.guild:setChecked(config.conditions.guild) targetSettings.groups.box.guild.onClick = function(widget) config.conditions.guild = not config.conditions.guild widget:setChecked(config.conditions.guild) validate(widget) end targetSettings.groups.box.botserver:setChecked(config.conditions.botserver) targetSettings.groups.box.botserver.onClick = function(widget) config.conditions.botserver = not config.conditions.botserver widget:setChecked(config.conditions.botserver) validate(widget) end validate(targetSettings.vocations.box.knights) validate(targetSettings.groups.box.friends) validate(targetSettings.vocations.box.sorcerers, 2) -- conditions for i, setting in ipairs(config.settings) do local widget = UI.createWidget(setting.type, conditions.box) local text = setting.text local val = setting.value widget.text:setText(text) if setting.type == "HealScroll" then widget.text:setText(widget.text:getText()..val) if not (text:find("Range") or text:find("Mas Res")) then widget.text:setText(widget.text:getText().."%") end widget.scroll:setValue(val) widget.scroll.onValueChange = function(scroll, value) setting.value = value widget.text:setText(text..value) if not (text:find("Range") or text:find("Mas Res")) then widget.text:setText(widget.text:getText().."%") end end if text:find("Range") or text:find("Mas Res") then widget.scroll:setMaximum(10) end else widget.item:setItemId(val) widget.item:setShowCount(false) widget.item.onItemChange = function(widget) setting.value = widget:getItemId() end end end -- priority and toggles local function setCrementalButtons() for i, child in ipairs(priority.list:getChildren()) do if i == 1 then child.increment:disable() elseif i == 6 then child.decrement:disable() else child.increment:enable() child.decrement:enable() end end end for i, action in ipairs(config.priorities) do local widget = UI.createWidget("PriorityEntry", priority.list) widget:setText(action.name) widget.increment.onClick = function() local index = priority.list:getChildIndex(widget) local table = config.priorities priority.list:moveChildToIndex(widget, index-1) table[index], table[index-1] = table[index-1], table[index] setCrementalButtons() end widget.decrement.onClick = function() local index = priority.list:getChildIndex(widget) local table = config.priorities priority.list:moveChildToIndex(widget, index+1) table[index], table[index+1] = table[index+1], table[index] setCrementalButtons() end widget.enabled:setChecked(action.enabled) widget:setColor(action.enabled and "#98BF64" or "#dfdfdf") widget.enabled.onClick = function() action.enabled = not action.enabled widget:setColor(action.enabled and "#98BF64" or "#dfdfdf") widget.enabled:setChecked(action.enabled) validate(widget, 1) end if action.custom then widget.onDoubleClick = function() local window = modules.client_textedit.show(widget, {title = "Custom Spell", description = "Enter below formula for a custom healing spell"}) schedule(50, function() window:raise() window:focus() end) end widget.onTextChange = function(widget,text) action.name = text end widget:setTooltip("Double click to set spell formula.") end if i == #config.priorities then validate(widget, 1) setCrementalButtons() end end local lastItemUse = now local function friendHealerAction(spec, targetsInRange) local name = spec:getName() local health = spec:getHealthPercent() local mana = spec:getManaPercent() local dist = distanceFromPlayer(spec:getPosition()) targetsInRange = targetsInRange or 0 local masResAmount = config.settings[4].value local itemRange = config.settings[2].value local healItem = config.settings[3].value local manaItem = config.settings[1].value local normalHeal = config.customPlayers[name] or config.settings[5].value local strongHeal = config.customPlayers[name] and normalHeal/2 or config.settings[6].value for i, action in ipairs(config.priorities) do if action.enabled then if action.area and masResAmount <= targetsInRange and canCast("exura gran mas res") then return say("exura gran mas res") end if action.mana and findItem(manaItem) and mana <= normalHeal and dist <= itemRange and now - lastItemUse > 1000 then lastItemUse = now return useWith(manaItem, spec) end if action.health and findItem(healItem) and health <= normalHeal and dist <= itemRange and now - lastItemUse > 1000 then lastItemUse = now return useWith(healItem, spec) end if action.strong and health <= strongHeal and not modules.game_cooldown.isCooldownIconActive(101) then return say('exura gran sio "'..name) end if (action.normal or action.custom) and health <= normalHeal and canCast('exura sio "'..name) then return say('exura sio "'..name) end end end end macro(100, function() if not config.enabled then return end if modules.game_cooldown.isGroupCooldownIconActive(2) then return end local minHp = config.settings[7].value local minMp = config.settings[8].value -- first index will be heal target local finalTable = {} local inMasResRange = 0 -- check basic if hppercent() <= minHp or manapercent() <= minMp then return end -- get all spectators local spectators = getSpectators() -- clear table from irrelevant spectators for i, spec in ipairs(getSpectators()) do if spec:isLocalPlayer() or not spec:isPlayer() or not spec:canShoot() then if not config.customPlayers[name] then table.remove(spectators, table.find(spectators, spec)) end else local specText = spec:getText() -- check players is enabled and spectator already verified if storage.extras.checkPlayer and specText:len() > 0 then if specText:find("EK") and not config.conditions.knights or specText:find("RP") and not config.conditions.paladins or specText:find("ED") and not config.conditions.druids or specText:find("MS") and not config.conditions.sorcerers then if not config.customPlayers[name] then table.remove(spectators, table.find(spectators, spec)) end end end local okParty = config.conditions.party and spec:isPartyMember() local okFriend = config.conditions.friends and isFriend(spec) local okGuild = config.conditions.guild and spec:getEmblem() == 1 local okBotServer = config.conditions.botserver and vBot.BotServerMembers[spec:getName()] if not (okParty or okFriend or okGuild or okBotServer) then if not config.customPlayers[name] then table.remove(spectators, table.find(spectators, spec)) end end end end -- no targets, return if #spectators == 0 then return end for name, health in pairs(config.customPlayers) do for i, spec in ipairs(spectators) do local specHp = spec:getHealthPercent() if spec:getName() == name and specHp <= health then if distanceFromPlayer(spec:getPosition()) <= 2 then inMasResRange = inMasResRange + 1 end table.insert(finalTable, spec) table.remove(spectators, i) end end end for i=1,#spectators do local spec = spectators[i] if distanceFromPlayer(spec:getPosition()) <= 3 then inMasResRange = inMasResRange + 1 end table.insert(finalTable, spec) end -- no targets, return if #finalTable == 0 then return end friendHealerAction(finalTable[1], inMasResRange) end)
--- wand cores minetest.register_craftitem("sorcery:basic_core", {description = "Basic Wand Core", inventory_image = "basic_core.png"}) minetest.register_craft({ output = "sorcery:basic_core", recipe = { {"", "default:glass", ""}, {"default:glass", "default:torch", "default:glass"}, {"", "default:glass", ""} } }) minetest.register_craftitem("sorcery:mese_core", {description = "Mese Wand Core", inventory_image = "mese_core.png"}) minetest.register_craft({ output = "sorcery:mese_core", recipe = { {"", "default:obsidian_glass", ""}, {"default:obsidian_glass", "default:mese_crystal", "default:obsidian_glass"}, {"", "default:obsidian_glass", ""} } }) minetest.register_craftitem("sorcery:diamond_core", {description = "Diamond Wand Core", inventory_image = "diamond_core.png"}) minetest.register_craft({ output = "sorcery:diamond_core", recipe = { {"", "default:obsidian_glass", ""}, {"default:obsidian_glass", "default:diamond", "default:obsidian_glass"}, {"", "default:obsidian_glass", ""} } }) --- the actual wands sorcery.register_wand({ name = "sorcery:basic_wand", desc = "Basic Wand", full_desc = "As you hold the wand, you feel a surge of excitement wash over you. Your very own wand, at last!", image = "basic_wand.png", power = 1, craft_recipe = { {"sorcery:basic_core"}, {"default:stick"}, {"default:stick"}, } }) sorcery.register_wand({ name = "sorcery:mese_wand", desc = "Mese Wand", full_desc = "it's yellow lol", image = "mese_wand.png", power = 2, craft_recipe = { {"sorcery:mese_core"}, {"default:mese_crystal_fragment"}, {"default:mese_crystal_fragment"} } }) sorcery.register_wand({ name = "sorcery:diamond_wand", desc = "Diamond Wand", full_desc = "The large diamond on the tip of the wand shimmers brightly as you put it up to the sun. So beautiful, yet so deadly...", image = "diamond_wand.png", power = 3, craft_recipe = { {"sorcery:diamond_core"}, {"default:obsidian_shard"}, {"default:obsidian_shard"} } })
local Animal = require("animal") local Timer = require("timer") local lume = require("vendor/lume") local Fox = {} setmetatable(Fox, {__index = Animal}) Fox.speed = 100 Fox.spacing = 30 Fox.visionDistance = 300 Fox.gestationPeriod = 60 Fox.color = {1, .5, 0} Fox.size = 15 function Fox.new(x, y, gender) local self = Animal.new(x, y, gender) setmetatable(self, {__index = Fox}) return self end function Fox:update(dt, world) if self.hunger:ready(dt) then if self.pregnant then self.fill = self.fill - 2 else self.fill = self.fill - 1 end if self.fill < 0 then lume.remove(world.creatures.foxes, self) return end end if self.pregnant and self.pregnant:ready(dt) then love.event.push("new fox", {self.x + 30, self.y}) love.event.push("new fox", {self.x - 30, self.y}) self.pregnant = nil end local food = world.creatures.rabbits if self.fill < self.full then self:lookForFood(food) else self.netTarget = {0, 0} end self:watchForSimilar(world.creatures.foxes) self:lookForMate(world.creatures.foxes) self:move(dt, world.maxX, world.maxY) if self.target and lume.distance(self.x, self.y, self.target.x, self.target.y, "squared") < 100 then self:eat(food) end if self.mate and lume.distance(self.x, self.y, self.mate.x, self.mate.y, "squared") < 961 then self:reproduce() end end return Fox
#!/opt/local/bin/lua local xml_string = [=[<?xml version="1.0" encoding="UTF-8"?> <ns1:basic_gYear xmlns:ns1="http://test_example.com">1973</ns1:basic_gYear>]=] mhf = require("schema_processor") basic_gYear = mhf:get_message_handler("basic_gYear", "http://test_example.com"); local content, msg = basic_gYear:from_xml(xml_string) if (type(content) == 'table') then require 'pl.pretty'.dump(content); else print(content, msg) end if (content) then print(basic_gYear:to_xml(content)); print(basic_gYear:to_json(content)); end if (content ~= nil) then os.exit(true); else os.exit(false); end
local function removeOsSpecificLibraryAffixes(filename) if path.islinkable(filename) then local basename = path.getbasename(filename) if os.host() == "windows" then return basename elseif string.startswith(basename, "lib") then return string.sub(basename, 4, -1) else return basename end end return filename end require("Premake/cleanAction") require("Premake/formatTidyAction") newoption({ trigger = "glfw_use_wayland", description = "Should glfw use wayland for linux build", value = "boolean", allowed = { { "N", "No" }, { "Y", "Yes" } }, default = "N" }) local openSSLLibCryptoPath = os.getenv("OPENSSL_LIB_CRYPTO_PATH") if not openSSLLibCryptoPath then error("Please find the path to openssl libcrypto and set 'OPENSSL_LIB_CRYPTO_PATH' environment variable to that!") end local openSSLLibCryptoSharedPath = os.getenv("OPENSSL_LIB_CRYPTO_SHARED_PATH") if not openSSLLibCryptoSharedPath then error("Please find the path to openssl libcrypto shared library and set 'OPENSSL_LIB_CRYPTO_SHARED_PATH' environment variable to that!") end local openSSLInclude = os.getenv("OPENSSL_INCLUDE") if not openSSLInclude then error("Please find the path to openssl include and set 'OPENSSL_INCLUDE' environment variable to that!") end local vulkanSDKPath = os.getenv("VULKAN_SDK") if not vulkanSDKPath then local hostOS = os.host() if hostOS == "windows" then error("Have you installed the Vulkan SDK correctly.\nIf you have then please go into environment variables and add 'VULKAN_SDK' with the path to the SDK!") elseif hostOS == "macosx" then error("Please find the Vulkan SDK and run the 'setup-env.sh' script in a terminal environment before running premake again!\nYou can open '~/.zshrc' or '~/.bashrc' and add:\ncd \"PathToVulkanSDK\"\nsource setup-env.sh\ncd ~/") else error("Please find the Vulkan SDK and run the 'setup-env.sh' script in a terminal environment before running premake again!\nYou can open '~/.zshrc' or '~/.bashrc' and add 'source \"PathToVulkanSDK/setup-env.sh\"'") end end workspace("PasswordManager") configurations({ "Debug", "Release", "Dist" }) platforms({ "x64" }) -- "x86", cppdialect("C++20") rtti("Off") exceptionhandling("On") flags("MultiProcessorCompile") runclangformat(false) runclangtidy(false) filter("configurations:Debug") defines({ "PM_CONFIG=PM_CONFIG_DEBUG" }) optimize("Off") symbols("On") filter("configurations:Release") defines({ "PM_CONFIG=PM_CONFIG_RELEASE" }) optimize("Full") symbols("On") filter("configurations:Dist") defines({ "PM_CONFIG=PM_CONFIG_DIST" }) optimize("Full") symbols("Off") filter("system:windows") defines({ "PM_SYSTEM=PM_SYSTEM_WINDOWS", "NOMINMAX", "WIN32_LEAN_AND_MEAN", "_CRT_SECURE_NO_WARNINGS" }) toolset("msc") filter("system:macosx") defines({ "PM_SYSTEM=PM_SYSTEM_MACOSX" }) filter("system:linux") defines({ "PM_SYSTEM=PM_SYSTEM_LINUX" }) filter("toolset:msc") defines({ "PM_TOOLSET=PM_TOOLSET_MSVC" }) filter("toolset:clang") defines({ "PM_TOOLSET=PM_TOOLSET_CLANG" }) filter("toolset:gcc") defines({ "PM_TOOLSET=PM_TOOLSET_GCC" }) filter("platforms:x86") defines({ "PM_PLATFORM=PM_PLATFORM_X86" }) filter("platforms:x64") defines({ "PM_PLATFORM=PM_PLATFORM_AMD64" }) filter({}) startproject("PasswordManager") project("GLFW") location("ThirdParty/GLFW/") kind("StaticLib") targetdir("%{wks.location}/Bin/Int-%{cfg.system}-%{cfg.platform}-%{cfg.buildcfg}/%{prj.name}/") objdir("%{wks.location}/Bin/Int-%{cfg.system}-%{cfg.platform}-%{cfg.buildcfg}/%{prj.name}/") warnings("Off") includedirs({ "%{prj.location}/include/" }) files({ "%{prj.location}/include/**", "%{prj.location}/src/context.c", "%{prj.location}/src/init.c", "%{prj.location}/src/input.c", "%{prj.location}/src/internal.h", "%{prj.location}/src/mappings.h", "%{prj.location}/src/monitor.c", "%{prj.location}/src/null_*", "%{prj.location}/src/platform.h", "%{prj.location}/src/platform.c", "%{prj.location}/src/vulkan.c", "%{prj.location}/src/window.c", "%{prj.location}/src/egl_*", "%{prj.location}/src/osmesa_*" }) filter("system:windows") files({ "%{prj.location}/src/win32_*", "%{prj.location}/src/wgl_*" }) defines({ "_GLFW_WIN32" }) filter("system:linux") files({ "%{prj.location}/src/linux_*", "%{prj.location}/src/posix_*", "%{prj.location}/src/xkb_*", "%{prj.location}/src/glx_*" }) if _OPTIONS["glfw_use_wayland"] == "Y" then files({ "%{prj.location}/src/wl_*" }) defines({ "_GLFW_WAYLAND" }) else files({ "%{prj.location}/src/x11_*" }) defines({ "_GLFW_X11" }) end filter("system:macosx") files({ "%{prj.location}/src/cocoa_*", "%{prj.location}/src/nsgl_*", "%{prj.location}/src/posix_*" }) removefiles({ "%{prj.location}/src/posix_time.h", "%{prj.location}/src/posix_time.c" }) defines({ "_GLFW_COCOA" }) filter({}) project("VMA") location("ThirdParty/VMA/") kind("StaticLib") targetdir("%{wks.location}/Bin/Int-%{cfg.system}-%{cfg.platform}-%{cfg.buildcfg}/%{prj.name}/") objdir("%{wks.location}/Bin/Int-%{cfg.system}-%{cfg.platform}-%{cfg.buildcfg}/%{prj.name}/") removedefines({ "NOMINMAX", "WIN32_LEAN_AND_MEAN" }) warnings("Off") includedirs({ "%{prj.location}/include/" }) filter("system:windows") sysincludedirs({ vulkanSDKPath .. "/Include/" }) filter("system:linux") sysincludedirs({ vulkanSDKPath .. "/include/" }) filter("system:macosx") sysincludedirs({ vulkanSDKPath .. "/include/" }) filter({}) files({ "%{prj.location}/include/**", "%{prj.location}/src/VmaUsage.h", "%{prj.location}/src/VmaUsage.cpp" }) project("PasswordManager") location("%{wks.location}/") targetdir("%{wks.location}/Bin/%{cfg.system}-%{cfg.buildcfg}-%{cfg.platform}/") objdir("%{wks.location}/Bin/Int-%{cfg.system}-%{cfg.buildcfg}-%{cfg.platform}/%{prj.name}") debugdir("%{prj.location}/Run/") filter("configurations:Debug") kind("ConsoleApp") filter("configurations:Release or Dist") kind("WindowedApp") filter({}) local openSSLLibCryptoPath = path.translate(openSSLLibCryptoPath, "/") local openSSLLibCryptoDir = path.getdirectory(openSSLLibCryptoPath) local openSSLLibCryptoSharedPath = path.translate(openSSLLibCryptoSharedPath, "/") postbuildcommands({ "{COPY} \"" .. openSSLLibCryptoSharedPath .. "\" \"Bin/%{cfg.system}-%{cfg.buildcfg}-%{cfg.platform}/\"" }) libdirs({ path.getdirectory(openSSLLibCryptoPath) }) links({ "GLFW", "VMA", removeOsSpecificLibraryAffixes(path.getname(openSSLLibCryptoPath)) }) sysincludedirs({ "%{wks.location}/ThirdParty/GLFW/include/", "%{wks.location}/ThirdParty/VMA/include/", "%{wks.location}/ThirdParty/STB/", openSSLInclude }) filter("system:windows") libdirs({ vulkanSDKPath .. "/Lib/" }) links({ "vulkan-1.lib", "glslang.lib" }) sysincludedirs({ vulkanSDKPath .. "/Include/" }) filter("system:linux") libdirs({ vulkanSDKPath .. "/lib/" }) links({ "libvulkan.so.1", "libglslang.a" }) sysincludedirs({ vulkanSDKPath .. "/include/" }) filter("system:macosx") libdirs({ vulkanSDKPath .. "/lib/" }) links({ "vulkan", "glslang", "CoreGraphics.framework", "IOKit.framework", "AppKit.framework" }) sysincludedirs({ vulkanSDKPath .. "/include/" }) filter({}) includedirs({ "%{prj.location}/Source/" }) files({ "%{prj.location}/Source/**" }) filter("files:**.h") runclangformat(true) filter("files:**.cpp or **.mm") runclangformat(true) runclangtidy(true) filter({})
--[[ PLAYER SPAWN POINT LIST revive_point(<map_id>, <x_pos>, <y_pos>); start_point(<map_id>, <x_pos>, <y_pos>); respawn_point(<map_id>, <x_pos>, <y_pos>); --]] start_point(19, 5196.1, 5182.86); respawn_point(19, 5212.27, 5184.06);
-- Path of Building -- -- Module: Tree Tab -- Passive skill tree tab for the current build. -- local ipairs = ipairs local t_insert = table.insert local m_min = math.min local TreeTabClass = newClass("TreeTab", "ControlHost", function(self, build) self.ControlHost() self.build = build self.viewer = new("PassiveTreeView") self.specList = { } self.specList[1] = new("PassiveSpec", build, build.targetVersionData.latestTreeVersion) self:SetActiveSpec(1) self.anchorControls = new("Control", nil, 0, 0, 0, 20) self.controls.specSelect = new("DropDownControl", {"LEFT",self.anchorControls,"RIGHT"}, 0, 0, 150, 20, nil, function(index, value) if self.specList[index] then self.build.modFlag = true self:SetActiveSpec(index) else self:OpenSpecManagePopup() end end) self.controls.specSelect.tooltipFunc = function(tooltip, mode, selIndex, selVal) tooltip:Clear() if mode ~= "OUT" then local spec = self.specList[selIndex] if spec then local used, ascUsed, sockets = spec:CountAllocNodes() tooltip:AddLine(16, "Class: "..spec.curClassName) tooltip:AddLine(16, "Ascendancy: "..spec.curAscendClassName) tooltip:AddLine(16, "Points used: "..used) if sockets > 0 then tooltip:AddLine(16, "Jewel sockets: "..sockets) end if selIndex ~= self.activeSpec then local calcFunc, calcBase = self.build.calcsTab:GetMiscCalculator() if calcFunc then local output = calcFunc({ spec = spec }) self.build:AddStatComparesToTooltip(tooltip, calcBase, output, "^7Switching to this tree will give you:") end if spec.curClassId == self.build.spec.curClassId then local respec = 0 for nodeId, node in pairs(self.build.spec.allocNodes) do if node.type ~= "ClassStart" and node.type ~= "AscendClassStart" and not spec.allocNodes[nodeId] then if node.ascendancyName then respec = respec + 5 else respec = respec + 1 end end end if respec > 0 then tooltip:AddLine(16, "^7Switching to this tree requires "..respec.." refund points.") end end end tooltip:AddLine(16, "Game Version: "..treeVersions[spec.treeVersion].short) end end end self.controls.reset = new("ButtonControl", {"LEFT",self.controls.specSelect,"RIGHT"}, 8, 0, 60, 20, "Reset", function() main:OpenConfirmPopup("Reset Tree", "Are you sure you want to reset your passive tree?", "Reset", function() self.build.spec:ResetNodes() self.build.spec:AddUndoState() self.build.buildFlag = true end) end) self.controls.import = new("ButtonControl", {"LEFT",self.controls.reset,"RIGHT"}, 8, 0, 90, 20, "Import Tree", function() self:OpenImportPopup() end) self.controls.export = new("ButtonControl", {"LEFT",self.controls.import,"RIGHT"}, 8, 0, 90, 20, "Export Tree", function() self:OpenExportPopup() end) self.controls.treeSearch = new("EditControl", {"LEFT",self.controls.export,"RIGHT"}, 8, 0, 300, 20, "", "Search", "%c%(%)", 100, function(buf) self.viewer.searchStr = buf end) self.controls.treeHeatMap = new("CheckBoxControl", {"LEFT",self.controls.treeSearch,"RIGHT"}, 130, 0, 20, "Show Node Power:", function(state) self.viewer.showHeatMap = state end) self.controls.treeHeatMapStatSelect = new("DropDownControl", {"LEFT",self.controls.treeHeatMap,"RIGHT"}, 8, 0, 150, 20, nil, function(index, value) self:SetPowerCalc(value) end) self.controls.treeHeatMap.tooltipText = function() local offCol, defCol = main.nodePowerTheme:match("(%a+)/(%a+)") return "When enabled, an estimate of the offensive and defensive strength of\neach unallocated passive is calculated and displayed visually.\nOffensive power shows as "..offCol:lower()..", defensive power as "..defCol:lower().."." end self.powerStatList = { } for _, stat in ipairs(data.powerStatList) do if not stat.ignoreForNodes then t_insert(self.powerStatList, stat) end end self.controls.specConvertText = new("LabelControl", {"BOTTOMLEFT",self.controls.specSelect,"TOPLEFT"}, 0, -14, 0, 16, "^7This is an older tree version, which may not be fully compatible with the current game version.") self.controls.specConvertText.shown = function() return self.showConvert end self.controls.specConvert = new("ButtonControl", {"LEFT",self.controls.specConvertText,"RIGHT"}, 8, 0, 120, 20, "^2Convert to "..treeVersions[self.build.targetVersionData.latestTreeVersion].short, function() local newSpec = new("PassiveSpec", self.build, self.build.targetVersionData.latestTreeVersion) newSpec.title = self.build.spec.title newSpec.jewels = copyTable(self.build.spec.jewels) newSpec:DecodeURL(self.build.spec:EncodeURL()) t_insert(self.specList, self.activeSpec + 1, newSpec) self:SetActiveSpec(self.activeSpec + 1) self.modFlag = true main:OpenMessagePopup("Tree Converted", "The tree has been converted to "..treeVersions[self.build.targetVersionData.latestTreeVersion].short..".\nNote that some or all of the passives may have been de-allocated due to changes in the tree.\n\nYou can switch back to the old tree using the tree selector at the bottom left.") end) end) function TreeTabClass:Draw(viewPort, inputEvents) self.anchorControls.x = viewPort.x + 4 self.anchorControls.y = viewPort.y + viewPort.height - 24 for id, event in ipairs(inputEvents) do if event.type == "KeyDown" then if event.key == "z" and IsKeyDown("CTRL") then self.build.spec:Undo() self.build.buildFlag = true inputEvents[id] = nil elseif event.key == "y" and IsKeyDown("CTRL") then self.build.spec:Redo() self.build.buildFlag = true inputEvents[id] = nil elseif event.key == "f" and IsKeyDown("CTRL") then self:SelectControl(self.controls.treeSearch) end end end self:ProcessControlsInput(inputEvents, viewPort) local treeViewPort = { x = viewPort.x, y = viewPort.y, width = viewPort.width, height = viewPort.height - (self.showConvert and 64 or 32) } self.viewer:Draw(self.build, treeViewPort, inputEvents) self.controls.specSelect.selIndex = self.activeSpec wipeTable(self.controls.specSelect.list) for id, spec in ipairs(self.specList) do t_insert(self.controls.specSelect.list, (spec.treeVersion ~= self.build.targetVersionData.latestTreeVersion and ("["..treeVersions[spec.treeVersion].short.."] ") or "")..(spec.title or "Default")) end t_insert(self.controls.specSelect.list, "Manage trees...") if not self.controls.treeSearch.hasFocus then self.controls.treeSearch:SetText(self.viewer.searchStr) end self.controls.treeHeatMap.state = self.viewer.showHeatMap self.controls.treeHeatMapStatSelect.list = self.powerStatList self.controls.treeHeatMapStatSelect.selIndex = 1 if self.build.calcsTab.powerStat then self.controls.treeHeatMapStatSelect:SelByValue(self.build.calcsTab.powerStat.stat, "stat") end SetDrawLayer(1) SetDrawColor(0.05, 0.05, 0.05) DrawImage(nil, viewPort.x, viewPort.y + viewPort.height - 28, viewPort.width, 28) SetDrawColor(0.85, 0.85, 0.85) DrawImage(nil, viewPort.x, viewPort.y + viewPort.height - 32, viewPort.width, 4) if self.showConvert then SetDrawColor(0.05, 0.05, 0.05) DrawImage(nil, viewPort.x, viewPort.y + viewPort.height - 60, viewPort.width, 28) SetDrawColor(0.85, 0.85, 0.85) DrawImage(nil, viewPort.x, viewPort.y + viewPort.height - 64, viewPort.width, 4) end self:DrawControls(viewPort) end function TreeTabClass:Load(xml, dbFileName) self.specList = { } if xml.elem == "Spec" then -- Import single spec from old build self.specList[1] = new("PassiveSpec", self.build, self.build.targetVersionData.defaultTreeVersion) self.specList[1]:Load(xml, dbFileName) self.activeSpec = 1 self.build.spec = self.specList[1] return end for _, node in pairs(xml) do if type(node) == "table" then if node.elem == "Spec" then local newSpec = new("PassiveSpec", self.build, node.attrib.treeVersion or self.build.targetVersionData.defaultTreeVersion) newSpec:Load(node, dbFileName) t_insert(self.specList, newSpec) end end end if not self.specList[1] then self.specList[1] = new("PassiveSpec", self.build, self.build.targetVersionData.latestTreeVersion) end self:SetActiveSpec(tonumber(xml.attrib.activeSpec) or 1) end function TreeTabClass:PostLoad() for _, spec in ipairs(self.specList) do spec:BuildAllDependsAndPaths() end end function TreeTabClass:Save(xml) xml.attrib = { activeSpec = tostring(self.activeSpec) } for specId, spec in ipairs(self.specList) do if specId == self.activeSpec then -- Update this spec's jewels from the socket slots for _, slot in pairs(self.build.itemsTab.slots) do if slot.nodeId then spec.jewels[slot.nodeId] = slot.selItemId end end end local child = { elem = "Spec" } spec:Save(child) t_insert(xml, child) end self.modFlag = false end function TreeTabClass:SetActiveSpec(specId) local prevSpec = self.build.spec self.activeSpec = m_min(specId, #self.specList) local curSpec = self.specList[self.activeSpec] self.build.spec = curSpec self.build.buildFlag = true for _, slot in pairs(self.build.itemsTab.slots) do if slot.nodeId then if prevSpec then -- Update the previous spec's jewel for this slot prevSpec.jewels[slot.nodeId] = slot.selItemId end if curSpec.jewels[slot.nodeId] then -- Socket the jewel for the new spec slot.selItemId = curSpec.jewels[slot.nodeId] end end end self.showConvert = curSpec.treeVersion ~= self.build.targetVersionData.latestTreeVersion if self.build.itemsTab.itemOrderList[1] then -- Update item slots if items have been loaded already self.build.itemsTab:PopulateSlots() end end function TreeTabClass:SetPowerCalc(selection) self.viewer.showHeatMap = true self.build.buildFlag = true self.build.powerBuildFlag = true self.build.calcsTab.powerStat = selection self.build.calcsTab:BuildPower() end function TreeTabClass:OpenSpecManagePopup() main:OpenPopup(370, 290, "Manage Passive Trees", { new("PassiveSpecListControl", nil, 0, 50, 350, 200, self), new("ButtonControl", nil, 0, 260, 90, 20, "Done", function() main:ClosePopup() end), }) end function TreeTabClass:OpenImportPopup() local controls = { } local function decodeTreeLink(treeLink) local errMsg = self.build.spec:DecodeURL(treeLink) if errMsg then controls.msg.label = "^1"..errMsg else self.build.spec:AddUndoState() self.build.buildFlag = true main:ClosePopup() end end controls.editLabel = new("LabelControl", nil, 0, 20, 0, 16, "Enter passive tree link:") controls.edit = new("EditControl", nil, 0, 40, 350, 18, "", nil, nil, nil, function(buf) controls.msg.label = "" end) controls.msg = new("LabelControl", nil, 0, 58, 0, 16, "") controls.import = new("ButtonControl", nil, -45, 80, 80, 20, "Import", function() local treeLink = controls.edit.buf if #treeLink == 0 then return end if treeLink:match("poeurl%.com/") then controls.import.enabled = false controls.msg.label = "Resolving PoEURL link..." local id = LaunchSubScript([[ local treeLink = ... local curl = require("lcurl.safe") local easy = curl.easy() easy:setopt_url(treeLink) easy:setopt_writefunction(function(data) return true end) easy:perform() local redirect = easy:getinfo(curl.INFO_REDIRECT_URL) easy:close() if not redirect or redirect:match("poeurl%.com/") then return nil, "Failed to resolve PoEURL link" end return redirect ]], "", "", treeLink) if id then launch:RegisterSubScript(id, function(treeLink, errMsg) if errMsg then controls.msg.label = "^1"..errMsg controls.import.enabled = true else decodeTreeLink(treeLink) end end) end else decodeTreeLink(treeLink) end end) controls.cancel = new("ButtonControl", nil, 45, 80, 80, 20, "Cancel", function() main:ClosePopup() end) main:OpenPopup(380, 110, "Import Tree", controls, "import", "edit") end function TreeTabClass:OpenExportPopup() local treeLink = self.build.spec:EncodeURL(treeVersions[self.build.spec.treeVersion].export) local popup local controls = { } controls.label = new("LabelControl", nil, 0, 20, 0, 16, "Passive tree link:") controls.edit = new("EditControl", nil, 0, 40, 350, 18, treeLink, nil, "%Z") controls.shrink = new("ButtonControl", nil, -90, 70, 140, 20, "Shrink with PoEURL", function() controls.shrink.enabled = false controls.shrink.label = "Shrinking..." launch:DownloadPage("http://poeurl.com/shrink.php?url="..treeLink, function(page, errMsg) controls.shrink.label = "Done" if errMsg or not page:match("%S") then main:OpenMessagePopup("PoEURL Shortener", "Failed to get PoEURL link. Try again later.") else treeLink = "http://poeurl.com/"..page controls.edit:SetText(treeLink) popup:SelectControl(controls.edit) end end) end) controls.copy = new("ButtonControl", nil, 30, 70, 80, 20, "Copy", function() Copy(treeLink) end) controls.done = new("ButtonControl", nil, 120, 70, 80, 20, "Done", function() main:ClosePopup() end) popup = main:OpenPopup(380, 100, "Export Tree", controls, "done", "edit") end
local addOnName, ns = ...; local RPTAGS = RPTAGS; local Module = RPTAGS.queue:GetModule(addOnName); Module:WaitUntil("before MODULE_G", function(self, event, ...) local Utils = RPTAGS.utils; local Config = Utils.config; local Locale = Utils.locale; local loc = Locale.loc; local Get = Config.get; local Set = Config.set; local source_order = Utils.options.source_order; local Spacer = Utils.options.spacer; local linkHandler = Utils.links.handler; local addOptions = Utils.modules.addOptions; local addOptionsPanel = Utils.modules.addOptionsPanel; local LibSharedMedia = LibStub("LibSharedMedia-3.0"); local scaleFrame = Utils.frames.scale; local scaleAllFrames = Utils.frames.scaleAll; local Refresh = Utils.frames.RPUF_Refresh; local RPUF_Disable = Utils.frames.RPUF_Disable; local popup1 = "RP_UNITFRAMES_CONFIRM_RELOAD_UI"; local popup2 = "RP_UNITFRAMES_CONFIRM_RELOAD_UI_ENABLE"; local menu = { align = { LEFT = loc("LEFT" ), CENTER = loc("CENTER" ), RIGHT = loc("RIGHT" ), }, small = { COMPACT = loc("RPUF_COMPACT" ), ABRIDGED = loc("RPUF_ABRIDGED" ), THUMBNAIL = loc("RPUF_THUMBNAIL" ), }, large = { COMPACT = loc("RPUF_COMPACT" ), ABRIDGED = loc("RPUF_ABRIDGED" ), THUMBNAIL = loc("RPUF_THUMBNAIL" ), PAPERDOLL = loc("RPUF_PAPERDOLL" ), FULL = loc("RPUF_FULL" ), }, fontSize = { extrasmall = loc("SIZE_EXTRA_SMALL" ), small = loc("SIZE_SMALL" ), medium = loc("SIZE_MEDIUM" ), large = loc("SIZE_LARGE" ), extralarge = loc("SIZE_EXTRA_LARGE" ), }, }; local frameList = -- uppercase name, isSmallFrame { { "PLAYER", false }, { "TARGET", false }, { "FOCUS", true }, { "TARGETTARGET", true }, }; -- specialized loc() local function cloc(s) return loc( "CONFIG_" .. ( s or "" ) ) end; local function tloc(s) return loc( "CONFIG_" .. ( s or "" ) .. "_TT" ) end; local function oloc(s) return loc( "OPT_" .. ( s or "" ) ) end; local function iloc(s) return loc( "OPT_" .. ( s or "" ) .. "_I" ) end; local function ploc(s) return loc( "PANEL_" .. ( s or "" ) ) end; -- constructor functions [---------------------------------------------] local function get(setting) return function() return Get(setting) end; end; -- builds a Getter function local function set(setting) return function(info, value) Set(setting, value); end; end; -- builds a Setter function local mainGroup = { name = loc("RPUF_NAME"), order = source_order(), type = "group", args = {}, }; mainGroup.args.instruct = { type = "description", dialogControl = "LMD30_Description", name = loc("PANEL_RPUF_MAIN"), order = source_order(), }; mainGroup.args.disableUF = { type = "toggle", order = source_order(), name = loc("CONFIG_DISABLE_RPUF"), desc = loc("CONFIG_DISABLE_RPUF_TT"), get = get("DISABLE_RPUF"), set = function(info, value) if Get("DISABLE_BLIZZARD") and value == true then StaticPopup_Show(popup2) else Set("DISABLE_RPUF", value); Refresh("all", "hiding"); end; end, width = 1.5, }; mainGroup.args.disableBliz = { type = "toggle", order = source_order(), name = cloc("DISABLE_BLIZZARD"), desc = tloc("DISABLE_BLIZZARD"), get = get("DISABLE_BLIZZARD"), set = function(info, value) StaticPopup_Show(popup1); end, disabled = get("DISABLE_RPUF"), width = 1.5, }; addOptionsPanel("RPUF_Main", mainGroup); StaticPopupDialogs[popup1] = { showAlert = 1, text = loc("RELOAD_UI_WARNING"), button1 = loc("RELOAD_UI_WARNING_YES"), button2 = loc("RELOAD_UI_WARNING_NO"), exclusive = true, OnAccept = function() Config.set("DISABLE_BLIZZARD", not(Config.get("DISABLE_BLIZZARD"))); ReloadUI() end, timeout = 60, whileDead = true, hideOnEscape = true, hideOnCancel = true, preferredIndex = 3, }; StaticPopupDialogs[popup2] = { showAlert = 1, text = loc("RELOAD_UI_WARNING_RPUF"), button1 = loc("RELOAD_UI_WARNING_YES"), button2 = loc("RELOAD_UI_WARNING_NO"), exclusive = true, OnAccept = function() Config.set("DISABLE_BLIZZARD", false); Config.set("DISABLE_RPUF", true); ReloadUI() end, timeout = 60, whileDead = true, hideOnEscape = true, hideOnCancel = true, preferredIndex = 3, }; end);
--waf.lua
if ( SERVER ) then AddCSLuaFile( "shared.lua" ) end SWEP.BulletLength = 9 SWEP.CaseLength = 19 SWEP.MuzVel = 255.905 SWEP.Attachments = { [1] = {"reflex"}} SWEP.InternalParts = { [1] = {{key = "ergonomichandle"}}} if ( CLIENT ) then SWEP.PrintName = "Glock 18" SWEP.Author = "Counter-Strike" SWEP.Slot = 1 SWEP.SlotPos = 0 // = 1 SWEP.IconLetter = "c" SWEP.ReloadAngleMod = -1 SWEP.Muzzle = "cstm_muzzle_pistol" SWEP.SparkEffect = "cstm_child_sparks_small" SWEP.SmokeEffect = "cstm_child_smoke_small" killicon.AddFont( "cstm_pistol_glock18", "CSKillIcons", SWEP.IconLetter, Color( 255, 80, 0, 255 ) ) SWEP.VElements = { ["silencer"] = { type = "Model", model = "models/props_c17/oildrum001.mdl", bone = "v_weapon.Glock_Parent", pos = Vector(-2.845, 3.2, -0.557), angle = Angle(92.43, 14.538, 1.187), size = Vector(0.043, 0.043, 0.136), color = Color(255, 255, 255, 0), surpresslightning = false, material = "models/bunneh/silencer", skin = 0, bodygroup = {} }, ["reflex"] = { type = "Model", model = "models/wystan/attachments/2octorrds.mdl", bone = "v_weapon.Glock_Slide", pos = Vector(0.887, 0.125, 0.312), angle = Angle(-77.087, -89.825, 0), size = Vector(1, 1, 1), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } SWEP.WElements = { ["silencer"] = { type = "Model", model = "models/props_c17/oildrum001.mdl", pos = Vector(10.404, 1.976, -3.8), angle = Angle(-91.904, 0, 5.664), size = Vector(0.043, 0.043, 0.136), color = Color(255, 255, 255, 0), surpresslightning = false, material = "models/bunneh/silencer", skin = 0, bodygroup = {} }, ["reflex"] = { type = "Model", model = "models/wystan/attachments/2octorrds.mdl", pos = Vector(2.273, 1.1, -2.3), angle = Angle(180, 85, 0), size = Vector(1.299, 1.299, 1.299), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } SWEP.SafeXMoveMod = 2 end SWEP.Category = "Customizable Weaponry" SWEP.HoldType = "ar2" SWEP.Base = "cstm_base_pistol" SWEP.FireModes = {"auto", "3burst", "semi"} SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.HoldType = "pistol" SWEP.ViewModelFOV = 70 SWEP.ViewModelFlip = true SWEP.ViewModel = "models/weapons/v_pist_glock18.mdl" SWEP.WorldModel = "models/weapons/w_pist_glock18.mdl" SWEP.ShowViewModel = true SWEP.ShowWorldModel = true SWEP.ViewModelBonescales = {} SWEP.Weight = 5 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false SWEP.Primary.Sound = Sound("Weapon_Glock.Single") SWEP.Primary.Recoil = 0.3 SWEP.Primary.Damage = 15 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.02 SWEP.Primary.ClipSize = 19 SWEP.Primary.Delay = 0.0545 SWEP.Primary.DefaultClip = 19 SWEP.Primary.Automatic = true SWEP.Primary.Ammo = "9x19MM" SWEP.InitialHoldtype = "pistol" SWEP.InHoldtype = "pistol" SWEP.NoBoltAnim = true SWEP.DryFireAnim = true SWEP.SprintAndShoot = true -- Animation speed/custom reload function related SWEP.IsReloading = false SWEP.AnimPrefix = "glock_" SWEP.ReloadSpeed = 1 SWEP.ShouldBolt = false SWEP.ReloadDelay = 0 SWEP.IncAmmoPerc = 0.72 -- Amount of frames required to pass (in percentage) of the reload animation for the weapon to have it's amount of ammo increased SWEP.FOVZoom = 85 -- Dynamic accuracy related SWEP.ShotsAmount = 0 SWEP.ConeDecAff = 0 SWEP.DefRecoil = 0.5 SWEP.CurCone = 0.04 SWEP.DecreaseRecoilTime = 0 SWEP.ConeAff1 = 0 -- Crouching/standing SWEP.ConeAff2 = 0 -- Using ironsights SWEP.UnConeTime = 0 -- Amount of time after firing the last shot that needs to pass until accuracy increases SWEP.FinalCone = 0 -- Self explanatory SWEP.VelocitySensivity = 1 -- Percentage of how much the cone increases depending on the player's velocity (moving speed). Rifles - 100%; SMGs - 80%; Pistols - 60%; Shotguns - 20% SWEP.HeadbobMul = 1 SWEP.IsSilenced = false SWEP.IronsightsCone = 0.017 SWEP.HipCone = 0.045 SWEP.ConeInaccuracyAff1 = 0.5 SWEP.PlayFireAnim = true SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.IsUsingIronsights = false SWEP.TargetMul = 0 SWEP.SetAndForget = false SWEP.IronSightsPos = Vector(6.0749, -5.5216, 2.3984) SWEP.IronSightsAng = Vector(2.5174, -0.0099, 0) SWEP.AimPos = Vector(4.335, -2.951, 2.875) SWEP.AimAng = Vector(0.444, 0.019, 0) SWEP.ChargePos = Vector (5.4056, -10.3522, -4.0017) SWEP.ChargeAng = Vector (-1.7505, -55.5187, 68.8356) SWEP.ReflexPos = Vector(4.335, -3.056, 2.553) SWEP.ReflexAng = Vector(0, 0, 0) SWEP.MeleePos = Vector(4.487, -1.497, -5.277) SWEP.MeleeAng = Vector(25.629, -30.039, 26.18) SWEP.SafePos = Vector(-0.392, -10.157, -6.064) SWEP.SafeAng = Vector(70, 0, 0)
-- Copyright (c) 2020 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT describe("game.ui.moon_display", function() require "game.ui" local moon = require "game.entities.moon" it("displays the text of the current state", function() local m = moon:new() m:set_last_quarter() local moon_dis = moonpie.ui.components.moon_display{ moon = m } assert.equals("Last Quarter", moon_dis.text) end) end)
local net = require 'net' local sh = require 'shell' local argv = {...} local dst = table.remove(argv, 1) local path = net.path("home", dst) table.remove(path,1) sh.execute("connect " .. table.concat(path, "; connect ") .. '; '..table.concat(argv, "; "))
require "lib" require("prototypes.item")
return { name={ [1] = "UnexposedDecl"; [2] = "StructDecl"; [3] = "UnionDecl"; [4] = "ClassDecl"; [5] = "EnumDecl"; [6] = "FieldDecl"; [7] = "EnumConstantDecl"; [8] = "FunctionDecl"; [9] = "VarDecl"; [10] = "ParmDecl"; [11] = "ObjCInterfaceDecl"; [12] = "ObjCCategoryDecl"; [13] = "ObjCProtocolDecl"; [14] = "ObjCPropertyDecl"; [15] = "ObjCIvarDecl"; [16] = "ObjCInstanceMethodDecl"; [17] = "ObjCClassMethodDecl"; [18] = "ObjCImplementationDecl"; [19] = "ObjCCategoryImplDecl"; [20] = "TypedefDecl"; [21] = "CXXMethod"; [22] = "Namespace"; [23] = "LinkageSpec"; [24] = "Constructor"; [25] = "Destructor"; [26] = "ConversionFunction"; [27] = "TemplateTypeParameter"; [28] = "NonTypeTemplateParameter"; [29] = "TemplateTemplateParameter"; [30] = "FunctionTemplate"; [31] = "ClassTemplate"; [32] = "ClassTemplatePartialSpecialization"; [33] = "NamespaceAlias"; [34] = "UsingDirective"; [35] = "UsingDeclaration"; [36] = "TypeAliasDecl"; [37] = "ObjCSynthesizeDecl"; [38] = "ObjCDynamicDecl"; [39] = "CXXAccessSpecifier"; [40] = "ObjCSuperClassRef"; [41] = "ObjCProtocolRef"; [42] = "ObjCClassRef"; [43] = "TypeRef"; [44] = "CXXBaseSpecifier"; [45] = "TemplateRef"; [46] = "NamespaceRef"; [47] = "MemberRef"; [48] = "LabelRef"; [49] = "OverloadedDeclRef"; [50] = "VariableRef"; [70] = "InvalidFile"; [71] = "NoDeclFound"; [72] = "NotImplemented"; [73] = "InvalidCode"; [100] = "UnexposedExpr"; [101] = "DeclRefExpr"; [102] = "MemberRefExpr"; [103] = "CallExpr"; [104] = "ObjCMessageExpr"; [105] = "BlockExpr"; [106] = "IntegerLiteral"; [107] = "FloatingLiteral"; [108] = "ImaginaryLiteral"; [109] = "StringLiteral"; [110] = "CharacterLiteral"; [111] = "ParenExpr"; [112] = "UnaryOperator"; [113] = "ArraySubscriptExpr"; [114] = "BinaryOperator"; [115] = "CompoundAssignOperator"; [116] = "ConditionalOperator"; [117] = "CStyleCastExpr"; [118] = "CompoundLiteralExpr"; [119] = "InitListExpr"; [120] = "AddrLabelExpr"; [121] = "StmtExpr"; [122] = "GenericSelectionExpr"; [123] = "GNUNullExpr"; [124] = "CXXStaticCastExpr"; [125] = "CXXDynamicCastExpr"; [126] = "CXXReinterpretCastExpr"; [127] = "CXXConstCastExpr"; [128] = "CXXFunctionalCastExpr"; [129] = "CXXTypeidExpr"; [130] = "CXXBoolLiteralExpr"; [131] = "CXXNullPtrLiteralExpr"; [132] = "CXXThisExpr"; [133] = "CXXThrowExpr"; [134] = "CXXNewExpr"; [135] = "CXXDeleteExpr"; [136] = "UnaryExpr"; [137] = "ObjCStringLiteral"; [138] = "ObjCEncodeExpr"; [139] = "ObjCSelectorExpr"; [140] = "ObjCProtocolExpr"; [141] = "ObjCBridgedCastExpr"; [142] = "PackExpansionExpr"; [143] = "SizeOfPackExpr"; [144] = "LambdaExpr"; [145] = "ObjCBoolLiteralExpr"; [146] = "ObjCSelfExpr"; [200] = "UnexposedStmt"; [201] = "LabelStmt"; [202] = "CompoundStmt"; [203] = "CaseStmt"; [204] = "DefaultStmt"; [205] = "IfStmt"; [206] = "SwitchStmt"; [207] = "WhileStmt"; [208] = "DoStmt"; [209] = "ForStmt"; [210] = "GotoStmt"; [211] = "IndirectGotoStmt"; [212] = "ContinueStmt"; [213] = "BreakStmt"; [214] = "ReturnStmt"; [215] = "AsmStmt"; [216] = "ObjCAtTryStmt"; [217] = "ObjCAtCatchStmt"; [218] = "ObjCAtFinallyStmt"; [219] = "ObjCAtThrowStmt"; [220] = "ObjCAtSynchronizedStmt"; [221] = "ObjCAutoreleasePoolStmt"; [222] = "ObjCForCollectionStmt"; [223] = "CXXCatchStmt"; [224] = "CXXTryStmt"; [225] = "CXXForRangeStmt"; [226] = "SEHTryStmt"; [227] = "SEHExceptStmt"; [228] = "SEHFinallyStmt"; [229] = "MSAsmStmt"; [230] = "NullStmt"; [231] = "DeclStmt"; [232] = "OMPParallelDirective"; [233] = "OMPSimdDirective"; [234] = "OMPForDirective"; [235] = "OMPSectionsDirective"; [236] = "OMPSectionDirective"; [237] = "OMPSingleDirective"; [238] = "OMPParallelForDirective"; [239] = "OMPParallelSectionsDirective"; [240] = "OMPTaskDirective"; [241] = "OMPMasterDirective"; [242] = "OMPCriticalDirective"; [243] = "OMPTaskyieldDirective"; [244] = "OMPBarrierDirective"; [245] = "OMPTaskwaitDirective"; [246] = "OMPFlushDirective"; [247] = "SEHLeaveStmt"; [248] = "OMPOrderedDirective"; [249] = "OMPAtomicDirective"; [250] = "OMPForSimdDirective"; [251] = "OMPParallelForSimdDirective"; [252] = "OMPTargetDirective"; [253] = "OMPTeamsDirective"; [300] = "TranslationUnit"; [400] = "UnexposedAttr"; [401] = "IBActionAttr"; [402] = "IBOutletAttr"; [403] = "IBOutletCollectionAttr"; [404] = "CXXFinalAttr"; [405] = "CXXOverrideAttr"; [406] = "AnnotateAttr"; [407] = "AsmLabelAttr"; [408] = "PackedAttr"; [409] = "PureAttr"; [410] = "ConstAttr"; [411] = "NoDuplicateAttr"; [412] = "CUDAConstantAttr"; [413] = "CUDADeviceAttr"; [414] = "CUDAGlobalAttr"; [415] = "CUDAHostAttr"; [416] = "CUDASharedAttr"; [500] = "PreprocessingDirective"; [501] = "MacroDefinition"; [502] = "MacroExpansion"; [503] = "InclusionDirective"; [600] = "ModuleImportDecl"; [700] = "OverloadCandidate"; }, }
return { level = 87, need_exp = 260000, clothes_attrs = { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, }, }
-- Code for basic item handling -- cItem: Objects which can be picked up and carried -- TODO cItem = {__metatable=cItem, __index=cItem} cItem.size = 1 -- Nominally, number of coke cans (volume) cItem.weight = 0 -- Nominally, in kg -- TODO cItem.CanTouch, CanPickup, CanDrop -- cWieldable: Objects which can be used in combat -- TODO cWieldable = {__metatable=cWieldable, __index=cWieldable} cWieldable.attackpoints = {} -- String-indexed list of attack types ("hilt", "edge", "point", etc.) -- Values are attack tables (see core_combat.lua) -- TODO -- Returns an attack table. -- TODO function cWieldable:getAttack(attackpoint, target, attackdetails) -- TODO end -- cWearable -- TODO cWearable = {__metatable=cWearable, __index=cWearable} cWearable.isWorn = false cWearable.slot = "UNDEFINED" -- Described where/how the item is worn -- Test if the current holder (self.owner.location) can wear this. -- Announces the reason for failure unless silent=true function cWearable:CanWear(silent) -- TODO end -- Test if the current wearer (self.owner.location) can remove it. -- Announces the reason for failure unless silent=true function cWearable:CanRemove(silent) -- TODO end function cWearable:Wear(silent) -- TODO end function cWearable:Remove(silent) -- TODO end -- cThrowable -- TODO cThrowable = {__metatable=cThrowable, __index=cThrowable} function cThrowable:Throw(actor, target) -- TODO end -- cContainerObject: Objects which can contain other objects -- TODO cContainerObject = {__metatable=cContainerObject, __index=cContainerObject} cContainerObject.contents = {} -- Keys = object IDs, value = true OR nil -- Can item be placed by actor into the container? -- Announces reason for failure unless silent=true function cContainerObject:CanPlaceInto(item, actor, silent) -- TODO end -- Can item be removed from the container by the actor? -- Announces reason for failure unless silent=true function cContainerObject:CanGetFrom(item, actor, silent) -- TODO end -- Actually moves the item from its previous container/room into this one -- Announces movement unless silent=true function cContainerObject:MoveInto(item, actor, silent) -- TODO end -- cDamageable: Objects which can be damaged or broken -- TODO
#!/usr/bin/env luajit -- (c) 2014 Team THORwIn local ok = pcall(dofile,'../fiddle.lua') if not ok then dofile'fiddle.lua' end local util = require'util' local xbox360 = require 'xbox360' local rospub = require 'rospub' local signal = require'signal'.signal local gettime = require'unix'.time require'hcm' rospub.init('lua_publisher') local t_last = gettime() local t_last_debug = gettime() local t_debug_interval = 1 local tDelay = 0.005*1E6 local running = true --precalculate local int_sz = ffi.sizeof("int") local float_sz = ffi.sizeof("float") local double_sz = ffi.sizeof("double") -- Cleanly exit on Ctrl-C local function shutdown() io.write('\n Soft shutdown!\n') running=false end signal("SIGINT", shutdown) signal("SIGTERM", shutdown) local seq=0 local function update(ret) local seq=hcm.get_xb360_seq() local t=hcm.get_xb360_t() local trigger=hcm.get_xb360_trigger() local lst=hcm.get_xb360_lstick() local rst=hcm.get_xb360_rstick() local dpad=hcm.get_xb360_dpad() local buttons=hcm.get_xb360_buttons() print(lst,rst,dpad,buttons) rospub.xb360(seq, trigger[1],trigger[2], lst[1],lst[2],rst[1],rst[2], dpad[1],dpad[2], buttons[1],buttons[2],buttons[3], buttons[4],buttons[5],buttons[6], buttons[7],buttons[8],buttons[9] ) end while running do -- local gccount = gcm.get_processes_xb360() -- gcm.set_processes_xb360({2,gccount[2]+1,gccount[3]}) update() unix.usleep(1e6*0.1) --20fps end -- if gcm.get_game_selfdestruct()==1 then -- -- os.execute("mpg321 ~/Desktop/NaverRobotics/media/selfdestruct.mp3") -- -- os.execute('sync') -- -- os.execute('systemctl poweroff -i') -- end
--[[ TheNexusAvenger Implementation of a command. --]] local BaseCommand = require(script.Parent.Parent:WaitForChild("BaseCommand")) local Command = BaseCommand:Extend() --[[ Creates the command. --]] function Command:__new() self:InitializeSuper("renameteam","BasicCommands","Renames a given team.") self.Arguments = { { Type = "team", Name = "Team", Description = "Team to rename.", }, { Type = "string", Name = "Name", Description = "Name to use.", }, } end --[[ Runs the command. --]] function Command:Run(CommandContext,Team,Name) self.super:Run(CommandContext) --Rename the team. local FilteredName = self.API.Filter:FilterString(Name,CommandContext.Executor) Team.Name = FilteredName end return Command
for _, objectReference in pairs(script:GetCustomProperties()) do objectReference:WaitForObject():LookAtLocalView(false) end
--- === plugins.core.console === --- --- Search Console local require = require local application = require "hs.application" local config = require "cp.config" local tools = require "cp.tools" local unpack = table.unpack local mod = {} -- plugins.core.console._appConsoles -> table -- Variable -- Table of application specific Search Consoles. mod._appConsoles = {} --- plugins.core.console.register(bundleID, activator) -> none --- Function --- Registers an application specific Search Console. --- --- Parameters: --- * bundleID - The bundle ID of the application --- * activatorFn - A function that returns an activator. --- --- Returns: --- * None function mod.register(bundleID, activator) mod._appConsoles[bundleID] = activator end --- plugins.core.console.show() -> none --- Function --- Shows the Search Console. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.show() -------------------------------------------------------------------------------- -- Check to see if there's any application specific activators: -------------------------------------------------------------------------------- local frontmostApplication = application.frontmostApplication() local bundleID = frontmostApplication and frontmostApplication:bundleID() if bundleID and mod._appConsoles[bundleID] then local activator = mod._appConsoles[bundleID]() if activator then activator:toggle() return end end -------------------------------------------------------------------------------- -- If not, use the global one: -------------------------------------------------------------------------------- if not mod.activator then mod.activator = mod.actionmanager.getActivator("core.console"):preloadChoices() -------------------------------------------------------------------------------- -- Restrict Allowed Handlers for Activator to current group: -------------------------------------------------------------------------------- local allowedHandlers = {} local handlerIds = mod.actionmanager.handlerIds() for _,id in pairs(handlerIds) do local handlerTable = tools.split(id, "_") if handlerTable[2]~= "widgets" and handlerTable[1] == "global" then table.insert(allowedHandlers, id) end end mod.activator:allowHandlers(unpack(allowedHandlers)) -------------------------------------------------------------------------------- -- Allow specific toolbar icons in the Console: -------------------------------------------------------------------------------- local iconPath = config.basePath .. "/plugins/core/console/images/" local toolbarIcons = { global_applications = { path = iconPath .. "apps.png", priority = 1}, global_menuactions = { path = iconPath .. "menu.png", priority = 2}, } mod.activator:toolbarIcons(toolbarIcons) end mod.activator:toggle() end local plugin = { id = "core.console", group = "core", dependencies = { ["core.commands.global"] = "global", ["core.action.manager"] = "actionmanager", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Add the command trigger: -------------------------------------------------------------------------------- mod.actionmanager = deps.actionmanager deps.global:add("cpGlobalConsole") :groupedBy("commandPost") :whenActivated(function() mod.show() end) :activatedBy():ctrl():option():cmd("space") return mod end return plugin
local canEnd = false function onEndSong() -- Block the first countdown and start a timer of 0.8 seconds to play the dialogue if isStoryMode and not canEnd then setProperty('inCutscene', true); triggerEvent('startDia') canEnd = true runTimer('endDialogue',2) return Function_Stop; else return Function_Continue; end end function onTimerCompleted(tag, loops, loopsLeft) if tag == 'endDialogue' then -- Timer completed, play dialogue startDialogue('dialogueEnd', ''); end end -- Dialogue (When a dialogue is finished, it calls startCountdown again) function onNextDialogue(count) -- triggered when the next dialogue line starts, 'line' starts with 1 end function onSkipDialogue(count) -- triggered when you press Enter and skip a dialogue line that was still being typed, dialogue line starts with 1 end