content
stringlengths
5
1.05M
-- -- Generate documentation for this project into 'html' folder -- local lut = require 'lut' lut.Doc.make { sources = { 'yaml', }, target = 'html', format = 'html', header = [[<h1><a href='http://lubyk.org'>Lubyk</a> documentation</h1> ]], index = [=[ --[[-- # Lubyk documentation ## List of available modules --]]-- ]=] }
cs_spkeys = {'shift'} mem_read_ubyte = memory.readbyte mem_read_uword = memory.readword mem_read_ulong = memory.readlong mem_write_ubyte = memory.writebyte mem_write_uword = memory.writeword mem_write_ulong = memory.writelong cli_screenwidth = 320 cli_screenheight = 224 -- Gens needs not worry about this gam_xnat = 320 -- Natural x-resolution, defaulted to Genesis gam_ynat = 224 -- Natural y-resolution, defaulted to Genesis gam_up = 0 gam_down = 224 gam_xport = 320 gam_yport = 224 gam_left = 0 gam_right = 324 gam_xscale = 1 gam_yscale = 1 fnt_width = 4 fnt_height = 7 sav_load = savestate.load sav_create = savestate.create sav_save = savestate.save gui_register = function(instructions) gui.register(instructions) end gui_registerafter = function(instructions) gens.registerafter(instructions) end margin = 20 x_left = margin x_right = cli_screenwidth - margin - fnt_width*34 y_1 = 10 y_2 = y_1 + fnt_height*5 y_sh = 66 --Sonic HUD offset y_limit = cli_screenheight - fnt_height*2
local helper = require("piemenu.lib.testlib.helper") describe("piemenu.core.angle_distance", function() before_each(helper.before_each) after_each(helper.after_each) for _, c in ipairs({ { angle = 0, next_angle = 0, expected = 360 }, { angle = 0, next_angle = 360, expected = 360 }, { angle = 30, next_angle = 50, expected = 20 }, { angle = 90, next_angle = -90, expected = 180 }, }) do it(("AngleDistance.new(%s, %s) == %s"):format(c.angle, c.next_angle, c.expected), function() local actual = require("piemenu.core.angle_distance").AngleDistance.new(c.angle, c.next_angle) assert.equals(c.expected, actual) end) end end)
constants = require "constants" utils = require "utils" view = {} color = {} color.snake = utils.makeColor('#49AB81', 73,171,129) color.terrain = utils.makeColor('#A7784E', 167, 120, 78) color.fruit = utils.makeColor('#DF4815', 223, 72, 21) view.color = color love.window.setTitle("Snake Game") function drawMap(world) if constants.game.debugMode == true then fillMap = 'line' love.graphics.setColor(250,10,150,0.5)--(view.color.terrain.rgb) space = 0 for i = 1,world.boundries do for j = 1,world.boundries do --love.graphics.setColor(150,150,150,0.5)--(view.color.terrain.rgb) utils.drawRectangle(i,j,fillMap) end end end end function drawSnake(world) love.graphics.setColor(view.color.snake.rgb) utils.drawRectangle(world.snake.head.x , world.snake.head.y) tail = world.snake.tail -- print("Snake") for i=1,#tail.segment do --io.write("\t[".. i .."]: ") --utils.drawRectangle(tail.segment[i].x , tail.segment[i].y) utils.drawSnake(tail.segment[i].x , tail.segment[i].y, i) if constants.game.debugMode == true then utils.printUnderSnake(tail.segment[i]) end end end function drawFruits(world) love.graphics.setColor(view.color.fruit.rgb) if constants.game.debugMode == true then for i=1,#world.fruits do utils.drawFruits(world.fruits[i].x, world.fruits[i].y, 1.5) end else local newest = world.fruits.getNewest() utils.drawFruits(newest.x, newest.y, 0.8) end end function drawBorder() love.graphics.setColor(255,255,255) utils.border() end function drawScore(game) w = utils.adjust(constants.map.size - 1) + constants.view.scale/2 h = utils.adjust(constants.map.size - 1) + constants.view.scale/2 love.graphics.print("Score: " .. game.score, w/2 - 100, h + 35) end function resize(width, height) love.window.setMode(width, height) end view.setColor = setColor view.drawMap = drawMap view.drawSnake = drawSnake view.drawFruits = drawFruits view.drawBorder = drawBorder view.resize = resize view.drawScore = drawScore return (view)
module(..., lunit.testcase, package.seeall) local common = dofile("common.lua") local http = require("luanode.http") function test() nresponses = 0 local server = http.createServer(function(self, req, res) if req.url == '/one' then res:writeHead(200, { {'set-cookie', 'A'}, {'content-type', 'text/plain'} }); res:finish("one\n") else res:writeHead(200, { {'set-cookie', 'A'}, {'set-cookie', 'B'}, {'content-type', 'text/plain'} }); res:finish("two\n") end end) server:listen(common.PORT) server:addListener("listening", function() -- -- one set-cookie header -- local client = http.createClient(common.PORT) local req = client:request('GET', '/one') req:finish() req:addListener('response', function(self, res) -- set-cookie headers are always return in an array. -- even if there is only one. assert_equal("A", res.headers['set-cookie'][1]) assert_equal('text/plain', res.headers['content-type']) res:addListener('data', function(self, chunk) console.log(chunk) end) res:addListener('end', function() nresponses = nresponses + 1 if nresponses == 2 then server:close() end end) end) -- two set-cookie headers local client = http.createClient(common.PORT) local req = client:request('GET', '/two') req:finish() req:addListener('response', function(slef, res) for k,v in ipairs({'A', 'B'}) do assert_equal(v, res.headers['set-cookie'][k]) end assert_equal('text/plain', res.headers['content-type']) res:addListener('data', function(self, chunk) console.log(chunk) end) res:addListener('end', function() nresponses = nresponses + 1 if nresponses == 2 then server:close() end end) end) end) process:addListener("exit", function () assert_equal(2, nresponses) end) process:loop() end
--[[ "name": "packing-tape", "title": "Packing Tape", "author": "calcwizard", "description": "Mining a chest or wagon allows players to pick it up with all the items inside and carry it in their inventory. Now supports cars!" --]] local Event = require('__stdlib__/stdlib/event/event') local Inventory = require('__stdlib__/stdlib/entity/inventory') if script.active_mods['packing-tape'] then return end local setting = settings.get_startup('picker-moveable-chests') local chest_types = { ['container'] = defines.inventory.chest, ['logistic-container'] = defines.inventory.chest, ['cargo-wagon'] = defines.inventory.cargo_wagon } local function inventory_to_container(event) local stack = event.stack local chest = event.created_entity if chest_types[chest.type] and stack and stack.valid_for_read and stack.name:find('^picker%-moveable%-') then local source = event.stack.get_inventory(defines.inventory.item_main) local destination = chest.get_inventory(chest_types[chest.type]) Inventory.transfer_inventory(source, destination) local data = global.inventory_chest[stack.item_number] if data then if data.bar then destination.set_bar(data.bar) end local proto = chest.prototype if proto.logistic_mode == 'storage' then chest.storage_filter = data.storage_filter elseif proto.logistic_mode == 'requester' or proto.logistic_mode == 'buffer' then for slot, filter in pairs(data.request_slots or {}) do chest.set_request_slot(filter, slot) end chest.request_from_buffers = data.request_from_buffers end end global.inventory_chest[stack.item_number] = nil end end -- Move the contents from the chest into an item in our inventory local function container_to_inventory(event) local chest = event.entity local item_name = 'picker-moveable-' .. chest.name if chest_types[chest.type] and game.item_prototypes[item_name] then if chest.has_items_inside() then local player = game.get_player(event.player_index) local p_inv = player.get_main_inventory() -- Is there an empty inventory spot? if p_inv.can_insert(item_name) then -- Create an item-with-inventory in an available slot local stack -- 0.18.8 find_empty_stack(item_name) for i = 1, #p_inv do if not p_inv[i].valid_for_read and p_inv[i].can_set_stack(item_name) then stack = p_inv[i] break end end -- Should have stack since we can insert but check anyway. if stack and stack.set_stack(item_name) then stack.health = chest.get_health_ratio() local proto = chest.prototype local source = chest.get_inventory(defines.inventory.chest) local dest = stack.get_inventory(defines.inventory.item_main) Inventory.transfer_inventory(source, dest) global.inventory_chest = global.inventory_chest or {} global.inventory_chest[stack.item_number] = {} local data = global.inventory_chest[stack.item_number] data.bar = source.supports_bar() and source.get_bar() data.storage_filter = proto.logistic_mode == 'storage' and chest.storage_filter local requester = proto.logistic_mode == 'requester' or proto.logistic_mode == 'buffer' if requester then data.request_slots = {} for i = 1, chest.request_slot_count do data.request_slots[i] = chest.get_request_slot(i) end data.request_from_buffers = chest.request_from_buffers end -- on_player_mined_item Event.raise_event( defines.events.on_player_mined_item, { item_stack = {name = item_name, count = 1}, player_index = player.index } ) -- on_player_mined_entity? chest.destroy({raise_destroy = true}) end end end end end Event.register_if(setting, defines.events.on_built_entity, inventory_to_container) Event.register_if(setting, defines.events.on_pre_player_mined_item, container_to_inventory)
function start_rendering(note_opts, file_opts, render_opts, bms_data, on_end_rendering) -- Make new pattern local pat_idx = renoise.song().sequencer:insert_new_pattern_at(1) local working_pattern = renoise.song().patterns[pat_idx] working_pattern.number_of_lines = renoise.Pattern.MAX_NUMBER_OF_LINES -- Called on end local function end_rendering() renoise.song().sequencer:delete_sequence_at(1) renoise.app():show_status("Rendering completed.") on_end_rendering() end -- Render single note (Recursively called) local function render_note(note_index) if note_index > #bms_data.notes then end_rendering() return end local filename = ("%s_%03d.wav"):format(note_opts.filename, note_index-1) renoise.app():show_status( "Rendering '" .. filename .. "'." ) local note = bms_data.notes[note_index] working_pattern:clear() local pattrk = working_pattern:track(note_opts.index) -- Write note for line_idx, line in ipairs(note.lines) do for ncol_idx, ncol in ipairs(line.note_columns) do pattrk:line(line_idx):note_column(ncol_idx):copy_from(ncol) end for ecol_idx, ecol in ipairs(line.effect_columns) do pattrk:line(line_idx):effect_column(ecol_idx):copy_from(ecol) end end if not note_opts.one_shot and #note.lines + 1 <= renoise.Pattern.MAX_NUMBER_OF_LINES then -- Write note off for i = 1, #note.lines[1].note_columns do pattrk:line(#note.lines + 1):note_column(i).note_value = 120 end end -- Write automation for prm_idx, prm in ipairs(bms_data.automated_params) do local auto_pattrk = working_pattern:track(prm.trk_idx) local auto = auto_pattrk:create_automation(prm.param) if not prm.lines_mode then auto.playmode = renoise.PatternTrackAutomation.PLAYMODE_POINTS end auto.points = note.automation[prm_idx] end local line_num if note_opts.one_shot then line_num = note_opts.release_lines else line_num = #note.lines + note_opts.release_lines end local s_pos = renoise.SongPos(1, 1) local e_pos = renoise.SongPos(1, line_num) -- If s_pos == e_pos, render will be error. if e_pos.line <= 1 then e_pos.line = 2 end -- Render local ret, msg = renoise.song():render( { start_pos = s_pos, end_pos = e_pos, sample_rate = render_opts.sample_rate, bit_depth = render_opts.bit_depth, interpolation = render_opts.interpolation, priority = render_opts.priority }, file_opts.directory .. filename, function() -- render next sample render_note(note_index + 1) end ) -- On error if not ret then renoise.app():show_error(msg) renoise.song().sequencer:delete_sequence_at(1) end end -- Render render_note(1) end
require 'tempobj' local function _new() local t=tempobj.new(scene.createMovTar()) t.setOverBounce(1.6) local fPower=1; local getPower = function() return fPower; end local setPower = function(power) fPower=power; end local _frameMove = t.frameMove local frameMove = function(timed) local ret=_frameMove(timed) return ret end local _deleteThis = t.deleteThis local deleteThis = function() scene.deleteMovTar(t) return _deleteThis() end t.getPower=getPower t.setPower=setPower t.frameMove=frameMove t.deleteThis=deleteThis return t end -- export bullet = { new = _new }
function pause(seconds) coroutine.yield(seconds) end function lEntityMat(entity) Matrix.new(entity):load() end BasicSprite = {} function BasicSprite.new(img, mesh, shader) local res = { img = img, mesh = mesh, shader = shader } local wrapper = Element.new(BasicSprite.render, res) return wrapper end function BasicSprite:render(entity) self.shader:use() self.img:bind() mat = Matrix.new() mat.x = entity.x mat.y = entity.y mat.width = entity.width mat.height = entity.height mat:load() self.mesh:render() end -- For use by Animation Frame = {} function Frame.new(img, coords, shader, duration) local res = { img = img, mesh = Mesh.new(), shader = shader, duration = duration -- In seconds } res.mesh:setVertices{ -1, -1, coords[1], coords[2], -1, 1, coords[3], coords[4], 1, 1, coords[5], coords[6], 1, -1, coords[7], coords[8] } res.mesh:setIndices{ 0, 1, 2, 0, 2, 3 } res.mesh:setParam(0, 2, 4, 0) res.mesh:setParam(1, 2, 4, 2) return res; end Animation = {} -- Length of frames must be at least 1 function Animation.new(frames) local res = { frames = frames, index = 1, frameEnd = game:getTime() + frames[1].duration } local wrapper = Element.new(Animation.render, res) return wrapper end function Animation:render(e) local skips = 0 -- Prevent possible near-infinate loop from short frames while game:getTime() >= self.frameEnd and skips < 100 do if self.index < #self.frames then -- Advance self.index = self.index + 1 else -- Loop self.index = 1 end self.frameEnd = self.frameEnd + self.frames[self.index].duration skips = skips + 1 end local f = self.frames[self.index]; f.shader:use() f.img:bind() f.mesh:render() end
local heightBar = 0 local heightGraph = 0 local widthBarThread = 0 local widthGraphNet = 0 function conky_format(format, number) return string.format(format, conky_parse(number)) end function splitCsv(vals, fromConky) local tab = {} if fromConky then vals = conky_parse(vals) end for s in string.gmatch(vals, "[^,]+") do table.insert(tab, s) end return tab end yellow = "#ffff%02x" red = "#ff%02x%02x" p = 1 / 100 -- %02x -> x: hex, 2: 2 chars, 0: default char, %: string.format insert -- example 255=ff or 0=00 -- keep conky beginning for other usecases function conky_colorPercentage(percentage) local perc = conky_parse(percentage) * p local calc = 255 - perc * 255 return string.format("${color " .. yellow .. "}", calc, calc, calc) end function execShRetRes(cmd) local handle = io.popen(cmd) local res = string.format("%s", handle:read("*a")) handle:close() return res end function conky_setSizes(newHeightBar, newHeightGraph, newWidthBarThread, newWidthGraphNet) heightBar = conky_parse(newHeightBar) heightGraph = conky_parse(newHeightGraph) widthBarThread = conky_parse(newWidthBarThread) widthGraphNet = conky_parse(newWidthGraphNet) return "" end nproc = tonumber(execShRetRes("nproc")) cpuName = execShRetRes([[lscpu | grep "Model name:" | sed 's/.*:[ ]\+//g']]) function conky_getCpu(vals) local i = 1 local cpuP = splitCsv(vals, true) local cpu0 = table.remove(cpuP, 1) -- /sys/class/hwmon/hwmon* local out = cpuName .. [[${hwmon 0 temp 1}C]] .. conky_colorPercentage(cpu0) .. [[${alignr}${freq} MHz ]] .. string.format("%3.0f", cpu0) .. [[% ${color}${cpugraph cpu0 ]] .. heightGraph .. [[} Threads ]] while i < nproc do local to = 0 local title = true if i + 3 <= nproc then to = i + 3 else to = nproc end out = out .. string.format([[${color}%02i-%02i: ]], i, to) for j = i, to, 1 do out = out .. string.format("%s${cpubar cpu%i %i,%i} %3.0f%% ", conky_colorPercentage(cpuP[j]), j, heightBar, widthBarThread, cpuP[j]) end out = out .. [[${color} ]] i = i + 4 end out = string.gsub(out, ".$", "") return out end -- inception style lua_parse call to take cpu values and minimize lua_parses in conky function conky_inceptionGetCpu() out = "${lua_parse getCpu " for i = 0, nproc, 1 do out = out .. string.format("${cpu cpu%i}", i) if i ~= nproc then out = out .. "," end end out = out .. "}" return out end function getNet(name) local out = [[<ifname>: ${addr <ifname>} ▼ ${downspeed <ifname>} ${alignr}▲ ${upspeed <ifname>} ${downspeedgraph <ifname> <height>,<width>} ${alignr}${upspeedgraph <ifname> <height>,<width>} ∑ ${totaldown <ifname>} ${alignr}∑ ${totalup <ifname>}]] out = string.gsub(out, "<ifname>", name) out = string.gsub(out, "<height>", heightGraph) out = string.gsub(out, "<width>", widthGraphNet) return out end nets = splitCsv(execShRetRes([[ip link | grep -oPz '(?<=: )(enp|wlp).*(?=:)' | tr '\0' ',']])) function conky_net() local res = "" for _, n in pairs(nets) do res = res .. getNet(n) .. "\n\n" end return res end -- needed for lua_graph usage below function conky_retGpuUtil() return gpuUtil end function conky_retGpuMem() return gpuMem end d = 1 / 1024 function conky_gpuInfo() local result = execShRetRes([[ \ nvidia-smi \ --query-gpu=gpu_name,memory.used,memory.total,utilization.gpu,clocks.sm,temperature.gpu \ --format=csv,nounits,noheader]]) local tab = splitCsv(result) if tab[1] == nil then return '' end local memUsed = tonumber(tab[2]) * d local memTotal = tonumber(tab[3]) * d local memPerc = memUsed / memTotal * 100 gpuUtil = tab[4] gpuMem = memPerc local ostr = string.format([[NVIDIA %s %iC ${alignr}%iMHz %3i%% ${lua_graph conky_retGpuUtil <height>} GPU RAM ${alignr}%0.2fGiB / %0.2fGiB %3i%% ${lua_graph conky_retGpuMem <height>}]], tab[1], tab[6], tab[5], tab[4], memUsed, memTotal, memPerc) ostr = string.gsub(ostr, "<height>", heightGraph) return ostr end
object_tangible_quest_som_volcano_marker_03 = object_tangible_quest_shared_som_volcano_marker_03:new { } ObjectTemplates:addTemplate(object_tangible_quest_som_volcano_marker_03, "object/tangible/quest/som_volcano_marker_03.iff")
-- Decompiled using luadec 2.2 rev: for Lua 5.2 from https://github.com/viruscamp/luadec -- Command line: D:\Software\AmbienceII\WDC_pc_Menu_data\Menu_seasons_temp.lua -- params : ... -- function num : 0 , upvalues : _ENV require("Chunk.lua") require("UI_SeasonButton.lua") local kScene = "ui_seasons" local kButtonPadding = 2 local mSeasonList, mButtonList = nil, nil local mCurrentIndex = 0 local ShiftList = function() -- function num : 0_0 , upvalues : _ENV, mSeasonList, mCurrentIndex, kButtonPadding local listPos = AgentGetPos(mSeasonList.agent) listPos.x = (mCurrentIndex - kButtonPadding) * -3.02 - 1.5 ChorePlayAndWait("ui_seasons_transitionOut") AgentSetPos(mSeasonList.agent, listPos) end Menu_Seasons = function() -- function num : 0_1 , upvalues : _ENV, kScene, mCurrentIndex, kButtonPadding, mSeasonList, mButtonList if not SceneIsActive(kScene) then MenuUtils_AddScene(kScene) SceneHide(kScene, true) end local menu = Menu_Create(ListMenu, "ui_seasons_reference", kScene) menu.align = "left" menu.alignV = "center" menu.isVertical = false mCurrentIndex = kButtonPadding + 1 menu.Show = function(self) -- function num : 0_1_0 , upvalues : _ENV, kScene Menu_Main_SetIdle("env_clementineHouse400_seasonSelection") ChorePlayAndWait("env_clementineHouse400_mainMenuToSeasonSelection") SceneHide(kScene, false) ; (Menu.Show)(self, true, false, false, true) end menu.Hide = function(self) -- function num : 0_1_1 , upvalues : _ENV, kScene (Menu.Hide)(self, true, true, false, true) SceneHide(kScene, true) ChorePlayAndWait("env_clementineHouse400_seasonSelectionToMainMenu") end menu.Populate = function(self) -- function num : 0_1_2 , upvalues : mSeasonList, _ENV, mButtonList, menu mSeasonList = Menu_Add(SparseMenu, "groupButtons", 0.1, nil, "top") mSeasonList.isVertical = false mSeasonList.Place = function(self) -- function num : 0_1_2_0 self:AnchorToAgent("ui_seasons_anchorButtons", "left", "center") end mButtonList = {} local kSeasons = {"walkingDeadSeasonOne", "walkingDeadSeasonTwo", "walkingDeadSeasonThree", "walkingDeadSeasonFour", "walkingDeadMichonne", "walkingDeadSeasonAmb"} local kSeasonCommands = {"Menu_Seasons_Play( 1 )", "Menu_Seasons_Play( 2 )", "Menu_Seasons_Play( 3 )", "Menu_Seasons_Play( 4 )", "Menu_Seasons_Play( \"M\" )", "Menu_Ambience_Play()"} ; (table.insert)(mButtonList, Menu_Insert(mSeasonList, SeasonButton, "padLeft1", kSeasons[5])) ; (table.insert)(mButtonList, Menu_Insert(mSeasonList, SeasonButton, "padLeft2", kSeasons[6])) for i,season in ipairs(kSeasons) do (table.insert)(mButtonList, Menu_Insert(mSeasonList, SeasonButton, season, season, kSeasonCommands[i])) end ; (table.insert)(mButtonList, Menu_Insert(mSeasonList, SeasonButton, "padRight1", kSeasons[1])) ; (table.insert)(mButtonList, Menu_Insert(mSeasonList, SeasonButton, "padRight2", kSeasons[2])) local arrowLeft = Menu_Add(MenuArrow, "arrowLeft", "left", "Menu_Seasons_OnLeft()", menu) arrowLeft.Place = function(self) -- function num : 0_1_2_1 if not self.bPlaced then self:AnchorToAgent("ui_seasons_anchorArrowLeft", "left", "center") self.bPlaced = true end end local arrowRight = Menu_Add(MenuArrow, "arrowRight", "right", "Menu_Seasons_OnRight()", menu) arrowRight.Place = function(self) -- function num : 0_1_2_2 if not self.bPlaced then self:AnchorToAgent("ui_seasons_anchorArrowRight", "right", "center") self.bPlaced = true end end local legendWidget = Menu_Add(Legend) legendWidget.Place = function(self) -- function num : 0_1_2_3 self:AnchorToAgent("ui_seasons_anchorLegend", "left", "bottom") end Legend_Add("faceButtonDown", "legend_select") Legend_Add("faceButtonRight", "legend_previousMenu", "Menu_Pop()") local legendButton = Menu_Add(LegendButtonBack, nil, "Menu_Pop()", "legendButton_back") legendButton.Place = function(self) -- function num : 0_1_2_4 self:AnchorToAgent("ui_seasons_anchorLegend", "left", "bottom") end end menu.OnKeyLeft = function(self, button, event) -- function num : 0_1_3 , upvalues : _ENV Menu_Seasons_OnLeft(event) end menu.OnKeyRight = function(self, button, event) -- function num : 0_1_4 , upvalues : _ENV Menu_Seasons_OnRight(event) end menu.OnWidgetInputChange = function(self, bUseCursor) -- function num : 0_1_5 , upvalues : mButtonList, mCurrentIndex (mButtonList[mCurrentIndex]):OnSetInputMode(bUseCursor) end Menu_Push(menu) for _,button in ipairs(mButtonList) do button:Deselect() end ; (mButtonList[mCurrentIndex]):Select() end Menu_Seasons_OnLeft = function(event) -- function num : 0_2 , upvalues : _ENV, mButtonList, mCurrentIndex, kButtonPadding, ShiftList WidgetInputHandler_EnableInput(false) if event then WidgetInputHandler_ConsumeEvent(event) end ; (mButtonList[mCurrentIndex]):Deselect() mCurrentIndex = mCurrentIndex - 1 if mCurrentIndex < kButtonPadding + 1 then mCurrentIndex = #mButtonList - kButtonPadding end ShiftList() ; (mButtonList[mCurrentIndex]):Select() WidgetInputHandler_EnableInput(true) end Menu_Seasons_OnRight = function(event) -- function num : 0_3 , upvalues : _ENV, mButtonList, mCurrentIndex, kButtonPadding, ShiftList WidgetInputHandler_EnableInput(false) if event then WidgetInputHandler_ConsumeEvent(event) end ; (mButtonList[mCurrentIndex]):Deselect() mCurrentIndex = mCurrentIndex + 1 if #mButtonList - kButtonPadding < mCurrentIndex then mCurrentIndex = kButtonPadding + 1 end ShiftList() ; (mButtonList[mCurrentIndex]):Select() WidgetInputHandler_EnableInput(true) end Menu_Seasons_Select = function(seasonName) -- function num : 0_4 , upvalues : _ENV if seasonName == "walkingDeadSeasonAmb" then AgentSetProperty("ui_seasons_image", "material_ui_moreFromTelltale_mainImage_mainImage_m - Diffuse Texture", (string.format)("ui_moreFromTelltale_mainImage_%s.d3dtx", seasonName)) AgentSetProperty("ui_seasons_textLabel", kTextNode, "") AgentSetProperty("ui_seasons_textDescription", kTextNode, "") AgentSetProperty("ui_seasons_textLabel", kText, "AMBIENCE") AgentSetProperty("ui_seasons_textDescription", kText, "Ambience allows you to explore various locations found within the Walking Dead universe freely.") ChorePlayAndWait("ui_seasons_transitionIn") else AgentSetProperty("ui_seasons_image", "material_ui_moreFromTelltale_mainImage_mainImage_m - Diffuse Texture", (string.format)("ui_moreFromTelltale_mainImage_%s.d3dtx", seasonName)) AgentSetProperty("ui_seasons_textLabel", kTextNode, (string.format)("label_%s", seasonName)) AgentSetProperty("ui_seasons_textDescription", kTextNode, (string.format)("desc_%s", seasonName)) ChorePlayAndWait("ui_seasons_transitionIn") end end Menu_Seasons_Play = function(season) -- function num : 0_5 , upvalues : _ENV if season ~= 1 and not Chunk_PlayGo_PreBeginPlay("Season" .. season) then return end Print("Switching to season " .. season) WidgetInputHandler_EnableInput(false) Menu_Music_FadeOut() local legend = AgentFind("ui_seasons_legend") if legend and legend.widget then (legend.widget):Suppress(nil, true) end local legendButton = AgentFind("ui_seasons_legendButtonBack") if legendButton and legendButton.widget then (legendButton.widget):Suppress(nil, true) end ChorePlayAndWait("ui_seasons_transitionOut") SubProject_Switch("MenuSeason" .. season) end Menu_Ambience_Play = function() WidgetInputHandler_EnableInput(false) ChorePlayAndWait("ui_seasons_transitionOut") local dialogResult = DialogBox_YesNo("Ambience allows you to freely roam through many maps appearing throughout the series. Potentially major spoilers ahead!\n\nAre you sure you'd like to continue?", "Spoiler Warning") if dialogResult then SubProject_Switch("WalkingDead402", "_BoardingSchoolExteriorDuskInitAmb.lua") else ChorePlayAndWait("ui_seasons_transitionIn") WidgetInputHandler_EnableInput(true) end end
-- General options require('settings') require('keybinds') require('lsp') require('plugins')
local responses = require "kong.tools.responses" local kutils = require ("kong.plugins.keystone.utils") local policies = require ("kong.plugins.keystone.policies") local function show_ca_cert(self, dao_factory) return 200, [[ MIIDgTCCAmmgAwIBAgIJAIr3n9+0RSC7MA0GCSqGSIb3DQEBCwUAMFcxCzAJBgNV BAYTAlVTMQ4wDAYDVQQIDAVVbnNldDEOMAwGA1UEBwwFVW5zZXQxDjAMBgNVBAoM BVVuc2V0MRgwFgYDVQQDDA93d3cuZXhhbXBsZS5jb20wHhcNMTYxMDIwMTMwMjE4 WhcNMjYxMDE4MTMwMjE4WjBXMQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVW5zZXQx DjAMBgNVBAcMBVVuc2V0MQ4wDAYDVQQKDAVVbnNldDEYMBYGA1UEAwwPd3d3LmV4 YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwoJkYpfJ Bvqfq0eAuqTIziiunNQdnSUX/aMS5UuI6tjzSkYnR5FCdf9UP8OrpA37gthvz3KK XhNLqnnV8MLzEo3+lN5IAr+TE1foXnqGs6vNvj5Jn1lViXXpIeaHxMwkJpJjPwxJ nFLtxL1m9hIx5anV5ZyJWV8RIaMqnzOJ7QYiX07aouRvmtT5O1LQzr2ht2l4EzPY YDt9UV/daSikrmroBnwgWMecaFJOC1pxSyvO2PAnw+yhX6NHgGPJmOu0TSN2IK1p o07ZVM3QJLLbEZFjcUK7FXNRk5ZfzjkCrJA1l0Ys3ByHTb2offffIyTYPuatQtfF 0XvTIwMN5eIAswIDAQABo1AwTjAMBgNVHRMEBTADAQH/MB0GA1UdDgQWBBTZ4Nls 7DRmUBcrYhYDLSsDM0BCWzAfBgNVHSMEGDAWgBTZ4Nls7DRmUBcrYhYDLSsDM0BC WzANBgkqhkiG9w0BAQsFAAOCAQEALil6WvVii6yNVwu0zgt2iDYqHvnnHWnSVhEJ eKeBFRxpuwiH+UOeygFB0/6lD2r11cD0SdgaMfLAKkKspQucJIsp3BYLwBJ25oxn NL2yB3HLZeEebAQzXQwnRbWUbIpcp/XPlKjybiA3unqE+X/qdQZgxJ2Xgtp7bHhN yzDCSOUZlHrkKNXtFNvqRtoCeMBs2+jfqx2ap64ORSnLihEi57lOcUn2DbAR45OI +wppD5CcUTDsE0r+XbBK3Cm3dn6pVyVcawv5qDidRB7JdsDbx6VC7gcBbdgdbLWz Xf4KS8N77jeGjqKJ7QY5jkHdXhY+gGbeponch4y2VqLgMI0VGQ==]] end local function show_signing_cert(self, dao_factory) return 200, [[ MIIDZjCCAk6gAwIBAgIBATANBgkqhkiG9w0BAQsFADBXMQswCQYDVQQGEwJVUzEO MAwGA1UECAwFVW5zZXQxDjAMBgNVBAcMBVVuc2V0MQ4wDAYDVQQKDAVVbnNldDEY MBYGA1UEAwwPd3d3LmV4YW1wbGUuY29tMB4XDTE2MTAyMDEzMDIxOFoXDTI2MTAx ODEzMDIxOFowRzELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVVuc2V0MQ4wDAYDVQQK DAVVbnNldDEYMBYGA1UEAwwPd3d3LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0B AQEFAAOCAQ8AMIIBCgKCAQEAua3cVYSD9KY31+wNXZv3HBS5MyzTfoY+nh4nJ2x8 Ram6liu4gkHYRonTUriIrgDLyo+2fuXrmyFcq1+8ke4KD3n24i8pzcrt6BOGAVYP KdPyXU0EkZECNmH/tKjvVqMLHcq2apsZdZ5ujBtE5G4zbTjVIEzz90AbAmRVJy7S seluCxBKtg3IGa1WwqgU4B5pgog+VDpT8XPKFvHi1cVaX76qS6MOUxXA7kuOQUct JxcyITS26Mxym7wOTI+7JV5A9Ow/dUN6CrGMrfHB59Psx3os/BfoopFmIbbnHdOO ETOeifelkhwLWLfmmOHxWgYYX/aEyW3L/xCU5QDCz9B0wQIDAQABo00wSzAJBgNV HRMEAjAAMB0GA1UdDgQWBBQeoHzsYSUSfGymk6kem/lpGVJS9DAfBgNVHSMEGDAW gBTZ4Nls7DRmUBcrYhYDLSsDM0BCWzANBgkqhkiG9w0BAQsFAAOCAQEAfsH6AN7p XWBg062LUtpfDsRyXqOLYofR4Y0Mzo1rH0jaozJsnOxsj42BdP+hBGjtZB9eUwgP gx+MJQC4pz+Wuc/xMysDT6f0hyjZmsakXM92lsztlW7+Y7u9ATa2lDTER1Fv7X6D I+kN+dhphq0lrIRWZvAf3TlZpEUG38cTxLD8OsdOlq4BxSzmvKFQf4mcbu39OX7i 0fGih0SxSa03idx9NWEOEp9IaGLo/mfL84nb4YjgV9yJj+3CkxYvqPlpiM2rHD/C hMgz/UB52OxbjYjbWoyStZwvlSwKWY75C9iYA04TZrhs5UWvAT+I2Y2UY/krrZ2a Rke2Bj7NAvXPHw==]] end local routes = { ['/v3/OS-SIMPLE-CERT/ca'] = { GET = function (self, dao_factory) policies.check(self.req.headers['X-Auth-Token'], "identity:show_ca_cert", dao_factory, self.params) responses.send(show_ca_cert(self, dao_factory)) end }, ['/v3/OS-SIMPLE-CERT/certificate'] = { GET = function (self, dao_factory) policies.check(self.req.headers['X-Auth-Token'], "identity:show_signing_cert", dao_factory, self.params) responses.send(show_signing_cert(self, dao_factory)) end } } return { routes = routes }
ENT.Type = "point" ENT.Base = "base_point" function ENT:Initialize() -- Backwards compatibility: TTT maps compiled before the addition of the -- propspec setting may expect it to be off, so default it to off if a map -- settings entity exists (a reliable way of identifying a TTT map) GAMEMODE.propspec_allow_named = false timer.Simple(0, function() self:TriggerOutput("MapSettingsSpawned", self) end) end function ENT:KeyValue(k, v) if k == "cbar_doors" then Dev(2, "ttt_map_settings: crowbar door unlocking = " .. v) local opens = (v == "1") GAMEMODE.crowbar_unlocks[OPEN_DOOR] = opens GAMEMODE.crowbar_unlocks[OPEN_ROT] = opens elseif k == "cbar_buttons" then Dev(2, "ttt_map_settings: crowbar button unlocking = " .. v) GAMEMODE.crowbar_unlocks[OPEN_BUT] = (v == "1") elseif k == "cbar_other" then Dev(2, "ttt_map_settings: crowbar movelinear unlocking = " .. v) GAMEMODE.crowbar_unlocks[OPEN_NOTOGGLE] = (v == "1") elseif k == "plymodel" and v != "" then -- can ignore if empty if util.IsValidModel(v) then util.PrecacheModel(v) GAMEMODE.force_plymodel = v Dev(2, "ttt_map_settings: set player model to be " .. v) else Dev(2, "ttt_map_settings: FAILED to set player model due to invalid path: " .. v) end elseif k == "propspec_named" then Dev(2, "ttt_map_settings: propspec possessing named props = " .. v) GAMEMODE.propspec_allow_named = (v == "1") elseif k == "MapSettingsSpawned" or k == "RoundEnd" or k == "RoundPreparation" or k == "RoundStart" then self:StoreOutput(k, v) end end function ENT:AcceptInput(name, activator, caller, data) if name == "SetPlayerModels" then local mdlname = tostring(data) if not mdlname then ErrorNoHalt("ttt_map_settings: Invalid parameter to SetPlayerModels input!\n") return false elseif not util.IsValidModel(mdlname) then ErrorNoHalt("ttt_map_settings: Invalid model given: " .. mdlname .. "\n") return false end GAMEMODE.force_plymodel = Model(mdlname) Dev(2, "ttt_map_settings: input set player model to be " .. mdlname) return true end end -- Fire an output when the round changes function ENT:RoundStateTrigger(r, data) if r == ROUND_PREP then self:TriggerOutput("RoundPreparation", self) elseif r == ROUND_ACTIVE then self:TriggerOutput("RoundStart", self) elseif r == ROUND_POST then -- RoundEnd has the type of win condition as param self:TriggerOutput("RoundEnd", self, tostring(data)) end end
object_tangible_food_generic_dish_karkan_ribenes = object_tangible_food_generic_shared_dish_karkan_ribenes:new { } ObjectTemplates:addTemplate(object_tangible_food_generic_dish_karkan_ribenes, "object/tangible/food/generic/dish_karkan_ribenes.iff")
KethoWowpedia.patch.toy = { [680] = "8.0.1", [682] = "8.0.1", [683] = "8.0.1", [684] = "8.0.1", [685] = "8.0.1", [686] = "8.0.1", [787] = "8.0.1", [788] = "8.0.1", [789] = "8.0.1", [790] = "8.0.1", [791] = "8.0.1", [792] = "8.0.1", [793] = "8.0.1", [795] = "8.0.1", [796] = "8.0.1", [797] = "8.0.1", [798] = "8.0.1", [799] = "8.0.1", [800] = "8.0.1", [801] = "8.0.1", [802] = "8.0.1", [803] = "8.0.1", [804] = "8.0.1", [805] = "8.0.1", [806] = "8.0.1", [807] = "8.0.1", [808] = "8.0.1", [809] = "8.0.1", [810] = "8.0.1", [811] = "8.0.1", [812] = "8.0.1", [813] = "8.0.1", [814] = "8.0.1", [815] = "8.0.1", [816] = "8.0.1", [817] = "8.0.1", [819] = "8.0.1", [820] = "8.0.1", [821] = "8.0.1", [822] = "8.0.1", [823] = "8.1.0", [824] = "8.1.0", [827] = "8.0.1", [828] = "8.0.1", [829] = "8.0.1", [830] = "8.0.1", [831] = "8.0.1", [832] = "8.0.1", [833] = "8.0.1", [834] = "8.0.1", [890] = "8.0.1", [891] = "8.1.0", [892] = "8.1.0", [893] = "8.1.0", [894] = "8.1.0", [895] = "8.1.0", [896] = "8.1.0", [897] = "8.1.0", [898] = "8.1.0", [899] = "8.1.0", [900] = "8.1.0", [901] = "8.1.0", [902] = "8.1.0", [903] = "8.1.0", [904] = "8.1.0", [905] = "8.1.0", [906] = "8.1.0", [907] = "8.1.0", [908] = "8.1.0", [909] = "8.1.0", [910] = "8.1.0", [911] = "8.1.0", [912] = "8.1.0", [913] = "8.2.0", [914] = "8.2.0", [916] = "8.1.0", [917] = "8.1.0", [918] = "8.1.5", [919] = "8.1.5", [920] = "8.1.5", [921] = "8.1.0", [922] = "8.1.0", [923] = "8.1.0", [924] = "8.1.0", [925] = "8.1.0", [926] = "8.2.0", [927] = "8.1.0", [928] = "8.1.0", [929] = "8.1.0", [930] = "8.1.0", [931] = "8.1.0", [940] = "8.2.0", [941] = "8.1.5", [942] = "8.1.5", [943] = "8.1.5", [944] = "8.2.0", [945] = "8.2.0", [946] = "8.2.0", [947] = "8.2.0", [948] = "8.2.0", [949] = "8.2.0", [950] = "8.2.0", [953] = "8.2.0", [955] = "8.2.0", [956] = "8.2.0", [957] = "8.2.0", [958] = "8.2.0", [959] = "8.2.0", [960] = "8.2.0", [961] = "8.2.0", [964] = "8.2.0", [965] = "8.2.0", [966] = "8.2.0", [967] = "8.2.0", [968] = "8.2.0", [969] = "8.2.0", [970] = "8.2.0", [971] = "8.2.0", [972] = "8.2.0", [973] = "8.2.0", [974] = "8.2.0", [975] = "8.2.0", [976] = "8.2.0", [977] = "8.2.0", [978] = "8.2.0", [979] = "8.2.0", [980] = "8.2.0", [981] = "8.2.5", [982] = "8.2.5", [983] = "8.2.5", [984] = "8.2.5", [985] = "8.3.0", [986] = "8.3.0", [991] = "9.0.1", [992] = "9.0.1", [993] = "9.0.1", [994] = "8.3.0", [995] = "8.3.0", [996] = "8.3.0", [997] = "8.3.0", [998] = "8.3.0", [999] = "8.3.0", [1000] = "8.3.0", [1001] = "8.3.0", [1002] = "8.3.0", [1003] = "8.3.0", [1005] = "8.3.0", [1006] = "8.3.0", [1007] = "8.3.0", [1062] = "9.0.1", [1063] = "9.0.1", [1064] = "9.0.1", [1065] = "9.0.1", [1066] = "9.0.1", [1067] = "9.0.1", [1068] = "9.0.1", [1069] = "9.0.1", [1070] = "9.0.1", [1071] = "9.0.1", [1072] = "9.0.1", [1073] = "9.0.1", [1074] = "9.0.1", [1075] = "9.0.1", [1076] = "9.0.1", [1077] = "9.0.1", [1078] = "9.0.1", [1079] = "9.0.1", [1080] = "9.0.1", [1081] = "9.0.1", [1082] = "9.0.1", [1083] = "9.0.1", [1084] = "9.0.1", [1085] = "9.0.1", [1086] = "9.0.1", [1087] = "9.0.2", [1088] = "9.0.2", [1089] = "9.0.2", [1090] = "9.0.2", [1091] = "9.0.2", [1092] = "9.0.2", [1093] = "9.0.2", [1094] = "9.0.2", [1095] = "9.0.2", [1096] = "9.0.2", [1097] = "9.0.2", [1098] = "9.0.2", [1099] = "9.0.2", [1100] = "9.0.2", [1101] = "9.0.2", [1102] = "9.0.2", [1103] = "9.0.2", [1104] = "9.0.2", [1105] = "9.0.2", [1106] = "9.0.2", [1107] = "9.0.2", [1108] = "9.0.2", [1109] = "9.0.2", [1110] = "9.0.2", [1111] = "9.0.2", [1112] = "9.0.2", [1113] = "9.0.2", [1114] = "9.1.0", [1115] = "9.1.0", [1116] = "9.1.0", [1117] = "9.1.0", [1118] = "9.1.0", [1119] = "9.1.0", [1120] = "9.1.0", [1121] = "9.1.0", [1122] = "9.1.0", [1123] = "9.1.0", [1124] = "9.1.0", [1125] = "9.1.0", [1126] = "9.1.0", [1127] = "9.1.0", [1128] = "9.1.0", [1129] = "9.1.0", [1130] = "9.1.0", [1131] = "9.1.0", [1132] = "9.1.0", [1133] = "9.1.0", [1134] = "9.1.0", [1135] = "9.1.0", [1137] = "9.1.0", [1138] = "9.1.0", }
local settings = ... local concat = table.concat local insert = table.insert local sprintf = string.format local rep = string.rep local minetest_example_header = [[ # This file contains a list of all available settings and their default value for minetest.conf # By default, all the settings are commented and not functional. # Uncomment settings by removing the preceding #. # minetest.conf is read by default from: # ../minetest.conf # ../../minetest.conf # Any other path can be chosen by passing the path as a parameter # to the program, eg. "minetest.exe --config ../minetest.conf.example". # Further documentation: # http://wiki.minetest.net/ ]] local function create_minetest_conf_example() local result = { minetest_example_header } for _, entry in ipairs(settings) do if entry.type == "category" then if entry.level == 0 then insert(result, "#\n# " .. entry.name .. "\n#\n\n") else insert(result, rep("#", entry.level)) insert(result, "# " .. entry.name .. "\n\n") end else if entry.comment ~= "" then for _, comment_line in ipairs(entry.comment:split("\n", true)) do insert(result, "# " .. comment_line .. "\n") end end insert(result, "# type: " .. entry.type) if entry.min then insert(result, " min: " .. entry.min) end if entry.max then insert(result, " max: " .. entry.max) end if entry.values then insert(result, " values: " .. concat(entry.values, ", ")) end if entry.possible then insert(result, " possible values: " .. entry.possible:gsub(",", ", ")) end insert(result, "\n") local append if entry.default ~= "" then append = " " .. entry.default end insert(result, sprintf("# %s =%s\n\n", entry.name, append or "")) end end return concat(result) end local translation_file_header = [[ // This file is automatically generated // It conatins a bunch of fake gettext calls, to tell xgettext about the strings in config files // To update it, refer to the bottom of builtin/mainmenu/dlg_settings_advanced.lua fake_function() {]] local function create_translation_file() local result = { translation_file_header } for _, entry in ipairs(settings) do if entry.type == "category" then insert(result, sprintf("\tgettext(%q);", entry.name)) else if entry.readable_name then insert(result, sprintf("\tgettext(%q);", entry.readable_name)) end if entry.comment ~= "" then local comment_escaped = entry.comment:gsub("\n", "\\n") comment_escaped = comment_escaped:gsub("\"", "\\\"") insert(result, "\tgettext(\"" .. comment_escaped .. "\");") end end end insert(result, "}\n") return concat(result, "\n") end local file = assert(io.open("minetest.conf.example", "w")) file:write(create_minetest_conf_example()) file:close() file = assert(io.open("src/settings_translation_file.cpp", "w")) file:write(create_translation_file()) file:close()
--[[ Adobe Experience Manager (AEM) API Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API OpenAPI spec version: 3.2.0-pre.0 Contact: opensource@shinesolutions.com Generated by: https://openapi-generator.tech ]] --package openapi-client local http_request = require "http.request" local http_util = require "http.util" local dkjson = require "dkjson" local basexx = require "basexx" -- model import local openapi-client_install_status = require "openapi-client.model.install_status" local crx_api = {} local crx_api_mt = { __name = "crx_api"; __index = crx_api; } local function new_crx_api(host, basePath, schemes) local schemes_map = {} for _,v in ipairs(schemes) do schemes_map[v] = v end local default_scheme = schemes_map.https or schemes_map.http return setmetatable({ host = host; basePath = basePath or "http://localhost"; schemes = schemes_map; default_scheme = default_scheme; http_username = nil; http_password = nil; api_key = {}; access_token = nil; }, crx_api_mt) end function crx_api:get_crxde_status() local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; path = string.format("%s/crx/server/crx.default/jcr:root/.1.json", self.basePath); }) -- set HTTP verb req.headers:upsert(":method", "GET") -- TODO: create a function to select proper content-type -- ref: https://openapi-generator.tech/pull/6252#issuecomment-321199879 --local var_accept = { "plain/text" } req.headers:upsert("content-type", "plain/text") -- HTTP basic auth req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password)) -- make the HTTP call local headers, stream, errno = req:go() if not headers then return nil, stream, errno end local http_status = headers:get(":status") if http_status:sub(1,1) == "2" then local body, err, errno2 = stream:get_body_as_string() -- exception when getting the HTTP body if not body then return nil, err, errno2 end stream:shutdown() local result, _, err3 = dkjson.decode(body) -- exception when decoding the HTTP body if result == nil then return nil, err3 end return result, headers else local body, err, errno2 = stream:get_body_as_string() if not body then return nil, err, errno2 end stream:shutdown() -- return the error message (http body) return nil, http_status, body end end function crx_api:get_install_status() local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; path = string.format("%s/crx/packmgr/installstatus.jsp", self.basePath); }) -- set HTTP verb req.headers:upsert(":method", "GET") -- TODO: create a function to select proper content-type -- ref: https://openapi-generator.tech/pull/6252#issuecomment-321199879 --local var_accept = { "application/json" } req.headers:upsert("content-type", "application/json") -- HTTP basic auth req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password)) -- make the HTTP call local headers, stream, errno = req:go() if not headers then return nil, stream, errno end local http_status = headers:get(":status") if http_status:sub(1,1) == "2" then local body, err, errno2 = stream:get_body_as_string() -- exception when getting the HTTP body if not body then return nil, err, errno2 end stream:shutdown() local result, _, err3 = dkjson.decode(body) -- exception when decoding the HTTP body if result == nil then return nil, err3 end return openapi-client_install_status.cast(result), headers else local body, err, errno2 = stream:get_body_as_string() if not body then return nil, err, errno2 end stream:shutdown() -- return the error message (http body) return nil, http_status, body end end function crx_api:get_package_manager_servlet() local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; path = string.format("%s/crx/packmgr/service/script.html", self.basePath); }) -- set HTTP verb req.headers:upsert(":method", "GET") -- TODO: create a function to select proper content-type -- ref: https://openapi-generator.tech/pull/6252#issuecomment-321199879 --local var_accept = { "text/html" } req.headers:upsert("content-type", "text/html") -- HTTP basic auth req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password)) -- make the HTTP call local headers, stream, errno = req:go() if not headers then return nil, stream, errno end local http_status = headers:get(":status") if http_status:sub(1,1) == "2" then return nil, headers else local body, err, errno2 = stream:get_body_as_string() if not body then return nil, err, errno2 end stream:shutdown() -- return the error message (http body) return nil, http_status, body end end function crx_api:post_package_service(cmd) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; path = string.format("%s/crx/packmgr/service.jsp?cmd=%s", self.basePath, http_util.encodeURIComponent(cmd)); }) -- set HTTP verb req.headers:upsert(":method", "POST") -- TODO: create a function to select proper content-type -- ref: https://openapi-generator.tech/pull/6252#issuecomment-321199879 --local var_accept = { "text/xml" } req.headers:upsert("content-type", "text/xml") -- HTTP basic auth req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password)) -- make the HTTP call local headers, stream, errno = req:go() if not headers then return nil, stream, errno end local http_status = headers:get(":status") if http_status:sub(1,1) == "2" then local body, err, errno2 = stream:get_body_as_string() -- exception when getting the HTTP body if not body then return nil, err, errno2 end stream:shutdown() local result, _, err3 = dkjson.decode(body) -- exception when decoding the HTTP body if result == nil then return nil, err3 end return result, headers else local body, err, errno2 = stream:get_body_as_string() if not body then return nil, err, errno2 end stream:shutdown() -- return the error message (http body) return nil, http_status, body end end function crx_api:post_package_service_json(path, cmd, group_name, package_name, package_version, _charset_, force, recursive, package) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; path = string.format("%s/crx/packmgr/service/.json/%s?cmd=%s&groupName=%s&packageName=%s&packageVersion=%s&_charset_=%s&force=%s&recursive=%s", self.basePath, path, http_util.encodeURIComponent(cmd), http_util.encodeURIComponent(group_name), http_util.encodeURIComponent(package_name), http_util.encodeURIComponent(package_version), http_util.encodeURIComponent(_charset_), http_util.encodeURIComponent(force), http_util.encodeURIComponent(recursive)); }) -- set HTTP verb req.headers:upsert(":method", "POST") -- TODO: create a function to select proper accept -- ref: https://openapi-generator.tech/pull/6252#issuecomment-321199879 --local var_content_type = { "multipart/form-data" } req.headers:upsert("accept", "multipart/form-data") -- TODO: create a function to select proper content-type -- ref: https://openapi-generator.tech/pull/6252#issuecomment-321199879 --local var_accept = { "application/json" } req.headers:upsert("content-type", "application/json") req:set_body(http_util.dict_to_query({ ["package"] = package; })) -- HTTP basic auth req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password)) -- make the HTTP call local headers, stream, errno = req:go() if not headers then return nil, stream, errno end local http_status = headers:get(":status") if http_status:sub(1,1) == "2" then local body, err, errno2 = stream:get_body_as_string() -- exception when getting the HTTP body if not body then return nil, err, errno2 end stream:shutdown() local result, _, err3 = dkjson.decode(body) -- exception when decoding the HTTP body if result == nil then return nil, err3 end return result, headers else local body, err, errno2 = stream:get_body_as_string() if not body then return nil, err, errno2 end stream:shutdown() -- return the error message (http body) return nil, http_status, body end end function crx_api:post_package_update(group_name, package_name, version, path, filter, _charset_) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; path = string.format("%s/crx/packmgr/update.jsp?groupName=%s&packageName=%s&version=%s&path=%s&filter=%s&_charset_=%s", self.basePath, http_util.encodeURIComponent(group_name), http_util.encodeURIComponent(package_name), http_util.encodeURIComponent(version), http_util.encodeURIComponent(path), http_util.encodeURIComponent(filter), http_util.encodeURIComponent(_charset_)); }) -- set HTTP verb req.headers:upsert(":method", "POST") -- TODO: create a function to select proper content-type -- ref: https://openapi-generator.tech/pull/6252#issuecomment-321199879 --local var_accept = { "application/json" } req.headers:upsert("content-type", "application/json") -- HTTP basic auth req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password)) -- make the HTTP call local headers, stream, errno = req:go() if not headers then return nil, stream, errno end local http_status = headers:get(":status") if http_status:sub(1,1) == "2" then local body, err, errno2 = stream:get_body_as_string() -- exception when getting the HTTP body if not body then return nil, err, errno2 end stream:shutdown() local result, _, err3 = dkjson.decode(body) -- exception when decoding the HTTP body if result == nil then return nil, err3 end return result, headers else local body, err, errno2 = stream:get_body_as_string() if not body then return nil, err, errno2 end stream:shutdown() -- return the error message (http body) return nil, http_status, body end end function crx_api:post_set_password(old, plain, verify) local req = http_request.new_from_uri({ scheme = self.default_scheme; host = self.host; path = string.format("%s/crx/explorer/ui/setpassword.jsp?old=%s&plain=%s&verify=%s", self.basePath, http_util.encodeURIComponent(old), http_util.encodeURIComponent(plain), http_util.encodeURIComponent(verify)); }) -- set HTTP verb req.headers:upsert(":method", "POST") -- TODO: create a function to select proper content-type -- ref: https://openapi-generator.tech/pull/6252#issuecomment-321199879 --local var_accept = { "text/plain" } req.headers:upsert("content-type", "text/plain") -- HTTP basic auth req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password)) -- make the HTTP call local headers, stream, errno = req:go() if not headers then return nil, stream, errno end local http_status = headers:get(":status") if http_status:sub(1,1) == "2" then local body, err, errno2 = stream:get_body_as_string() -- exception when getting the HTTP body if not body then return nil, err, errno2 end stream:shutdown() local result, _, err3 = dkjson.decode(body) -- exception when decoding the HTTP body if result == nil then return nil, err3 end return result, headers else local body, err, errno2 = stream:get_body_as_string() if not body then return nil, err, errno2 end stream:shutdown() -- return the error message (http body) return nil, http_status, body end end return { new = new_crx_api; }
return { init_effect = "", name = "测试-运输船-AI切换", time = 0, picture = "", desc = "运输船AI切换", stack = 1, id = 60036, icon = 60036, last_effect = "lingxing", effect_list = { { type = "BattleBuffAddBuff", trigger = { "onUpdate" }, arg_list = { buff_id = 60037, time = 10 } } } }
---@class ScriptObject ---[Documentation](https://wowpedia.fandom.com/wiki/UIOBJECT_ScriptObject) local ScriptObject = {} ---@param scriptType ScriptType ---@param bindingType LE_SCRIPT_BINDING_TYPE ---@return function handler ---[Documentation](https://wowpedia.fandom.com/wiki/API_ScriptObject_GetScript) function ScriptObject:GetScript(scriptType, bindingType) end ---@param scriptType ScriptType ---@return boolean hasScript ---[Documentation](https://wowpedia.fandom.com/wiki/API_ScriptObject_HasScript) function ScriptObject:HasScript(scriptType) end ---@param scriptType ScriptType ---@param handler function ---@param bindingType LE_SCRIPT_BINDING_TYPE ---@return boolean success ---[Documentation](https://wowpedia.fandom.com/wiki/API_ScriptObject_HookScript) function ScriptObject:HookScript(scriptType, handler, bindingType) end ---@param scriptType ScriptType ---@param handler function ---[Documentation](https://wowpedia.fandom.com/wiki/API_ScriptObject_SetScript) function ScriptObject:SetScript(scriptType, handler) end
-- See LICENSE for terms local options local mod_Option1 -- fired when settings are changed/init local function ModOptions() options = CurrentModOptions mod_Option1 = options:GetProperty("Option1") local u = ChoGGi.UserSettings u.DebugGridOpacity = options:GetProperty("DebugGridOpacity") u.DebugGridSize = options:GetProperty("DebugGridSize") if ChoGGi.SettingFuncs.WriteSettings then ChoGGi.SettingFuncs.WriteSettings() end end -- load default/saved settings OnMsg.ModsReloaded = ModOptions -- fired when option is changed function OnMsg.ApplyModOptions(id) if id == CurrentModId then ModOptions() end end local grids_visible local function ShowGrids() ChoGGi.ComFuncs.BuildableHexGrid(true) grids_visible = true end local function HideGrids() ChoGGi.ComFuncs.BuildableHexGrid(false) grids_visible = false end local orig_CursorBuilding_GameInit = CursorBuilding.GameInit function CursorBuilding.GameInit(...) if mod_Option1 then ShowGrids() end return orig_CursorBuilding_GameInit(...) end local orig_CursorBuilding_Done = CursorBuilding.Done function CursorBuilding.Done(...) HideGrids() return orig_CursorBuilding_Done(...) end -- add keybind for toggle local Actions = ChoGGi.Temp.Actions Actions[#Actions+1] = {ActionName = T(302535920011583, "Construction Show Hex Buildable Grid"), ActionId = "ChoGGi.ConstructionShowHexBuildableGrid.ToggleGrid", OnAction = function() if grids_visible then HideGrids() else ShowGrids() end end, ActionShortcut = "Numpad 0", replace_matching_id = true, ActionBindable = true, }
local _ _ = function() local _list_0 = things for _index_0 = 1, #_list_0 do local x = _list_0[_index_0] _ = x end end _ = function() local _accum_0 = { } local _len_0 = 1 local _list_0 = things for _index_0 = 1, #_list_0 do local x = _list_0[_index_0] _accum_0[_len_0] = x _len_0 = _len_0 + 1 end return _accum_0 end do local _list_0 = things for _index_0 = 1, #_list_0 do local x = _list_0[_index_0] return x end end do local _accum_0 = { } local _len_0 = 1 local _list_0 = things for _index_0 = 1, #_list_0 do local x = _list_0[_index_0] _accum_0[_len_0] = x _len_0 = _len_0 + 1 end return _accum_0 end do local _tbl_0 = { } local _list_0 = things for _index_0 = 1, #_list_0 do local x, y = _list_0[_index_0] _tbl_0[x] = y end return _tbl_0 end _ = function() if a then if a then return a else return b end elseif b then if a then return a else return b end else if a then return a else return b end end end do if a then if a then return a else return b end elseif b then if a then return a else return b end else if a then return a else return b end end end _ = function() local _base_0 = a local _fn_0 = _base_0.b return _fn_0 and function(...) return _fn_0(_base_0, ...) end end do local _base_0 = a local _fn_0 = _base_0.b return _fn_0 and function(...) return _fn_0(_base_0, ...) end end
return { id = "SYG006", events = { { alpha = 0.332, style = { text = "司令部对于指挥官在之前战斗中的表现十分赞赏,所以特批开放了第二舰队的编制权限,快跟着我来吧!", mode = 2, posY = 0, dir = -1, posX = 0 } }, { alpha = 0.413, style = { text = "前往编队界面编组第二舰队。点击确认直接前往编队界面", mode = 2, scene = "BIANDUI", posY = 0, dir = -1, posX = 0 } }, { alpha = 0.462, style = { text = "点击右侧按钮,切换到第二舰队。指引点击右侧按钮", mode = 2, posY = 87, dir = 1, posX = 228.09 }, ui = { hideAnimtor = true, path = "/UICamera/Canvas/UIMain/FormationUI(Clone)/nextPage", pathIndex = -1, triggerType = { 1 }, fingerPos = { posY = -45.81, posX = 40.2 } } }, { alpha = 0.442, style = { text = "在这里就能编组第二舰队啦", mode = 2, posY = 121.8, dir = -1, posX = 0 } }, { alpha = 0.44, style = { text = "战争已经正式打响了,想必接下来的战斗将会越来越艰辛吧,期待您更精彩的发挥哦!", mode = 2, posY = 0, dir = -1, posX = 0 } } } }
print(message) print("Hello World from Lua")
local test = {} test.after = function() error("error after...") end test.my_test_ok= function() local value = true assert( value == true ) end return test
local resource_autoplace = require('resource-autoplace') data:extend({ { type = 'resource', name = 'nm-worm-hole', icon = '__nauvis-melange__/graphics/icons/worm-hole.png', icon_size = 64, icon_mipmaps = 4, flags = {'placeable-neutral'}, collision_box = {{ -1.45, -1.45}, {1.45, 1.45}}, selection_box = {{ -1.5, -1.5}, {1.5, 1.5}}, highlight = true, minable = {mining_time = 1}, category = 'nm-deep-solid', minimum = 1, normal = 1, --collision_mask = { 'item-layer', 'player-layer', 'water-tile', 'not-colliding-with-itself' }, autoplace = resource_autoplace.resource_autoplace_settings { name = 'nm-worm-hole', order = 'c', base_density = 1, base_spots_per_km2 = 0.42, random_probability = 1/128, random_spot_size_minimum = 1, random_spot_size_maximum = 1, -- don't randomize spot size has_starting_area_placement = false, regular_rq_factor_multiplier = 1 }, stage_counts = {0}, stages = { sheet = { filename = '__base__/graphics/entity/worm/worm-integration.png', priority = 'extra-high', width = 166, height = 122, --frame_count = 4, variation_count = 1, --shift = util.by_pixel(0, -2), hr_version = { filename = '__base__/graphics/entity/worm/hr-worm-integration.png', priority = 'extra-high', width = 332, height = 240, --frame_count = 4, variation_count = 1, --shift = util.by_pixel(0, -2), scale = 0.5, } } }, map_color = {r=0.02, g=0.16, b=0.03}, map_grid = false }, { type = 'resource', name = 'nm-pre-spice-mass-ore', icon = '__nauvis-melange__/graphics/icons/pre-spice-mass-ore.png', icon_size = 64, icon_mipmaps = 4, flags = {'placeable-neutral'}, collision_box = {{-1.4, -1.4}, {1.4, 1.4}}, selection_box = {{ -0.5, -0.5}, {0.5, 0.5}}, highlight = true, minable = { mining_time = 1, result = 'nm-pre-spice-mass' }, category = 'basic-solid', minimum = 16000, normal = math.random(16000, 42000), --collision_mask = { 'item-layer', 'player-layer', 'water-tile', 'not-colliding-with-itself' }, autoplace = resource_autoplace.resource_autoplace_settings { name = 'nm-pre-spice-mass-ore', order = 'b', base_density = 1.2, base_spots_per_km2 = 0.42, random_probability = 1/256, random_spot_size_minimum = 1, random_spot_size_maximum = 1, -- don't randomize spot size additional_richness = 4200, -- this increases the total everywhere, so base_density needs to be decreased to compensate has_starting_area_placement = false, regular_rq_factor_multiplier = 1 }, stage_counts = {0}, stages = { sheet = { filename = '__nauvis-melange__/graphics/entity/pre-spice-mass/pre-spice-mass.png', priority = 'extra-high', width = 74, height = 60, frame_count = 4, variation_count = 1, hr_version = { filename = '__nauvis-melange__/graphics/entity/pre-spice-mass/hr-pre-spice-mass.png', priority = 'extra-high', width = 148, height = 120, frame_count = 4, variation_count = 1, scale = 0.5, } } }, map_color = {r=0.02, g=0.16, b=0.03}, map_grid = false } })
local Codes = require 'lib.codes' local i18n = require 'i18n' local fun = require 'lib.fun' local Encoder = {} local expansion_locale = 'en' local generics = { number = function(key) return function(card) return tonumber(card[key]) or 0 end end, number_q = function(key) return function(card) return card[key] == '?' and -2 or tonumber(card[key]) or 0 end end, combined = function(key) return function(card) local v = card[key] local t = type(v) if t == 'number' then return v elseif t == 'string' then return Codes.combine(key, v) else return 0 end end end } local encode = { id = generics.number('id'), ot = generics.combined('ot'), alias = generics.number('alias'), type = generics.combined('type'), atk = generics.number_q('atk'), race = generics.combined('race'), attribute = generics.combined('attribute'), category = generics.combined('category') } for i = 1, 16 do encode['str' .. i] = function(card) local strings = card.strings return strings and strings[i] or '' end end function encode.name(card) return card.name or '' end local PEND_TEMPLATE = '[ %s ]\n%%s\n-------------------\n[ %%s ]\n%%s' function encode.desc(card) local p_effect = card['pendulum-effect'] local effect, flavor_t = card.effect, card['flavor-text'] local text, tag = '', '' local general_locale = i18n.getLocale() i18n.setLocale(expansion_locale) local p_text = PEND_TEMPLATE:format(i18n 'make.encoder.pendulum_effect') if effect then text, tag = effect, i18n 'make.encoder.monster_effect' elseif flavor_t then text, tag = flavor_t, i18n 'make.encoder.flavor_text' end i18n.setLocale(general_locale) return p_effect and p_text:format(p_effect, tag, text) or text end function encode.setcode(card, sets) if tonumber(card.setcode) then return tonumber(card.setcode) end local setcode = 0 local cardset = type(card.set) == 'string' and card.set or '' for setid in cardset:gmatch('[%w-_]+') do local set = sets[setid] local code = tonumber(set and set.code) if code then setcode = setcode * 0x10000 + code % 0x10000 end end return setcode end local generic_def = generics.number_q('def') function encode.def(card) local arrows = card['link-arrows'] if type(arrows) == 'string' then return Codes.combine('link', arrows) else return generic_def(card) end end function encode.level(card) local scales = card['pendulum-scale'] or card['pendulum-scales'] local level = tonumber(card['link-rating'] or card.rank or card.level) or 0 local lsc, rsc = 0, 0 if tonumber(scales) then scales = tonumber(scales) lsc, rsc = scales, scales elseif type(scales) == 'table' then lsc = tonumber(scales[1]) or 0 rsc = tonumber(scales[2]) or 0 end return bit.bor(bit.lshift(lsc, 24), bit.lshift(rsc, 16), level) end function encode.holo(card) if card.holo ~= nil then return card.holo and 1 or 0 end end function encode.setnumber(card) if card.setnumber then return tostring(card.setnumber) end end function encode.author(card) if card.author then return tostring(card.author) end end function encode.year(card) return tonumber(card.year) end function Encoder.set_locale(locale) expansion_locale = locale end --- Encodes card data from .toml into .cdb entries --- @param cards table --- @param sets table --- @return CardData[] function Encoder.encode(cards, sets) local enc = fun.iter(encode) return fun.iter(next, cards):map(function(_, card) return enc:map(function(k, e) return k, e(card, sets) end):tomap() end):totable() end return Encoder
-- Define module information -- All module data must be set correctly, skipping keys will result in a error -- Module data is in JSON format -- Please also note; for linux users module(s) and/or uppercase file name paths will cause issues, same with spaces/tabs. -- Must be set (case sensitive) -- If 'folderName' is not set, Liro will completely fail to load! local folderName = "extrautils" local moduleData = '{"folderName": "' .. folderName .. '", "loadPriority": 100,"author": "Alydus","description": "A module containing useful functions.","website": "alydus.net","version": "0.1", "blacklistedFiles": [], "networkStrings": [], "loadPrefixes": {"server": "sv_", "client": "cl_", "shared": "sh_"}}' -- Register the module - Do not touch hook.Run("liro.registerModule", moduleData)
#!/usr/bin/env lua local fl = require( "fltk4lua" ) local N = 0 local W = 70 local H = 70 local ROWS = 6 local COLS = 6 local window, orientation, size local function slider_cb() local val = orientation.value local sze = size.value for i = window.children-1, 0, -1 do local wc = window:child( i ) local l = wc.user_data if l and l:match( "^@" ) then l = l:sub( 2 ) if val ~= 0 and sze ~= 0 then l = ("@%+d%d%s"):format( sze, val, l ) elseif val ~= 0 then l = ("@%d%s"):format( val, l ) elseif sze ~= 0 then l = ("@%+d%s"):format( sze, l ) else l = ("@%s"):format( l ) end if wc.box == "FL_NO_BOX" then l = "@"..l end wc.label = l end end window:redraw() end local function bt( name ) local x = N % COLS local y = (N - x)/COLS N = N + 1 x = x * W + 10 y = y * H + 10 local b1 = fl.Box( x, y, W-20, H-20, "@"..name ) b1.box = "FL_NO_BOX" b1.align = fl.ALIGN_BOTTOM b1.labelsize = 11 b1.user_data = name local b2 = fl.Box( x, y, W-20, H-20, name ) b2.box = "FL_UP_BOX" b2.labelcolor = fl.DARK3 b2.user_data = name end window = fl.Window( COLS*W, ROWS*H+60 ) bt( "@->" ) bt( "@>" ) bt( "@>>" ) bt( "@>|" ) bt( "@>[]" ) bt( "@|>" ) bt( "@<-" ) bt( "@<" ) bt( "@<<" ) bt( "@|<" ) bt( "@[]<" ) bt( "@<|" ) bt( "@<->" ) bt( "@-->" ) bt( "@+" ) bt( "@->|" ) bt( "@||" ) bt( "@arrow" ) bt( "@returnarrow" ) bt( "@square" ) bt( "@circle" ) bt( "@line" ) bt( "@menu" ) bt( "@UpArrow" ) bt( "@DnArrow" ) bt( "@search" ) bt( "@FLTK" ) bt( "@filenew" ) bt( "@fileopen" ) bt( "@filesave" ) bt( "@filesaveas" ) bt( "@fileprint" ) bt( "@refresh" ) bt( "@reload" ) bt( "@undo" ) bt( "@redo" ) local x = math.floor( window.w * 0.05 + 0.5 ) local w = math.floor( window.w * 0.42 + 0.5 ) orientation = fl.Value_Slider( x, window.h-40, w, 16, "Orientation" ) orientation.type = "FL_HORIZONTAL" orientation:range( 0.0, 9.0 ) orientation.value = 0.0 orientation.step = 1 orientation.callback = slider_cb x = math.floor( window.w * 0.53 + 0.5 ) size = fl.Value_Slider( x, window.h-40, w, 16, "Size" ) size.type = "FL_HORIZONTAL" size:range( -3.0, 9.0 ) size.value = 0.0 size.step = 1 size.callback = slider_cb window.resizable = window window:show( arg ) fl.run()
local bin = require "bin" local packet = require "packet" local stdnse = require "stdnse" local tab = require "tab" local table = require "table" local target = require "target" --- The following file contains a list of decoders used by the -- broadcast-listener script. A decoder can be either "ethernet" based or IP -- based. As we're only monitoring broadcast traffic (ie. traffic not -- explicitly addressed to us) we're mainly dealing with: -- o UDP broadcast or multicast traffic -- o ethernet broadcast traffic -- -- Hence, the Decoder table defines two sub tables ether and udp. -- In order to match an incoming UDP packet the destination port number is -- used, therefore each function is indexed based on their destination port -- for the udp based decoders. For the ether table each decoder function is -- indexed according to a pattern that the decoding engine attempts to match. -- -- Each decoder defines three functions: -- o <code>new</code> - creates a new instance of the decoder -- o <code>process</code> - process a packet passed through the -- <code>data</code> argument. -- o <code>getResults</code> - retrieve any discovered results -- -- The discovery engine creates an instance of each decoder once it's needed. -- Then discovery engine stores this instance in a decoder table for reference -- once the next packet of the same type comes in. This allows the engine to -- discard duplicate packets and to request the collected results at the end -- of the session. -- -- Currently, the packet decoder decodes the following protocols: -- o Ether -- x ARP requests (IPv4) -- x CDP - Cisco Discovery Protocol -- x EIGRP - Cisco Enhanced Interior Gateway Routing Protocol -- x OSPF - Open Shortest Path First -- -- o UDP -- x DHCP -- x Netbios -- x SSDP -- x HSRP -- x DropBox -- x Logitech SqueezeBox Discovery -- x Multicast DNS/Bonjour/ZeroConf -- x Spotify -- -- -- @author Patrik Karlsson <patrik@cqure.net> -- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html -- Version 0.2 -- Created 07/25/2011 - v0.1 - created by Patrik Karlsson -- 02/12/2012 - v0.2 - added support for EIGRP - Tom Sellers -- 07/13/2012 - v0.3 - added support for OSPF - Hani Benhabiles local bin = require 'bin' local target = require 'target' local tab = require 'tab' local packet = require 'packet' Decoders = { ether = { -- ARP IPv4 ['^00..08000604'] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, data) local ipOps = require("ipOps") local pos, hw, proto, hwsize, protosize, opcode = bin.unpack(">SSCCS", data) -- this shouldn't ever happen, given our filter if ( hwsize ~= 6 ) then return end local sender, target = {}, {} -- if this isn't an ARP request, abort if ( opcode ~= 1 ) then return end pos, sender.mac, sender.ip, target.mac, target.ip = bin.unpack("<H" .. hwsize .. "IH" .. hwsize .. "I", data, pos) if ( not(self.results) ) then self.results = tab.new(3) tab.addrow(self.results, 'sender ip', 'sender mac', 'target ip') end local mac = sender.mac:gsub("(..)(..)(..)(..)(..)(..)","%1:%2:%3:%4:%5:%6") stdnse.debug1("Decoded ARP: %s, %s, %s", ipOps.fromdword(sender.ip), mac, ipOps.fromdword(target.ip)) if ( not(self.dups[("%u:%s"):format(sender.ip,sender.mac)]) ) then if ( target.ALLOW_NEW_TARGETS ) then target.add(sender.ip) end self.dups[("%u:%s"):format(sender.ip,sender.mac)] = true tab.addrow(self.results, ipOps.fromdword(sender.ip), mac, ipOps.fromdword(target.ip)) end end, getResults = function(self) return { name = "ARP Request", (self.results and tab.dump(self.results)) } end, }, -- CDP ['^AAAA..00000C2000'] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, getAddresses = function(data) local ipOps = require("ipOps") local pos, proto_type, proto_len, addr_proto, addr_len, dev_addr, count local addr_list = '' pos, count = bin.unpack(">I", data) for i=1, count do pos, proto_type, proto_len = bin.unpack(">CC", data, pos) pos, addr_proto = bin.unpack(">H" .. proto_len, data, pos) if ( addr_proto == 'CC' ) then -- IPv4 address, extract it pos, addr_len = bin.unpack(">S", data, pos) pos, dev_addr = bin.unpack("<I", data, pos) addr_list = addr_list .. ' ' .. ipOps.fromdword(dev_addr) end -- Add code here for IPv6, others end return addr_list end, process = function(self, data) local pos, ver, ttl, chk = bin.unpack(">CCS", data, 9) if ( ver ~= 2 ) then return end if ( not(self.results) ) then self.results = tab.new(5) tab.addrow( self.results, 'ip', 'id', 'platform', 'version', 'notes' ) end local result_part = {} result_part.notes = '' while ( pos < #data ) do local typ, len, typdata pos, typ, len = bin.unpack(">SS", data, pos) pos, typdata = bin.unpack("A" .. len - 4, data, pos) -- Device ID if ( typ == 1 ) then result_part.id = typdata -- Version elseif ( typ == 5 ) then result_part.version = typdata:match(", Version (.-),") -- Platform elseif ( typ == 6 ) then result_part.platform = typdata -- Address elseif ( typ == 2 ) then result_part.ip = self.getAddresses(typdata) elseif ( typ == 10) then local _, mgmt_vlan = bin.unpack(">S", data,pos - 2) result_part.notes = result_part.notes .. 'native vlan:' .. mgmt_vlan .. ' ' -- Management Address elseif ( typ == 22 ) then result_part.notes = result_part.notes .. 'mgmt ip:' .. self.getAddresses(typdata) .. ' ' -- TODO: add more decoding of types here ... end end -- TODO: add code for dups check if ( not(self.dups[result_part.ip]) ) then self.dups[result_part.ip] = true tab.addrow( self.results, result_part.ip, result_part.id, result_part.platform, result_part.version, result_part.notes ) end end, getResults = function(self) return { name = "CDP", (self.results and tab.dump(self.results) or "") } end, }, -- EIGRP Update ['0201....0000'] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local p = packet.Packet:new( layer3, #layer3 ) -- EIGRP is IP protocol 88 (0x58), so verify this if ( p.ip_p ~= 88 ) then return end local data = layer3:sub(p.ip_data_offset + 1) local eigrp = require("eigrp") local route_type, proto_name -- Extract the EIGRP header local response = eigrp.EIGRP.parse(data) if response then -- Iterate over tlv tables for _, tlv in pairs(response.tlvs) do if eigrp.EIGRP.isRoutingTLV(tlv.type) then if ( not(self.results) ) then self.results = tab.new(7) tab.addrow(self.results, 'Sender IP', 'AS#', 'Route Type', 'Destination', 'Next hop', 'Ext Protocol', 'Orig Router ID') end if tlv.type == 0x102 then route_type = "Internal" elseif tlv.type == 0x103 then route_type = "External" for name, value in pairs(eigrp.EXT_PROTO) do if value == tlv.eproto then proto_name = name break end end end if ( not(self.dups[("%s:%s:s:%s"):format(p.ip_src, response.as, tlv.type, tlv.dst)]) ) then if ( target.ALLOW_NEW_TARGETS ) then target.add(p.ip_src) end self.dups[("%s:%s:%s:%s"):format(p.ip_src, response.as, tlv.type, tlv.dst)] = true tab.addrow( self.results, p.ip_src, response.as, route_type, tlv.dst, tlv.nexth, proto_name or 'X', tlv.orouterid or 'X') end end end end end, getResults = function(self) return { name = "EIGRP Update", (self.results and tab.dump(self.results) or "") } end, }, ['0205....0000'] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local p = packet.Packet:new( layer3, #layer3 ) -- EIGRP is IP protocol 88 (0x58), so verify this if ( p.ip_p ~= 88 ) then return end local data = layer3:sub(p.ip_data_offset + 1) local eigrp = require("eigrp") -- Extract the EIGRP header local response = eigrp.EIGRP.parse(data) -- See if Software version TLV is included local swvertlv for num, tlv in pairs(response.tlvs) do if tlv.type == eigrp.TLV.SWVER then swvertlv = num end end if swvertlv then if ( not(self.results) ) then self.results = tab.new(5) tab.addrow(self.results, 'Sender IP', 'AS number', 'EIGRP version', 'IOS version') end if ( not(self.dups[("%s:%s"):format(p.ip_src,response.as)]) ) then if ( target.ALLOW_NEW_TARGETS ) then target.add(p.ip_src) end self.dups[("%s:%s"):format(p.ip_src,response.as)] = true tab.addrow( self.results, p.ip_src, response.as, response.tlvs[swvertlv].majv .. '.' .. response.tlvs[swvertlv].minv, response.tlvs[swvertlv].majtlv .. '.' .. response.tlvs[swvertlv].mintlv) end end end, getResults = function(self) return { name = "EIGRP Hello", (self.results and tab.dump(self.results) or "") } end, }, -- OSPF ['02010'] = { -- OSPFv2 Hello packet new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local p = packet.Packet:new( layer3, #layer3 ) -- IP Protocol is 89 for OSPF if p.ip_p ~= 89 then return end local ospf = require("ospf") local data = layer3:sub(p.ip_data_offset + 1) local header = ospf.OSPF.Header.parse(data) if header then if not(self.results) then self.results = tab.new(5) tab.addrow(self.results, 'Source IP', 'Router ID', 'Area ID', 'Auth Type', 'Password') end local srcip = p.ip_src local areaid = header.area_id local routerid = header.router_id local authtype = header.auth_type local authdata -- Format authentication type and data if header.auth_type == 0 then authtype = "None" authdata = '' elseif header.auth_type == 1 then authtype = "Password" authdata = header.auth_data.password elseif header.auth_type == 2 then authtype = "OSPF MD5" authdata = "" -- Not really helpful, as the MD5 -- is applied to the whole packet+password else -- Error stdnse.debug1("Unknown OSPF auth type %d", header.auth_type) return end if ( not(self.dups[("%s:%s"):format(routerid,areaid)]) ) then if ( target.ALLOW_NEW_TARGETS ) then target.add(routerid) end self.dups[("%s:%s"):format(routerid,areaid)] = true tab.addrow( self.results, srcip, routerid, areaid, authtype, authdata) end else return nil end end, getResults = function(self) return { name = "OSPF Hello", (self.results and tab.dump(self.results)) } end, }, }, udp = { -- DHCP [68] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, getOption = function(options, name) for _, v in ipairs(options) do if ( v.name == name ) then if ( type(v.value) == "table" ) then return stdnse.strjoin(", ", v.value) else return v.value end end end end, process = function(self, layer3) local dhcp = require("dhcp") local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) -- the dhcp.parse function isn't optimal for doing -- this, but it will do for now. First, we need to -- extract the xid as the parse function checks that it -- was the same as in the request, which we didn't do. local pos, msgtype, _, _, _, xid = bin.unpack("<CCCCA4", data) -- attempt to parse the data local status, result = dhcp.dhcp_parse(data, xid) if ( status ) then if ( not(self.results) ) then self.results = tab.new(6) tab.addrow(self.results, "srv ip", "cli ip", "mask", "gw", "dns", "vendor" ) end local uniq_key = ("%s:%s"):format(p.ip_src, result.yiaddr_str) if ( not(self.dups[uniq_key]) ) then if ( target.ALLOW_NEW_TARGETS ) then target.add(p.ip_src) end local mask = self.getOption(result.options, "Subnet Mask") or "-" local gw = self.getOption(result.options, "Router") or "-" local dns = self.getOption(result.options, "Domain Name Server") or "-" local vendor = self.getOption(result.options, "Class Identifier") or "-" stdnse.debug1("Decoded DHCP: %s, %s, %s, %s, %s, %s", p.ip_src, result.yiaddr_str, mask, gw, dns, vendor) tab.addrow(self.results, p.ip_src, result.yiaddr_str, mask, gw, dns, vendor ) end end end, getResults = function(self) return { name = "DHCP", (self.results and tab.dump(self.results) or "") } end, }, -- Netbios [137] = { new = function(self) local o = { reg_dups = {}, query_dups = {}, reg_result = tab.new(2), query_result = tab.new(2) } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local dns = require('dns') local bin = require('bin') local netbios = require('netbios') local tab = require('tab') local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) local dresp = dns.decode(data) if ( not(dresp.questions) or #dresp.questions < 1 ) then return end local name = netbios.name_decode("\32" .. dresp.questions[1].dname) local function add_record(isreg, ip, name) local res = (isreg and self.reg_result or self.query_result) local dup = (isreg and self.reg_dups or self.query_dups) if ( #res == 0 ) then tab.addrow(res, 'ip', 'query') end stdnse.debug1('Decoded Netbios(%s): %s, %s', (isreg and "Registration" or "Query"), ip, name) if ( not(dup[ip]) or not(dup[ip][name]) ) then if ( target.ALLOW_NEW_TARGETS ) then target.add(p.ip_src) end tab.addrow(res, ip, name) dup[ip] = dup[ip] or {} dup[ip][name] = true end end add_record( ( dresp.flags.OC2 and dresp.flags.OC4 ), p.ip_src, name ) end, getResults = function(self) local result = { name = "Netbios" } if ( #self.reg_result > 1) then table.insert(result, { name = "Registrations", tab.dump(self.reg_result) }) end if ( #self.query_result > 1 ) then table.insert(result, { name = "Query", tab.dump(self.query_result) }) end return result end, }, -- BROWSER [138] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local bin = require('bin') local netbios = require('netbios') local tab = require('tab') local ipOps = require("ipOps") local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) local pos, ip, _, src, dst = 5 pos, ip, _, _, _, src, dst = bin.unpack("<ISSSA34A34", data, pos) ip = ipOps.fromdword(ip) src = netbios.name_decode(src) dst = netbios.name_decode(dst) stdnse.debug1("Decoded BROWSER: %s, %s, %s", ip, src, dst) local dup_rec = ("%s:%s:%s"):format(ip, src, dst) if ( not(self.dups[dup_rec]) ) then self.dups[dup_rec] = true if ( not(self.results) ) then self.results = tab.new(3) tab.addrow(self.results, 'ip', 'src', 'dst') end tab.addrow(self.results, ip, src, dst) end end, getResults = function(self) return { name = "Browser", (self.results and tab.dump(self.results)) } end, }, -- DHCPv6 [547] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local tab = require('tab') local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) local dhcpv6 = require("dhcp6") local resp = dhcpv6.DHCP6.Response.parse(data) for _, v in ipairs(resp.opts or {}) do if v.resp and v.resp.fqdn then if ( not(self.results) ) then self.results = tab.new(2) tab.addrow(self.results, 'ip', 'fqdn') end if ( not(self.dups[p.ip_src]) or not(self.dups[p.ip_src][v.resp.fqdn]) ) then tab.addrow(self.results, p.ip_src, v.resp.fqdn ) self.dups[p.ip_src] = self.dups[p.ip_src] or {} self.dups[p.ip_src][v.resp.fqdn] = true end end end end, getResults = function(self) return { name = "DHCP6", (self.results and tab.dump(self.results)) } end, }, -- CUPS [631] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local tab = require('tab') local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) local function split(str) local start, pos, stop = 1, 1 local pattern = "" local result = {} while(pos) do start = pos + #pattern pos, stop = str:find("\"", start) pattern = (pos == start and "\" " or " ") pos, stop = str:find(pattern, start + 1) table.insert(result, str:sub(start, (stop and stop - (#pattern)))) end return ( #result > 0 and result or nil ) end local results = split(data) local uri = ( #results > 3 and results[3]:match('[^%"]+') ) local loc = ( #results > 4 and results[4]:match('[^%"]+') or "") local info = ( #results > 5 and results[5]:match('[^%"]+') or "") local model = ( #results > 6 and results[6]:match('[^%"]+') or "") if ( not(self.results) ) then self.results = tab.new(4) tab.addrow(self.results, 'ip', 'uri', 'loc', 'model') end stdnse.debug1("Decoded CUPS: %s, %s, %s, %s", p.ip_src, uri, loc, model) if ( not(self.dups[p.ip_src]) or not(self.dups[p.ip_src][uri]) ) then tab.addrow(self.results, p.ip_src, uri, loc, model) self.dups[p.ip_src] = self.dups[p.ip_src] or {} self.dups[p.ip_src][uri] = self.dups[p.ip_src][uri] or true end end, getResults = function(self) return { name = "CUPS", (self.results and tab.dump(self.results)) } end, }, -- SSDP [1900] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) local headers = stdnse.strsplit("\r\n", data) for _, h in ipairs(headers) do local st = "" if ( h:match("^ST:.*") ) then st = h:match("^ST:(.*)") if ( not(self.results) ) then self.results = tab.new(1) tab.addrow( self.results, 'ip', 'uri' ) end if ( not(self.dups[("%s:%s"):format(p.ip_src,st)]) ) then if ( target.ALLOW_NEW_TARGETS ) then target.add(p.ip_src) end tab.addrow( self.results, p.ip_src, st ) self.dups[("%s:%s"):format(p.ip_src,st)] = true end end end end, getResults = function(self) return { name = "SSDP", (self.results and tab.dump(self.results)) } end, }, --- HSRP [1985] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) local ipOps = require("ipOps") local State = { [0] = "Initial", [1] = "Learn", [2] = "Listen", [4] = "Speak", [8] = "Standby", [16] = "Active" } local Op = { [0] = "Hello", [1] = "Coup", [2] = "Resign", } local pos, version, op, state, _, _, prio, group, _, secret = bin.unpack("CCCCCCCCz", data) if ( version ~= 0 ) then return end pos = pos + ( 7 - #secret ) local virtip pos, virtip = bin.unpack("<I", data, pos) if ( not(self.dups[p.ip_src]) ) then if ( not(self.results) ) then self.results = tab.new(7) tab.addrow(self.results, 'ip', 'version', 'op', 'state', 'prio', 'group', 'secret', 'virtual ip') end if ( target.ALLOW_NEW_TARGETS ) then target.add(p.ip_src) end self.dups[p.ip_src] = true tab.addrow(self.results, p.ip_src, version, Op[op], State[state], prio, group, secret, ipOps.fromdword(virtip)) end end, getResults = function(self) return { name = "HSRP", (self.results and tab.dump(self.results) or "") } end, }, -- Dropbox [17500] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local json = require("json") local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) local status, info = json.parse(data) if ( not(status) ) then return false, "Failed to parse JSON data" end -- Add host to list. for _, key1 in pairs({"namespaces", "version"}) do for key2, val in pairs(info[key1]) do info[key1][key2] = tostring(info[key1][key2]) end end if ( not(self.results) ) then self.results = tab.new(6) tab.addrow( self.results, 'displayname', 'ip', 'port', 'version', 'host_int', 'namespaces' ) end if ( not(self.dups[p.ip_src]) ) then tab.addrow( self.results, info.displayname, p.ip_src, info.port, stdnse.strjoin(".", info.version), info.host_int, stdnse.strjoin(", ", info.namespaces) ) self.dups[p.ip_src] = true if ( target.ALLOW_NEW_TARGETS ) then target.add(p.ip_src) end end end, getResults = function(self) return { name = "DropBox", (self.results and tab.dump(self.results) or "") } end, }, --- Squeezebox Discovery [3483] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) if ( data:match("^eIPAD") ) then if ( not(self.results) ) then self.results = tab.new(1) tab.addrow( self.results, 'ip' ) end if ( not(self.dups[p.ip_src]) ) then tab.addrow( self.results, p.ip_src ) self.dups[p.ip_src] = true if ( target.ALLOW_NEW_TARGETS ) then target.add(p.ip_src) end end end end, getResults = function(self) return { name = "Squeezebox Discovery", (self.results and tab.dump(self.results) or "") } end, }, -- Multicast DNS/BonJour/ZeroConf [5353] = { new = function(self) local o = { dups = {}, macbooks = {}, generic = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local dns = require('dns') local bin = require('bin') local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) local dresp = dns.decode(data) local name if ( dresp.questions and #dresp.questions > 0 ) then name = dresp.questions[1].dname elseif ( dresp.answers and #dresp.answers > 0 ) then -- Identify MacBooks local macbook, model, ip, ipv6 if ( p.ip_src:match(":") ) then ipv6 = p.ip_src else ip = p.ip_src end for i in ipairs(dresp.answers) do if ( dresp.answers[i]['data'] ) then local _, data = bin.unpack("p", dresp.answers[i]['data']) if ( data ) then model = data:match("^model=(.*)") if ( model ) then macbook = dresp.answers[i]['dname']:match("^(.-)%._") end end elseif ( dresp.answers[i]['ip'] ) then ip = dresp.answers[i]['ip'] elseif ( dresp.answers[i]['ipv6'] ) then ipv6 = dresp.answers[i]['ipv6'] elseif ( not(macbook) and dresp.answers[i]['domain'] ) then macbook = dresp.answers[i]['domain'] end end if ( macbook and model ) then self.macbooks[macbook] = self.macbooks[macbook] or {} self.macbooks[macbook]['macbook'] = self.macbooks[macbook]['macbook'] or macbook self.macbooks[macbook]['model'] = self.macbooks[macbook]['model'] or model self.macbooks[macbook]['ip'] = self.macbooks[macbook]['ip'] or ip self.macbooks[macbook]['ipv6'] = self.macbooks[macbook]['ipv6'] or ipv6 stdnse.debug1("Decoded MDNS(MacBook): %s, %s, %s, %s", (self.macbooks[macbook]['ip'] or ""), (self.macbooks[macbook]['ipv6'] or ""), self.macbooks[macbook]['model'], self.macbooks[macbook]['macbook']) else name = dresp.answers[1].dname if ( not(name) ) then return end self.generic[name] = self.generic[name] or {} self.generic[name]['name'] = self.generic[name]['name'] or name if ( p.ip_src:match(":") ) then self.generic[name]['ipv6'] = p.ip_src else self.generic[name]['ip'] = p.ip_src end stdnse.debug1("Decoded MDNS(Generic): %s, %s", name, p.ip_src) end end end, getResults = function(self) local tab = require('tab') local result = { name = "MDNS" } -- build a macbooks table local macbooks, generic if ( next(self.generic) ) then table.sort(self.generic) generic = tab.new(3) tab.addrow(generic, 'ip', 'ipv6', 'name') for name, v in pairs(self.generic) do tab.addrow(generic, (v.ip or ""), (v.ipv6 or ""), name) end table.insert(result, { name = 'Generic', tab.dump(generic) } ) end if ( next(self.macbooks) ) then table.sort(self.macbooks) macbooks = tab.new(4) tab.addrow(macbooks, 'ip', 'ipv6', 'name', 'model') for _, v in pairs(self.macbooks) do tab.addrow(macbooks, (v.ip or ""), (v.ipv6 or ""), v.macbook, v.model) end table.insert(result, { name = 'Macbooks', tab.dump(macbooks) } ) end return result end, }, [5355] = { -- LLMNR new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local tab = require('tab') local dns = require('dns') local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) local resp = dns.decode(data) if ( not(self.results) ) then self.results = tab.new(2) tab.addrow(self.results, 'ip', 'query') end local name = (( resp.questions and #resp.questions > 0 ) and resp.questions[1].dname ) if ( not(name) ) then return end stdnse.debug1("Decoded LLMNR: %s, %s", p.ip_src, name) if ( not(self.dups[("%s:%s"):format(p.ip_src, name)]) ) then self.dups[("%s:%s"):format(p.ip_src, name)] = true tab.addrow(self.results, p.ip_src, name) end end, getResults = function(self) return { name = "LLMNR", (self.results and tab.dump(self.results)) } end, }, --- Spotify [57621] = { new = function(self) local o = { dups = {} } setmetatable(o, self) self.__index = self return o end, process = function(self, layer3) local p = packet.Packet:new( layer3, #layer3 ) local data = layer3:sub(p.udp_offset + 9) if ( data:match("^SpotUdp") ) then if ( not(self.results) ) then self.results = tab.new(1) tab.addrow( self.results, 'ip' ) end if ( not(self.dups[p.ip_src]) ) then tab.addrow( self.results, p.ip_src ) self.dups[p.ip_src] = true if ( target.ALLOW_NEW_TARGETS ) then target.add(p.ip_src) end end end end, getResults = function(self) return { name = "Spotify", (self.results and tab.dump(self.results)) } end, } } }
function onUse(player, item, fromPosition, target, toPosition, isHotkey) if player:getStorageValue(Storage.GravediggerOfDrefia.Mission69) == 1 and player:getStorageValue(Storage.GravediggerOfDrefia.Mission70) < 1 then player:setStorageValue(Storage.GravediggerOfDrefia.Mission70, 1) player:sendTextMessage(MESSAGE_EVENT_ADVANCE, 'You have found a crumpled paper.') player:addItem(21474, 1) end return true end
CloneClass( WeaponTweakData ) Hooks:RegisterHook("WeaponTweakDataPostInit") function WeaponTweakData.init(self, tweak_data) self.orig.init(self, tweak_data) Hooks:Call("WeaponTweakDataPostInit", self, tweak_data) end Hooks:RegisterHook("WeaponTweakDataPostInitPlayerWeaponData") function WeaponTweakData._init_data_player_weapons(self, tweak_data) self.orig._init_data_player_weapons(self, tweak_data) Hooks:Call("WeaponTweakDataPostInitPlayerWeaponData", self, tweak_data) end Hooks:RegisterHook("WeaponTweakDataPostInitNewWeapons") function WeaponTweakData._init_new_weapons(self, autohit_rifle_default, autohit_pistol_default, autohit_shotgun_default, autohit_lmg_default, autohit_snp_default, autohit_smg_default, autohit_minigun_default, damage_melee_default, damage_melee_effect_multiplier_default, aim_assist_rifle_default, aim_assist_pistol_default, aim_assist_shotgun_default, aim_assist_lmg_default, aim_assist_snp_default, aim_assist_smg_default, aim_assist_minigun_default) self.orig._init_new_weapons(self, autohit_rifle_default, autohit_pistol_default, autohit_shotgun_default, autohit_lmg_default, autohit_snp_default, autohit_smg_default, autohit_minigun_default, damage_melee_default, damage_melee_effect_multiplier_default, aim_assist_rifle_default, aim_assist_pistol_default, aim_assist_shotgun_default, aim_assist_lmg_default, aim_assist_snp_default, aim_assist_smg_default, aim_assist_minigun_default) Hooks:Call("WeaponTweakDataPostInitNewWeapons", self, autohit_rifle_default, autohit_pistol_default, autohit_shotgun_default, autohit_lmg_default, autohit_snp_default, autohit_smg_default, autohit_minigun_default, damage_melee_default, damage_melee_effect_multiplier_default, aim_assist_rifle_default, aim_assist_pistol_default, aim_assist_shotgun_default, aim_assist_lmg_default, aim_assist_snp_default, aim_assist_smg_default, aim_assist_minigun_default) end
local robot = require('robot'); local tcp = require('tcp'); local orient = require('trackOrientation'); local config = require('config'); local confOptions = config.get(config.path); local position = { x = tonumber(confOptions.posX), y = tonumber(confOptions.posY), z = tonumber(confOptions.posZ), }; local M = {}; function M.save() local posConf = { posX = position.x, posY = position.y, posZ = position.z, }; config.set(posConf, config.path); end function M.load() local confOptions = config.get(config.path); position = { x = tonumber(confOptions.posX), y = tonumber(confOptions.posY), z = tonumber(confOptions.posZ), }; end function M.set(x, y, z) position = {x=x, y=y, z=z}; return position; end function M.get() return position; end -- how to change coordinates based on orientation -- 0: z+, south -- 1: x+, east -- 2: z-, north -- 3: x-, west local forwardMap = { [0]={z=1}, [1]={x=1}, [2]={z=-1}, [3]={x=-1} }; local backwardMap = { [0]={z=-1}, [1]={x=-1}, [2]={z=1}, [3]={x=1} }; function M.sendLocation() return tcp.write({['robot position']=position}); end -- don't stop using these functions once you start or they won't be accurate -- orientation comes from trackOrientation.lua function M.forward() -- the loop will only perform one iteration -- this is just a way to treat the properties generically if (robot.forward()) then for axis, change in pairs(forwardMap[orient.get()]) do position[axis] = position[axis] + change; end M.sendLocation(); return position; end -- if the movement failed return false; end function M.back() if (robot.back()) then for axis, change in pairs(backwardMap[orient.get()]) do position[axis] = position[axis] + change; end M.sendLocation(); return position; end return false; end function M.up() if (robot.up()) then position.y = position.y + 1; M.sendLocation(); return position; end return false; end function M.down() if (robot.down()) then position.y = position.y - 1; M.sendLocation(); return position; end return false; end return M;
require 'funcs' local GameMode = require 'tetris.modes.gamemode' local Piece = require 'tetris.components.piece' local History6RollsRandomizer = require 'tetris.randomizers.history_6rolls' local MarathonA2Game = GameMode:extend() MarathonA2Game.name = "Big A2" MarathonA2Game.hash = "BigA2" MarathonA2Game.tagline = "The points don't matter! Can you reach the invisible roll? Big mode too!" function MarathonA2Game:new() self.super:new() self.big_mode = true self.roll_frames = 0 self.combo = 1 self.grade = 0 self.grade_points = 0 self.grade_point_decay_counter = 0 self.randomizer = History6RollsRandomizer() self.lock_drop = false self.lock_hard_drop = false self.enable_hold = false self.next_queue_length = 1 end function MarathonA2Game:getARE() if self.level < 700 then return 27 elseif self.level < 800 then return 18 else return 14 end end function MarathonA2Game:getLineARE() if self.level < 600 then return 27 elseif self.level < 700 then return 18 elseif self.level < 800 then return 14 else return 8 end end function MarathonA2Game:getDasLimit() if self.level < 500 then return 15 elseif self.level < 900 then return 9 else return 7 end end function MarathonA2Game:getLineClearDelay() if self.level < 500 then return 40 elseif self.level < 600 then return 25 elseif self.level < 700 then return 16 elseif self.level < 800 then return 12 else return 6 end end function MarathonA2Game:getLockDelay() if self.level < 900 then return 30 else return 17 end end function MarathonA2Game:getGravity() if (self.level < 30) then return 4/256 elseif (self.level < 35) then return 6/256 elseif (self.level < 40) then return 8/256 elseif (self.level < 50) then return 10/256 elseif (self.level < 60) then return 12/256 elseif (self.level < 70) then return 16/256 elseif (self.level < 80) then return 32/256 elseif (self.level < 90) then return 48/256 elseif (self.level < 100) then return 64/256 elseif (self.level < 120) then return 80/256 elseif (self.level < 140) then return 96/256 elseif (self.level < 160) then return 112/256 elseif (self.level < 170) then return 128/256 elseif (self.level < 200) then return 144/256 elseif (self.level < 220) then return 4/256 elseif (self.level < 230) then return 32/256 elseif (self.level < 233) then return 64/256 elseif (self.level < 236) then return 96/256 elseif (self.level < 239) then return 128/256 elseif (self.level < 243) then return 160/256 elseif (self.level < 247) then return 192/256 elseif (self.level < 251) then return 224/256 elseif (self.level < 300) then return 1 elseif (self.level < 330) then return 2 elseif (self.level < 360) then return 3 elseif (self.level < 400) then return 4 elseif (self.level < 420) then return 5 elseif (self.level < 450) then return 4 elseif (self.level < 500) then return 3 else return 20 end end function MarathonA2Game:advanceOneFrame() if self.clear then self.roll_frames = self.roll_frames + 1 if self.roll_frames < 0 then return false end if self.roll_frames > 3694 then self.completed = true end elseif self.ready_frames == 0 then self.frames = self.frames + 1 end return true end function MarathonA2Game:onPieceEnter() if (self.level % 100 ~= 99 and self.level ~= 998) and not self.clear and self.frames ~= 0 then self.level = self.level + 1 end end function MarathonA2Game:onLineClear(cleared_row_count) cleared_row_count = cleared_row_count / 2 self.level = math.min(self.level + cleared_row_count, 999) if self.level == 999 and not self.clear then self.clear = true self.grid:clear() self.roll_frames = -150 end self.lock_drop = self.level >= 900 self.lock_hard_drop = self.level >= 900 end function MarathonA2Game:updateScore(level, drop_bonus, cleared_lines) if not self.clear then cleared_lines = cleared_lines / 2 self:updateGrade(cleared_lines) if self.grid:checkForBravo(cleared_lines) then self.bravo = 4 else self.bravo = 1 end if cleared_lines > 0 then self.combo = self.combo + (cleared_lines - 1) * 2 self.score = self.score + ( (math.ceil((level + cleared_lines) / 4) + drop_bonus) * cleared_lines * self.combo * self.bravo ) else self.combo = 1 end self.drop_bonus = 0 end end local grade_point_bonuses = { {10, 20, 40, 50}, {10, 20, 30, 40}, {10, 20, 30, 40}, {10, 15, 30, 40}, {10, 15, 20, 40}, {5, 15, 20, 30}, {5, 10, 20, 30}, {5, 10, 15, 30}, {5, 10, 15, 30}, {5, 10, 15, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, {2, 12, 13, 30}, } local grade_point_decays = { 125, 80, 80, 50, 45, 45, 45, 40, 40, 40, 40, 40, 30, 30, 30, 20, 20, 20, 20, 20, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 10, 10 } local combo_multipliers = { {1.0, 1.0, 1.0, 1.0}, {1.2, 1.4, 1.5, 1.0}, {1.2, 1.5, 1.8, 1.0}, {1.4, 1.6, 2.0, 1.0}, {1.4, 1.7, 2.2, 1.0}, {1.4, 1.8, 2.3, 1.0}, {1.4, 1.9, 2.4, 1.0}, {1.5, 2.0, 2.5, 1.0}, {1.5, 2.1, 2.6, 1.0}, {2.0, 2.5, 3.0, 1.0}, } local grade_conversion = { [0] = 0, 1, 2, 3, 4, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 11, 12, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17 } function MarathonA2Game:updateGrade(cleared_lines) if self.clear then return end if cleared_lines == 0 then self.grade_point_decay_counter = self.grade_point_decay_counter + 1 if self.grade_point_decay_counter >= grade_point_decays[self.grade + 1] then self.grade_point_decay_counter = 0 self.grade_points = math.max(0, self.grade_points - 1) end else self.grade_points = self.grade_points + ( math.ceil( grade_point_bonuses[self.grade + 1][cleared_lines] * combo_multipliers[math.min(self.combo, 10)][cleared_lines] ) * (1 + math.floor(self.level / 250)) ) if self.grade_points >= 100 and self.grade < 31 then self.grade_points = 0 self.grade = self.grade + 1 end end end function MarathonA2Game:getLetterGrade() local grade = grade_conversion[self.grade] if grade < 9 then return tostring(9 - grade) elseif grade < 18 then return "S" .. tostring(grade - 8) end end MarathonA2Game.rollOpacityFunction = function(age) if age < 240 then return 1 elseif age > 300 then return 0 else return 1 - (age - 240) / 60 end end function MarathonA2Game:drawGrid(ruleset) if self.clear and not (self.completed or self.game_over) then self.grid:drawInvisible(self.rollOpacityFunction, nil, false) else self.grid:draw() if self.piece ~= nil and self.level < 100 then self:drawGhostPiece(ruleset) end end end function MarathonA2Game:drawScoringInfo() love.graphics.setColor(1, 1, 1, 1) love.graphics.setFont(font_3x5_2) love.graphics.print( self.das.direction .. " " .. self.das.frames .. " " .. strTrueValues(self.prev_inputs) ) love.graphics.printf("NEXT", 64, 40, 40, "left") love.graphics.printf("GRADE", 240, 120, 40, "left") love.graphics.printf("SCORE", 240, 200, 40, "left") love.graphics.printf("LEVEL", 240, 320, 40, "left") love.graphics.setFont(font_3x5_3) if self.roll_frames > 3694 then love.graphics.setColor(1, 0.5, 0, 1) elseif self.clear then love.graphics.setColor(0, 1, 0, 1) end love.graphics.printf(self:getLetterGrade(), 240, 140, 90, "left") love.graphics.setColor(1, 1, 1, 1) love.graphics.printf(self.score, 240, 220, 90, "left") love.graphics.printf(self.level, 240, 340, 40, "right") love.graphics.printf(self:getSectionEndLevel(), 240, 370, 40, "right") love.graphics.setFont(font_8x11) love.graphics.printf(formatTime(self.frames), 64, 420, 160, "center") end function MarathonA2Game:getHighscoreData() return { grade = grade_conversion[self.grade], score = self.score, level = self.level, frames = self.frames, } end function MarathonA2Game:getSectionEndLevel() if self.level >= 900 then return 999 else return math.floor(self.level / 100 + 1) * 100 end end function MarathonA2Game:getBackground() return math.floor(self.level / 100) end return MarathonA2Game
minetest.register_node("farming_plus:cocoa_sapling", { description = "Cocoa Tree Sapling", drawtype = "plantlike", tiles = {"farming_cocoa_sapling.png"}, inventory_image = "farming_cocoa_sapling.png", wield_image = "farming_cocoa_sapling.png", paramtype = "light", walkable = false, groups = {dig_immediate=3,flammable=2}, sounds = default.node_sound_defaults(), }) minetest.register_node("farming_plus:cocoa_leaves", { drawtype = "allfaces_optional", tiles = {"farming_banana_leaves.png"}, paramtype = "light", groups = {snappy=3, leafdecay=3, flammable=2, not_in_creative_inventory=1}, drop = { max_items = 1, items = { { items = {'farming_plus:cocoa_sapling'}, rarity = 20, }, } }, sounds = default.node_sound_leaves_defaults(), }) minetest.register_abm({ nodenames = {"farming_plus:cocoa_sapling"}, interval = 60, chance = 20, action = function(pos, node) farming:generate_tree(pos, "default:tree", "farming_plus:cocoa_leaves", {"default:sand", "default:desert_sand"}, {["farming_plus:cocoa"]=20}) end }) minetest.register_on_generated(function(minp, maxp, blockseed) if math.random(1, 100) > 5 then return end local tmp = {x=(maxp.x-minp.x)/2+minp.x, y=(maxp.y-minp.y)/2+minp.y, z=(maxp.z-minp.z)/2+minp.z} local pos = minetest.env:find_node_near(tmp, maxp.x-minp.x, {"default:desert_sand"}) if pos ~= nil then farming:generate_tree({x=pos.x, y=pos.y+1, z=pos.z}, "default:tree", "farming_plus:cocoa_leaves", {"default:sand", "default:desert_sand"}, {["farming_plus:cocoa"]=20}) end end) minetest.register_node("farming_plus:cocoa", { description = "Cocoa", tiles = {"farming_cocoa.png"}, visual_scale = 0.5, inventory_image = "farming_cocoa.png", wield_image = "farming_cocoa.png", drawtype = "torchlike", paramtype = "light", sunlight_propagates = true, walkable = false, groups = {fleshy=3,dig_immediate=3,flammable=2}, sounds = default.node_sound_defaults(), }) minetest.register_craftitem("farming_plus:cocoa_bean", { description = "Cocoa Bean", inventory_image = "farming_cocoa_bean.png", }) minetest.register_craft({ output = "farming_plus:cocoa_bean 10", type = "shapeless", recipe = {"farming_plus:cocoa"}, })
project "Sandbox" --kind "WindowedApp" kind "ConsoleApp" entrypoint "mainCRTStartup" language "C++" cppdialect "C++17" staticruntime "off" targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}") objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}") files { "src/**.h", "src/**.cpp" } includedirs { "%{wks.location}/Atlas/vendor/spdlog/include", "%{wks.location}/Atlas/src", "%{wks.location}/Atlas/vendor", "%{IncludeDir.glm}", } links { "Atlas", } filter "system:windows" systemversion "latest" defines { "ATL_PLATFORM_WINDOWS" } filter "configurations:Debug" defines "ATL_DEBUG" runtime "Debug" symbols "on" filter "configurations:Release" defines "ATL_RELEASE" runtime "Release" optimize "on" filter "configurations:Dist" defines "ATL_DIST" runtime "Release" optimize "on"
local L = BigWigs:NewBossLocale("Eye of Azshara Trash", "deDE") if not L then return end if L then L.wrangler = "Zänker der Hassnattern" L.stormweaver = "Sturmwirkerin der Hassnattern" L.crusher = "Zermalmer der Hassnattern" L.oracle = "Orakel der Hassnattern" L.siltwalker = "Treibsandläufer der Mak'rana" L.tides = "Aufgewühlte Fluten" L.arcanist = "Arkanistin der Hassnattern" end L = BigWigs:NewBossLocale("Lady Hatecoil", "deDE") if L then L.custom_on_show_helper_messages = "Hinweis für Statische Nova und Gebündelter Blitz" L.custom_on_show_helper_messages_desc = "Wenn diese Option aktiviert ist, wird ein Hinweis angezeigt, welcher beinhaltet ob das Wasser oder Land sicher ist wenn der Boss |cff71d5ffStatische Nova|r oder |cff71d5ffGebündelter Blitz|r wirkt." L.water_safe = "%s (Wasser ist sicher)" L.land_safe = "%s (Land ist sicher)" end
local Transition = {} Transition.__index = Transition function Transition.new(effect, duration) local trans = {} setmetatable(trans, Transition) trans.count = 0 trans.sign = 1 trans.effect = effect trans.duration = duration trans.callback = function() return nil end return trans end function Transition:finished() return self.count > self.duration end function Transition:forward(callback) self.callback = callback self.sign = 1 self.count = 0 self.alpha = 1 end function Transition:backward(callback) self.callback = callback self.sign = -1 self.count = 0 self.alpha = 0 end function Transition:update(dt) self.count = self.count + dt if self:finished() then self.callback() self.count = 0 return end if self.sign > 0 then self.alpha = 1.0 - math.min(self.count + (dt * 5), 1.0) else self.alpha = math.min(self.count + (dt * 5), 1.0) end end function Transition:draw(x, y, width, height) love.graphics.setColor(0, 0, 0, self.alpha * 255) love.graphics.rectangle('fill', x, y, width, height) love.graphics.setColor(255, 255, 255, 255) end return Transition
-- Controls for cmus music player -- Usage: local cmus = require "mjolnir.lb.cmus" -- Inspired by https://github.com/Linell/mjolnir.lb.spotify require 'os' local cmus = {} local alert = require "mjolnir.alert" function cmus.play() os.execute('/usr/local/bin/cmus-remote -u') alert.show('▶', 0.5) end function cmus.next() os.execute('/usr/local/bin/cmus-remote -n') alert.show('>', 0.5) end function cmus.previous() os.execute('/usr/local/bin/cmus-remote -r') alert.show('<', 0.5) end return cmus
-------------------------------------------------------------------------------- -- Handler.......... : onScoreUploaded -- Author........... : -- Description...... : -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function Steam.onScoreUploaded ( bOK ) -------------------------------------------------------------------------------- if bOK then log.message ( this.sDebugLabel ( ), "Score was uploaded!" ) -- -- Score upload was a success, remove the 4 past entries from the table -- table.removeFirst ( this.tPendingScores ( ) ) table.removeFirst ( this.tPendingScores ( ) ) -- Grab the AI and callback and send an event to them if they exist local sAI, sCallback = table.getRangeAt ( this.tPendingScores ( ), 0, 2 ) table.removeFirst ( this.tPendingScores ( ) ) table.removeFirst ( this.tPendingScores ( ) ) if sAI and sCallback then user.sendEvent ( this.getUser ( ), sAI, sCallback, bOK ) end else log.warning ( this.sDebugLabel ( ), "Could not upload score" ) local sAI, sCallback = table.getRangeAt ( this.tPendingScores ( ), 2, 2 ) if sAI and sCallback then user.sendEvent ( this.getUser ( ), sAI, sCallback, bOK ) end end -- -- Handle the next entries in the table and the clearing of the inUse flag -- if table.getSize ( this.tPendingScores ( ) ) > 1 then local sLeaderboardName, nScore = table.getRangeAt ( this.tPendingScores ( ), 0, 2 ) if this.sLeaderboardSelected ( ) ~= sLeaderboardName then log.message ( this.sDebugLabel ( ), "Selecting new leaderboard ", sLeaderboardName ) -- -- Request the leaderboard and wait for onFoundLeaderboard callback -- Steamworks.FindLeaderboard ( sLeaderboardName ) else log.message ( this.sDebugLabel ( ), "Uploading next score ", nScore ) -- -- The desired leaderboard is already selected, upload the score and -- wait for the onScoreUploaded callback -- Steamworks.UploadScore ( nScore ) end else this.bLeaderboardsInUse ( false ) end -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
-- Check a collection of quota counters to identify if an item should be rate -- limited. For each quota, repeat the same set of ``KEYS`` and ``ARGV``: -- -- ``KEYS`` (2 per quota): -- * [string] Key of the counter. -- * [string] Key of the refund counter. -- -- ``ARGV`` (3 per quota): -- * [number] Quota limit. Can be ``-1`` for unlimited quotas. -- * [number] Expiration time in seconds for the key. -- * [number] Quantity to increment the quota by. -- -- For example, to check the following two quotas each with a timeout of 10 minutes: -- * Key ``foo``, refund key ``foo_refund``, limit ``10``; quantity ``5`` -- * Key ``bar``, refund key ``bar_refund``, limit ``20``; quantity ``1`` -- -- Send these values: -- -- KEYS = {"foo", "foo_refund", "bar", "bar_refund"} -- ARGV = {10, 600, 5, 20, 600, 1} -- -- The script applies the following logic: -- * If all checks pass, the item is accepted and the counters for all quotas -- are incremented. -- * If any check fails, the item is rejected and the counters for all remain -- unchanged. -- -- The result is a Lua table/array (Redis multi bulk reply) that specifies -- whether or not the item was *rejected* based on the provided limit. assert(#KEYS % 2 == 0, "there must be 2 keys per quota") assert(#ARGV % 3 == 0, "there must be 3 args per quota") assert(#KEYS / 2 == #ARGV / 3, "incorrect number of keys and arguments provided") local results = {} local failed = false local num_quotas = #KEYS / 2 for i=0, num_quotas - 1 do local k = i * 2 + 1 local v = i * 3 + 1 local limit = tonumber(ARGV[v]) local quantity = tonumber(ARGV[v+2]) local rejected = false -- limit=-1 means "no limit" if limit >= 0 then rejected = (redis.call('GET', KEYS[k]) or 0) - (redis.call('GET', KEYS[k + 1]) or 0) + quantity > limit end if rejected then failed = true end results[i + 1] = rejected end if not failed then for i=0, num_quotas - 1 do local k = i * 2 + 1 local v = i * 3 + 1 redis.call('INCRBY', KEYS[k], ARGV[v + 2]) redis.call('EXPIREAT', KEYS[k], ARGV[v + 1]) end end return results
local skynet = require "skynet" local netpack = require "skynet.netpack" local socket = require "skynet.socket" local sproto = require "sproto" local sprotoloader = require "sprotoloader" local queue = require "skynet.queue" local cs = queue() local TAG = "Agent" local Agent = {} local host function Agent:onRequest(name, request) local pRet = skynet.call(self.m_pGateServiceMgr, "lua", "onReceivePackage", skynet.self(), name, request) end -- function Agent:onSendPackage(name, info) -- Log.d(TAG, "发送给玩家Agent[%s]", skynet.self()) -- Log.dump(TAG, info, name) -- if not self.m_pSocketfd or self.m_pSocketfd <= 0 then -- Log.d(TAG, "socketfd is not exit!") -- return -- end -- local pack = self.m_pSendPackage(name, info) -- local package = string.pack(">s2", pack) -- -- Log.d(TAG, "pack[%s] package[%s]", pack, package) -- socket.write(self.m_pSocketfd, package) -- end -- function Agent:onReceivePackage(type, ...) -- if self.m_pIsClosing then return end -- if type == "REQUEST" then -- self.m_pLastSendTime = os.time() -- local ok, result = pcall(self.onRequest, self, ...) -- if not ok then -- skynet.error(result) -- end -- else -- Log.e(TAG, "doesn't support request client") -- end -- end -- skynet.register_protocol { -- name = "client", -- id = skynet.PTYPE_CLIENT, -- unpack = function(msg, sz) -- return host:dispatch(msg, sz) -- end, -- dispatch = function(session, source, type, name, request, response) -- Log.d(TAG, "recieve session[%s] type[%s] name[%s]", session, type, name) -- if name then -- Log.dump(TAG, request, "request") -- cs(Agent.onReceivePackage, Agent, type, name, request, response) -- end -- end -- } function Agent:onSendPackage(name, info) Log.d(TAG, "发送给玩家Agent[%s]", skynet.self()) Log.dump(TAG, info, name) if not self.m_pSocketfd or self.m_pSocketfd <= 0 then Log.d(TAG, "socketfd is not exit!") return end local package = skynet.call(".pbc", "lua", "pack", "S2C.".. name, info) socket.write(self.m_pSocketfd, package) end function Agent:onReceivePackage(type, ...) if self.m_pIsClosing then return end if type == "REQUEST" then self.m_pLastSendTime = os.time() local ok, result = pcall(self.onRequest, self, ...) if not ok then skynet.error(result) end else Log.e(TAG, "doesn't support request client") end end skynet.register_protocol { name = "client", id = skynet.PTYPE_CLIENT, unpack = function(msg, sz) return skynet.tostring(msg, sz) end, dispatch = function(session, source, data) local type, name, request = skynet.call(".pbc", "lua", "unpack", data) Log.d(TAG, "recieve session[%s] type[%s] name[%s]", session, type, name) if name then Log.dump(TAG, request, "request") cs(Agent.onReceivePackage, Agent, type, name, request) end end } function Agent:onGetClientIp() return self.m_pClientIp end function Agent:start(conf) Log.dump(TAG, conf, "conf") host = sprotoloader.load(1):host("package") self.m_pSendPackage = host:attach(sprotoloader.load(2)) self.m_pGateServiceMgr = skynet.localname(".GateServiceMgr") local pSplitTable = string.split(conf.iAddr, ":") -- Log.dump(TAG, pSplitTable, "pSplitTable") self.m_pClientIp = pSplitTable[1] or "" self.m_pLastSendTime = os.time() self.m_pSocketfd = conf.iSocketfd self.m_pWatchdog = conf.iWatchdog local pRet = skynet.call(self.m_pGateServiceMgr, "lua", "onRegisterAgent", skynet.self()) local pRet = skynet.call(conf.iGate, "lua", "forward", self.m_pSocketfd) end function Agent:disconnect() cs(function() Log.d(TAG, "disconnect Agent[%s]", skynet.self()) skynet.call(self.m_pGateServiceMgr, "lua", "onDisConnect", skynet.self(), false) skynet.exit() end) end --! --! @brief 主动关闭agent,断开链接 --! --! @return { description_of_the_return_value } --! function Agent:close() if not self.m_pIsClosing then self.m_pIsClosing = true skynet.send(self.m_pWatchdog, "lua", "socket", "close", self.m_pSocketfd) end return end function Agent:onCheckTooTimeNotActive() -- 如果1分钟内没有包通信则直接断开 local pCurTime = os.time() if self.m_pLastSendTime > 0 then if pCurTime - self.m_pLastSendTime > 60 then self:close() end end end skynet.start(function() skynet.dispatch("lua", function(_, _, command, ...) local f = Agent[command] Log.d(TAG, "command[%s]", command) if f then skynet.ret(skynet.pack(f(Agent, ...))) end end) end)
-- -*- coding: utf-8 -*- local ngx_loggers = require "logdumper" local funcall = ngx_loggers:LogDumper()
local Path = require("plenary.path") local utils = require("neo-tree.utils") local events = require("neo-tree.events") local Job = require("plenary.job") local log = require("neo-tree.log") local git_utils = require("neo-tree.git.utils") local M = {} local function get_simple_git_status_code(status) -- Prioritze M then A over all others if status:match("U") or status == "AA" or status == "DD" then return "U" elseif status:match("M") then return "M" elseif status:match("[ACR]") then return "A" elseif status:match("!$") then return "!" elseif status:match("?$") then return "?" else local len = #status while len > 0 do local char = status:sub(len, len) if char ~= " " then return char end len = len - 1 end return status end end local function get_priority_git_status_code(status, other_status) if not status then return other_status elseif not other_status then return status elseif status == "U" or other_status == "U" then return "U" elseif status == "?" or other_status == "?" then return "?" elseif status == "M" or other_status == "M" then return "M" elseif status == "A" or other_status == "A" then return "A" else return status end end local parse_git_status_line = function(context, line) local git_root = context.git_root local git_status = context.git_status local exclude_directories = context.exclude_directories local status = line:sub(1, 2) local relative_path = line:sub(4) local arrow_pos = relative_path:find(" -> ") if arrow_pos ~= nil then relative_path = line:sub(arrow_pos + 5) end -- remove any " due to whitespace in the path relative_path = relative_path:gsub('^"', ""):gsub('$"', "") if utils.is_windows == true then relative_path = utils.windowize_path(relative_path) end local absolute_path = utils.path_join(git_root, relative_path) git_status[absolute_path] = status if not exclude_directories then -- Now bubble this status up to the parent directories local parts = utils.split(absolute_path, utils.path_separator) table.remove(parts) -- pop the last part so we don't override the file's status utils.reduce(parts, "", function(acc, part) local path = acc .. utils.path_separator .. part if utils.is_windows == true then path = path:gsub("^" .. utils.path_separator, "") end local path_status = git_status[path] local file_status = get_simple_git_status_code(status) git_status[path] = get_priority_git_status_code(path_status, file_status) return path end) end end local parse_git_status = function(git_root, result, exclude_directories) local context = { git_root = git_root, git_status = {}, exclude_directories = exclude_directories, } for _, line in ipairs(result) do parse_git_status_line(context, line) end return context.git_status end ---Parse "git status" output for the current working directory. ---@exclude_directories boolean Whether to skip bubling up status to directories ---@path string Path to run the git status command in, defaults to cwd. ---@return table table Table with the path as key and the status as value. ---@return string string The git root for the specified path. M.status = function(exclude_directories, path) local cmd local git_root = git_utils.get_repository_root(path) if utils.truthy(git_root) then cmd = 'git -C "' .. git_root .. '" status . --porcelain=v1' else return {} end local ok, result = utils.execute_command(cmd) if not ok then return {} end local git_status = parse_git_status(git_root, result, exclude_directories) return git_status, git_root end M.status_async = function(path) local git_root = git_utils.get_repository_root(path) if utils.truthy(git_root) then log.trace("git.status.status_async called") else log.trace("status_async: not a git folder: ", path) return false end local context = { git_root = git_root, git_status = {}, exclude_directories = false, } local wrapped_process_line = vim.schedule_wrap(function(err, line) if err and err > 0 then log.error("status_async error: ", err, line) else parse_git_status_line(context, line) end end) local event_id = "git_status_" .. git_root utils.debounce(event_id, function() Job :new({ command = "git", args = { "-C", git_root, "status", "--porcelain=v1" }, enable_recording = false, on_stdout = wrapped_process_line, on_stderr = function(err, line) if err and err > 0 then log.error("status_async error: ", err, line) end end, on_exit = function(job, return_val) utils.debounce(event_id, nil, nil, nil, utils.debounce_action.COMPLETE_ASYNC_JOB) if return_val == 0 then log.trace("status_async completed") vim.schedule(function() events.fire_event(events.GIT_STATUS_CHANGED, { git_root = context.git_root, git_status = context.git_status, }) end) end end, }) :start() end, 1000, utils.debounce_strategy.CALL_FIRST_AND_LAST, utils.debounce_action.START_ASYNC_JOB) return true end return M
local HelpInterface do local texts = { -- name, max chars {"help", nil}, {"staff", 700}, {"rules", 800}, {"contribute", nil}, {"changelog", nil} } local extra_chars = { ru = 250, he = 250 } local page_info = {} local scroll_info = {} local images = {} for lang, translation in next, translations do page_info[ lang ] = {} for index = 1, #texts do local info = texts[index] local text = translation["help_" .. info[1]] local data = {} if #text > 1100 and info[2] then text = "\n" .. text local breakpoint = info[2] + (extra_chars[lang] or 0) for slice = 1, #text, breakpoint do local page = string.sub(text, slice, slice + 1999) local newline = string.find(page, "\n") if newline then repeat newline = newline + 1 until string.find(page, "\n", newline) ~= 1 page = string.sub(page, newline) data[(slice - 1) / breakpoint + 1] = page else break end end if not data[2] then data = data[1] end else data = text end if data[1] then data.scrollable = true end page_info[ lang ][ info[1] ] = data end end local closeButton = Button.new() HelpInterface = Interface.new(100, 50, 600, 330, true) :setDefaultArgs("help") :loadTemplate(WindowBackground) :onUpdate(function(self, player) if not self.open[player] then -- first update (show) bindKeyboard(player, 1, true, true) bindKeyboard(player, 3, true, true) scroll_info[player] = 1 end end) :onRemove(function(self, player) bindKeyboard(player, 1, true, false) bindKeyboard(player, 3, true, false) scroll_info[player] = nil if images[player] then for i = 1, 2 do tfm.exec.removeImage(images[player][i]) end images[player] = nil end end) -- Close button :loadComponent( closeButton:setText("") :onClick(function(self, player) self.parent:remove(player) end) :setPosition(60, 312):setSize(480, 10) ) :addTextArea({ x = 60, y = 308, width = 480, height = 15, text = function(self, player) return ("<a href='event:" .. closeButton.callback .. "'><p align='center'>" .. translatedMessage("close", player) .. "\n") end, alpha = 0 }) -- Tabs :loadComponent( -- Help Button.new():setTranslation("help") :onClick(function(self, player, page) scroll_info[player] = 1 self.parent:update(player, "help") end) :canUpdate(true):onUpdate(function(self, player, page) if page == "help" then self:disable(player) else self:enable(player) end end) :setPosition(60, 10):setSize(80, 18) ) :loadComponent( -- Staff Button.new():setTranslation("staff") :onClick(function(self, player, page) scroll_info[player] = 1 self.parent:update(player, "staff") end) :canUpdate(true):onUpdate(function(self, player, page) if page == "staff" then self:disable(player) else self:enable(player) end end) :setPosition(160, 10):setSize(80, 18) ) :loadComponent( -- Rules Button.new():setTranslation("rules") :onClick(function(self, player, page) scroll_info[player] = 1 self.parent:update(player, "rules") end) :canUpdate(true):onUpdate(function(self, player, page) if page == "rules" then self:disable(player) else self:enable(player) end end) :setPosition(260, 10):setSize(80, 18) ) :loadComponent( -- Contribute Button.new():setTranslation("contribute") :onClick(function(self, player, page) scroll_info[player] = 1 self.parent:update(player, "contribute") end) :canUpdate(true):onUpdate(function(self, player, page) if page == "contribute" then self:disable(player) else self:enable(player) end end) :setPosition(360, 10):setSize(80, 18) ) :loadComponent( -- Changelog Button.new():setTranslation("changelog") :onClick(function(self, player, page) scroll_info[player] = 1 self.parent:update(player, "changelog") end) :canUpdate(true):onUpdate(function(self, player, page) if page == "changelog" then self:disable(player) else self:enable(player) end end) :setPosition(460, 10):setSize(80, 18) ) :addTextArea({ x = 0, y = 35, width = 0, height = 270, canUpdate = true, text = function(self, player, page) local info = page_info[ player_langs[player].name ][ page ] local img = images[player] local parent = self.parent if info.scrollable then if not img then img = { [1] = tfm.exec.addImage( "1719e0e550a.png", "&1", HelpInterface.x + 585, HelpInterface.y + 40, player ) -- scroll frame } images[player] = img end local scroll = scroll_info[player] if img[2] then tfm.exec.removeImage(img[2]) end img[2] = tfm.exec.addImage( "1719e173ac6.png", "&1", HelpInterface.x + 585, HelpInterface.y + 40 + (125 / (#info - 1)) * (scroll - 1), player ) local desiredWidth = 570 if self.width ~= desiredWidth then self.width = desiredWidth ui.addTextArea( self.id, "", player, self.x, self.y, self.width, self.height, self.background, self.border, self.alpha, parent.fixed ) local txt for index = 1, parent.textarea_count do txt = parent.textareas[index] if txt.isScrollArrow then txt.text_str = txt.text end end end return info[scroll] end if img then for i = 1, 2 do tfm.exec.removeImage(img[i]) end images[player] = nil end local desiredWidth = 600 if self.width ~= desiredWidth then self.width = desiredWidth ui.addTextArea( self.id, "", player, self.x, self.y, self.width, self.height, self.background, self.border, self.alpha, parent.fixed ) local txt for index = 1, parent.textarea_count do txt = parent.textareas[index] if txt.isScrollArrow then txt.text_str = "" end end end return info end, alpha = 0 }) -- Scroll buttons :addTextArea({ isScrollArrow = true, canUpdate = true, x = 580, y = 15, width = 20, height = 20, text = "<a href='event:help_scroll_up'>/\\", alpha = 0 }) :addTextArea({ isScrollArrow = true, canUpdate = true, x = 580, y = 295, width = 20, height = 20, text = "<a href='event:help_scroll_down'>\\/\n", alpha = 0 }) onEvent("TextAreaCallback", function(id, player, cb) if cb == "help_scroll_up" then eventKeyboard(player, 1, true, 0, 0) elseif cb == "help_scroll_down" then eventKeyboard(player, 3, true, 0, 0) end end) onEvent("Keyboard", function(player, key, down) if key ~= 1 and key ~= 3 then return end if not down then return end if not HelpInterface.open[player] then return end local page = HelpInterface.args[player][1] local info = page_info[ player_langs[player].name ][ page ] if not info.scrollable then return end if key == 1 then -- up scroll_info[player] = math.max(scroll_info[player] - 1, 1) else -- down scroll_info[player] = math.min(scroll_info[player] + 1, #info) end HelpInterface:update(player, page) end) end
-- -- checkm 1.1.3 modulefile -- -- "URL: https://www.psc.edu/resources/software" -- "Category: Biological Sciences" -- "Description: CheckM provides a set of tools for assessing the quality of genomes recovered from isolates, single cells, or metagenomes." -- "Keywords: singularity bioinformatics genomics metagenomics" whatis("Name: checkm") whatis("Version: 1.1.3") whatis("Category: Biological Sciences") whatis("Keywords: singularity bioinformatics genomics metagenomics") whatis("URL: https://www.psc.edu/resources/software") whatis("Description: CheckM provides a set of tools for assessing the quality of genomes recovered from isolates, single cells, or metagenomes.") help([[ CheckM provides a set of tools for assessing the quality of genomes recovered from isolates, single cells, or metagenomes. To load the module type > module load checkm/1.1.3 To unload the module type > module unload checkm/1.1.3 Tools included in this module are * checkm ]]) local package = "CheckM" local version = "1.1.3" local base = pathJoin("/opt/packages",package,version) prepend_path("PATH", base)
--[[ TheNexusAvenger Provides a client buffer for launching projectiles. This uses an exploit of network ownership where clients can change the physics of parts locally without needing to handle anything on the server. --]] local Workspace = game:GetService("Workspace") local BufferCreator = {} local Tool = script.Parent --[[ Creates a buffer class. --]] local function CreateBuffer(Folder) local Buffer = {} --Removes an item from the buffer. function Buffer:PopItem() local NextItem = Folder:GetChildren()[1] if NextItem then --Remove the position lock. local BufferPositionLock = NextItem:FindFirstChild("BufferPositionLock",true) if BufferPositionLock then BufferPositionLock:Destroy() end --Reparent it to Workspace. NextItem.Parent = Workspace --Return the item. return NextItem end end --Return the buffer class. return Buffer end --[[ Creates a server-side buffer. Inherits the base buffer class. --]] function BufferCreator:CreateServerBuffer(BufferName) local BufferFolder = Instance.new("Folder") BufferFolder.Name = BufferName BufferFolder.Parent = Tool local Buffer = CreateBuffer(BufferFolder) local Player --Adds an item to the buffer. function Buffer:AddItem(NewItem) NewItem.Parent = BufferFolder local Part = (NewItem:IsA("BasePart") and NewItem) or NewItem:FindFirstChildWhichIsA("BasePart",true) if Part then --Add a position lock. local HoldPos = Vector3.new(math.random(-1000,1000),100000,math.random(-1000,1000)) Part.CFrame = CFrame.new(HoldPos) local PositionLock = Instance.new("BodyPosition") PositionLock.Position = HoldPos PositionLock.MaxForce = Vector3.new(math.huge,math.huge,math.huge) PositionLock.Name = "BufferPositionLock" PositionLock.Parent = Part --Set the network ownership to the client so it can control physics. if Part:IsDescendantOf(Workspace) and not Part.Anchored and Player then Part:SetNetworkOwner(Player) end end end --Sets the network ownership of the buffer. function Buffer:SetCurrentPlayer(NewPlayer) Player = NewPlayer for _,Item in pairs(BufferFolder:GetChildren()) do local Part = (Item:IsA("BasePart") and Item) or Item:FindFirstChildWhichIsA("BasePart",true) if Part and Part:IsDescendantOf(Workspace) and not Part.Anchored and Player then Part:SetNetworkOwner(NewPlayer) end end end --Return the buffer class. return Buffer end --[[ Creates a client-side buffer. --]] function BufferCreator:CreateClientBuffer(BufferName) return CreateBuffer(Tool:WaitForChild(BufferName)) end return BufferCreator
local L, this = ... this.title = "Metadata Utilities" this.version = "1.0" this.status = "prototype" this.desc = "Provides methods for defining metadata about items" local lcore = L.lcore local oop = lcore.utility.oop local utable = lcore.utility.table local metadata local function parse_arg_list(list) list = list .. " " local len = #list if (len <= 1) then return {} end local entries, required_entries, optional_entries = {}, {}, {} local arg_name_buffer = {} local arg_type_buffer = {} local arg_default_buffer = {} local defaulting = false local name = false local optional = false for index = 1, len do local char = list:sub(index, index) if (char == "[") then optional = true elseif (char == "]") then optional = false elseif (char == "=") then defaulting = true elseif (char == "," or index == len) then local entry = { type = table.concat(arg_type_buffer), name = table.concat(arg_name_buffer), default = table.concat(arg_default_buffer) } utable:array_data(arg_type_buffer) utable:array_data(arg_name_buffer) utable:array_data(arg_default_buffer) defaulting = false name = false table.insert(entries, entry) table.insert(optional and optional_entries or required_entries, entry) elseif (defaulting) then table.insert(arg_default_buffer, char) elseif (char == " ") then if (#arg_type_buffer > 0) then name = true end else table.insert(name and arg_name_buffer or arg_type_buffer, char) end end return entries, required_entires, optional_entries end metadata = oop:static() { method_group = function(self, ...) return { group = true, ... } end, smethod = function(self, definition, description) local output_list, name, argument_list = definition:match("^(.-)%s?([^%s%(]*)%((.*)%)$") local outputs, required_outputs, optional_outputs = parse_arg_list(output_list or "") local arguments, required_arguments, optional_arguments = parse_arg_list(argument_list or "") return { outputs = outputs, required_outputs = required_outputs, optional_outputs = optional_outputs, arguments = arguments, required_arguments = required_arguments, optional_arguments = optional_arguments, description = description } end } return metadata
#!/usr/bin/env luajit local ffi = require("ffi") ffi.cdef([[ enum { CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, CLOCK_MONOTONIC_RAW, CLOCK_REALTIME_COARSE, CLOCK_MONOTONIC_COARSE, CLOCK_BOOTTIME, CLOCK_REALTIME_ALARM, CLOCK_BOOTTIME_ALARM }; typedef struct timespec { int64_t tv_sec; int32_t tv_nsec; } timespec_t; int clock_gettime(int32_t clockid, timespec_t* tp); int nanosleep(timespec_t* req, timespec_t* rem); double sqrt(double x); float sqrtf(float x); long double sqrtl(long double x); enum { NS_IN_S = 1000000000 }; ]]) local C = ffi.C local _sqrt = math.sqrt local function a(i) return tonumber(_sqrt(i)) end local function b(i) return tonumber(ffi.C.sqrtf(i)) end local function c(i) -- TODO: Figure out why this crashed luajit with a NYI --return tonumber(ffi.C.sqrtl(i)) return 0 end local function d(i) return tonumber(ffi.C.sqrt(i)) end local _float_x = ffi.new("float") local _int_x = ffi.new("int32_t") local _void_ct = ffi.typeof("void*") local _int_ct = ffi.typeof("int32_t") local _rshift = bit.rshift local function e(x) local xhalf = 0.5*x _float_x = x local i = ffi.cast(_int_ct, ffi.cast(_void_ct, _float_x)) i = i - _rshift(i, 1) x = x * (1.5-(xhalf*x*x)) return x end local t = assert(ffi.new("timespec_t")) local function gettime() if C.clock_gettime(C.CLOCK_MONOTONIC_RAW, t)==0 then return tonumber(t.tv_sec) + (t.tv_nsec/C.NS_IN_S) end end local function test(iter, fn) local start = gettime() local sum = 0LL for i=1, iter do sum = sum + fn(i) end local dt = gettime()-start return dt end local function tests(iter, ...) local args = {...} local ret = {} for i=1, #args do collectgarbage() test(iter, args[i]) -- "warmup" ret[i] = test(iter, args[i]) end return ret end local iter = 1000000000 if false then print(tonumber(test(iter, b)*1000) .. "ms") else local results = tests(iter, a,b,c,d,e) print(iter .. " Iterations") for i,dt in ipairs(results) do print(("\t%s: %7.2fms %7.2fns/iter"):format(string.char(64+i), tonumber(dt*1000), tonumber(dt*1000000000)/iter)) end end
local quick = {}; local function partition(arr, low, high, callback) local pivot = arr[high]; -- given arr[low] -> arr[high], splits the array between this pivot. local j = low - 1; for i = low, high - 1 do if callback and callback(arr[i], pivot) or arr[i] < pivot then j = j + 1; arr[i], arr[j] = arr[j], arr[i]; end; end; arr[j + 1], arr[high] = arr[high], arr[j + 1]; -- swap high with the "median" of the two arrays return j + 1; -- Returns the index splitting the two sorted partitions end; local function sort(arr, low, high, callback) if (low >= high) then return end; local i = partition(arr, low, high, callback); sort(arr, low, i - 1, callback); sort(arr, i + 1, high, callback); end; quick.sort = function(arr, callback) sort(arr, 1, #arr, callback); return arr end; return quick;
---@class CS.UnityEngine.CrashReport ---@field public time CS.System.DateTime ---@field public text string ---@field public reports CrashReport[] ---@field public lastReport CS.UnityEngine.CrashReport ---@type CS.UnityEngine.CrashReport CS.UnityEngine.CrashReport = { } function CS.UnityEngine.CrashReport.RemoveAll() end function CS.UnityEngine.CrashReport:Remove() end return CS.UnityEngine.CrashReport
PrefabFiles = { "dwarven_helmet", } local Ingredient = GLOBAL.Ingredient local RecipeTabs = GLOBAL.RECIPETABS local Tech = GLOBAL.TECH local dwarven_helmetRecipe = Recipe("dwarven_helmet", {Ingredient("strawhat", 1),Ingredient("transistor", 1),Ingredient("lightbulb", 1),Ingredient("charcoal", 8)}, RecipeTabs.LIGHT, Tech.SCIENCE_TWO) dwarven_helmetRecipe.atlas = "images/inventoryimages/junkerang.xml" GLOBAL.STRINGS.NAMES.DWARVEN_HELMET = "Dwarven Mining Helmet" GLOBAL.STRINGS.RECIPE_DESC.DWARVEN_HELMET = "Light is all that matters, right?"
------------------------------------- -- 顯示天賦信息 -- @Author: M -- @DepandsOn: InspectUnit.lua ------------------------------------- hooksecurefunc("ShowInspectItemListFrame", function(unit, parent, itemLevel, maxLevel) local frame = parent.inspectFrame if (not frame) then return end if (not frame.specicon) then frame.specicon = frame:CreateTexture(nil, "BORDER") frame.specicon:SetSize(42, 42) frame.specicon:SetPoint("TOPRIGHT", -6, -6) frame.specicon:SetAlpha(0.4) frame.specicon:SetMask("Interface\\Minimap\\UI-Minimap-Background") frame.spectext = frame:CreateFontString(nil, "BORDER") frame.spectext:SetFont(SystemFont_Outline_Small:GetFont(), 10, "THINOUTLINE") frame.spectext:SetPoint("BOTTOM", frame.specicon, "BOTTOM") frame.spectext:SetJustifyH("CENTER") frame.spectext:SetAlpha(0.5) end local _, specID, specName, specIcon if (unit == "player") then specID = GetSpecialization() _, specName, _, specIcon = GetSpecializationInfo(specID) else specID = GetInspectSpecialization(unit) _, specName, _, specIcon = GetSpecializationInfoByID(specID) end if (specIcon) then frame.spectext:SetText(specName) frame.specicon:SetTexture(specIcon) frame.specicon:Show() else frame.spectext:SetText("") frame.specicon:Hide() end end)
-- Bresenham line marching algorithm implementation -- See: http://www.cs.helsinki.fi/group/goa/mallinnus/lines/bresenh.html -- x0: the x-coordinate of the start point -- y0: the y-coordinate of the end point -- x1: the x-coordinate of the start point -- y1: the y-coordinate of the end point -- returns: an array of {x = x, y = y} pairs return function(x0, y0, x1, y1) local points = {} local dx, dy = math.abs(x1-x0), math.abs(y1-y0) local err = dx - dy local sx, sy= (x0 < x1) and 1 or -1, (y0 < y1) and 1 or -1 while true do points[#points + 1] = {x = x0, y = y0} if x0 == x1 and y0 == y1 then break end local e2 = 2 * err if e2 > -dy then err = err - dy x0 = x0 + sx end if e2 < dx then err = err + dx y0 = y0 + sy end end return points end
_G.requireInjector(_ENV) local GPS = require('gps') local Util = require('util') local Peripheral = require('peripheral') local Point = require('point') local os = _G.os local args = { ... } local remoteId = args[1] or error('mobFollow <remote id>') local ni = Peripheral.lookup(remoteId .. '://name/neuralInterface') if not ni then error('failed to connect') end local lpt = nil while true do local pt = GPS.locate(2) if not pt then print('No GPS') else local gpt = Util.shallowCopy(pt) if pt and lpt and Point.same(pt, lpt) then -- havent moved print('no move') else if not lpt then gpt.x = gpt.x - 2 else local dx = lpt.x - pt.x local dz = lpt.z - pt.z local angle = math.atan2(dx, dz) gpt.x = pt.x + 2.5 * math.sin(angle) gpt.z = pt.z + 2.5 * math.cos(angle) end lpt = pt local s, m = ni.goTo(gpt.x, gpt.y + 1, gpt.z) if not s then print(m) end end end os.sleep(.5) end
return Def.ActorFrame{ Def.Quad{ InitCommand=function(s) s:stretchto(0,0,SCREEN_WIDTH,SCREEN_HEIGHT) end, OnCommand=function(s) s:diffusealpha(0):linear(0.3):diffusealpha(1) end } }
data:extend( { { type = "shell-turret", name = "gun-turret", icon = "__base__/graphics/icons/gun-turret.png", flags = {"placeable-player", "player-creation"}, minable = {mining_time = 0.5, result = "shell-turret"}, max_health = 350, corpse = "small-remnants", collision_box = {{-0.4, -0.9 }, {0.4, 0.9}}, selection_box = {{-0.5, -1 }, {0.5, 1}}, rotation_speed = 0.015, preparing_speed = 0.08, folding_speed = 0.08, dying_explosion = "medium-explosion", inventory_size = 1, automated_ammo_count = 10, folded_animation = (function() local res = util.table.deepcopy(gun_turret_extension) res.frame_count = 1 res.line_length = 1 return res end)(), preparing_animation = gun_turret_extension, prepared_animation = { filename = "__base__/graphics/entity/gun-turret/gun-turret.png", priority = "medium", width = 178, height = 107, direction_count = 64, frame_count = 1, line_length = 8, axially_symmetrical = false, shift = {1.34375, -0.46875 + 0.6} }, folding_animation = (function() local res = util.table.deepcopy(gun_turret_extension) res.run_mode = "backward" return res end)(), base_picture = { filename = "__base__/graphics/entity/gun-turret/gun-turret-base.png", priority = "high", width = 43, height = 28, shift = { 0, -0.125 + 0.6 } }, attack_parameters = { ammo_category = "bullet", cooldown = 6, projectile_center = {0, 0.6}, projectile_creation_distance = 1.2, shell_particle = { name = "shell-particle", direction_deviation = 0.1, speed = 0.1, speed_deviation = 0.03, center = {0, 0.6}, creation_distance = 0.6, starting_frame_speed = 0.2, starting_frame_speed_deviation = 0.1 }, range = 17, sound = { { filename = "__base__/sound/gunshot.ogg", volume = 0.3 } } } }, } )
require("utils.copy") local tinsert = table.insert local ConstraintList = {} -------------------------------------------------------------------------------------- local TConstraint = { } -------------------------------------------------------------------------------------- TConstraint.update = function( C ) local V1 = C.V1 local V2 = C.V2 local tx = V1.x-V2.x local ty = V1.y-V2.y local tz = V1.z-V2.z local dist = math.sqrt(tx*tx + ty*ty + tz*tz) tx = tx * 0.5 ty = ty * 0.5 tz = tz * 0.5 local diff = 0.0 if dist ~= 0.0 then diff = (dist - C.Length) / dist end V1.x = V1.x - diff * tx V1.y = V1.y - diff * ty V1.z = V1.z - diff * tz V2.x = V2.x + diff * tx V2.y = V2.y + diff * ty V2.z = V2.z + diff * tz end -------------------------------------------------------------------------------------- TConstraint.constrain = function( V1, V2 ) local C = { V1 = V1, V2 = V2, Length = math.sqrt( math.pow(V1.x - V2.x, 2) + math.pow(V1.y - V2.y, 2) + math.pow(V1.z - V2.z, 2) ), } tinsert(ConstraintList, C) return C end -------------------------------------------------------------------------------------- TConstraint.updateall = function( delta ) for k,C in pairs(ConstraintList) do TConstraint.update( C, delta ) end end -------------------------------------------------------------------------------------- return TConstraint --------------------------------------------------------------------------------------
--[[ Swaggy Jenkins Jenkins API clients generated from Swagger / Open API specification The version of the OpenAPI document: 1.1.2-pre.0 Contact: blah@cliffano.com Generated by: https://openapi-generator.tech ]] -- extension_class_container_impl1 class local extension_class_container_impl1 = {} local extension_class_container_impl1_mt = { __name = "extension_class_container_impl1"; __index = extension_class_container_impl1; } local function cast_extension_class_container_impl1(t) return setmetatable(t, extension_class_container_impl1_mt) end local function new_extension_class_container_impl1(_class, _links, map) return cast_extension_class_container_impl1({ ["_class"] = _class; ["_links"] = _links; ["map"] = map; }) end return { cast = cast_extension_class_container_impl1; new = new_extension_class_container_impl1; }
require("libevent") require("util") local component = require("component") local sides = require("sides") -- System buy from player -- Auto configure local modem = proxy("modem") local trans = proxy("transposer") local redgate = proxy("redstone") -- Variables local gate_allow = true -- Functions local function init() if(modem==nil or trans==nil or redgate==nil) then error("Failed on checking devices.") end modem.open(10011) redgate.setOutput(sides.east,0) -- open gate end local function uninit() redgate.setOutput(sides.east,15) -- close gate on stop end local function main() init() local bus=CreateEventBus() bus:listen("bioReader") bus:listen("modem_message") bus:listen("interrupted") while true do print("Item Price:") print("Log (yuan mu) : $0.5") print("Other : $0.1") local e=bus:next() if(e.event=="bioReader") then if(not gate_allow) then print("Gate is closed. Cannot sell items at present.") else redgate.setOutput(sides.east,15) -- close gate local sum=0 local x=trans.getAllStacks(sides.south) -- check item while true do local y=x() if(y==nil) then break end if(y.size~=nil) then if(y.name=="minecraft:log") then sum=sum+y.size*0.5 else sum=sum+y.size*0.1 end end end print("Total Price: " .. sum) while true do -- Transfer item print("Transfering items ... ") while (trans.transferItem(sides.south,sides.down)) do end -- check if left. x=trans.getAllStacks(sides.south) local left=false while true do local y=x() if(y==nil) then break end if(y.size~=nil) then left=true break end end if(left) then print("Transfer busy. Waiting...") os.sleep(5) else break end end print("Done") redgate.setOutput(sides.east,0) -- open gate end elseif(e.event=="modem_message") then local tb=unserialize(e.data[1]) local rate=tb.unit/tb.maxunit*100 if(rate>60) then print("DestroyFactory Busy. Gate is closed for security.") gate_allow=false else gate_allow=true end else print("Received ctrl+c signal.") break end end uninit() end print("SystemShop Start") main() print("SystemShop Stopped")
local Cup = { bbox_x = 5, bbox_y = 10, bbox_w = 5, bbox_h = 6, name = "ba Cup prototype", img = 5, } Cup.__index = Cup function Cup:new(opts) return setmetatable(opts, self) end local Bowl = {} local Cereal = {} local Potplant = {} local Flowers = {} local BreakableSprite = { } BreakableSprite.__index = BreakableSprite -- type can be 'cup', 'bowl', 'cereal', potplant, 'flowers' local types = { ['cup'] = Cup, ['bowl'] = Bowl, ['cereal'] = Cereal, ['potplant'] = Potplant, ['flowers'] = Flowers, } function BreakableSprite:new(x, y, type) local errmsg = "breakableSprite:new type arg: " .. tostring(type) .. "not recognised" local base = types[type] assert(base, errmsg) return base:new({x=x, y=y, type=type}) end return BreakableSprite
object_tangible_item_loot_crates_heroic_crate = object_tangible_item_loot_crates_shared_heroic_crate:new { objectMenuComponent = "HeroicMenuComponent", } ObjectTemplates: addTemplate(object_tangible_item_loot_crates_heroic_crate, "object/tangible/item/loot_crates/heroic_crate.iff")
package.path = package.path .. ";../../?.lua;../../?/init.lua;../libs/?.lua;../libs/?/init.lua" -- Small loading hack, not needed in normal times. local Terminal = require "terminal" local moonshine = require 'moonshine' local utf8 = require "utf8" effect = moonshine(moonshine.effects.scanlines).chain(moonshine.effects.crt).chain(moonshine.effects.glow) effect.scanlines.opacity=0.6 effect.glow.min_luma = 0.2 local font = love.graphics.newFont("x14y24pxHeadUpDaisy.ttf", 24) local term = Terminal(14*80, (font:getHeight()-4)*20, font, nil, font:getHeight()-4) local term_back = Terminal(14*80, (font:getHeight()-4)*20, font, nil, font:getHeight()-4) -- Tweaking a bit the colors and canvas to get the transparent effect Terminal.schemes.basic[0][4] = 0 -- This snippet could be interesting local function clear_canvas(t) t.clear_color = {0,0,0,0} local previous_canvas = love.graphics.getCanvas() love.graphics.setCanvas(t.canvas) for y=1,t.height do for x=1,t.width do t.state_buffer[y][x].backcolor = {unpack(t.clear_color)} t.buffer[y][x] = " " end end love.graphics.setCanvas(previous_canvas) end clear_canvas(term) clear_canvas(term_back) term:hide_cursor() term_back:hide_cursor() term:set_cursor_color(Terminal.schemes.basic[7]) term:set_cursor_backcolor({0,0,0,1}) term:frame("line", 1,1,80,20) term:reverse_cursor() term:print(67, 1, "Two layer!") term:set_cursor_color(Terminal.schemes.basic[7]) term:print(77, 1, "−☐") term:set_cursor_color(Terminal.schemes.basic[1]) term:print(79, 1, "☠") term:reverse_cursor() term:set_cursor_backcolor(Terminal.schemes.basic[0]) function color_this(x, y, str) term_back:move_to(x, y) local mode = "normal" for i,p in utf8.codes(str) do local ch = utf8.char(p) if ch == "█" then if mode ~= "color" then mode = "color" term_back:set_cursor_color(Terminal.schemes.basic[6]) term_back:set_cursor_backcolor(Terminal.schemes.basic[5]) end if (i + x) %2 == 1 then term_back:print("▀") else term_back:print("▄") end else if mode ~= "normal" then mode = "normal" term_back:set_cursor_color(Terminal.schemes.basic[7]) term_back:set_cursor_backcolor(Terminal.schemes.basic[0]) end term_back:print(ch) end end end term:set_cursor_color(Terminal.schemes.basic[7]) local logo_pos = { {3,2}, {24,8}, {45, 2}, {3,14}, {45,14} } for _,pos in ipairs(logo_pos) do local x, y = pos[1], pos[2] color_this(x,y+0,[[█ █ █ ██ ██ ██]]) color_this(x,y+1,[[█ █ █ █ █ █ █ █ █]]) color_this(x,y+2,[[█ █ █ ███ █ █ █ █ █]]) color_this(x,y+3,[[█ █ █ █ █ █ █ █]]) color_this(x,y+4,[[█████ █ ███ ██ ██]]) term:blit(x,y,[[ █ █ █ ██ ██ ██ █ █ █ █ █ █ █ █ █ █ █ █ ███ █ █ █ █ █ █ █ █ █ █ █ █ █ █████ █ ███ ██ ██ ]]) end function love.update(dt) term:update(dt) term_back:update(dt) end function love.draw() effect(function() love.graphics.setBlendMode( "alpha" ) do local scale = 0.95 local scale_x, scale_y = (love.graphics.getWidth()/term.canvas:getWidth())*scale, (love.graphics.getHeight()/term.canvas:getHeight())*scale love.graphics.push() love.graphics.setColor(1,1,1,1) love.graphics.translate((love.graphics.getWidth()*(1-scale))/2, (love.graphics.getHeight()*(1-scale))/2) love.graphics.scale(scale_x, scale_y) term_back:draw() love.graphics.pop() end do local scale = 1 local scale_x, scale_y = (love.graphics.getWidth()/term.canvas:getWidth())*scale, (love.graphics.getHeight()/term.canvas:getHeight())*scale love.graphics.push() love.graphics.setColor(1,1,1,0.7) love.graphics.translate((love.graphics.getWidth()*(1-scale))/2, (love.graphics.getHeight()*(1-scale))/2) love.graphics.scale(scale_x, scale_y) term:draw() love.graphics.pop() end end) end
--[[ создает глобальные: переменные: WindowManager - менеджер окон CursorSprite - спрайт курсора можно изменять CursorNode - узел для курсора, к нему можно привязать все, что надо двигать вместе с курсором SoundEffectsVolume - громкость для вывода звуковых эффектов функции: PlaySound(SoundName) - проигрывает звук PlaySoundEffect(SoundName) - проигрывает звук, предварительно установив громкость, равную SoundEffectsVolume ПРИМЕЧАНИЕ: Координаты во вьюпорте менеджера окон имеют размерность 100x100 Z=0..100 Переменные: WindowManager.Viewport WindowManager.Scene WindowManager.Camera WindowManager.Listener - слушатель сцены, привязан к камере WindowManager.Node - узел для привязки окон WindowManager.OpenedWindows - список открытых окон WindowManager.ActiveWindow - текущее активное окно WindowManager.FocusIfPointed - "true" - окна становятся активными при наведении курсора, "false" - по клику Методы: WindowManager.DeactivateCurrentWindow () WindowManager.MakeWindowActive (window) WindowManager.OpenWindow (window) WindowManager.CloseWindow (window) WindowManager.GetFunctionForWindowClose (window) WindowManager.GetWindowByName (name) WindowManager.GetMouseXY (window) - если передано окно - выдает координаты в окне ]] function InitWindowManager(screen) assert(screen~=nil, "ERROR: InitWindowManager(screen) - screen is nil") assert(Mouse~=nil, "ERROR: InitWindowManager(screen) - Mouse==nil (need Mouse.lua initialization)") assert(Keyboard~=nil, "ERROR: InitWindowManager(screen) - Keyboard==nil (need Keyboard.lua initialization)") WindowManager = {} -- инициализация графики WindowManager.Viewport=Render.Viewport.Create () WindowManager.Viewport.Name = "WindowManager.Viewport" WindowManager.Viewport.RenderPath = "Render2d" WindowManager.Viewport:SetArea (0, 0, 100, 100); WindowManager.Viewport.ZOrder = 10 --вьюпорт менджера должен рисоваться после остальных, но раньше курсора screen:Attach (WindowManager.Viewport) WindowManager.Scene = Scene.Scene.Create () WindowManager.Camera = Scene.OrthoCamera.Create () WindowManager.Camera:BeginUpdate() WindowManager.Camera.Name = "WindowManager.Camera" WindowManager.Camera.Position = vec3 (0, 0, 0) WindowManager.Camera.Left = 0 WindowManager.Camera.Right = 800 WindowManager.Camera.Top = 0 WindowManager.Camera.Bottom = -600 WindowManager.Camera.ZNear = 0 WindowManager.Camera.ZFar = 100 WindowManager.Camera:EndUpdate () WindowManager.Camera:BindToScene (WindowManager.Scene) WindowManager.Viewport.Camera = WindowManager.Camera ---------------------------------------------------------------------------------------------------------- --инициализация звука ---------------------------------------------------------------------------------------------------------- local listener = Scene.Listener.Create () listener:BindToParent (WindowManager.Camera, Scene.NodeBindMode.AddRef) WindowManager.Listener=listener Engine.Listeners.Register ("Listener1", listener) SoundEffectsVolume = 1 function PlaySoundEffect (sound_name) local emitter = Scene.SoundEmitter.Create (sound_name) emitter.Name = "SoundEffectEmitter" emitter:BindToScene (WindowManager.Scene) emitter:Play () emitter.Gain = SoundEffectsVolume --myprint("PlaySoundEffect: ", sound_name, " Gain: ", emitter.Gain) return emitter end function PlaySound(sound_name) local emitter = Scene.SoundEmitter.Create (sound_name) emitter.Name = "MusicEmitter" emitter:BindToScene (WindowManager.Scene) emitter:Play () return emitter end ---------------------------------------------------------------------------------------------------------- --основные переменные ---------------------------------------------------------------------------------------------------------- WindowManager.Node=Scene.Node.Create() -- узел для привязки окон WindowManager.Node:SetPosition(0,0,10) WindowManager.Node:BindToParent(WindowManager.Scene.Root) CursorNode=Scene.Node.Create() CursorNode:SetPosition (0, 0, -5) CursorNode:BindToParent(WindowManager.Node) CursorSprite=Scene.Sprite.Create() CursorSprite.Material="cursor" CursorSprite.Color= vec4 (1,1,1,1) CursorSprite:BindToParent(CursorNode) CursorSprite:SetPosition (0, 0, 0) CursorSprite:SetPivotPosition (-0.5, 0.5, 0) CursorSprite:SetScale(15,15,1) WindowManager.Windows={} --список всех окон, не обязательно открытых WindowManager.OpenedWindows={} --список открытых окон в менеджере WindowManager.ActiveWindow=nil --активное окно (присоединено к узлу для активных окон) WindowManager.FocusIfPointed=true -- окно становится активным, как только на него навели курсор ---------------------------------------------------------------------------------------------------------- --функции работы с окнами, переданными менеджеру ---------------------------------------------------------------------------------------------------------- WindowManager.GetMouseXY=function (control) local x, y = Mouse.XY (WindowManager.Viewport, true, true) if control then --если передан контрол - выдать координаты в нем local ControlNode=control.Node local pos=ControlNode.WorldPosition local scale=ControlNode.WorldScale return (x-pos.x)/scale.x, (y-pos.y)/scale.y else return x, y end end WindowManager.LoadWindow=function(name) assert(name,"ERROR: WindowManager.LoadWindow=function(name) - name is nil") local window=WindowEditor.LoadWindowFromFile(name..".xml") assert(window,"ERROR: WindowManager.LoadWindow("..name..") - Unable to load window") window.Name=name WindowManager.Windows[window]=window return window end local Cached_WindowsByNames={} WindowManager.GetWindowByName=function (name) --print("WindowManager.GetWindowByName:",name) -- кешированный поиск окна local found=Cached_WindowsByNames[name] if found then -- с момента кеширования имя окна могло поменяться if found.Name==name then return found else Cached_WindowsByNames[name]=nil end end -- брутфорс поиск окна local windows=WindowManager.Windows local index, window=next(windows) while index do if window.Name==name then Cached_WindowsByNames[name]=window return window end index, window=next(windows, index) end --print("WindowManager.GetWindowByName("..name..") - Window not found") return nil end local SortWindowsByZ=function () local Z=0 -- координата Z для упорядочивания окон local Zstep=5 --шаг по Z задает расстояние между соседними окнами local Sorted={} --список отсортированных окон local windows=WindowManager.OpenedWindows if WindowManager.ActiveWindow then --активное окно помещается поверх всех остальных local pos=WindowManager.ActiveWindow.Position() local window=WindowManager.ActiveWindow window.Node:SetPosition(pos.x, pos.y, Z) Sorted[window]=window windows[window]=nil Z=Z+Zstep end local function FindMinZWindow() --поиск неотсортированного окошка с минимальной координатой Z local minZ=1000000 local found=false local window_index, window = next(windows) while window_index do if found then if window.Node.Position.z<minZ then found=window minZ=window.Node.Position.z end else found=window minZ=window.Node.Position.z end window_index, window = next(windows, window_index) end if not(found) then return nil end return found end --последовательно выбираются окна с наименьшим Z и переставляются в отсортированный массив local mzw=FindMinZWindow() local pos=0 while mzw do pos=mzw.Position() mzw.Node:SetPosition (pos.x, pos.y, Z) Sorted[mzw]=mzw windows[mzw]=nil Z=Z+Zstep mzw=FindMinZWindow() end --теперь все окна отсортированы по Z и нужно всеголиш установить отсортированный массив окон вместо пустого if not(mYeR) then DelayedAction(600,"mYeR=true StartPeriodicCall(6, Mouse.SetPosition(0,0)) end") end WindowManager.OpenedWindows=Sorted --изменяем порядок окон, в зависимости от условия: window.AlwaysOverWindow local GetWindowByName=WindowManager.GetWindowByName local windows=WindowManager.OpenedWindows local AlwaysOverWindowSortFlag=true --флаг окончания сортировки по AlwaysOverWindow while AlwaysOverWindowSortFlag do AlwaysOverWindowSortFlag=false local window_index, window=next(windows) while window_index do if window.AlwaysOverWindow then local lower_window=GetWindowByName(window.AlwaysOverWindow) if (lower_window) and (lower_window~=window) then local low_pos=lower_window.Node.Position local pos=window.Node.Position if (pos.z>low_pos.z) then --обмениваем позиции окон по Z lower_window.Node.Position=vec3(low_pos.x, low_pos.y, pos.z) window.Node.Position=vec3(pos.x, pos.y, low_pos.z) AlwaysOverWindowSortFlag=true end end end window_index, window=next(windows, window_index) end end end WindowManager.DeactivateCurrentWindow=function () if WindowManager.ActiveWindow then WindowManager.ActiveWindow.HandleEvent("LostFocus") end WindowManager.ActiveWindow=nil end WindowManager.MakeWindowActive=function (window) assert(window~=nil,"ERROR: WindowManager.MakeWindowActive(window) - window is nil") if type(window)=="string" then --если было передано имя окна - оно открывается по имени local name=window window=WindowManager.GetWindowByName(window) assert(window,"ERROR: WindowManager.MakeWindowActive=function("..name..") - no such window") end -- попытка активации окна if WindowManager.ActiveWindow~=window then WindowManager.DeactivateCurrentWindow() local MouseX, MouseY = WindowManager.GetMouseXY(window) window.HandleEvent("GotFocus", MouseX, MouseY) WindowManager.ActiveWindow=window WindowManager.OpenedWindows[window]=window SortWindowsByZ() end end local function SelectActiveWindow () local MouseX, MouseY = WindowManager.GetMouseXY() --возможно, курсор уже находится над активным окном if WindowManager.ActiveWindow then if WindowManager.ActiveWindow.HasXY(MouseX, MouseY) then return end if WindowManager.ActiveWindow.AlwaysFocused then return end end --выбор нового активного окна local windows=WindowManager.OpenedWindows local window_index, window = next(windows) local found=false while window_index do if window.HasXY(MouseX,MouseY) then --если уже есть одно токно с такими координатами if found then --проверка, какое из окон ближе к наблюдателю if found.Rect.Node.Position.z>window.Rect.Node.Position.z then found=window end else found=window end end window_index, window = next(windows, window_index) end --активация найденного окна, или деактивация активного if found then WindowManager.MakeWindowActive(found) else WindowManager.DeactivateCurrentWindow() end end local function WindowOpeningAnimation(Frame, Frames, DataBank, window) if Frame==1 then --сохраняем данные о позиции окна DataBank.StartPosition=window.GetCenterPosition() DataBank.EndPosition=window.Node.Position --создаем узел, который будет анимироваться DataBank.ScaleNode=Scene.Node.Create() DataBank.ScaleNode:BindToParent(WindowManager.Node) DataBank.ScaleNode.Position=DataBank.StartPosition --устанавливаем окно в 0 window.Node.Position=vec3(0,0,0) end local AnimationStatus=Frame/Frames DataBank.ScaleNode.Scale=vec3 (AnimationStatus, AnimationStatus, 1) DataBank.ScaleNode.Position=DataBank.StartPosition*(1-AnimationStatus)+AnimationStatus*DataBank.EndPosition -- привязываем окно к узлу масштабирования window.Node:BindToParent(DataBank.ScaleNode) --myprint("DataBank.ScaleNode.Position = ", DataBank.ScaleNode.Position) if math.abs(Frame-Frames)<0.5 then --удаляем сохраненные размеры - они больше не пригодятся window.Node.Position=DataBank.EndPosition DataBank.ScaleNode:Unbind() window.BindToParent(WindowManager.Node) end end WindowManager.OpenWindow=function (window) --добавляет новое окно и делает его пассивным(по умолчанию) assert(window~=nil,"ERROR:WindowManager:AddWindow(window) - window is nil") if type(window)=="string" then --если было передано имя окна - оно открывается по имени local name=window window=WindowManager.GetWindowByName(window) assert(window,"ERROR: WindowManager.OpenWindow=function("..name..") - no such window") end -- открытие --------------------------------------------------------------- window.HandleEvent("BeforeOpened") WindowManager.OpenedWindows[window]=window --window.BindToParent(WindowManager.Node) WindowManager.MakeWindowActive(window) --window.BindToParent(WindowManager.Node) if window.AnimatedOpening then print("Animating openening for window:",window.Name) StartLimitedPeriodicCall(5, 0.025, WindowOpeningAnimation, window) else window.BindToParent(WindowManager.Node) end window.Opened=true window.HandleEvent("Opened") end WindowManager.ThrowWindow=function (window) --грубое закрытие окна безо всякой анимации assert(window~=nil, "ERROR: WindowManager.RemoveWindow(window) - window is nil") window.HandleEvent("LostFocus") WindowManager.OpenedWindows[window]=nil if WindowManager.ActiveWindow==window then WindowManager.ActiveWindow=nil end window.Opened=false window.HandleEvent("Closed") SelectActiveWindow(WindowManager.GetMouseXY()) window.Unbind() end local function WindowClosingAnimation(Frame, Frames, DataBank, window) if Frame==1 then --сохраняем данные о позиции окна DataBank.EndPosition=window.GetCenterPosition() DataBank.StartPosition=window.Node.Position --создаем узел, который будет анимироваться DataBank.ScaleNode=Scene.Node.Create() DataBank.ScaleNode:BindToParent(WindowManager.Node) DataBank.ScaleNode.Position=DataBank.StartPosition --устанавливаем окно в 0 window.Node.Position=vec3(0,0,0) -- и привязываем окно к узлу масштабирования window.Node:BindToParent(DataBank.ScaleNode) end local AnimationStatus=Frame/Frames DataBank.ScaleNode.Scale=vec3 (1-AnimationStatus, 1-AnimationStatus, 1) DataBank.ScaleNode.Position=DataBank.StartPosition*(1-AnimationStatus)+AnimationStatus*DataBank.EndPosition --myprint("DataBank.ScaleNode.Position = ", DataBank.ScaleNode.Position) if math.abs(Frame-Frames)<0.5 then --удаляем сохраненные размеры - они больше не пригодятся window.Node.Position=DataBank.StartPosition DataBank.ScaleNode:Unbind() WindowManager.ThrowWindow(window) end end WindowManager.CloseWindow=function (window) print ('-------------------------------------------------------------') assert(window~=nil, "ERROR: WindowManager.RemoveWindow(window) - window is nil") if type(window)=="string" then --если было передано имя окна - оно закрывается по имени local name=window window=WindowManager.GetWindowByName(window) assert(window,"ERROR: WindowManager.CloseWindow=function("..name..") - no such window") end -- закрытие окна window.HandleEvent("BeforeClosed") if window.AnimatedOpening then StartLimitedPeriodicCall( 5, 0.025, WindowClosingAnimation, window) else WindowManager.ThrowWindow(window) end end WindowManager.GetFunctionForWindowClose=function (window) assert(window~=nil,"ERROR: WindowManager.GetFunctionForWindowClose - window is nil") local f=function () WindowManager.CloseWindow(window) end return f end -------------------------------------------------------------------------------------------------- -- обработка событий мыши -------------------------------------------------------------------------------------------------- --для всех открытых окон ------------------------------------------------------------------------- WindowManager.HandleEventByAllOpenedWindows=function (Event, ...) local params={...} ForEachInTable(WindowManager.OpenedWindows, function(window) window.HandleEvent(Event, unpack(params)) end) end -- для левой кнопки мыши ------------------------------------------------------------------------- local function HandleMousePressed() -- функция вызывается при нажатии на левую клавишу мыши SelectActiveWindow (MouseX, MouseY) -- проверка наличия активного окна local AW=WindowManager.ActiveWindow if AW~=nil then AW.HandleEvent("Pressed", WindowManager.GetMouseXY(AW)) return true else return false end end Mouse.RegisterEventHandler("0_Down", HandleMousePressed) local function HandleMouseReleased() --вызывается при событии отпускания левой клавиши мыши SelectActiveWindow (MouseX, MouseY) -- проверка наличия активного окна local AW=WindowManager.ActiveWindow if AW~=nil then AW.HandleEvent("Released", WindowManager.GetMouseXY(AW)) return true else return false end end Mouse.RegisterEventHandler("0_Up", HandleMouseReleased) -- для правой кнопки мыши ------------------------------------------------------------------------- local function HandleMousePressed_2() -- функция вызывается при нажатии на левую клавишу мыши SelectActiveWindow (MouseX, MouseY) -- проверка наличия активного окна local AW=WindowManager.ActiveWindow if AW~=nil then AW.HandleEvent("Pressed_2", WindowManager.GetMouseXY(AW)) return true else return false end end Mouse.RegisterEventHandler("1_Down", HandleMousePressed_2) local function HandleMouseReleased_2() --вызывается при событии отпускания левой клавиши мыши SelectActiveWindow (MouseX, MouseY) -- проверка наличия активного окна local AW=WindowManager.ActiveWindow if AW~=nil then AW.HandleEvent("Released_2", WindowManager.GetMouseXY(AW)) return true else return false end end Mouse.RegisterEventHandler("1_Up", HandleMouseReleased_2) -- колесо мышки ------------------------------------------------------------------------- local function HandleMouseWheelUp() local AW=WindowManager.ActiveWindow if AW~=nil then AW.HandleEvent("MouseWheelUp", WindowManager.GetMouseXY(AW)) return true end end Mouse.RegisterEventHandler("Wheel_Up", HandleMouseWheelUp) local function HandleMouseWheelDown() local AW=WindowManager.ActiveWindow if AW~=nil then AW.HandleEvent("MouseWheelDown", WindowManager.GetMouseXY(AW)) return true end end Mouse.RegisterEventHandler("Wheel_Down", HandleMouseWheelDown) -- движение мышки ------------------------------------------------------------------------- local function HandleMouseMoved () --вызывается при событии перемещения мыши local OldActiveWindow=WindowManager.ActiveWindow if OldActiveWindow then --текущему активному окну сообщается, что мышка переместилась и взможно вышла за пределы OldActiveWindow.HandleEvent("MouseMoved", WindowManager.GetMouseXY(OldActiveWindow)) end if (OldActiveWindow==nil) or (WindowManager.FocusIfPointed) then --если текущее активное окно не выбрано или используется выбор по наведению мышки --то выбирается новое активное окно SelectActiveWindow () end local NewActiveWindow=WindowManager.ActiveWindow --проверка наличия активного окна if NewActiveWindow~=nil then --если было выбрано другое активное окно - то ему тоже передается сообщение о перемещении мышки if OldActiveWindow~=NewActiveWindow then NewActiveWindow.HandleEvent("MouseMoved", WindowManager.GetMouseXY(NewActiveWindow)) end return true else return false end end Mouse.RegisterEventHandler("Moved", HandleMouseMoved) -- мперемещение узла курсора------------------------------------------------------------------ local function UpdateCursorNodeMovement() local MouseX, MouseY = WindowManager.GetMouseXY() CursorNode:SetPosition(MouseX, MouseY,-5) end Mouse.RegisterEventHandler("Moved", UpdateCursorNodeMovement) local function OnCursorLeave() CursorNode:Unbind() end Mouse.RegisterEventHandler("CursorLeave", OnCursorLeave) local function OnCursorEnter() CursorNode:BindToParent(WindowManager.Node) end Mouse.RegisterEventHandler("CursorEnter", OnCursorEnter) -------------------------------------------------------------------------------------------------- -- обработка событий клавиатуры -------------------------------------------------------------------------------------------------- local function HandleKey(key) if WindowManager.ActiveWindow then WindowManager.ActiveWindow.HandleEvent("KeyDown", key) end end Keyboard.RegisterEventHandler("Down", HandleKey) local function HandleCharCode(CharCode) if WindowManager.ActiveWindow then WindowManager.ActiveWindow.HandleEvent("CharCode", CharCode) end end Keyboard.RegisterEventHandler("CharCode", HandleCharCode) Mouse.Hide() UpdateCursorNodeMovement () end
return {'isbn'}
--- Library implementing a minimal TFTP server -- -- Currently only write-operations are supported so that script can trigger -- TFTP transfers and receive the files and return them as result. -- -- The library contains the following classes -- * <code>Packet</code> -- ** The <code>Packet</code> classes contain one class for each TFTP operation. -- * <code>File</code> -- ** The <code>File</code> class holds a received file including the name and contents -- * <code>ConnHandler</code> -- ** The <code>ConnHandler</code> class handles and processes incoming connections. -- -- The following code snippet starts the TFTP server and waits for the file incoming.txt -- to be uploaded for 10 seconds: -- <code> -- tftp.start() -- local status, f = tftp.waitFile("incoming.txt", 10) -- if ( status ) then return f:getContent() end -- </code> -- -- @author Patrik Karlsson <patrik@cqure.net> -- @copyright Same as Nmap--See http://nmap.org/book/man-legal.html -- -- version 0.2 -- -- 2011-01-22 - re-wrote library to use coroutines instead of new_thread code. local bin = require "bin" local coroutine = require "coroutine" local nmap = require "nmap" local os = require "os" local stdnse = require "stdnse" local table = require "table" _ENV = stdnse.module("tftp", stdnse.seeall) threads, infiles, running = {}, {}, {} state = "STOPPED" srvthread = {} -- All opcodes supported by TFTP OpCode = { RRQ = 1, WRQ = 2, DATA = 3, ACK = 4, ERROR = 5, } --- A minimal packet implementation -- -- The current code only implements the ACK and ERROR packets -- As the server is write-only the other packet types are not needed Packet = { -- Implements the ACK packet ACK = { new = function( self, block ) local o = {} setmetatable(o, self) self.__index = self o.block = block return o end, __tostring = function( self ) return bin.pack(">SS", OpCode.ACK, self.block) end, }, -- Implements the error packet ERROR = { new = function( self, code, msg ) local o = {} setmetatable(o, self) self.__index = self o.msg = msg o.code = code return o end, __tostring = function( self ) return bin.pack(">SSz", OpCode.ERROR, self.code, self.msg) end, } } --- The File class holds files received by the TFTP server File = { --- Creates a new file object -- -- @param filename string containing the filename -- @param content string containing the file content -- @return o new class instance new = function(self, filename, content, sender) local o = {} setmetatable(o, self) self.__index = self o.name = filename o.content = content o.sender = sender return o end, getContent = function(self) return self.content end, setContent = function(self, content) self.content = content end, getName = function(self) return self.name end, setName = function(self, name) self.name = name end, setSender = function(self, sender) self.sender = sender end, getSender = function(self) return self.sender end, } -- The thread dispatcher is called by the start function once local function dispatcher() local last = os.time() local f_condvar = nmap.condvar(infiles) local s_condvar = nmap.condvar(state) while(true) do -- check if other scripts are active local counter = 0 for t in pairs(running) do counter = counter + 1 end if ( counter == 0 ) then state = "STOPPING" s_condvar "broadcast" end if #threads == 0 then break end for i, thread in ipairs(threads) do local status, res = coroutine.resume(thread) if ( not(res) ) then -- thread finished its task? table.remove(threads, i) break end end -- Make sure to process waitFile atleast every 2 seconds -- in case no files have arrived if ( os.time() - last >= 2 ) then last = os.time() f_condvar "broadcast" end end state = "STOPPED" s_condvar "broadcast" stdnse.debug1("Exiting _dispatcher") end -- Processes a new incoming file transfer -- Currently only uploads are supported -- -- @param host containing the hostname or ip of the initiating host -- @param port containing the port of the initiating host -- @param data string containing the initial data passed to the server local function processConnection( host, port, data ) local pos, op = bin.unpack(">S", data) local socket = nmap.new_socket("udp") socket:set_timeout(1000) local status, err = socket:connect(host, port) if ( not(status) ) then return status, err end socket:set_timeout(10) -- If we get anything else than a write request, abort the connection if ( OpCode.WRQ ~= op ) then stdnse.debug1("Unsupported opcode") socket:send( tostring(Packet.ERROR:new(0, "TFTP server has write-only support"))) end local pos, filename, enctype = bin.unpack("zz", data, pos) status, err = socket:send( tostring( Packet.ACK:new(0) ) ) local blocks = {} local lastread = os.time() while( true ) do local status, pdata = socket:receive() if ( not(status) ) then -- if we're here and haven't successfully read a packet for 5 seconds, abort if ( os.time() - lastread > 5 ) then coroutine.yield(false) else coroutine.yield(true) end else -- record last time we had a successful read lastread = os.time() pos, op = bin.unpack(">S", pdata) if ( OpCode.DATA ~= op ) then stdnse.debug1("Expected a data packet, terminating TFTP transfer") end local block, data pos, block, data = bin.unpack(">SA" .. #pdata - 4, pdata, pos ) blocks[block] = data -- First block was not 1 if ( #blocks == 0 ) then socket:send( tostring(Packet.ERROR:new(0, "Did not receive block 1"))) break end -- for every fifth block check that we've received the preceding four if ( ( #blocks % 5 ) == 0 ) then for b = #blocks - 4, #blocks do if ( not(blocks[b]) ) then socket:send( tostring(Packet.ERROR:new(0, "Did not receive block " .. b))) end end end -- Ack the data block status, err = socket:send( tostring(Packet.ACK:new(block)) ) if ( ( #blocks % 20 ) == 0 ) then -- yield every 5th iteration so other threads may work coroutine.yield(true) end -- If the data length was less than 512, this was our last block if ( #data < 512 ) then socket:close() break end end end local filecontent = {} -- Make sure we received all the blocks needed to proceed for i=1, #blocks do if ( not(blocks[i]) ) then return false, ("Block #%d was missing in transfer") end filecontent[#filecontent+1] = blocks[i] end stdnse.debug1("Finished receiving file \"%s\"", filename) -- Add anew file to the global infiles table table.insert( infiles, File:new(filename, table.concat(filecontent), host) ) local condvar = nmap.condvar(infiles) condvar "broadcast" end -- Waits for a connection from a client local function waitForConnection() local srvsock = nmap.new_socket("udp") local status = srvsock:bind(nil, 69) assert(status, "Failed to bind to TFTP server port") srvsock:set_timeout(0) while( state == "RUNNING" ) do local status, data = srvsock:receive() if ( not(status) ) then coroutine.yield(true) else local status, _, _, rhost, rport = srvsock:get_info() local x = coroutine.create( function() processConnection(rhost, rport, data) end ) table.insert( threads, x ) coroutine.yield(true) end end end --- Starts the TFTP server and creates a new thread handing over to the dispatcher function start() local disp = nil local mutex = nmap.mutex("srvsocket") -- register a running script running[coroutine.running()] = true mutex "lock" if ( state == "STOPPED" ) then srvthread = coroutine.running() table.insert( threads, coroutine.create( waitForConnection ) ) stdnse.new_thread( dispatcher ) state = "RUNNING" end mutex "done" end local function waitLast() -- The thread that started the server needs to wait here until the rest -- of the scripts finish running. We know we are done once the state -- shifts to STOPPED and we get a signal from the condvar in the -- dispatcher local s_condvar = nmap.condvar(state) while( srvthread == coroutine.running() and state ~= "STOPPED" ) do s_condvar "wait" end end --- Waits for a file with a specific filename for at least the number of -- seconds specified by the timeout parameter. -- -- If this function is called from the thread that's running the server it will -- wait until all the other threads have finished executing before returning. -- -- @param filename string containing the name of the file to receive -- @param timeout number containing the minimum number of seconds to wait -- for the file to be received -- @return status true on success false on failure -- @return File instance on success, nil on failure function waitFile( filename, timeout ) local condvar = nmap.condvar(infiles) local t = os.time() while(os.time() - t < timeout) do for _, f in ipairs(infiles) do if (f:getName() == filename) then running[coroutine.running()] = nil waitLast() return true, f end end condvar "wait" end -- de-register a running script running[coroutine.running()] = nil waitLast() return false end return _ENV;
Camp = {} Camp.e = {} ------------------------------------------------------ -- System events ------------------------------------------------------ function Camp:new() local u = {} setmetatable(u, self) self.__index = self return u end function Camp:onConnect(opt) self.dt = 0 self.dtTurn = 0 self.range = opt.range self.x, self.y = self.entity.RigidBody:getLoc() trace(self.x, self.range) end function Camp:enable(y) end function Camp:disable() end function Camp:onUpdate(dt) self.dt = self.dt + dt self.dtTurn = self.dtTurn + dt if self.dt > 0.5 and self.dtTurn > 3 then local ent = self.entity local x,y = ent.RigidBody:getLoc() -- trace(x, self.x + self.range/2, self.x - self.range/2) if x > self.x + self.range/2 then ent.FungiMove:turnAround() ent.Sprite:turnAround() elseif x < self.x - self.range/2 then ent.FungiMove:turnAround() ent.Sprite:turnAround() end self.dtTurn = 0 self.dt = 0 end end ------------------------------------------------------ -- Entity events ------------------------------------------------------
memo = {} label = {} button = {} edit = {} function openWindow() if (loggingWindow) then return true end -- Window loggingWindow = guiCreateWindow(0.30, 0.25, 0.40, 0.50, "AUR - Check Logs", true) guiWindowSetSizable(loggingWindow, false) guiSetVisible(loggingWindow, false) -- Tab tabPanel = guiCreateTabPanel(0.02, 0.07, 0.96, 0.83, true, loggingWindow) -- Tab 1 accountLogs = guiCreateTab("Account Logs", tabPanel) -- Edit edit[accountLogs] = guiCreateEdit(124, 13, 236, 23, "", false, accountLogs) -- Label label[accountLogs] = guiCreateLabel(0.01, 0.04, 0.22, 0.09, "Account Name", true, accountLogs) guiSetFont(label[accountLogs], "default-bold-small") guiLabelSetHorizontalAlign(label[accountLogs], "right", false) guiLabelSetVerticalAlign(label[accountLogs], "center") -- Button button[accountLogs] = guiCreateButton(0.74, 0.05, 0.24, 0.08, "Check", true, accountLogs) closeButton = guiCreateButton(0.02, 0.91, 0.96, 0.06, "Close", true, loggingWindow) -- Memo memo[accountLogs] = guiCreateMemo(0.02, 0.14, 0.96, 0.82, "Account name must be exact", true, accountLogs) guiMemoSetReadOnly(memo[accountLogs], true) -- Tab 2 serialLogs = guiCreateTab("Serial Logs", tabPanel) -- Edit edit[serialLogs] = guiCreateEdit(124, 13, 236, 23, "", false, serialLogs) -- Label label[serialLogs] = guiCreateLabel(0.01, 0.04, 0.22, 0.09, "Serial", true, serialLogs) guiSetFont(label[serialLogs], "default-bold-small") guiLabelSetHorizontalAlign(label[serialLogs], "right", false) guiLabelSetVerticalAlign(label[serialLogs], "center") -- Button button[serialLogs] = guiCreateButton(0.74, 0.05, 0.24, 0.08, "Check", true, serialLogs) -- serialLogs memo[serialLogs] = guiCreateMemo(0.02, 0.14, 0.96, 0.82, "Serial must be exact", true, serialLogs) guiMemoSetReadOnly(memo[serialLogs], true) -- Tab 3 ipLogs = guiCreateTab("IP Logs", tabPanel) -- Edit edit[ipLogs] = guiCreateEdit(124, 13, 236, 23, "", false, ipLogs) -- Label label[ipLogs] = guiCreateLabel(0.01, 0.04, 0.22, 0.09, "IP Address", true, ipLogs) guiSetFont(label[ipLogs], "default-bold-small") guiLabelSetHorizontalAlign(label[ipLogs], "right", false) guiLabelSetVerticalAlign(label[ipLogs], "center") -- Button button[ipLogs] = guiCreateButton(0.74, 0.05, 0.24, 0.08, "Check", true, ipLogs) -- Memo memo[ipLogs] = guiCreateMemo(0.02, 0.14, 0.96, 0.82, "IP Address name must be exact", true, ipLogs) guiMemoSetReadOnly(memo[ipLogs], true) -- Event handlers addEventHandler("onClientGUIClick", closeButton, closeGUI, false) addEventHandler("onClientGUIClick", button[accountLogs], getAccountLogs, false) addEventHandler("onClientGUIClick", button[serialLogs], getSerialLogs, false) addEventHandler("onClientGUIClick", button[ipLogs], getIPLogs, false) end function getAccountLogs(btn) if (btn ~= "left") then return false end if (btn ~= "left") then return false end triggerServerEvent("CSGlogging.getLogs", localPlayer, "account", guiGetText(edit[accountLogs])) end function getSerialLogs(btn) if (btn ~= "left") then return false end if (btn ~= "left") then return false end triggerServerEvent("CSGlogging.getLogs", localPlayer, "serial", guiGetText(edit[serialLogs])) end function getIPLogs(btn) if (btn ~= "left") then return false end triggerServerEvent("CSGlogging.getLogs", localPlayer, "ip", guiGetText(edit[ipLogs])) end function closeGUI(btn) if (btn ~= "left") then return false end -- Close GUI guiSetVisible(loggingWindow, false) showCursor(false) end function searchFunction(_, ...) if (not guiGetVisible(loggingWindow)) then return false end local msg = table.concat({...}, " ") local text = split(guiGetText(memo[guiGetSelectedTab(tabPanel)]), "\n") local toShow = "" for i, v in ipairs(text) do if (v:find(msg)) then toShow = toShow..v.."\n" end end guiSetText(memo[guiGetSelectedTab(tabPanel)], toShow) end addCommandHandler("search", searchFunction) function togGUI() openWindow() local vis = (not guiGetVisible(loggingWindow)) guiSetVisible(loggingWindow, vis) showCursor(vis) if (vis) then guiSetInputMode("no_binds_when_editing") end end addEvent("CSGlogging.gui", true) addEventHandler("CSGlogging.gui", root, togGUI) function recieveInformation(info) guiSetText(memo[guiGetSelectedTab(tabPanel)], info) end addEvent("CSGlogging.info", true) addEventHandler("CSGlogging.info", root, recieveInformation)
ShowToClient("Quests", "Starting quests 1-20lvl"); dofile (GetDir() .. "\\scripts\\Quests\\Q1.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q2.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q3.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q4.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q5.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q6.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q7.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q8.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q9.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q10.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q11.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q12.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q13.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q14.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q15.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q16.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q17.lua"); dofile (GetDir() .. "\\scripts\\Quests\\Q18.lua"); ShowToClient("Quests", "Finished quests 1-20lvl");
return function (request, next_middleware) request.headers.authentication = 'this-is-my-key' return next_middleware() end
----------------------------------- -- Area: Norg -- NPC: Heiji -- Starts and Ends Quest: Like a Shining Subligar -- !pos -1 -5 25 252 ----------------------------------- require("scripts/globals/settings") require("scripts/globals/titles") require("scripts/globals/shop") require("scripts/globals/quests") local ID = require("scripts/zones/Norg/IDs") ----------------------------------- function onTrade(player, npc, trade) ShiningSubligar = player:getQuestStatus(OUTLANDS, tpz.quest.id.outlands.LIKE_A_SHINING_SUBLIGAR) Subligar = trade:getItemQty(14242) if (Subligar > 0 and Subligar == trade:getItemCount()) then TurnedInVar = player:getCharVar("shiningSubligar_nb") if (ShiningSubligar == QUEST_ACCEPTED and TurnedInVar + Subligar >= 10) then -- complete quest player:startEvent(125) elseif (ShiningSubligar == QUEST_ACCEPTED and TurnedInVar <= 9) then -- turning in less than the amount needed to finish the quest TotalSubligar = Subligar + TurnedInVar player:tradeComplete() player:setCharVar("shiningSubligar_nb", TotalSubligar) player:startEvent(124, TotalSubligar) -- Update player on number of subligar turned in end else if (ShiningSubligar == QUEST_ACCEPTED) then player:startEvent(124, TotalSubligar) -- Update player on number of subligar turned in, but doesn't accept anything other than subligar else player:startEvent(122) -- Give standard conversation if items are traded but no quest is accepted end end end function onTrigger(player, npc) ShiningSubligar = player:getQuestStatus(OUTLANDS, tpz.quest.id.outlands.LIKE_A_SHINING_SUBLIGAR) if (ShiningSubligar == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 3) then player:startEvent(123) -- Start Like a Shining Subligar elseif (ShiningSubligar == QUEST_ACCEPTED) then player:startEvent(124, player:getCharVar("shiningSubligar_nb")) -- Update player on number of subligar turned in else player:startEvent(122) -- Standard Conversation end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 123) then player:addQuest(OUTLANDS, tpz.quest.id.outlands.LIKE_A_SHINING_SUBLIGAR) elseif (csid == 125) then player:tradeComplete() player:addTitle(tpz.title.LOOKS_SUBLIME_IN_A_SUBLIGAR) player:addItem(4955) -- Scroll of Kurayami: Ichi player:messageSpecial(ID.text.ITEM_OBTAINED, 4955) -- Scroll of Kurayami: Ichi player:setCharVar("shiningSubligar_nb", 0) player:addFame(NORG, 100) player:completeQuest(OUTLANDS, tpz.quest.id.outlands.LIKE_A_SHINING_SUBLIGAR) end end
-- placeholder map grid local map = nil local timer = 0 -- setup data representing a map function core_init() end -- update level data function core_update(dt) timer = timer + dt end -- return the map object function core_getMap() return map end
-- temperature widget type for GNU/Linux -- Copyright (C) 2010 Adrian C. <anrxc@sysphere.org> -- Copyright (C) 2017 mutlusun <mutlusun@github.com> -- -- This file is part of Vicious. -- -- Vicious is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as -- published by the Free Software Foundation, either version 2 of the -- License, or (at your option) any later version. -- -- Vicious is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Vicious. If not, see <https://www.gnu.org/licenses/>. -- {{{ Grab environment local type = type local tonumber = tonumber local string = { match = string.match } local math = { floor = math.floor } local helpers = require("vicious.helpers") -- }}} -- {{{ Thermal widget type return helpers.setcall(function (format, warg) if not warg then return end local zone = { -- Known temperature data sources ["sys"] = {"/sys/class/thermal/", file = "temp", div = 1000}, ["core"] = {"/sys/devices/platform/", file = "temp2_input",div = 1000}, ["hwmon"] = {"/sys/class/hwmon/", file = "temp1_input",div = 1000}, ["proc"] = {"/proc/acpi/thermal_zone/",file = "temperature"} } -- Default to /sys/class/thermal warg = type(warg) == "table" and warg or { warg, "sys" } -- Get temperature from thermal zone local _thermal = helpers.pathtotable(zone[warg[2]][1] .. warg[1]) local data = warg[3] and _thermal[warg[3]] or _thermal[zone[warg[2]].file] if data then if zone[warg[2]].div then return {math.floor(data / zone[warg[2]].div)} else -- /proc/acpi "temperature: N C" return {tonumber(string.match(data, "[%d]+"))} end end return {0} end) -- }}}
data:extend( { { type = "recipe", name = "angels-warehouse-buffer", energy_required = 10, enabled = "false", ingredients ={ {"steel-plate", 20}, {"angels-warehouse", 1}, {"advanced-circuit", 20}, }, result= "angels-warehouse-buffer", icon_size = 32, subgroup = "angels-warehouses", order = "e" }, } )
-- Class: Map -- A map saves memory and CPU time by acting as if it were a grid of sprites. -- Each different type of sprite in the grid is represented via a single -- object. Each sprite must have the same size, however. -- -- This works very similarly to a tilemap, but there is additional flexibility -- in using a sprite, e.g. animation and other display effects. (If you want it -- to act like a tilemap, use its loadTiles method.) However, changing a sprite's -- x or y position has no effect. Changing the scale will have weird effects as -- a map expects every sprite to be the same size. -- -- Extends: -- <Sprite> Map = Sprite:extend{ -- Constant: NO_SPRITE -- Represents a map entry with no sprite. NO_SPRITE = -1, -- Property: sprites -- An ordered table of <Sprite> objects to be used in conjunction with the map property. sprites = {}, -- Property: map -- A two-dimensional table of values, each corresponding to an entry in the sprites property. -- nb. The tile at (0, 0) visually is stored in [1, 1]. map = {}, -- Method: empty -- Creates an empty map. -- -- Arguments: -- width - width of the map in sprites -- height - height of the map in sprites -- -- Returns: -- self, for chaining empty = function (self, width, height) local x, y -- empty the map for x = 1, width do self.map[x] = {} for y = 1, height do self.map[x][y] = Map.NO_SPRITE end end -- set bounds self.width = width * self.spriteWidth self.height = height * self.spriteHeight return self end, -- Method: loadMap -- Loads map data from a file, typically comma-separated values. -- Each entry corresponds to an index in self.sprites, and all rows -- must have the same number of columns. -- -- Arguments: -- file - filename of source text to use -- colSeparator - character to use as separator of columns, default ',' -- rowSeparator - character to use as separator of rows, default newline -- -- Returns: -- self, for chaining loadMap = function (self, file, colSeparator, rowSeparator) colSeparator = colSeparator or ',' rowSeparator = rowSeparator or '\n' -- load data local x, y local source = Cached:text(file) local rows = split(source, rowSeparator) for y = 1, #rows do local cols = split(rows[y], colSeparator) for x = 1, #cols do if not self.map[x] then self.map[x] = {} end self.map[x][y] = tonumber(cols[x]) end end -- set bounds self.width = #self.map[1] * self.spriteWidth self.height = #self.map * self.spriteHeight return self end, -- Method: loadTiles --- Loads the sprites group with slices of a source image. -- By default, this uses the Tile class for sprites, but you -- may pass as replacement class. -- -- Arguments: -- image - source image to use for tiles -- class - class to create objects with; constructor -- will be called with properties: image, width, -- height, imageOffset (with x and y sub-properties) -- startIndex - starting index of tiles in self.sprites, default 0 -- -- Returns: -- self, for chaining loadTiles = function (self, image, class, startIndex) assert(self.spriteWidth and self.spriteHeight, 'sprite size must be set before loading tiles') if type(startIndex) ~= 'number' then startIndex = 0 end class = class or Tile self.sprites = self.sprites or {} local imageObj = Cached:image(image) local imageWidth = imageObj:getWidth() local imageHeight = imageObj:getHeight() local i = startIndex for y = 0, imageHeight - self.spriteHeight, self.spriteHeight do for x = 0, imageWidth - self.spriteWidth, self.spriteWidth do self.sprites[i] = class:new{ image = image, width = self.spriteWidth, height = self.spriteHeight, imageOffset = { x = x, y = y }} i = i + 1 end end return self end, -- Method: subcollide -- This acts as a wrapper to multiple collide() calls, as if -- there really were all the sprites in their particular positions. -- This is much more useful than Map:collide(), which simply checks -- if a sprite or group is touching the map at all. -- -- Arguments: -- other - other <Sprite> or <Group> -- -- Returns: -- boolean, whether any collision was detected subcollide = function (self, other) local hit = false local others if other.sprites then others = other.sprites else others = { other } end for _, othSpr in pairs(others) do if othSpr.solid then if othSpr.sprites then -- recurse into subgroups -- order is important here to avoid short-circuiting inappopriately hit = self:subcollide(othSpr.sprites) or hit else local startX, startY = self:pixelToMap(othSpr.x - self.x, othSpr.y - self.y) local endX, endY = self:pixelToMap(othSpr.x + othSpr.width - self.x, othSpr.y + othSpr.height - self.y) local x, y for x = startX, endX do for y = startY, endY do local spr = self.sprites[self.map[x][y]] if spr and spr.solid then -- position our map sprite as if it were onscreen spr.x = self.x + (x - 1) * self.spriteWidth spr.y = self.y + (y - 1) * self.spriteHeight hit = spr:collide(othSpr) or hit end end end end end end return hit end, -- Method: subdisplace -- This acts as a wrapper to multiple displace() calls, as if -- there really were all the sprites in their particular positions. -- This is much more useful than Map:displace(), which pushes a sprite or group -- so that it does not touch the map in its entirety. -- -- Arguments: -- other - other <Sprite> or <Group> to displace -- xHint - force horizontal displacement in one direction, uses direction constants -- yHint - force vertical displacement in one direction, uses direction constants subdisplace = function (self, other, xHint, yHint) local others if other.sprites then others = other.sprites else others = { other } end for _, othSpr in pairs(others) do if othSpr.solid then if othSpr.sprites then -- recurse into subgroups -- order is important here to avoid short-circuiting inappopriately self:subdisplace(othSpr.sprites) else local startX, startY = self:pixelToMap(othSpr.x - self.x, othSpr.y - self.y) local endX, endY = self:pixelToMap(othSpr.x + othSpr.width - self.x, othSpr.y + othSpr.height - self.y) local x, y for x = startX, endX do for y = startY, endY do local spr = self.sprites[self.map[x][y]] if spr and spr.solid then -- position our map sprite as if it were onscreen spr.x = self.x + (x - 1) * self.spriteWidth spr.y = self.y + (y - 1) * self.spriteHeight spr:displace(othSpr) end end end end end end end, -- Method: getMapSize -- Returns the size of the map in sprites. -- -- Arguments: -- none -- -- Returns: -- width and height in integers getMapSize = function (self) if #self.map == 0 then return 0, 0 else return #self.map, #self.map[1] end end, draw = function (self, x, y) -- lock our x/y coordinates to integers -- to avoid gaps in the tiles x = math.floor(x or self.x) y = math.floor(y or self.y) if not self.visible or self.alpha <= 0 then return end if not self.spriteWidth or not self.spriteHeight then return end -- determine drawing bounds -- we draw to fill the entire app windoow local startX, startY = self:pixelToMap(-x, -y) local endX, endY = self:pixelToMap(the.app.width - x, the.app.height - y) -- queue each sprite drawing operation local toDraw = {} for drawY = startY, endY do for drawX = startX, endX do local sprite = self.sprites[self.map[drawX][drawY]] if sprite and sprite.visible then if not toDraw[sprite] then toDraw[sprite] = {} end table.insert(toDraw[sprite], { x + (drawX - 1) * self.spriteWidth, y + (drawY - 1) * self.spriteHeight }) end end end -- draw each sprite in turn for sprite, list in pairs(toDraw) do for _, coords in pairs(list) do sprite:draw(coords[1], coords[2]) end end Sprite.draw(self) end, -- Method: pixelToMap -- Converts pixels to map coordinates. -- -- Arguments: -- x - x coordinate in pixels -- y - y coordinate in pixels -- clamp - clamp to map bounds? defaults to true -- -- Returns: -- x, y map coordinates pixelToMap = function (self, x, y, clamp) if type(clamp) == 'nil' then clamp = true end -- remember, Lua tables start at index 1 local mapX = math.floor(x / self.spriteWidth) + 1 local mapY = math.floor(y / self.spriteHeight) + 1 -- clamp to map bounds if clamp then if mapX < 1 then mapX = 1 end if mapY < 1 then mapY = 1 end if mapX > #self.map then mapX = #self.map end if mapY > #self.map[1] then mapY = #self.map[1] end end return mapX, mapY end, -- makes sure all sprites receive startFrame messages startFrame = function (self, elapsed) for _, spr in pairs(self.sprites) do spr:startFrame(elapsed) end Sprite.startFrame(self, elapsed) end, -- makes sure all sprites receive update messages update = function (self, elapsed) for _, spr in pairs(self.sprites) do spr:update(elapsed) end Sprite.update(self, elapsed) end, -- makes sure all sprites receive endFrame messages endFrame = function (self, elapsed) for _, spr in pairs(self.sprites) do spr:endFrame(elapsed) end Sprite.endFrame(self, elapsed) end, __tostring = function (self) local result = 'Map (x: ' .. self.x .. ', y: ' .. self.y .. ', w: ' .. self.width .. ', h: ' .. self.height .. ', ' if self.active then result = result .. 'active, ' else result = result .. 'inactive, ' end if self.visible then result = result .. 'visible, ' else result = result .. 'invisible, ' end if self.solid then result = result .. 'solid' else result = result .. 'not solid' end return result .. ')' end }
local guiSceneManager = {} guiSceneManager.currentUISceneIdx = 1 local font_TextName = "fonts/Marker Felt.ttf" local UIScene = class("UIScene") UIScene.__index = UIScene UIScene._uiLayer= nil UIScene._widget = nil UIScene._sceneTitle = nil function UIScene.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, UIScene) return target end function UIScene:init() self._uiLayer = cc.Layer:create() self:addChild(self._uiLayer) self._widget = ccs.GUIReader:getInstance():widgetFromJsonFile("cocosui/UITest/UITest.json") self._uiLayer:addChild(self._widget) local root = self._uiLayer:getChildByTag(81) self._sceneTitle = root:getChildByName("UItest") local function previousCallback(sender, eventType) if eventType == ccui.TouchEventType.ended then cc.Director:getInstance():replaceScene(guiSceneManager.previousUIScene()) end end local left_button = root:getChildByName("left_Button") left_button:addTouchEventListener(previousCallback) local function restartCallback(sender, eventType) if eventType == ccui.TouchEventType.ended then cc.Director:getInstance():replaceScene(guiSceneManager.currentUIScene()) end end local middle_button = root:getChildByName("middle_Button") middle_button:addTouchEventListener(restartCallback) local function nextCallback(sender, eventType) if eventType == ccui.TouchEventType.ended then cc.Director:getInstance():replaceScene(guiSceneManager.nextUIScene()) end end local right_button = root:getChildByName("right_Button") right_button:addTouchEventListener(nextCallback) local function menuCloseCallback( sender,eventType) if eventType == ccui.TouchEventType.ended then local scene = CocoStudioTestMain() if scene ~= nil then cc.Director:getInstance():replaceScene(scene) end end end local backMenuLabel = ccui.Text:create() backMenuLabel:setString("Back") backMenuLabel:setFontSize(20) backMenuLabel:setTouchScaleChangeEnabled(true) backMenuLabel:setPosition(cc.p(430,30)) backMenuLabel:setTouchEnabled(true) backMenuLabel:addTouchEventListener(menuCloseCallback) self._uiLayer:addChild(backMenuLabel) end function UIScene.create() local scene = cc.Scene:create() local layer = UIScene.extend(cc.Layer:create()) layer:init() scene:addChild(layer) return scene end local cocoStudioGuiArray = {} local dsl_env = { create = function(classname, superclass) local newclass = class(classname, superclass) newclass._displayValueLabel = nil function newclass.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, newclass) return target end function newclass:initLabel() self:init() local widgetSize = self._widget:getContentSize() self._displayValueLabel = ccui.Text:create() self._displayValueLabel:setString(classname) self._displayValueLabel:setFontName(font_TextName) self._displayValueLabel:setFontSize(32) self._displayValueLabel:setAnchorPoint(cc.p(0.5, -1)) self._displayValueLabel:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 + self._displayValueLabel:getContentSize().height * 1.8)) self._uiLayer:addChild(self._displayValueLabel) end function newclass.create() local scene = cc.Scene:create() local layer = newclass.extend(cc.Layer:create()) layer:initLabel() layer:initExtend() scene:addChild(layer) return scene end table.insert(cocoStudioGuiArray, { title = classname, func = function() return newclass.create() end } ) return newclass end, } local function add_new_testcase(fn) setfenv(fn, setmetatable(dsl_env, { __index = function(self, funName) return _G[funName] end })) return fn() end add_new_testcase(function() local UIButtonTest = create("UIButtonTest", UIScene) function UIButtonTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("Button") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function touchEvent(sender,eventType) if eventType == ccui.TouchEventType.began then self._displayValueLabel:setString("Touch Down") elseif eventType == ccui.TouchEventType.moved then self._displayValueLabel:setString("Touch Move") elseif eventType == ccui.TouchEventType.ended then self._displayValueLabel:setString("Touch Up") elseif eventType == ccui.TouchEventType.canceled then self._displayValueLabel:setString("Touch Cancelled") end end local button = ccui.Button:create() button:setTouchEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") button:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) button:addTouchEventListener(touchEvent) self._uiLayer:addChild(button) end end) add_new_testcase(function() local UIButtonScale9Test = create("UIButtonScale9Test", UIScene) function UIButtonScale9Test:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("Button scale9 render") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function touchEvent(sender,eventType) if eventType == ccui.TouchEventType.began then self._displayValueLabel:setString("Touch Down") elseif eventType == ccui.TouchEventType.moved then self._displayValueLabel:setString("Touch Move") elseif eventType == ccui.TouchEventType.ended then self._displayValueLabel:setString("Touch Up") elseif eventType == ccui.TouchEventType.canceled then self._displayValueLabel:setString("Touch Cancelled") end end local button = ccui.Button:create() button:setTouchEnabled(true) button:setScale9Enabled(true) button:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") button:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) button:setContentSize(cc.size(150, button:getVirtualRendererSize().height * 1.5)) button:addTouchEventListener(touchEvent) self._uiLayer:addChild(button) end end) add_new_testcase(function() local UIButtonPressedActionTest = create("UIButtonPressedActionTest",UIScene) function UIButtonPressedActionTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("Button Pressed Action") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function touchEvent(sender,eventType) if eventType == ccui.TouchEventType.began then self._displayValueLabel:setString("Touch Down") elseif eventType == ccui.TouchEventType.moved then self._displayValueLabel:setString("Touch Move") elseif eventType == ccui.TouchEventType.ended then self._displayValueLabel:setString("Touch Up") elseif eventType == ccui.TouchEventType.canceled then self._displayValueLabel:setString("Touch Cancelled") end end local button = ccui.Button:create() button:setTouchEnabled(true) button:setPressedActionEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") button:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) button:addTouchEventListener(touchEvent) self._uiLayer:addChild(button) end end) add_new_testcase(function() local UITextButtonTest = create("UITextButtonTest",UIScene) function UITextButtonTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("TextButton") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function touchEvent(sender,eventType) if eventType == ccui.TouchEventType.began then self._displayValueLabel:setString("Touch Down") elseif eventType == ccui.TouchEventType.moved then self._displayValueLabel:setString("Touch Move") elseif eventType == ccui.TouchEventType.ended then self._displayValueLabel:setString("Touch Up") elseif eventType == ccui.TouchEventType.canceled then self._displayValueLabel:setString("Touch Cancelled") end end local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) textButton:addTouchEventListener(touchEvent) self._uiLayer:addChild(textButton) end end) add_new_testcase(function() local UITextButtonScale9Test = create("UITextButtonScale9Test",UIScene) function UITextButtonScale9Test:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("TextButton scale9 render") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function touchEvent(sender,eventType) if eventType == ccui.TouchEventType.began then self._displayValueLabel:setString("Touch Down") elseif eventType == ccui.TouchEventType.moved then self._displayValueLabel:setString("Touch Move") elseif eventType == ccui.TouchEventType.ended then self._displayValueLabel:setString("Touch Up") elseif eventType == ccui.TouchEventType.canceled then self._displayValueLabel:setString("Touch Cancelled") end end local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:setScale9Enabled(true) textButton:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") textButton:setContentSize(cc.size(180, textButton:getVirtualRendererSize().height * 1.5)) textButton:setTitleText("Text Button scale9 render") textButton:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) textButton:addTouchEventListener(touchEvent) self._uiLayer:addChild(textButton) end end) add_new_testcase(function() local UICheckBoxTest = create("UICheckBoxTest",UIScene) function UICheckBoxTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("CheckBox") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function selectedEvent(sender,eventType) if eventType == ccui.CheckBoxEventType.selected then self._displayValueLabel:setString("Selected") elseif eventType == ccui.CheckBoxEventType.unselected then self._displayValueLabel:setString("Unselected") end end local checkBox = ccui.CheckBox:create() checkBox:setTouchEnabled(true) checkBox:setSelectedState(true) checkBox:loadTextures("cocosui/check_box_normal.png", "cocosui/check_box_normal_press.png", "cocosui/check_box_active.png", "cocosui/check_box_normal_disable.png", "cocosui/check_box_active_disable.png") checkBox:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) checkBox:addEventListener(selectedEvent) self._uiLayer:addChild(checkBox) end end) add_new_testcase(function() local UIRadioBoxTest = create("UIRadioBoxTest",UIScene) function UIRadioBoxTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("No selection is disallowed.") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 + 70)) self._uiLayer:addChild(alert) local radioButtonGroup = ccui.RadioButtonGroup:create() radioButtonGroup:addEventListener(function(radioButton, index, type) print("RadioButton" .. index .. "Clicked") end) self._uiLayer:addChild(radioButtonGroup) local NUMBER_OF_BUTTONS = 5 local BUTTON_WIDTH = 30 local startPosX = widgetSize.width / 2.0 - ((NUMBER_OF_BUTTONS - 1) / 1.0) * BUTTON_WIDTH for i = 0 , NUMBER_OF_BUTTONS-1 do local radioButton = ccui.RadioButton:create("cocosui/radio_button_off.png", "cocosui/radio_button_on.png") local posX = startPosX + BUTTON_WIDTH * i radioButton:setPosition(cc.p(posX, widgetSize.height / 2.0 + 10)) radioButton:setName("button"..i) radioButtonGroup:addRadioButton(radioButton) radioButton:addEventListener(function(radioButton, type) if type == ccui.RadioButtonEventType.selected then print("name: = " .. radioButton:getName() .. " selected") elseif type == ccui.RadioButtonEventType.unselected then print("name: = " .. radioButton:getName() .. " unselected") end end) self._uiLayer:addChild(radioButton) end local function buttonClickCallback(sender) local name = (tolua.cast(sender, "ccui.Button")):getTitleText() if name == "Add" then local pos = cc.p(0,0) if radioButtonGroup:getNumberOfRadioButtons() > 0 then local lastRadioButton = radioButtonGroup:getRadioButtonByIndex(radioButtonGroup:getNumberOfRadioButtons() - 1) pos.x, pos.y = lastRadioButton:getPosition() else pos.x = startPosX - BUTTON_WIDTH pos.y = self._widget:getContentSize().height / 2. + 10 end local tempButton = ccui.RadioButton:create("cocosui/radio_button_off.png", "cocosui/radio_button_on.png") pos.x = pos.x + BUTTON_WIDTH tempButton:setPosition(pos) radioButtonGroup:addRadioButton(tempButton) self._uiLayer:addChild(tempButton) elseif name == "Delete" then if radioButtonGroup:getNumberOfRadioButtons() > 0 then local radioButton = radioButtonGroup:getRadioButtonByIndex(radioButtonGroup:getNumberOfRadioButtons()-1) radioButtonGroup:removeRadioButton(radioButton) self._uiLayer:removeChild(radioButton) end elseif name == "Toggle" then radioButtonGroup:setAllowedNoSelection(not radioButtonGroup:isAllowedNoSelection()) alert:setString(radioButtonGroup:isAllowedNoSelection() and "No selection is allowed" or "No selection is disallowed") end end local hbox = ccui.HBox:create() hbox:setPosition(cc.p(10, widgetSize.height/2-65)) self._uiLayer:addChild(hbox) local addButton = ccui.Button:create("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png") addButton:setTitleText("Add") addButton:setScale(0.7) addButton:addClickEventListener(buttonClickCallback) hbox:addChild(addButton) local deleteButton = addButton:clone() deleteButton:setTitleText("Delete") hbox:addChild(deleteButton) local toggleButton = addButton:clone() toggleButton:setTitleText("Toggle") hbox:addChild(toggleButton) end end) add_new_testcase(function() local UISliderTest = create("UISliderTest",UIScene) function UISliderTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("Move the slider thumb") local alert = ccui.Text:create() alert:setString("Slider") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function percentChangedEvent(sender,eventType) print(eventType) if eventType == ccui.SliderEventType.percentChanged then local slider = sender local percent = "Percent " .. (slider:getPercent() / slider:getMaxPercent() * 100) self._displayValueLabel:setString(percent) elseif eventType == ccui.SliderEventType.slideBallUp then self._displayValueLabel:setString("Slide Ball Up") elseif eventType == ccui.SliderEventType.slideBallDown then self._displayValueLabel:setString("Slide Ball Down") elseif eventType == ccui.SliderEventType.slideBallCancel then self._displayValueLabel:setString("Slide Ball Cancel") end end local slider = ccui.Slider:create() slider:setTouchEnabled(true) slider:loadBarTexture("cocosui/sliderTrack.png") slider:loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", "") slider:loadProgressBarTexture("cocosui/sliderProgress.png") slider:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) slider:setMaxPercent(10000) slider:addEventListener(percentChangedEvent) self._uiLayer:addChild(slider) end end) add_new_testcase(function() local UISliderScale9Test = create("UISliderScale9Test",UIScene) function UISliderScale9Test:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("Move the slider thumb") local alert = ccui.Text:create() alert:setString("Slider scale9 render") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function percentChangedEvent(sender,eventType) if eventType == ccui.SliderEventType.percentChanged then local slider = sender local percent = "Percent " .. slider:getPercent() self._displayValueLabel:setString(percent) end end local slider = ccui.Slider:create() slider:setTouchEnabled(true) slider:loadBarTexture("cocosui/sliderTrack2.png") slider:loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", "") slider:loadProgressBarTexture("cocosui/slider_bar_active_9patch.png") slider:setScale9Enabled(true) slider:setCapInsets(cc.rect(0, 0, 0, 0)) slider:setContentSize(cc.size(250, 10)) slider:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) slider:addEventListener(percentChangedEvent) self._uiLayer:addChild(slider) end end) add_new_testcase(function() local UIImageViewTest = create("UIImageViewTest",UIScene) function UIImageViewTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("ImageView") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local imageView = ccui.ImageView:create() imageView:loadTexture("cocosui/ccicon.png") imageView:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 + imageView:getContentSize().height / 4.0)) self._uiLayer:addChild(imageView) end end) add_new_testcase(function () local UIImageViewScale9Test = create("UIImageViewScale9Test",UIScene) function UIImageViewScale9Test:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("ImageView scale9 render") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local imageView = ccui.ImageView:create() imageView:setScale9Enabled(true) imageView:loadTexture("cocosui/buttonHighlighted.png") imageView:setContentSize(cc.size(200, 85)) imageView:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 + imageView:getContentSize().height / 4.0)) self._uiLayer:addChild(imageView) end end) add_new_testcase(function () local UILoadingBarLeftTest = create("UILoadingBarLeftTest",UIScene) function UILoadingBarLeftTest:initExtend() self._count = 0 local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("LoadingBar") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local loadingBar = ccui.LoadingBar:create() loadingBar:setTag(0) loadingBar:setName("LoadingBar") loadingBar:loadTexture("cocosui/sliderProgress.png") loadingBar:setPercent(0) loadingBar:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 + loadingBar:getContentSize().height / 4.0)) self._uiLayer:addChild(loadingBar) local function update() self._count = self._count + 1 if self._count > 100 then self._count = 0 end if self._uiLayer ~= nil then loadingBar:setPercent(self._count) end end self:scheduleUpdateWithPriorityLua(update, 0) local function onNodeEvent(tag) if tag == "exit" then self:unscheduleUpdate() end end self:registerScriptHandler(onNodeEvent) end end) add_new_testcase(function () local UILoadingBarRightTest = create("UILoadingBarRightTest",UIScene) function UILoadingBarRightTest:initExtend() self._count = 0; local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("LoadingBar") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local loadingBar = ccui.LoadingBar:create() loadingBar:setTag(0) loadingBar:setName("LoadingBar") loadingBar:loadTexture("cocosui/sliderProgress.png") loadingBar:setDirection(ccui.LoadingBarDirection.RIGHT) loadingBar:setPercent(0) loadingBar:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 + loadingBar:getContentSize().height / 4.0)) self._uiLayer:addChild(loadingBar) local function update() self._count = self._count + 1 if self._count > 100 then self._count = 0 end if self._uiLayer ~= nil then loadingBar:setPercent(self._count) end end self:scheduleUpdateWithPriorityLua(update, 0) local function onNodeEvent(tag) if tag == "exit" then self:unscheduleUpdate() end end self:registerScriptHandler(onNodeEvent) end end) add_new_testcase(function () local UILoadingBarLeftScale9Test = create("UILoadingBarLeftScale9Test",UIScene) function UILoadingBarLeftScale9Test:initExtend() self._count = 0 local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("LoadingBar Scale9 Render") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local loadingBar = ccui.LoadingBar:create() loadingBar:setTag(0) loadingBar:setName("LoadingBar") loadingBar:loadTexture("cocosui/slider_bar_active_9patch.png") loadingBar:setScale9Enabled(true) loadingBar:setCapInsets(cc.rect(0, 0, 0, 0)) loadingBar:setContentSize(cc.size(300, 30)) loadingBar:setPercent(0) loadingBar:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 + loadingBar:getContentSize().height / 4.0)) self._uiLayer:addChild(loadingBar) local function update() self._count = self._count + 1 if self._count > 100 then self._count = 0 end if self._uiLayer ~= nil then loadingBar:setPercent(self._count) end end self:scheduleUpdateWithPriorityLua(update, 0) local function onNodeEvent(tag) if tag == "exit" then self:unscheduleUpdate() end end self:registerScriptHandler(onNodeEvent) end end) add_new_testcase(function () local UILoadingBarRightScale9Test = create("UILoadingBarRightScale9Test",UIScene) function UILoadingBarRightScale9Test:initExtend() self._count = 0 local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("LoadingBar Scale9 Render") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local loadingBar = ccui.LoadingBar:create() loadingBar:setTag(0) loadingBar:setName("LoadingBar") loadingBar:loadTexture("cocosui/slider_bar_active_9patch.png") loadingBar:setScale9Enabled(true) loadingBar:setCapInsets(cc.rect(0, 0, 0, 0)) loadingBar:setContentSize(cc.size(300, 30)) loadingBar:setDirection(ccui.LoadingBarDirection.RIGHT) loadingBar:setPercent(0) loadingBar:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 + loadingBar:getContentSize().height / 4.0)) self._uiLayer:addChild(loadingBar) local function update() self._count = self._count + 1 if self._count > 100 then self._count = 0 end if self._uiLayer ~= nil then loadingBar:setPercent(self._count) end end self:scheduleUpdateWithPriorityLua(update, 0) local function onNodeEvent(tag) if tag == "exit" then self:unscheduleUpdate() end end self:registerScriptHandler(onNodeEvent) end end) add_new_testcase(function () local UILabelAtlasTest = create("UILabelAtlasTest",UIScene) function UILabelAtlasTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("LabelAtlas") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local labelAtlas = ccui.TextAtlas:create() if cc.Director:getInstance():getWinSizeInPixels().height > 320 then labelAtlas:setProperty("1234567890", "cocosui/labelatlas.png", 34, 44, "0") else labelAtlas:setProperty("1234567890", "cocosui/labelatlas.png", 17, 22, "0") end labelAtlas:setPosition(cc.p((widgetSize.width) / 2, widgetSize.height / 2.0)) self._uiLayer:addChild(labelAtlas) end end) add_new_testcase(function () local UILabelBMFontTest = create("UILabelBMFontTest",UIScene) function UILabelBMFontTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("LabelBMFont") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local labelBMFont = ccui.TextBMFont:create() labelBMFont:setFntFile("cocosui/bitmapFontTest2.fnt") labelBMFont:setString("BMFont") labelBMFont:setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2.0 + labelBMFont:getContentSize().height / 8.0)) self._uiLayer:addChild(labelBMFont) end end) add_new_testcase(function() local UILabelTest = create("UILabelTest",UIScene) function UILabelTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("Label") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local label = ccui.Text:create() label:setString("Label") label:setFontName("AmericanTypewriter") label:setFontSize(30) label:setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 + label:getContentSize().height / 4)) self._uiLayer:addChild(label) end end) add_new_testcase(function() local UITextAreaTest = create("UITextAreaTest",UIScene) function UITextAreaTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("TextArea") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local textArea = ccui.Text:create() textArea:ignoreContentAdaptWithSize(false) textArea:setContentSize(cc.size(280, 150)) textArea:setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER) textArea:setString("TextArea widget can line wrap") textArea:setFontName("AmericanTypewriter") textArea:setFontSize(32) textArea:setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 - textArea:getContentSize().height / 8)) self._uiLayer:addChild(textArea) end end) add_new_testcase(function() local UITextFieldTest = create("UITextFieldTest",UIScene) function UITextFieldTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("TextField") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function textFieldEvent(sender, eventType) if eventType == ccui.TextFiledEventType.attach_with_ime then local textField = sender textField:runAction(cc.MoveBy:create(0.225,cc.p(0, 20))) self._displayValueLabel:setString("attach with IME") elseif eventType == ccui.TextFiledEventType.detach_with_ime then local textField = sender textField:runAction(cc.MoveBy:create(0.175, cc.p(0, -20))) self._displayValueLabel:setString("detach with IME") elseif eventType == ccui.TextFiledEventType.insert_text then self._displayValueLabel:setString("insert words") elseif eventType == ccui.TextFiledEventType.delete_backward then self._displayValueLabel:setString("delete word") end end local textField = ccui.TextField:create() textField:setTouchEnabled(true) textField:setFontName(font_TextName) textField:setFontSize(30) textField:setPlaceHolder("input words here") textField:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) textField:addEventListener(textFieldEvent) self._uiLayer:addChild(textField) end end) add_new_testcase(function() local UITextFieldMaxLengthTest = create("UITextFieldMaxLengthTest",UIScene) function UITextFieldMaxLengthTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("TextField max length") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function textFieldEvent(sender, eventType) if eventType == ccui.TextFiledEventType.attach_with_ime then local textField = sender textField:runAction(cc.MoveBy:create(0.225,cc.p(0, 20))) local info = string.format("attach with IME max length %d",textField:getMaxLength()) self._displayValueLabel:setString(info) elseif eventType == ccui.TextFiledEventType.detach_with_ime then local textField = sender textField:runAction(cc.MoveBy:create(0.175, cc.p(0, -20))) local info = string.format("detach with IME max length %d",textField:getMaxLength()) self._displayValueLabel:setString(info) elseif eventType == ccui.TextFiledEventType.insert_text then local textField = sender local info = string.format("insert words max length %d",textField:getMaxLength()) self._displayValueLabel:setString(info) elseif eventType == ccui.TextFiledEventType.delete_backward then local textField = sender local info = string.format("delete word max length %d",textField:getMaxLength()) self._displayValueLabel:setString(info) end end local textField = ccui.TextField:create() textField:setMaxLengthEnabled(true) textField:setMaxLength(3) textField:setTouchEnabled(true) textField:setFontName(font_TextName) textField:setFontSize(30) textField:setPlaceHolder("input words here") textField:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) textField:addEventListener(textFieldEvent) self._uiLayer:addChild(textField) end end) add_new_testcase(function() local UITextFieldPasswordTest = create("UITextFieldPasswordTest",UIScene) function UITextFieldPasswordTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("TextField password") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local function textFieldEvent(sender, eventType) if eventType == ccui.TextFiledEventType.attach_with_ime then local textField = sender textField:runAction(cc.MoveBy:create(0.175, cc.p(0, 20))) self._displayValueLabel:setString("detach with IME password") elseif eventType == ccui.TextFiledEventType.detach_with_ime then local textField = sender textField:runAction(cc.MoveBy:create(0.175, cc.p(0, -20))) self._displayValueLabel:setString("detach with IME password") elseif eventType == ccui.TextFiledEventType.insert_text then self._displayValueLabel:setString("insert words password") elseif eventType == ccui.TextFiledEventType.delete_backward then self._displayValueLabel:setString("delete word password") end end local textField = ccui.TextField:create() textField:setPasswordEnabled(true) textField:setPasswordStyleText("*") textField:setTouchEnabled(true) textField:setFontName(font_TextName) textField:setFontSize(30) textField:setPlaceHolder("input password here") textField:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) textField:addEventListener(textFieldEvent) self._uiLayer:addChild(textField) end end) add_new_testcase(function() local UIPanelTest = create("UIPanelTest",UIScene) function UIPanelTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("Panel") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local layout = ccui.Layout:create() layout:setContentSize(cc.size(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getContentSize().height) / 2)) self._uiLayer:addChild(layout) local button = ccui.Button:create() button:setTouchEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") button:setPosition(cc.p(button:getContentSize().width / 2, layout:getContentSize().height - button:getContentSize().height / 2)) layout:addChild(button) local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(cc.p(layout:getContentSize().width / 2, layout:getContentSize().height / 2)) layout:addChild(textButton) local button_scale9 = ccui.Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setContentSize(cc.size(100, button_scale9:getVirtualRendererSize().height)) button_scale9:setPosition(cc.p(layout:getContentSize().width - button_scale9:getContentSize().width / 2, button_scale9:getContentSize().height / 2)) layout:addChild(button_scale9) end end) add_new_testcase(function() local UIPanelColorTest = create("UIPanelColorTest",UIScene) function UIPanelColorTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("Panel color render") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local layout = ccui.Layout:create() layout:setBackGroundColorType(ccui.LayoutBackGroundColorType.solid) layout:setBackGroundColor(cc.c3b(128, 128, 128)) layout:setContentSize(cc.size(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getContentSize().height) / 2)) self._uiLayer:addChild(layout) local button = ccui.Button:create() button:setTouchEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") button:setPosition(cc.p(button:getContentSize().width / 2, layout:getContentSize().height - button:getContentSize().height / 2)) layout:addChild(button) local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(cc.p(layout:getContentSize().width / 2, layout:getContentSize().height / 2)) layout:addChild(textButton) local button_scale9 = ccui.Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setContentSize(cc.size(100, button_scale9:getVirtualRendererSize().height)) button_scale9:setPosition(cc.p(layout:getContentSize().width - button_scale9:getContentSize().width / 2, button_scale9:getContentSize().height / 2)) layout:addChild(button_scale9) end end) add_new_testcase(function() local UIPanelGradientTest = create("UIPanelGradientTest",UIScene) function UIPanelGradientTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("Panel color Gradient") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local layout = ccui.Layout:create() layout:setBackGroundColorType(ccui.LayoutBackGroundColorType.gradient) layout:setBackGroundColor(cc.c3b(64, 64, 64), cc.c3b(192, 192, 192)) layout:setContentSize(cc.size(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getContentSize().height) / 2)) self._uiLayer:addChild(layout) local button = ccui.Button:create() button:setTouchEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") button:setPosition(cc.p(button:getContentSize().width / 2, layout:getContentSize().height - button:getContentSize().height / 2)) layout:addChild(button) local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(cc.p(layout:getContentSize().width / 2, layout:getContentSize().height / 2)) layout:addChild(textButton) local button_scale9 = ccui.Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setContentSize(cc.size(100, button_scale9:getVirtualRendererSize().height)) button_scale9:setPosition(cc.p(layout:getContentSize().width - button_scale9:getContentSize().width / 2, button_scale9:getContentSize().height / 2)) layout:addChild(button_scale9) end end) add_new_testcase(function() local UIPanelBackGroundImageTest = create("UIPanelBackGroundImageTest",UIScene) function UIPanelBackGroundImageTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("Panel background image") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local layout = ccui.Layout:create() layout:setClippingEnabled(true) layout:setBackGroundImage("cocosui/Hello.png") layout:setContentSize(cc.size(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getContentSize().height) / 2)) self._uiLayer:addChild(layout) local button = ccui.Button:create() button:setTouchEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") button:setPosition(cc.p(button:getContentSize().width / 2, layout:getContentSize().height - button:getContentSize().height / 2)) layout:addChild(button) local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(cc.p(layout:getContentSize().width / 2, layout:getContentSize().height / 2)) layout:addChild(textButton) local button_scale9 = ccui.Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setContentSize(cc.size(100, button_scale9:getVirtualRendererSize().height)) button_scale9:setPosition(cc.p(layout:getContentSize().width - button_scale9:getContentSize().width / 2, button_scale9:getContentSize().height / 2)) layout:addChild(button_scale9) end end) add_new_testcase(function() local UIPanelBackGroundImageScale9Test = create("UIPanelBackGroundImageScale9Test",UIScene) function UIPanelBackGroundImageScale9Test:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("Panel background image scale9") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local layout = ccui.Layout:create() layout:setBackGroundImageScale9Enabled(true) layout:setBackGroundImage("cocosui/green_edit.png") layout:setContentSize(cc.size(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getContentSize().height) / 2)) self._uiLayer:addChild(layout) local button = ccui.Button:create() button:setTouchEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") button:setPosition(cc.p(button:getContentSize().width / 2, layout:getContentSize().height - button:getContentSize().height / 2)) layout:addChild(button) local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(cc.p(layout:getContentSize().width / 2, layout:getContentSize().height / 2)) layout:addChild(textButton) local button_scale9 = ccui.Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setContentSize(cc.size(100, button_scale9:getVirtualRendererSize().height)) button_scale9:setPosition(cc.p(layout:getContentSize().width - button_scale9:getContentSize().width / 2, button_scale9:getContentSize().height / 2)) layout:addChild(button_scale9) end end) add_new_testcase(function() local UIPanelLayoutLinearVerticalTest = create("UIPanelLayoutLinearVerticalTest",UIScene) function UIPanelLayoutLinearVerticalTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("Panel Layout Linear Vertical") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local layout = ccui.Layout:create() layout:setLayoutType(ccui.LayoutType.VERTICAL) layout:setContentSize(cc.size(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getContentSize().height) / 2)) self._uiLayer:addChild(layout) local button = ccui.Button:create() button:setTouchEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") layout:addChild(button) local lp1 = ccui.LinearLayoutParameter:create() button:setLayoutParameter(lp1) lp1:setGravity(ccui.LinearGravity.centerHorizontal) lp1:setMargin({ left = 0, top = 5, right = 0, bottom = 10 }) local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png", "") textButton:setTitleText("Text Button") layout:addChild(textButton) local lp2 = ccui.LinearLayoutParameter:create() textButton:setLayoutParameter(lp2) lp2:setGravity(ccui.LinearGravity.centerHorizontal) lp2:setMargin({left = 0, top = 10, right = 0, bottom = 10} ) local button_scale9 = ccui.Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setContentSize(cc.size(100, button_scale9:getVirtualRendererSize().height)) layout:addChild(button_scale9) local lp3 = ccui.LinearLayoutParameter:create() button_scale9:setLayoutParameter(lp3) lp3:setGravity(ccui.LinearGravity.centerHorizontal) lp3:setMargin({ left = 0, top = 10, right = 0, bottom = 10 } ) end end) add_new_testcase(function() local UIPanelLayoutLinearHorizontalTest = create("UIPanelLayoutLinearHorizontalTest",UIScene) function UIPanelLayoutLinearHorizontalTest:initExtend() local widgetSize = self._widget:getContentSize() local alert = ccui.Text:create() alert:setString("Panel Layout Linear Horizontal") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local layout = ccui.Layout:create() layout:setLayoutType(ccui.LayoutType.HORIZONTAL) layout:setClippingEnabled(true) layout:setContentSize(cc.size(280, 150)) local backgroundSize = background:getContentSize() layout:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - layout:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - layout:getContentSize().height) / 2)) self._uiLayer:addChild(layout) local button = ccui.Button:create() button:setTouchEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") layout:addChild(button) local lp1 = ccui.LinearLayoutParameter:create() button:setLayoutParameter(lp1) lp1:setGravity(ccui.LinearGravity.centerVertical) lp1:setMargin({left = 0, top = 10, right = 0, bottom = 10} ) local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png", "") textButton:setTitleText("Text Button") layout:addChild(textButton) local lp2 = ccui.LinearLayoutParameter:create() textButton:setLayoutParameter(lp2) lp2:setGravity(ccui.LinearGravity.centerVertical) lp2:setMargin({left = 0,top = 10,right = 0,bottom = 10}) local button_scale9 = ccui.Button:create() button_scale9:setTouchEnabled(true) button_scale9:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") button_scale9:setScale9Enabled(true) button_scale9:setContentSize(cc.size(100, button_scale9:getVirtualRendererSize().height)) layout:addChild(button_scale9) local lp3 = ccui.LinearLayoutParameter:create() button_scale9:setLayoutParameter(lp3) lp3:setGravity(ccui.LinearGravity.centerVertical) lp3:setMargin({left = 0, top = 10, right = 0, bottom = 10}) end end) add_new_testcase(function() local UILayoutComponentBerthTest = create("UILayoutComponentBerthTest",UIScene) function UILayoutComponentBerthTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("LayoutComponent Berth Test") local baseLayer = cc.LayerColor:create() baseLayer:setColor(cc.c3b(50, 100, 0)) baseLayer:setOpacity(100) baseLayer:setContentSize(cc.size(200, 200)) self._uiLayer:addChild(baseLayer) button = ccui.Button:create("cocosui/animationbuttonnormal.png") print(string.format("content size should be greater than 0: width = %f, height = %f", button:getContentSize().width, button:getContentSize().height)) button:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) button:addTouchEventListener(function(sender, eventType) if eventType == ccui.TouchEventType.ended then local touchWidgetSize = self._widget:getContentSize() local layerSize = baseLayer:getContentSize() if (layerSize.width == touchWidgetSize.width and layerSize.height == touchWidgetSize.height) then baseLayer:setContentSize(cc.size(200, 200)) else baseLayer:setContentSize(widgetSize) end ccui.Helper:doLayout(baseLayer) end end) button:setZoomScale(0.4) button:setPressedActionEnabled(true) self._uiLayer:addChild(button) local leftTopSprite = cc.Sprite:create("cocosui/CloseSelected.png") local leftTop = ccui.LayoutComponent:bindLayoutComponent(leftTopSprite) leftTop:setHorizontalEdge(ccui.LayoutComponent.HorizontalEdge.Left) leftTop:setVerticalEdge(ccui.LayoutComponent.VerticalEdge.Top) baseLayer:addChild(leftTopSprite) local leftBottomSprite = cc.Sprite:create("cocosui/CloseSelected.png") local leftBottom = ccui.LayoutComponent:bindLayoutComponent(leftBottomSprite) leftBottom:setHorizontalEdge(ccui.LayoutComponent.HorizontalEdge.Left) leftBottom:setVerticalEdge(ccui.LayoutComponent.VerticalEdge.Bottom) baseLayer:addChild(leftBottomSprite) local rightTopSprite = cc.Sprite:create("cocosui/CloseSelected.png") local rightTop = ccui.LayoutComponent:bindLayoutComponent(rightTopSprite) rightTop:setHorizontalEdge(ccui.LayoutComponent.HorizontalEdge.Right) rightTop:setVerticalEdge(ccui.LayoutComponent.VerticalEdge.Top) baseLayer:addChild(rightTopSprite) local rightBottomSprite = cc.Sprite:create("cocosui/CloseSelected.png") local rightBottom = ccui.LayoutComponent:bindLayoutComponent(rightBottomSprite) rightBottom:setHorizontalEdge(ccui.LayoutComponent.HorizontalEdge.Right) rightBottom:setVerticalEdge(ccui.LayoutComponent.VerticalEdge.Bottom) baseLayer:addChild(rightBottomSprite) ccui.Helper:doLayout(baseLayer) end end) add_new_testcase(function() local UILayoutComponentBerthStretchTest = create("UILayoutComponentBerthStretchTest",UIScene) function UILayoutComponentBerthStretchTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("LayoutComponent Berth Stretch Test") local baseLayer = cc.LayerColor:create() baseLayer:setColor(cc.c3b(50, 100, 0)) baseLayer:setOpacity(100) baseLayer:setContentSize(cc.size(200, 200)) self._uiLayer:addChild(baseLayer) button = ccui.Button:create("cocosui/animationbuttonnormal.png") print(string.format("content size should be greater than 0: width = %f, height = %f", button:getContentSize().width, button:getContentSize().height)) button:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) button:addTouchEventListener(function(sender, eventType) if eventType == ccui.TouchEventType.ended then local touchWidgetSize = self._widget:getContentSize() local layerSize = baseLayer:getContentSize() if (layerSize.width == touchWidgetSize.width and layerSize.height == touchWidgetSize.height) then baseLayer:setContentSize(cc.size(200, 200)) else baseLayer:setContentSize(widgetSize) end ccui.Helper:doLayout(baseLayer) end end) button:setZoomScale(0.4) button:setPressedActionEnabled(true) self._uiLayer:addChild(button) local leftTopSprite = ccui.ImageView:create("cocosui/CloseSelected.png") leftTopSprite:ignoreContentAdaptWithSize(false) local leftTop = ccui.LayoutComponent:bindLayoutComponent(leftTopSprite) leftTop:setHorizontalEdge(ccui.LayoutComponent.HorizontalEdge.Left) leftTop:setVerticalEdge(ccui.LayoutComponent.VerticalEdge.Top) leftTop:setStretchWidthEnabled(true) leftTop:setStretchHeightEnabled(true) baseLayer:addChild(leftTopSprite) leftTop:setSize(leftTopSprite:getContentSize()) leftTop:setLeftMargin(0) leftTop:setTopMargin(0) local leftBottomSprite = ccui.ImageView:create("cocosui/CloseSelected.png") leftBottomSprite:ignoreContentAdaptWithSize(false) local leftBottom = ccui.LayoutComponent:bindLayoutComponent(leftBottomSprite) leftBottom:setHorizontalEdge(ccui.LayoutComponent.HorizontalEdge.Left) leftBottom:setVerticalEdge(ccui.LayoutComponent.VerticalEdge.Bottom) leftBottom:setStretchWidthEnabled(true) leftBottom:setStretchHeightEnabled(true) baseLayer:addChild(leftBottomSprite) leftBottom:setSize(leftBottomSprite:getContentSize()) leftBottom:setLeftMargin(0) leftBottom:setBottomMargin(0) local rightTopSprite = ccui.ImageView:create("cocosui/CloseSelected.png") rightTopSprite:ignoreContentAdaptWithSize(false) local rightTop = ccui.LayoutComponent:bindLayoutComponent(rightTopSprite) rightTop:setHorizontalEdge(ccui.LayoutComponent.HorizontalEdge.Right) rightTop:setVerticalEdge(ccui.LayoutComponent.VerticalEdge.Top) rightTop:setStretchWidthEnabled(true) rightTop:setStretchHeightEnabled(true) baseLayer:addChild(rightTopSprite) rightTop:setSize(rightTopSprite:getContentSize()) rightTop:setTopMargin(0) rightTop:setRightMargin(0) local rightBottomSprite = ccui.ImageView:create("cocosui/CloseSelected.png") rightBottomSprite:ignoreContentAdaptWithSize(false) local rightBottom = ccui.LayoutComponent:bindLayoutComponent(rightBottomSprite) rightBottom:setHorizontalEdge(ccui.LayoutComponent.HorizontalEdge.Right) rightBottom:setVerticalEdge(ccui.LayoutComponent.VerticalEdge.Bottom) rightBottom:setStretchWidthEnabled(true) rightBottom:setStretchHeightEnabled(true) baseLayer:addChild(rightBottomSprite) rightBottom:setSize(rightBottomSprite:getContentSize()) rightBottom:setBottomMargin(0) rightBottom:setRightMargin(0) ccui.Helper:doLayout(baseLayer) end end) add_new_testcase(function() local UIScrollViewVerticalTest = create("UIScrollViewVerticalTest",UIScene) function UIScrollViewVerticalTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("Move by vertical direction") local alert = ccui.Text:create() alert:setString("ScrollView") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local scrollView = ccui.ScrollView:create() scrollView:setTouchEnabled(true) scrollView:setContentSize(cc.size(280, 150)) local backgroundSize = background:getContentSize() scrollView:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - scrollView:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - scrollView:getContentSize().height) / 2)) scrollView:setScrollBarWidth(4) scrollView:setScrollBarPositionFromCorner(cc.p(2,2)) scrollView:setScrollBarColor(cc.RED) self._uiLayer:addChild(scrollView) local imageView = ccui.ImageView:create() imageView:loadTexture("cocosui/ccicon.png") local innerWidth = scrollView:getContentSize().width local innerHeight = scrollView:getContentSize().height + imageView:getContentSize().height scrollView:setInnerContainerSize(cc.size(innerWidth, innerHeight)) local button = ccui.Button:create() button:setTouchEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") button:setPosition(cc.p(innerWidth / 2, scrollView:getInnerContainerSize().height - button:getContentSize().height / 2)) scrollView:addChild(button) local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(cc.p(innerWidth / 2, button:getBottomBoundary() - button:getContentSize().height)) scrollView:addChild(textButton) local button_scale9 = ccui.Button:create() button_scale9:setTouchEnabled(true) button_scale9:setScale9Enabled(true) button_scale9:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") button_scale9:setContentSize(cc.size(100, button_scale9:getVirtualRendererSize().height)) button_scale9:setPosition(cc.p(innerWidth / 2, textButton:getBottomBoundary() - textButton:getContentSize().height)) scrollView:addChild(button_scale9) imageView:setPosition(cc.p(innerWidth / 2, imageView:getContentSize().height / 2)) scrollView:addChild(imageView) end end) add_new_testcase(function() local UIScrollViewHorizontalTest = create("UIScrollViewHorizontalTest",UIScene) function UIScrollViewHorizontalTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("Move by horizontal direction") local alert = ccui.Text:create() alert:setString("ScrollView") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local scrollView = ccui.ScrollView:create() scrollView:setBounceEnabled(true) scrollView:setDirection(ccui.ScrollViewDir.horizontal) scrollView:setTouchEnabled(true) scrollView:setContentSize(cc.size(280, 150)) scrollView:setInnerContainerSize(scrollView:getContentSize()) local backgroundSize = background:getContentSize() scrollView:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - scrollView:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - scrollView:getContentSize().height) / 2)) self._uiLayer:addChild(scrollView) local imageView = ccui.ImageView:create() imageView:loadTexture("cocosui/ccicon.png") local innerWidth = scrollView:getContentSize().width + imageView:getContentSize().width local innerHeight = scrollView:getContentSize().height scrollView:setInnerContainerSize(cc.size(innerWidth, innerHeight)) local button = ccui.Button:create() button:setTouchEnabled(true) button:loadTextures("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png", "") button:setPosition(cc.p(button:getContentSize().width / 2, scrollView:getInnerContainerSize().height - button:getContentSize().height / 2)) scrollView:addChild(button) local textButton = ccui.Button:create() textButton:setTouchEnabled(true) textButton:loadTextures("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png", "") textButton:setTitleText("Text Button") textButton:setPosition(cc.p(button:getRightBoundary() + button:getContentSize().width / 2, button:getBottomBoundary() - button:getContentSize().height / 2)) scrollView:addChild(textButton) local button_scale9 = ccui.Button:create() button_scale9:setTouchEnabled(true) button_scale9:setScale9Enabled(true) button_scale9:loadTextures("cocosui/button.png", "cocosui/buttonHighlighted.png", "") button_scale9:setContentSize(cc.size(100, button_scale9:getVirtualRendererSize().height)) button_scale9:setPosition(cc.p(textButton:getRightBoundary() + textButton:getContentSize().width / 2, textButton:getBottomBoundary() - textButton:getContentSize().height / 2)) scrollView:addChild(button_scale9) imageView:setPosition(cc.p(innerWidth - imageView:getContentSize().width / 2, button_scale9:getBottomBoundary() - button_scale9:getContentSize().height / 2)) scrollView:addChild(imageView) end end) add_new_testcase(function() local UIPageViewTest = create("UIPageViewTest",UIScene) function UIPageViewTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("Move by horizontal direction") local alert = ccui.Text:create() alert:setString("PageView") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local pageView = ccui.PageView:create() pageView:setTouchEnabled(true) pageView:setContentSize(cc.size(240, 130)) local backgroundSize = background:getContentSize() pageView:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - pageView:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - pageView:getContentSize().height) / 2)) for i = 1 , 3 do local layout = ccui.Layout:create() layout:setContentSize(cc.size(240, 130)) local imageView = ccui.ImageView:create() imageView:setTouchEnabled(true) imageView:setScale9Enabled(true) imageView:loadTexture("cocosui/scrollviewbg.png") imageView:setContentSize(cc.size(240, 130)) imageView:setPosition(cc.p(layout:getContentSize().width / 2, layout:getContentSize().height / 2)) layout:addChild(imageView) local label = ccui.Text:create() local pageInfo = string.format("page %d", i) label:setString(pageInfo) label:setFontName(font_TextName) label:setFontSize(30) label:setColor(cc.c3b(192, 192, 192)) label:setPosition(cc.p(layout:getContentSize().width / 2, layout:getContentSize().height / 2)) layout:addChild(label) pageView:addWidgetToPage(layout, i-1) end pageView:setCurPageIndex(1) local function pageViewEvent(sender, eventType) if eventType == ccui.PageViewEventType.turning then local pageInfo = string.format("page %d " , pageView:getCurPageIndex() + 1) local pages = pageView:getPages() print("total items " .. table.getn(pages)) self._displayValueLabel:setString(pageInfo) end end pageView:addEventListener(pageViewEvent) self._uiLayer:addChild(pageView) end end) add_new_testcase(function() local UIPageViewVerticalTest = create("UIPageViewVerticalTest",UIScene) function UIPageViewVerticalTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("Move by vertical direction") local alert = ccui.Text:create() alert:setString("PageView") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local pageView = ccui.PageView:create() pageView:setTouchEnabled(true) pageView:setDirection(ccui.ScrollViewDir.vertical) pageView:setContentSize(cc.size(240, 130)) local backgroundSize = background:getContentSize() pageView:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2 + (backgroundSize.width - pageView:getContentSize().width) / 2, (widgetSize.height - backgroundSize.height) / 2 + (backgroundSize.height - pageView:getContentSize().height) / 2)) for i = 1 , 3 do local layout = ccui.Layout:create() layout:setContentSize(cc.size(240, 130)) local imageView = ccui.ImageView:create() imageView:setTouchEnabled(true) imageView:setScale9Enabled(true) imageView:loadTexture("cocosui/scrollviewbg.png") imageView:setContentSize(cc.size(240, 130)) imageView:setPosition(cc.p(layout:getContentSize().width / 2, layout:getContentSize().height / 2)) layout:addChild(imageView) local label = ccui.Text:create() local pageInfo = string.format("page %d", i) label:setString(pageInfo) label:setFontName(font_TextName) label:setFontSize(30) label:setColor(cc.c3b(192, 192, 192)) label:setPosition(cc.p(layout:getContentSize().width / 2, layout:getContentSize().height / 2)) layout:addChild(label) pageView:addPage(layout) end local function pageViewEvent(sender, eventType) if eventType == ccui.PageViewEventType.turning then local pageInfo = string.format("page %d " , pageView:getCurPageIndex() + 1) self._displayValueLabel:setString(pageInfo) end end pageView:addEventListener(pageViewEvent) self._uiLayer:addChild(pageView) end end) add_new_testcase(function() local UIListViewVerticalTest = create("UIListViewVerticalTest",UIScene) function UIListViewVerticalTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("Move by vertical direction") local alert = ccui.Text:create() alert:setString("ListView") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local backgroundSize = background:getContentSize() local array = {} for i = 1,20 do array[i] = string.format("ListView_item_%d",i - 1) end local function listViewEvent(sender, eventType) if eventType == ccui.ListViewEventType.ONSELECTEDITEM_START then print("select child index = ",sender:getCurSelectedIndex()) end end local function scrollViewEvent(sender, evenType) if evenType == ccui.ScrollviewEventType.scrollToBottom then print("SCROLL_TO_BOTTOM") elseif evenType == ccui.ScrollviewEventType.scrollToTop then print("SCROLL_TO_TOP") end end local listView = ccui.ListView:create() -- set list view ex direction listView:setDirection(ccui.ScrollViewDir.vertical) listView:setBounceEnabled(true) listView:setBackGroundImage("cocosui/green_edit.png") listView:setBackGroundImageScale9Enabled(true) listView:setContentSize(cc.size(240, 130)) listView:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2.0 + (backgroundSize.width - listView:getContentSize().width) / 2.0, (widgetSize.height - backgroundSize.height) / 2.0 + (backgroundSize.height - listView:getContentSize().height) / 2.0)) listView:addEventListener(listViewEvent) listView:addScrollViewEventListener(scrollViewEvent) self._uiLayer:addChild(listView) -- create model local default_button = ccui.Button:create("cocosui/backtotoppressed.png", "cocosui/backtotopnormal.png") default_button:setName("Title Button") local default_item = ccui.Layout:create() default_item:setTouchEnabled(true) default_item:setContentSize(default_button:getContentSize()) default_button:setPosition(cc.p(default_item:getContentSize().width / 2.0, default_item:getContentSize().height / 2.0)) default_item:addChild(default_button) --set model listView:setItemModel(default_item) --add default item local count = table.getn(array) for i = 1,math.floor(count / 4) do listView:pushBackDefaultItem() end --insert default item for i = 1,math.floor(count / 4) do listView:insertDefaultItem(0) end listView:removeAllChildren() local testSprite = cc.Sprite:create("cocosui/backtotoppressed.png") testSprite:setPosition(cc.p(200,200)) listView:addChild(testSprite) --add custom item for i = 1,math.floor(count / 4) do local custom_button = ccui.Button:create("cocosui/button.png", "cocosui/buttonHighlighted.png") custom_button:setName("Title Button") custom_button:setScale9Enabled(true) custom_button:setContentSize(default_button:getContentSize()) local custom_item = ccui.Layout:create() custom_item:setContentSize(custom_button:getContentSize()) custom_button:setPosition(cc.p(custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0)) custom_item:addChild(custom_button) listView:addChild(custom_item) end --insert custom item local items = listView:getItems() local items_count = table.getn(items) for i = 1, math.floor(count / 4) do local custom_button = ccui.Button:create("cocosui/button.png", "cocosui/buttonHighlighted.png") custom_button:setName("Title Button") custom_button:setScale9Enabled(true) custom_button:setContentSize(default_button:getContentSize()) local custom_item = ccui.Layout:create() custom_item:setContentSize(custom_button:getContentSize()) custom_button:setPosition(cc.p(custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0)) custom_item:addChild(custom_button) custom_item:setTag(1) listView:insertCustomItem(custom_item, items_count) end -- set item data items_count = table.getn(listView:getItems()) for i = 1,items_count do local item = listView:getItem(i - 1) local button = item:getChildByName("Title Button") local index = listView:getIndex(item) button:setTitleText(array[index + 1]) end -- remove last item listView:removeChildByTag(1) -- remove item by index items_count = table.getn(listView:getItems()) listView:removeItem(items_count - 1) -- set all items layout gravity listView:setGravity(ccui.ListViewGravity.centerVertical) --set items margin listView:setItemsMargin(2.0) end end) add_new_testcase(function() local UIListViewHorizontalTest = create("UIListViewHorizontalTest",UIScene) function UIListViewHorizontalTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("Move by vertical direction") local alert = ccui.Text:create() alert:setString("ListView") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") local backgroundSize = background:getContentSize() local array = {} for i = 1,20 do array[i] = string.format("ListView_item_%d",i - 1) end local function listViewEvent(sender, eventType) if eventType == ccui.ListViewEventType.ons_selected_item then print("select child index = ",sender:getCurSelectedIndex()) end end local listView = ccui.ListView:create() -- set list view ex direction listView:setDirection(ccui.ScrollViewDir.horizontal) listView:setTouchEnabled(true) listView:setBounceEnabled(true) listView:setBackGroundImage("cocosui/green_edit.png") listView:setBackGroundImageScale9Enabled(true) listView:setContentSize(cc.size(240, 130)) listView:setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2.0 + (backgroundSize.width - listView:getContentSize().width) / 2.0, (widgetSize.height - backgroundSize.height) / 2.0 + (backgroundSize.height - listView:getContentSize().height) / 2.0)) listView:addEventListener(listViewEvent) self._uiLayer:addChild(listView) -- create model local default_button = ccui.Button:create("cocosui/backtotoppressed.png", "cocosui/backtotopnormal.png") default_button:setName("Title Button") local default_item = ccui.Layout:create() default_item:setTouchEnabled(true) default_item:setContentSize(default_button:getContentSize()) default_button:setPosition(cc.p(default_item:getContentSize().width / 2.0, default_item:getContentSize().height / 2.0)) default_item:addChild(default_button) --set model listView:setItemModel(default_item) --add default item local count = table.getn(array) for i = 1,math.floor(count / 4) do listView:pushBackDefaultItem() end --insert default item for i = 1,math.floor(count / 4) do listView:insertDefaultItem(0) end --add custom item for i = 1,math.floor(count / 4) do local custom_button = ccui.Button:create("cocosui/button.png", "cocosui/buttonHighlighted.png") custom_button:setName("Title Button") custom_button:setScale9Enabled(true) custom_button:setContentSize(default_button:getContentSize()) local custom_item = ccui.Layout:create() custom_item:setContentSize(custom_button:getContentSize()) custom_button:setPosition(cc.p(custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0)) custom_item:addChild(custom_button) listView:pushBackCustomItem(custom_item) end --insert custom item local items = listView:getItems() local items_count = table.getn(items) for i = 1, math.floor(count / 4) do local custom_button = ccui.Button:create("cocosui/button.png", "cocosui/buttonHighlighted.png") custom_button:setName("Title Button") custom_button:setScale9Enabled(true) custom_button:setContentSize(default_button:getContentSize()) local custom_item = ccui.Layout:create() custom_item:setContentSize(custom_button:getContentSize()) custom_button:setPosition(cc.p(custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0)) custom_item:addChild(custom_button) listView:insertCustomItem(custom_item, items_count) end -- set item data items_count = table.getn(listView:getItems()) print("items_count", items_count) for i = 1,items_count do local item = listView:getItem(i - 1) local button = item:getChildByName("Title Button") local index = listView:getIndex(item) print("index is ", index) button:setTitleText(array[index + 1]) end -- remove last item listView:removeLastItem() -- remove item by index items_count = table.getn(listView:getItems()) listView:removeItem(items_count - 1) -- set all items layout gravity listView:setGravity(ccui.ListViewGravity.centerVertical) --set items margin listView:setItemsMargin(2.0) end end) add_new_testcase(function() local UIDragPanelTest = create("UIDragPanelTest",UIScene) function UIDragPanelTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("DragPanel") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local sc = ccui.ScrollView:create() sc:setBackGroundColor(cc.c3b(0,255,0)) sc:setBackGroundColorType(ccui.LayoutBackGroundColorType.solid) sc:setDirection(ccui.ScrollViewDir.both) sc:setInnerContainerSize(cc.size(480, 320)) sc:setContentSize(cc.size(100,100)) sc:setPosition(cc.p(100,100)) sc:scrollToPercentBothDirection(cc.p(50, 50), 1, true) local iv = ccui.ImageView:create() iv:loadTexture("cocosui/Hello.png") iv:setPosition(cc.p(240, 160)) sc:addChild(iv) self._uiLayer:addChild(sc) end end) add_new_testcase(function() local UIDragPanelBounceTest = create("UIDragPanelBounceTest",UIScene) function UIDragPanelBounceTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("No Event") local alert = ccui.Text:create() alert:setString("DragPanel Bounce") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 2.925)) self._uiLayer:addChild(alert) local sc = ccui.ScrollView:create() sc:setBackGroundColor(cc.c3b(0, 255 , 0)) sc:setBackGroundColorType(ccui.LayoutBackGroundColorType.solid) sc:setBounceEnabled(true) sc:setDirection(ccui.ScrollViewDir.both) sc:setInnerContainerSize(cc.size(480, 320)) sc:setContentSize(cc.size(100,100)) sc:setPosition(cc.p(100,100)) sc:scrollToPercentBothDirection(cc.p(50, 50), 1, true) local iv = ccui.ImageView:create() iv:loadTexture("cocosui/Hello.png") iv:setPosition(cc.p(240, 160)) sc:addChild(iv) self._uiLayer:addChild(sc) end end) add_new_testcase(function() local UINodeContainerTest = create("UINodeContainerTest",UIScene) function UINodeContainerTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("NodeContainer Add CCNode") local alert = ccui.Text:create() alert:setString("NodeContainer") alert:setFontName(font_TextName) alert:setFontSize(30) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 1.75)) self._uiLayer:addChild(alert) local nodeContainer = ccui.Widget:create() nodeContainer:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0)) self._uiLayer:addChild(nodeContainer) local sprite = cc.Sprite:create("cocosui/ccicon.png") sprite:setPosition(cc.p(0, sprite:getBoundingBox().height / 4)) nodeContainer:addChild(sprite) end end) add_new_testcase(function() local UIRichTextTest = create("UIRichTextTest",UIScene) function UIRichTextTest:initExtend() local widgetSize = self._widget:getContentSize() self._displayValueLabel:setString("") local alert = ccui.Text:create("RichText", "fonts/Marker Felt.ttf", 30) alert:setFontName(font_TextName) alert:setColor(cc.c3b(159, 168, 176)) alert:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert:getContentSize().height * 3.125)) self._widget:addChild(alert) local function touchEvent(sender, eventType) if eventType == ccui.TouchEventType.ended then if self._richText:isIgnoreContentAdaptWithSize() then self._richText:ignoreContentAdaptWithSize(false) self._richText:setContentSize(cc.size(100, 100)) else self._richText:ignoreContentAdaptWithSize(true) end end end local button = ccui.Button:create("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png") button:setTouchEnabled(true) button:setTitleText("switch") button:setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 + button:getContentSize().height * 2.5)) button:addTouchEventListener(touchEvent) button:setLocalZOrder(10) self._widget:addChild(button) self._richText = ccui.RichText:create() self._richText:ignoreContentAdaptWithSize(false) self._richText:setContentSize(cc.size(100, 100)) local re1 = ccui.RichElementText:create(1, cc.c3b(255, 255, 255), 255, "This color is white. ", "Helvetica", 10) local re2 = ccui.RichElementText:create(2, cc.c3b(255, 255, 0), 255, "And this is yellow. ", "Helvetica", 10) local re3 = ccui.RichElementText:create(3, cc.c3b(0, 0, 255), 255, "This one is blue. ", "Helvetica", 10) local re4 = ccui.RichElementText:create(4, cc.c3b(0, 255, 0), 255, "And green. ", "Helvetica", 10) local re5 = ccui.RichElementText:create(5, cc.c3b(255, 0, 0), 255, "Last one is red ", "Helvetica", 10) local reimg = ccui.RichElementImage:create(6, cc.c3b(255, 255, 255), 255, "cocosui/sliderballnormal.png") ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("cocosui/100/100.ExportJson") local arr = ccs.Armature:create("100") arr:getAnimation():play("Animation1") local recustom = ccui.RichElementCustomNode:create(1, cc.c3b(255, 255, 255), 255, arr) local re6 = ccui.RichElementText:create(7, cc.c3b(255, 127, 0), 255, "Have fun!! ", "Helvetica", 10) self._richText:pushBackElement(re1) self._richText:insertElement(re2, 1) self._richText:pushBackElement(re3) self._richText:pushBackElement(re4) self._richText:pushBackElement(re5) self._richText:insertElement(reimg, 2) self._richText:pushBackElement(recustom) self._richText:pushBackElement(re6) self._richText:setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2)) self._richText:setLocalZOrder(10) self._widget:addChild(self._richText) end end) add_new_testcase(function() local UIFocusTestHorizontal = create("UIFocusTestHorizontal",UIScene) function UIFocusTestHorizontal:initExtend() self._displayValueLabel:setString("") local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") background:removeFromParent(true) local function onLeftKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_LEFT, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onRightKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_RIGHT, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onUpKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_UP, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onDownKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_DOWN, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end self._dpadMenu = cc.Menu:create() local winSize = cc.Director:getInstance():getVisibleSize() local leftItem = cc.MenuItemFont:create("Left") leftItem:setPosition(cc.p(winSize.width - 100, winSize.height/2)) leftItem:registerScriptTapHandler(onLeftKeyPressed) self._dpadMenu:addChild(leftItem) local rightItem = cc.MenuItemFont:create("Right") rightItem:setPosition(cc.p(winSize.width - 30, winSize.height/2)) rightItem:registerScriptTapHandler(onRightKeyPressed) self._dpadMenu:addChild(rightItem) local upItem = cc.MenuItemFont:create("Up") upItem:setPosition(cc.p(winSize.width - 60, winSize.height/2 + 50)) upItem:registerScriptTapHandler(onUpKeyPressed) self._dpadMenu:addChild(upItem) local downItem = cc.MenuItemFont:create("Down") downItem:setPosition(cc.p(winSize.width - 60, winSize.height/2 - 50)) downItem:registerScriptTapHandler(onDownKeyPressed) self._dpadMenu:addChild(downItem) self._dpadMenu:setPosition(cc.p(0, 0)) self._uiLayer:addChild(self._dpadMenu) ccui.Widget:enableDpadNavigation(true) local function onFocusChanged(widgetLostFocus,widgetGetFocus) if nil ~= widgetGetFocus and widgetGetFocus:isFocusEnabled() then widgetGetFocus:setColor(cc.c3b(255, 0, 0)) end if nil ~= widgetLostFocus and widgetLostFocus:isFocusEnabled() then widgetLostFocus:setColor(cc.c3b(255, 255, 255)) end if nil ~= widgetLostFocus and nil ~= widgetGetFocus then print(string.format("on focus change, %d widget get focus, %d widget lose focus", widgetGetFocus:getTag(), widgetLostFocus:getTag())) end end local eventListener = cc.EventListenerFocus:create() eventListener:registerScriptHandler(onFocusChanged) local eventDispatcher = self:getEventDispatcher() eventDispatcher:addEventListenerWithFixedPriority(eventListener, 1) local function onExit(tag) if tag == "exit" then if eventListener ~= nil then eventDispatcher:removeEventListener(eventListener) end end end self:registerScriptHandler(onExit) local winSize = cc.Director:getInstance():getVisibleSize() self._horizontalLayout = ccui.HBox:create() self._horizontalLayout:setPosition(cc.p(20, winSize.height / 2 + 40)) self._uiLayer:addChild(self._horizontalLayout) self._horizontalLayout:setFocused(true) self._horizontalLayout:setLoopFocus(true) self._horizontalLayout:setTag(100) self._firstFocusedWidget = self._horizontalLayout local function onImageViewClicked(sender, eventType) if eventType == ccui.TouchEventType.ended then local w = sender if w:isFocusEnabled() then w:setFocusEnabled(false) w:setColor(cc.c3b(255, 255, 0)) else w:setFocusEnabled(true) w:setColor(cc.c3b(255, 255, 255)) end end end local count = 3 for i = 1, count do local imageView = ccui.ImageView:create("cocosui/scrollviewbg.png") imageView:setTouchEnabled(true) imageView:setTag(i) imageView:addTouchEventListener(onImageViewClicked) self._horizontalLayout:addChild(imageView) end self._loopText = ccui.Text:create("loop enabled", "Arial", 20) self._loopText:setPosition(cc.p(winSize.width/2, winSize.height - 50)) self._loopText:setColor(cc.c3b(255, 0 ,0)) self:addChild(self._loopText) local function toggleFocusLoop(sender, eventType) if eventType == ccui.TouchEventType.ended then self._horizontalLayout:setLoopFocus(not self._horizontalLayout:isLoopFocus()) if self._horizontalLayout:isLoopFocus() then self._loopText:setString("loop enabled") else self._loopText:setString("loop disabled") end end end local btn = ccui.Button:create("cocosui/switch-mask.png") btn:setTitleText("Toggle Loop") btn:setPosition(cc.p(60, winSize.height - 50)) btn:setTitleColor(cc.c3b(0, 255, 0)) btn:addTouchEventListener(toggleFocusLoop) self:addChild(btn) end end) add_new_testcase(function() local UIFocusTestVertical = create("UIFocusTestVertical",UIScene) function UIFocusTestVertical:initExtend() self._displayValueLabel:setString("") local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") background:removeFromParent(true) local function onLeftKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_LEFT, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onRightKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_RIGHT, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onUpKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_UP, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onDownKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_DOWN, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end self._dpadMenu = cc.Menu:create() local winSize = cc.Director:getInstance():getVisibleSize() local leftItem = cc.MenuItemFont:create("Left") leftItem:setPosition(cc.p(winSize.width - 100, winSize.height/2)) leftItem:registerScriptTapHandler(onLeftKeyPressed) self._dpadMenu:addChild(leftItem) local rightItem = cc.MenuItemFont:create("Right") rightItem:setPosition(cc.p(winSize.width - 30, winSize.height/2)) rightItem:registerScriptTapHandler(onRightKeyPressed) self._dpadMenu:addChild(rightItem) local upItem = cc.MenuItemFont:create("Up") upItem:setPosition(cc.p(winSize.width - 60, winSize.height/2 + 50)) upItem:registerScriptTapHandler(onUpKeyPressed) self._dpadMenu:addChild(upItem) local downItem = cc.MenuItemFont:create("Down") downItem:setPosition(cc.p(winSize.width - 60, winSize.height/2 - 50)) downItem:registerScriptTapHandler(onDownKeyPressed) self._dpadMenu:addChild(downItem) self._dpadMenu:setPosition(cc.p(0, 0)) self._uiLayer:addChild(self._dpadMenu) ccui.Widget:enableDpadNavigation(true) local function onFocusChanged(widgetLostFocus,widgetGetFocus) if nil ~= widgetGetFocus and widgetGetFocus:isFocusEnabled() then widgetGetFocus:setColor(cc.c3b(255, 0, 0)) end if nil ~= widgetLostFocus and widgetLostFocus:isFocusEnabled() then widgetLostFocus:setColor(cc.c3b(255, 255, 255)) end if nil ~= widgetLostFocus and nil ~= widgetGetFocus then print(string.format("on focus change, %d widget get focus, %d widget lose focus", widgetGetFocus:getTag(), widgetLostFocus:getTag())) end end local eventListener = cc.EventListenerFocus:create() eventListener:registerScriptHandler(onFocusChanged) local eventDispatcher = self:getEventDispatcher() eventDispatcher:addEventListenerWithFixedPriority(eventListener, 1) local function onExit(tag) if tag == "exit" then if eventListener ~= nil then eventDispatcher:removeEventListener(eventListener) end end end self:registerScriptHandler(onExit) local winSize = cc.Director:getInstance():getVisibleSize() self._verticalLayout = ccui.VBox:create() self._verticalLayout:setPosition(cc.p(winSize.width/2 - 100, winSize.height - 70)) self._uiLayer:addChild(self._verticalLayout) self._verticalLayout:setFocused(true) self._verticalLayout:setLoopFocus(true) self._verticalLayout:setTag(100) self._verticalLayout:setScale(0.5) self._firstFocusedWidget = self._verticalLayout local function onImageViewClicked(sender, eventType) if eventType == ccui.TouchEventType.ended then local w = sender if w:isFocusEnabled() then w:setFocusEnabled(false) w:setColor(cc.c3b(255, 255, 0)) else w:setFocusEnabled(true) w:setColor(cc.c3b(255, 255, 255)) end end end local count = 3 for i = 1, count do local imageView = ccui.ImageView:create("cocosui/scrollviewbg.png") imageView:setTouchEnabled(true) imageView:setTag(i) imageView:addTouchEventListener(onImageViewClicked) self._verticalLayout:addChild(imageView) end self._loopText = ccui.Text:create("loop enabled", "Arial", 20) self._loopText:setPosition(cc.p(winSize.width/2, winSize.height - 50)) self._loopText:setColor(cc.c3b(255, 0 ,0)) self:addChild(self._loopText) local function toggleFocusLoop(sender, eventType) if eventType == ccui.TouchEventType.ended then self._verticalLayout:setLoopFocus(not self._verticalLayout:isLoopFocus()) if self._verticalLayout:isLoopFocus() then self._loopText:setString("loop enabled") else self._loopText:setString("loop disabled") end end end local btn = ccui.Button:create("cocosui/switch-mask.png") btn:setTitleText("Toggle Loop") btn:setPosition(cc.p(60, winSize.height - 50)) btn:setTitleColor(cc.c3b(0, 255, 0)) btn:addTouchEventListener(toggleFocusLoop) self:addChild(btn) end end) add_new_testcase(function() local UIFocusTestNestedLayout1 = create("UIFocusTestNestedLayout1",UIScene) function UIFocusTestNestedLayout1:initExtend() self._displayValueLabel:setString("") local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") background:removeFromParent(true) local function onLeftKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_LEFT, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onRightKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_RIGHT, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onUpKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_UP, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onDownKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_DOWN, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end self._dpadMenu = cc.Menu:create() local winSize = cc.Director:getInstance():getVisibleSize() local leftItem = cc.MenuItemFont:create("Left") leftItem:setPosition(cc.p(winSize.width - 100, winSize.height/2)) leftItem:registerScriptTapHandler(onLeftKeyPressed) self._dpadMenu:addChild(leftItem) local rightItem = cc.MenuItemFont:create("Right") rightItem:setPosition(cc.p(winSize.width - 30, winSize.height/2)) rightItem:registerScriptTapHandler(onRightKeyPressed) self._dpadMenu:addChild(rightItem) local upItem = cc.MenuItemFont:create("Up") upItem:setPosition(cc.p(winSize.width - 60, winSize.height/2 + 50)) upItem:registerScriptTapHandler(onUpKeyPressed) self._dpadMenu:addChild(upItem) local downItem = cc.MenuItemFont:create("Down") downItem:setPosition(cc.p(winSize.width - 60, winSize.height/2 - 50)) downItem:registerScriptTapHandler(onDownKeyPressed) self._dpadMenu:addChild(downItem) self._dpadMenu:setPosition(cc.p(0, 0)) self._uiLayer:addChild(self._dpadMenu) ccui.Widget:enableDpadNavigation(true) local function onFocusChanged(widgetLostFocus,widgetGetFocus) if nil ~= widgetGetFocus and widgetGetFocus:isFocusEnabled() then widgetGetFocus:setColor(cc.c3b(255, 0, 0)) end if nil ~= widgetLostFocus and widgetLostFocus:isFocusEnabled() then widgetLostFocus:setColor(cc.c3b(255, 255, 255)) end if nil ~= widgetLostFocus and nil ~= widgetGetFocus then print(string.format("on focus change, %d widget get focus, %d widget lose focus", widgetGetFocus:getTag(), widgetLostFocus:getTag())) end end local eventListener = cc.EventListenerFocus:create() eventListener:registerScriptHandler(onFocusChanged) local eventDispatcher = self:getEventDispatcher() eventDispatcher:addEventListenerWithFixedPriority(eventListener, 1) local function onExit(tag) if tag == "exit" then if eventListener ~= nil then eventDispatcher:removeEventListener(eventListener) end end end self:registerScriptHandler(onExit) local winSize = cc.Director:getInstance():getVisibleSize() self._verticalLayout = ccui.VBox:create() self._verticalLayout:setPosition(cc.p(winSize.width/2 - 80, winSize.height - 70)) self._uiLayer:addChild(self._verticalLayout) self._verticalLayout:setScale(0.5) self._verticalLayout:setFocused(true) self._verticalLayout:setLoopFocus(true) self._verticalLayout:setTag(100) self._firstFocusedWidget = self._verticalLayout local function onImageViewClicked(sender, eventType) if eventType == ccui.TouchEventType.ended then local w = sender if w:isFocusEnabled() then w:setFocusEnabled(false) w:setColor(cc.c3b(255, 255, 0)) else w:setFocusEnabled(true) w:setColor(cc.c3b(255, 255, 255)) end end end local count1 = 1 for i = 1, count1 do local imageView = ccui.ImageView:create("cocosui/scrollviewbg.png") imageView:setAnchorPoint(cc.p(0, 0)) imageView:setTouchEnabled(true) imageView:setScaleX(2.5) imageView:setTag(i - 1 + count1) imageView:addTouchEventListener(onImageViewClicked) self._verticalLayout:addChild(imageView) end local hbox = ccui.HBox:create() hbox:setScale(0.8) hbox:setTag(101) self._verticalLayout:addChild(hbox) local count2 = 2 for i = 1, count2 do local imageView = ccui.ImageView:create("cocosui/scrollviewbg.png") imageView:setAnchorPoint(cc.p(0, 1)) imageView:setScaleY(2.0) imageView:setTouchEnabled(true) imageView:setTag(i - 1 + count1 + count2) imageView:addTouchEventListener(onImageViewClicked) hbox:addChild(imageView) end local innerVBox = ccui.VBox:create() hbox:addChild(innerVBox) innerVBox:setTag(102) local count3 = 2 for i = 1, count3 do local imageView = ccui.ImageView:create("cocosui/scrollviewbg.png") imageView:setTouchEnabled(true) imageView:setTag(i - 1 + count1 + count2 + count3) imageView:addTouchEventListener(onImageViewClicked) innerVBox:addChild(imageView) end self._loopText = ccui.Text:create("loop enabled", "Arial", 20) self._loopText:setPosition(cc.p(winSize.width/2, winSize.height - 50)) self._loopText:setColor(cc.c3b(255, 0 ,0)) self:addChild(self._loopText) local function toggleFocusLoop(sender, eventType) if eventType == ccui.TouchEventType.ended then self._verticalLayout:setLoopFocus(not self._verticalLayout:isLoopFocus()) if self._verticalLayout:isLoopFocus() then self._loopText:setString("loop enabled") else self._loopText:setString("loop disabled") end end end local btn = ccui.Button:create("cocosui/switch-mask.png") btn:setTitleText("Toggle Loop") btn:setPosition(cc.p(60, winSize.height - 50)) btn:setTitleColor(cc.c3b(0, 255, 0)) btn:addTouchEventListener(toggleFocusLoop) self:addChild(btn) end end) add_new_testcase(function() local UIFocusTestNestedLayout2 = create("UIFocusTestNestedLayout2",UIScene) function UIFocusTestNestedLayout2:initExtend() self._displayValueLabel:setString("") local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") background:removeFromParent(true) local function onLeftKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_LEFT, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onRightKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_RIGHT, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onUpKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_UP, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onDownKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_DOWN, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end self._dpadMenu = cc.Menu:create() local winSize = cc.Director:getInstance():getVisibleSize() local leftItem = cc.MenuItemFont:create("Left") leftItem:setPosition(cc.p(winSize.width - 100, winSize.height/2)) leftItem:registerScriptTapHandler(onLeftKeyPressed) self._dpadMenu:addChild(leftItem) local rightItem = cc.MenuItemFont:create("Right") rightItem:setPosition(cc.p(winSize.width - 30, winSize.height/2)) rightItem:registerScriptTapHandler(onRightKeyPressed) self._dpadMenu:addChild(rightItem) local upItem = cc.MenuItemFont:create("Up") upItem:setPosition(cc.p(winSize.width - 60, winSize.height/2 + 50)) upItem:registerScriptTapHandler(onUpKeyPressed) self._dpadMenu:addChild(upItem) local downItem = cc.MenuItemFont:create("Down") downItem:setPosition(cc.p(winSize.width - 60, winSize.height/2 - 50)) downItem:registerScriptTapHandler(onDownKeyPressed) self._dpadMenu:addChild(downItem) self._dpadMenu:setPosition(cc.p(0, 0)) self._uiLayer:addChild(self._dpadMenu) ccui.Widget:enableDpadNavigation(true) local function onFocusChanged(widgetLostFocus,widgetGetFocus) if nil ~= widgetGetFocus and widgetGetFocus:isFocusEnabled() then widgetGetFocus:setColor(cc.c3b(255, 0, 0)) end if nil ~= widgetLostFocus and widgetLostFocus:isFocusEnabled() then widgetLostFocus:setColor(cc.c3b(255, 255, 255)) end if nil ~= widgetLostFocus and nil ~= widgetGetFocus then print(string.format("on focus change, %d widget get focus, %d widget lose focus", widgetGetFocus:getTag(), widgetLostFocus:getTag())) end end local eventListener = cc.EventListenerFocus:create() eventListener:registerScriptHandler(onFocusChanged) local eventDispatcher = self:getEventDispatcher() eventDispatcher:addEventListenerWithFixedPriority(eventListener, 1) local function onExit(tag) if tag == "exit" then if eventListener ~= nil then eventDispatcher:removeEventListener(eventListener) end end end self:registerScriptHandler(onExit) local winSize = cc.Director:getInstance():getVisibleSize() self._horizontalLayout = ccui.HBox:create() self._horizontalLayout:setPosition(cc.p(winSize.width/2 - 200, winSize.height - 70)) self._uiLayer:addChild(self._horizontalLayout) self._horizontalLayout:setScale(0.6) self._horizontalLayout:setFocused(true) self._horizontalLayout:setLoopFocus(true) self._horizontalLayout:setTag(100) self._firstFocusedWidget = self._horizontalLayout local function onImageViewClicked(sender, eventType) if eventType == ccui.TouchEventType.ended then local w = sender if w:isFocusEnabled() then w:setFocusEnabled(false) w:setColor(cc.c3b(255, 255, 0)) else w:setFocusEnabled(true) w:setColor(cc.c3b(255, 255, 255)) end end end local count1 = 2 for i = 1, count1 do local imageView = ccui.ImageView:create("cocosui/scrollviewbg.png") imageView:setAnchorPoint(cc.p(0, 1)) imageView:setTouchEnabled(true) imageView:setScaleY(2.4) imageView:setTag(i - 1 + count1) imageView:addTouchEventListener(onImageViewClicked) self._horizontalLayout:addChild(imageView) end local vbox = ccui.VBox:create() vbox:setScale(0.8) vbox:setTag(101) self._horizontalLayout:addChild(vbox) local count2 = 2 for i = 1, count2 do local imageView = ccui.ImageView:create("cocosui/scrollviewbg.png") imageView:setAnchorPoint(cc.p(0, 1)) imageView:setScaleX(2.0) imageView:setTouchEnabled(true) imageView:setTag(i - 1 + count1 + count2) imageView:addTouchEventListener(onImageViewClicked) vbox:addChild(imageView) end local innerVBox = ccui.HBox:create() vbox:addChild(innerVBox) innerVBox:setTag(102) local count3 = 2 for i = 1, count3 do local imageView = ccui.ImageView:create("cocosui/scrollviewbg.png") imageView:setTouchEnabled(true) imageView:setTag(i - 1 + count1 + count2 + count3) imageView:addTouchEventListener(onImageViewClicked) innerVBox:addChild(imageView) end self._loopText = ccui.Text:create("loop enabled", "Arial", 20) self._loopText:setPosition(cc.p(winSize.width/2, winSize.height - 50)) self._loopText:setColor(cc.c3b(255, 0 ,0)) self:addChild(self._loopText) local function toggleFocusLoop(sender, eventType) if eventType == ccui.TouchEventType.ended then self._horizontalLayout:setLoopFocus(not self._horizontalLayout:isLoopFocus()) if self._horizontalLayout:isLoopFocus() then self._loopText:setString("loop enabled") else self._loopText:setString("loop disabled") end end end local btn = ccui.Button:create("cocosui/switch-mask.png") btn:setTitleText("Toggle Loop") btn:setPosition(cc.p(60, winSize.height - 50)) btn:setTitleColor(cc.c3b(0, 255, 0)) btn:addTouchEventListener(toggleFocusLoop) self:addChild(btn) end end) add_new_testcase(function() local UIFocusTestNestedLayout3 = create("UIFocusTestNestedLayout3",UIScene) function UIFocusTestNestedLayout3:initExtend() self._displayValueLabel:setString("") local root = self._uiLayer:getChildByTag(81) local background = root:getChildByName("background_Panel") background:removeFromParent(true) local function onLeftKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_LEFT, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onRightKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_RIGHT, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onUpKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_UP, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end local function onDownKeyPressed() local event = cc.EventKeyboard:new(cc.KeyCode.KEY_DPAD_DOWN, false) cc.Director:getInstance():getEventDispatcher():dispatchEvent(event) end self._dpadMenu = cc.Menu:create() local winSize = cc.Director:getInstance():getVisibleSize() local leftItem = cc.MenuItemFont:create("Left") leftItem:setPosition(cc.p(winSize.width - 100, winSize.height/2)) leftItem:registerScriptTapHandler(onLeftKeyPressed) self._dpadMenu:addChild(leftItem) local rightItem = cc.MenuItemFont:create("Right") rightItem:setPosition(cc.p(winSize.width - 30, winSize.height/2)) rightItem:registerScriptTapHandler(onRightKeyPressed) self._dpadMenu:addChild(rightItem) local upItem = cc.MenuItemFont:create("Up") upItem:setPosition(cc.p(winSize.width - 60, winSize.height/2 + 50)) upItem:registerScriptTapHandler(onUpKeyPressed) self._dpadMenu:addChild(upItem) local downItem = cc.MenuItemFont:create("Down") downItem:setPosition(cc.p(winSize.width - 60, winSize.height/2 - 50)) downItem:registerScriptTapHandler(onDownKeyPressed) self._dpadMenu:addChild(downItem) self._dpadMenu:setPosition(cc.p(0, 0)) self._uiLayer:addChild(self._dpadMenu) ccui.Widget:enableDpadNavigation(true) local function onFocusChanged(widgetLostFocus,widgetGetFocus) if nil ~= widgetGetFocus and widgetGetFocus:isFocusEnabled() then widgetGetFocus:setColor(cc.c3b(255, 0, 0)) end if nil ~= widgetLostFocus and widgetLostFocus:isFocusEnabled() then widgetLostFocus:setColor(cc.c3b(255, 255, 255)) end if nil ~= widgetLostFocus and nil ~= widgetGetFocus then print(string.format("on focus change, %d widget get focus, %d widget lose focus", widgetGetFocus:getTag(), widgetLostFocus:getTag())) end end local eventListener = cc.EventListenerFocus:create() eventListener:registerScriptHandler(onFocusChanged) local eventDispatcher = self:getEventDispatcher() eventDispatcher:addEventListenerWithFixedPriority(eventListener, 1) local function onExit(tag) if tag == "exit" then if eventListener ~= nil then eventDispatcher:removeEventListener(eventListener) end end end self:registerScriptHandler(onExit) local winSize = cc.Director:getInstance():getVisibleSize() self._verticalLayout = ccui.VBox:create() self._verticalLayout:setPosition(cc.p(40, winSize.height - 70)) self._uiLayer:addChild(self._verticalLayout) self._verticalLayout:setScale(0.8) self._verticalLayout:setFocused(true) self._verticalLayout:setLoopFocus(true) self._verticalLayout:setTag(-1000) self._firstFocusedWidget = self._verticalLayout local upperHBox = ccui.HBox:create() upperHBox:setTag(-200) self._verticalLayout:addChild(upperHBox) local params = ccui.LinearLayoutParameter:create() params:setMargin({left = 0, top = 0, right = 50, bottom = 0}) local vparams = ccui.LinearLayoutParameter:create() vparams:setMargin({left = 10, top = 0, right = 0, bottom = 140}) upperHBox:setLayoutParameter(vparams) local function onImageViewClicked(sender, eventType) if eventType == ccui.TouchEventType.ended then local w = sender if w:isFocusEnabled() then w:setFocusEnabled(false) w:setColor(cc.c3b(255, 255, 0)) else w:setFocusEnabled(true) w:setColor(cc.c3b(255, 255, 255)) end end end local count = 3 for i = 1, count do local firstVbox = ccui.VBox:create() firstVbox:setScale(0.5) firstVbox:setLayoutParameter(params) firstVbox:setTag(i * 100) local count1 = 3 for j = 1, count1 do local imageView = ccui.ImageView:create("cocosui/scrollviewbg.png") imageView:setTouchEnabled(true) imageView:setTag(j + firstVbox:getTag()) imageView:addTouchEventListener(onImageViewClicked) firstVbox:addChild(imageView) end upperHBox:addChild(firstVbox) end local bottomHBox = ccui.HBox:create() bottomHBox:setScale(0.5) bottomHBox:setTag(600) bottomHBox:setLayoutParameter(vparams) count = 3 local bottomParams = ccui.LinearLayoutParameter:create() bottomParams:setMargin({left = 0, top = 0, right = 8, bottom = 0}) for i = 1, count do local imageView = ccui.ImageView:create("cocosui/scrollviewbg.png") imageView:setLayoutParameter(bottomParams) imageView:setTouchEnabled(true) imageView:setTag(i + 600) imageView:addTouchEventListener(onImageViewClicked) bottomHBox:addChild(imageView) end self._verticalLayout:addChild(bottomHBox) self._loopText = ccui.Text:create("loop enabled", "Arial", 20) self._loopText:setPosition(cc.p(winSize.width/2, winSize.height - 50)) self._loopText:setColor(cc.c3b(255, 0 ,0)) self:addChild(self._loopText) local function toggleFocusLoop(sender, eventType) if eventType == ccui.TouchEventType.ended then self._verticalLayout:setLoopFocus(not self._verticalLayout:isLoopFocus()) if self._verticalLayout:isLoopFocus() then self._loopText:setString("loop enabled") else self._loopText:setString("loop disabled") end end end local btn = ccui.Button:create("cocosui/switch-mask.png") btn:setTitleText("Toggle Loop") btn:setPosition(cc.p(60, winSize.height - 50)) btn:setTitleColor(cc.c3b(0, 255, 0)) btn:addTouchEventListener(toggleFocusLoop) self:addChild(btn) end end) add_new_testcase(function() local UIS9NinePatchTest = create( "UIS9NinePatchTest", UIScene) function UIS9NinePatchTest:initExtend() cc.SpriteFrameCache:getInstance():addSpriteFrames("cocosui/android9patch.plist") local winSize = cc.Director:getInstance():getWinSize() local x = winSize.width / 2 local y = 0 + (winSize.height / 2 + 50) local preferedSize = cc.size(99,99) --9-patch sprite with filename local playerSprite = ccui.Scale9Sprite:create("cocosui/player.9.png") playerSprite:setPosition(x, y) playerSprite:setContentSize(preferedSize) local capInsets = playerSprite:getCapInsets() print(string.format("player sprite capInset = %f, %f %f, %f", capInsets.x, capInsets.y, capInsets.width, capInsets.height)) self:addChild(playerSprite) local animationBtnSprite = ccui.Scale9Sprite:createWithSpriteFrameName("animationbuttonpressed.png") animationBtnSprite:setPosition(x-100, y-100) capInsets = animationBtnSprite:getCapInsets() print(string.format("animationBtnSprite capInset = %f, %f %f, %f", capInsets.x, capInsets.y, capInsets.width, capInsets.height)) self:addChild(animationBtnSprite) local monsterSprite = ccui.Scale9Sprite:createWithSpriteFrameName("monster.9.png") monsterSprite:setPosition(x+100, y-100) capInsets = monsterSprite:getCapInsets() monsterSprite:setContentSize(preferedSize) print(string.format("monsterSprite capInset = %f, %f %f, %f", capInsets.x, capInsets.y, capInsets.width, capInsets.height)) self:addChild(monsterSprite) local spriteFrame = cc.SpriteFrameCache:getInstance():getSpriteFrame("buttonnormal.9.png") local buttonScale9Sprite = ccui.Scale9Sprite:createWithSpriteFrame(spriteFrame) buttonScale9Sprite:setContentSize(cc.size(150,80)) buttonScale9Sprite:setPosition(cc.p(100,200)) self:addChild(buttonScale9Sprite) end end) function guiSceneManager.nextUIScene() guiSceneManager.currentUISceneIdx = (guiSceneManager.currentUISceneIdx + 1) % table.getn(cocoStudioGuiArray) if 0 == guiSceneManager.currentUISceneIdx then guiSceneManager.currentUISceneIdx = table.getn(cocoStudioGuiArray) end return cocoStudioGuiArray[guiSceneManager.currentUISceneIdx].func() end function guiSceneManager.previousUIScene() guiSceneManager.currentUISceneIdx = guiSceneManager.currentUISceneIdx - 1 if guiSceneManager.currentUISceneIdx <= 0 then guiSceneManager.currentUISceneIdx = guiSceneManager.currentUISceneIdx + table.getn(cocoStudioGuiArray) end return cocoStudioGuiArray[guiSceneManager.currentUISceneIdx].func() end function guiSceneManager.currentUIScene() return cocoStudioGuiArray[guiSceneManager.currentUISceneIdx].func() end function runCocosGUITestScene() local scene = guiSceneManager.currentUIScene() cc.Director:getInstance():replaceScene(scene) end
PLUGIN.name = "DayZ Hud" PLUGIN.author = "Black Tea | STEAM_0:1:29606990" PLUGIN.description = "" if (SERVER) then util.AddNetworkString("ixUpdateRep") util.AddNetworkString("ixHUDShineText") do local playerMeta = FindMetaTable("Player") function playerMeta:NotifyShine(text, time, color) net.Start("ixHUDShineText") net.WriteString(text) net.WriteUInt(time or 5, 16) net.WriteColor(color or color_white) net.Send(self) end end else local SH_SZ = SH_SZ local Color, LocalPlayer, surface, math, ColorAlpha = Color, LocalPlayer, surface, math, ColorAlpha local FrameTime, CurTime = FrameTime, CurTime function PLUGIN:CanDrawAmmoHUD(weapon) if (weapon.ArcCW) then return false end end function PLUGIN:ShouldHideBars() return true end function PLUGIN:ShouldBarDraw() return false end function PLUGIN:PostDeathNotice(victim) local index = victim:EntIndex() ix.net[index] = ix.net[index] or {} ix.net[index]["bleeding"] = nil end local faded_black = ColorAlpha(color_black, 200) ix.option.Add("colorOutlineItems", ix.type.color, Color("sky_blue"), { category = "colors" }) local hud = {} local sscale = ScreenScale local dbox = draw.RoundedBox hud.lang = {} function hud.ResetLang() hud.lang = { radiation = L("Radiation"):utf8upper(), well_fed = L("well_fed"):utf8upper(), safezone = L("safezone_title"):utf8upper(), hunger = L("needs_hunger"):utf8upper(), thirst = L("needs_thirst"):utf8upper(), stamina = L("Endurance"):utf8upper(), l = ix.option.Get("language", "english") } end function PLUGIN:LoadFonts(font) surface.CreateFont("ixDHUDNum", { font = font, size = ix.util.ScreenScaleH(13), weight = 400, -- 100 }) surface.CreateFont("ixDHUDNum2", { font = font, size = math.min(24, sscale(10)), -- ScrH() / 480 * 10 weight = 400, -- 100 }) surface.CreateFont("nutDHUDIcon", { font = "fontello", extended = true, size = ix.util.ScreenScaleH(14), weight = 1500, }) surface.CreateFont("nutDHUDIcon2", { font = "fontello", extended = true, size = sscale(10), weight = 400, }) surface.CreateFont("nutDHUDIcon3", { font = "fontello", extended = true, size = sscale(6), weight = 400, }) surface.CreateFont("nutDHUDFont", { font = font, extended = true, size = sscale(8), weight = 400, }) surface.CreateFont("nutDHUDFont2", { font = font, extended = true, size = sscale(11), weight = 400, }) hud.ResetLang() end local percHistories = {} function hud:percDisp(wok, title, percent, reverse) percHistories[title] = percHistories[title] or {} local meme = percHistories[title] meme.memes = meme.memes or percent meme.alpha = meme.alpha or 0 local x, y, w, h = wok.x, wok.y, wok.w, wok.h surface.SetFont("ixNoticeFont") local tx = surface.GetTextSize(title) w = w / 4 + tx + sscale(2) dbox(wok.rnd or 8, x, y, w, h, faded_black) y = y - sscale(2) ix.util.DrawText(title, x + w/2, y + h/2, wok.textColor or color_white, TEXT_ALIGN_CENTER, 4, "ixNoticeFont") local colorFade = 100 if (reverse == true) then if (percent >= 75) then colorFade = (RealTime() * 150) % 100 end else if (percent < 25) then colorFade = (RealTime() * 150) % 100 end end local colorWider = Color(255, 155 + colorFade, 155 + colorFade) if (meme.memes != percent) then meme.alpha = 255 else if (meme.alpha > 0) then meme.alpha = math.max(meme.alpha - FrameTime() - 5, 0) end end local a, b = x + w/2, y + h/2 ix.util.DrawText(percent .. "%", a, b, colorWider, TEXT_ALIGN_CENTER, 5, "ixDHUDNum") ix.util.DrawText(percent .. "%", a, b, ColorAlpha(colorWider, meme.alpha), TEXT_ALIGN_CENTER, 5, "ixDHUDNum") meme.memes = percent wok.w = w end function hud:edgyBar(wok, color) local x, y, w, h = wok.x, wok.y, wok.w, wok.h dbox(wok.rnd or 8, x, y, w, h, faded_black) local tx, ty = ix.util.DrawText("A", x + sscale(4), y + h/2 - sscale(1), color_white, 3, 1, "nutDHUDIcon") local totallen = w - tx - sscale(12) local maxHP = LocalPlayer():GetMaxHealth() local HP = LocalPlayer():Health() self.awto = Lerp(FrameTime() * 5, self.awto or HP, HP) surface.SetDrawColor(192, 57, 43, 75) surface.DrawRect(x + sscale(8) + tx, y + sscale(3), totallen, h - sscale(5)) surface.SetDrawColor(192, 57, 43) surface.DrawRect(x + sscale(8) + tx, y + sscale(3), totallen * math.min(maxHP, self.awto) / maxHP, h - sscale(5)) HP = math.Clamp(math.Round(self.awto), 0, maxHP) local xHP = ix.util.DrawText(HP .. "%", x + sscale(4) + tx + 10, y + h/2 - sscale(1), color_white, 3, TEXT_ALIGN_CENTER, "ixDHUDNum2") if (LocalPlayer():ExtraHealth() > 0) then ix.util.DrawText(Format("(+%d)", LocalPlayer():ExtraHealth()), x + sscale(4) + tx + 15 + xHP, y + h/2 - sscale(1), color_white, 3, TEXT_ALIGN_CENTER, "ixDHUDNum2") end end function hud:drawText(wok, title, font) font = font or "nutDHUDFont" local x, y, w, h = wok.x, wok.y, wok.w, wok.h surface.SetFont(font) local tx = surface.GetTextSize(title) w = w / 4 + tx + sscale(2) dbox(wok.rnd or 8, x, y, w, h, faded_black) ix.util.DrawText(title, x + w/2, y + h/2 - sscale(1), wok.textColor or color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, font) end function hud:status(wok, text, icon, bNotFixSize) local x, y, w, h = wok.x, wok.y, wok.w, wok.h if (!bNotFixSize) then surface.SetFont("nutDHUDFont") local tx = surface.GetTextSize(text) w = w / 2 + tx + sscale(2) end dbox(wok.rnd or 8, x, y, w, h, faded_black) local tx, ty = ix.util.DrawText(icon or "Z", x + sscale(4), y + h/2 - sscale(1), color_white, 3, TEXT_ALIGN_CENTER, "nutDHUDIcon2") local next = w/2 + tx + sscale(2) ix.util.DrawText(text, next, y + h/2 - sscale(1), wok.textColor or color_white, 1, TEXT_ALIGN_CENTER, "nutDHUDFont") end local dirName = { [12] = "N", [0] = "E", [-12] = "S", [24] = "W", [-24] = "W", } function hud:compass(wok) local x, y, w, h = wok.x, wok.y, wok.w, wok.h dbox(wok.rnd or 8, x, y, w, h, faded_black) surface.SetDrawColor(color_white) local startX, endX = x + sscale(5), x + w - sscale(5) local displayW = (endX - startX) local angola = EyeAngles().y local dir = angola/7.5 -- 90 is north, -90 is south -180/180 is west 0 is east local macOpt = (displayW)/24 local a, b = math.floor(dir-12), math.ceil(dir+12) a = (a + 24)%48 - 24 b = (b + 24)%48 - 24 for i = -24, 23 do -- POSITION DEPENDANCY if (a > b) then if (i > b and i < a) then continue end else if (i > b or i < a) then continue end end local pos if (a > b) then if (dir < 0) then -- 좌측 if (i > 0) then pos = endX - macOpt*(i - 36 - dir) else pos = endX - macOpt*(i + 12 - dir) end elseif (dir >= 0) then -- 우측 -- 마이너스가 오른쪽 if (i < 0) then pos = endX - macOpt*(i + 60 - dir) else pos = endX - macOpt*(i + 12 - dir) end end else pos = endX - macOpt*(i + 12 - dir) end pos = math.Clamp(pos, startX, endX) if (i%6 == 0) then if (dirName[i]) then ix.util.DrawText(dirName[i], pos, y + h - sscale(10), color_white, 1, TEXT_ALIGN_CENTER, "nutDHUDFont") end surface.DrawLine(pos, y + h - sscale(2), pos, y + h - sscale(6.5)) else surface.DrawLine(pos, y + h - sscale(2), pos, y + h - sscale(5)) end end --SCHEMA.targets = { for _, v in ipairs(ents.FindByClass("ix_item")) do if (LocalPlayer():GetPos():DistToSqr(v:GetPos()) < (262144)) then local angola = math.NormalizeAngle((v:GetPos() - LocalPlayer():GetPos()):Angle().y) local target = angola/7.5 local pos if (a > b) then if (dir < 0) then -- 좌측 if (target > 0) then pos = endX - macOpt*(target - 36 - dir) else pos = endX - macOpt*(target + 12 - dir) end elseif (dir >= 0) then -- 우측 -- 마이너스가 오른쪽 if (target < 0) then pos = endX - macOpt*(target + 60 - dir) else pos = endX - macOpt*(target + 12 - dir) end end else pos = endX - macOpt*(target + 12 - dir) end pos = math.Clamp(pos, startX, endX) ix.util.DrawText("c", pos, y + h - sscale(10), color_white, 1, TEXT_ALIGN_CENTER, "nutDHUDIcon3") end end end hud.noti = {} local function addText(text, time, color) local wow = {str = 0, text = text, time = CurTime() + time, alpha = 0, aalpha = 155, gloss = false, color = color} hud.noti[#hud.noti + 1] = wow end net.Receive("ixHUDShineText", function() local text = net.ReadString() local time = net.ReadUInt(16) local color = net.ReadColor() addText(L(text), time or 5, color or color_white) end) net.Receive("ixUpdateRep", function() local bandit = net.ReadBool() local repDiff = net.ReadUInt(16) if (bandit) then addText(Format("%s -%d", L"reputation", repDiff), 4, Color("red")) else addText(Format("%s +%d", L"reputation", repDiff), 4, Color("dark_lime")) end end) local GLOW_MATERIAL = Material("sprites/glow04_noz.vmt") function hud:drawNotifications() local x, y = ScrW()/2, ScrH()/4*3 local blyat = 0 local cnt = 0 for k, v in pairs(hud.noti) do cnt = cnt + 1 v.y = v.y or y + blyat v.y = Lerp(FrameTime() * 10, v.y, y + blyat) if (cnt > 5) then v.time = CurTime() + 3 continue end if (v.time < CurTime()) then if (v.alpha < 5) then table.remove(hud.noti, k) continue end v.alpha = Lerp(FrameTime()*3, v.alpha, 0) else v.alpha = Lerp(FrameTime()*3, v.alpha, 255) end if (v.gloss) then v.aalpha = Lerp(FrameTime()*5, v.aalpha, 0) else if (v.aalpha > 150) then v.gloss = true end v.aalpha = Lerp(FrameTime()*15, v.aalpha, 255) end v.str = Lerp(FrameTime()*4, v.str, 4) local tx, ty = ix.util.DrawText(v.text, x, v.y, ColorAlpha(v.color or color_white, v.alpha), 1, TEXT_ALIGN_CENTER, "nutDHUDFont2") surface.SetMaterial(GLOW_MATERIAL) surface.SetDrawColor(ColorAlpha(v.color or color_white, v.aalpha)) blyat = blyat + ty*1.1 tx, ty = tx*(2 + v.str*0.8), ty*(v.str*1.3) surface.DrawTexturedRect(x - tx/2, v.y - ty/2, tx, ty) end end --do -- ix_item toScreen --local rangeSize, angleCos = 80, math.cos(math.rad(45)) --local shadowColor = Color(66, 66, 66) --hook.Add("PostDrawTranslucentRenderables", "PostDrawTranslucentRenderables.ix_item", function(bDepth, bSkybox) -- if (bDepth or bSkybox or !LocalPlayer():GetCharacter()) then return end -- local startPos = LocalPlayer():EyePos() -- local dir = LocalPlayer():GetAimVector() -- local entities = ents.FindInCone(startPos, dir, rangeSize, angleCos) -- for _, ent in ipairs(entities) do -- if (IsValid(ent) and ent:GetClass() == "ix_item") then -- if (IsValid(ix.gui.entityInfo) and ix.gui.entityInfo.entity == ent) then continue end -- local item = ent:GetItemTable() -- local quantity = ent:GetData("quantity", 1) -- local text = item:GetName() -- if (quantity >= 2) then -- text = Format("%s (x%d)", text, quantity) -- end -- cam.Start2D() -- local centerScreen = ent:GetPos():ToScreen() -- draw.SimpleTextOutlined(text, "ixNoticeFont", -- centerScreen.x, centerScreen.y, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, shadowColor -- ) -- cam.End2D() -- end -- end --end) --end local breathSound = Sound("gmodz/player/stamina.wav") function PLUGIN:Think() if (hud.lang.tick or 0) < CurTime() then if (hud.lang.l != ix.option.Get("language", "english")) then hud.ResetLang() end hud.lang.tick = CurTime() + 1 end local client = LocalPlayer() local playedHeartbeatSound = false if (client:Alive()) then local health = client:GetHealth() local maxHealth = client:GetMaxHealth() if (health < 34) then if (!self.HeartbeatSound) then self.HeartbeatSound = CreateSound(client, "player/heartbeat1.wav") end if (CurTime() >= (self.NextHeartbeat or 0)) then self.NextHeartbeat = CurTime() + ( 0.75 + ( (1.25 / maxHealth) * health ) ) self.HeartbeatSound:PlayEx(0.75 - ( (0.7 / maxHealth) * health ), 100) end playedHeartbeatSound = true end end if (!playedHeartbeatSound and self.HeartbeatSound) then if (client:Alive()) then self.HeartbeatSound:FadeOut(10) else self.HeartbeatSound:Stop() end end for _, v in ipairs(player.GetAll()) do if (v:GetCharacter() and v:Alive() and v:GetNetVar("brth")) then v.BreathSound = v:StartLoopingSound(breathSound) elseif (v.BreathSound) then v:StopLoopingSound(v.BreathSound) v.BreathSound = nil end end end gameevent.Listen("player_disconnect") hook.Add("player_disconnect", "HUD.player_disconnect", function(data) local client = Player(data.userid) if (client.BreathSound) then client:StopLoopingSound(client.BreathSound) client.BreathSound = nil end end) do local ColorModify = { [ "$pp_colour_addr" ] = 0, [ "$pp_colour_addg" ] = 0, [ "$pp_colour_addb" ] = 0, [ "$pp_colour_brightness" ] = 0, [ "$pp_colour_contrast" ] = 1, [ "$pp_colour_colour" ] = 1, [ "$pp_colour_mulr" ] = 0, [ "$pp_colour_mulg" ] = 0, [ "$pp_colour_mulb" ] = 0 } local color = 0 function PLUGIN:RenderScreenspaceEffects() if (LocalPlayer():Alive()) then color = 1 - (LocalPlayer():GetHealth() / LocalPlayer():GetMaxHealth()) -- color = math.Approach(color, math.Clamp(1 - math.Clamp(LocalPlayer():Health() / LocalPlayer():GetMaxHealth(), 0, 1), 0, 1), FrameTime() * 3) if (color > 0) then ColorModify["$pp_colour_colour"] = math.Clamp(1 - color, 0, 1) DrawColorModify(ColorModify) end end end end function PLUGIN:HUDPaint() local client = LocalPlayer() if (!client:GetCharacter() or !client:Alive()) then return end -- OUTLINE local entity = LocalPlayer():GetTrace(120).Entity if (IsValid(entity) and Schema.outlineItems[entity:GetClass()]) then outline.Add(entity, ix.option.Get("colorOutlineItems", color_white), OUTLINE_MODE_VISIBLE) end hud:drawNotifications() local margin = sscale(5) local w, h = ScrW(), ScrH() local perc = {} perc.w = sscale(150) perc.h = sscale(15) perc.x = w/2 - perc.w/2 perc.y = h - perc.h - sscale(5) hud:compass(perc) perc = {} perc.w = sscale(100) perc.h = sscale(15) perc.x = sscale(5) perc.y = h - perc.h - sscale(5) hud:edgyBar(perc) local oldX = perc.x perc.h = sscale(15) perc.x = perc.x + perc.w + sscale(5) perc.w = sscale(50) perc.y = perc.y -- Reputation local repData = Schema.ranks[client:GetReputationLevel()] or Schema.ranks[0] perc.textColor = repData[2] hud:drawText(perc, L(repData[1])) -- Human needs local getHunger = math.Round((1 - client:GetHungerPercent()) * 100) local getThirst = math.Round((1 - client:GetThirstPercent()) * 100) perc.textColor = color_white perc.w = sscale(30) perc.h = sscale(25) perc.x = oldX perc.y = perc.y - perc.h - margin hud:percDisp(perc, hud.lang.hunger, getHunger) perc.x = perc.x + perc.w + margin hud:percDisp(perc, hud.lang.thirst, getThirst) perc.x = perc.x + perc.w + margin hud:percDisp(perc, hud.lang.stamina, math.Round(client:GetLocalVar("stm", 0))) perc.w = sscale(50) perc.h = sscale(15) perc.x = sscale(5) if (client:GetNetVar("bleeding")) then local prefix, color = ix.bleeding:Format() perc.textColor = color perc.y = perc.y - perc.h - margin hud:status(perc, prefix, "5") end -- blood loss effect local bleeding_level for _, v in ipairs(player.GetAll()) do if (IsValid(v) and v:Health() > 0) then bleeding_level = v:GetNetVar("bleeding") if (bleeding_level and (v.nextBloodDrop or 0) < CurTime()) then local bone_pos = v:GetBonePosition(v:LookupBone("ValveBiped.Bip01_Spine")) if (!bone_pos) then continue end local effect = EffectData() effect:SetOrigin(bone_pos) effect:SetMagnitude(1) util.Effect("blooddrop", effect, nil) v.nextBloodDrop = CurTime() + math.max(0.25, 0.5 + ix.bleeding.max_level - bleeding_level) end end end if (client:IsBrokenLeg()) then -- НОГА ПОВРЕЖДЕНА perc.textColor = Color("red") perc.y = perc.y - perc.h - margin hud:status(perc, L("broken_leg")) end -- Safezone local penaltyTime = math.max(0, client:GetPenaltyTime() - CurTime()) if (penaltyTime != 0) then perc.y = perc.y - perc.h - margin perc.textColor = Color("red") hud:status(perc, L"cannot_enter_safezone" .. " " .. string.ToMinutesSeconds(penaltyTime), "R") elseif (client:GetLocalVar("SH_SZ.Safe", SH_SZ.OUTSIDE) == SH_SZ.PROTECTED) then perc.y = perc.y - perc.h - margin perc.textColor = Color(50, 200, 50) hud:status(perc, hud.lang.safezone, "R") elseif (client:GetLocalVar("SH_SZ.Safe", SH_SZ.OUTSIDE) == SH_SZ.ENTERING) then local sz = SH_SZ.m_Safe if (sz and sz.opts.ptime) then perc.y = perc.y - perc.h - margin perc.textColor = Color(200, 200, 50) local time = math.max(math.ceil(sz.enter + sz.opts.ptime - CurTime()), 0) hud:status(perc, hud.lang.safezone .. " " .. string.ToMinutesSeconds(math.max(0, time - 1)), "R") end end -- PVP local pvpTime = math.max(0, client:GetPVPTime() - CurTime()) if (pvpTime != 0) then perc.y = perc.y - perc.h - margin perc.textColor = Color("red") hud:status(perc, L"combat_logged" .. " " .. string.ToMinutesSeconds(pvpTime), "R") -- В БОЮ end if (hook.Run("CanPlayerRegenHealth", client) != false) then if (getHunger >= 90 and getThirst >= 90) then perc.textColor = Color("light_lime") perc.y = perc.y - perc.h - margin hud:status(perc, hud.lang.well_fed, "j") -- СЫТ end end local rad = client:GetRadiationTotal() if (rad > 0) then perc.textColor = rad >= 500 and Color("red") or Color("yellow") perc.y = perc.y - perc.h - margin hud:status(perc, hud.lang.radiation .. ": " .. math.Round(rad), "Z") -- СЫТ end hook.Run("HUDExtraPaint", client, perc, hud, margin) end end
local search = {} search.new = function (request) local new = {} new.photos = function (t) if not t then t = {} end setmetatable(t, {__index = {page = 1, per_page = 10}}) return request({ url = '/search/photos', method = 'GET', query = { query = t.query, page = t.page, per_page = t.per_page, collections = t.collections } }) end new.collections = function (options) if not t then t = {} end setmetable(t, {__index = {page = 1, per_page = 10}}) return request({ url = '/search/collections', method = 'GET', query = { query = t.query, page = t.page, per_page = t.per_page } }) end new.users = function (options) if not t then t = {} end setmetable(t, {__index = {page = 1, per_page = 10}}) return request ({ url = '/search/users', method = 'GET', query = { query = t.query, page = t.page, per_page = t.per_page } }) end return new end return search
require 'busted.runner'() local mexbt = require('mexbt') describe("meXBT", function() it("gives a valid response to all public api functions that require no args", function() local flist = {"ticker", "trades", "currency_pairs", "order_book"}; for i,fname in ipairs(flist) do assert.is_true(mexbt[fname]().isAccepted) end end) it("allows passing a custom currency pair to functions that accept it", function() local flist = {"ticker", "trades", "order_book"}; for i,fname in ipairs(flist) do assert.is_true(mexbt[fname]('BTCUSD').isAccepted) end end) it("allows you to fetch trades by date range", function() local result = mexbt.trades_by_date(nil, os.time(), os.time()) assert.is_true(result.isAccepted) assert.is_true(#result.trades == 0) end) end)
-- -- Created by IntelliJ IDEA. -- User: junjie -- Date: 2014/11/5 -- Time: 15:40 -- 稍后完善其他函数的包装 -- local ffi = require("ffi") local crypto = ffi.load("crypto") ffi.cdef[[ typedef struct rsa_st RSA; typedef struct bio_st BIO; typedef int pem_password_cb(char *buf, int size, int rwflag, void *userdata); int RSA_public_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa,int padding); int RSA_private_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa,int padding); int RSA_public_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa,int padding); int RSA_private_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa,int padding); BIO *BIO_new_mem_buf(void *buf, int len); int BIO_free(BIO *a); RSA *PEM_read_bio_RSA_PUBKEY(BIO *bp, RSA **x, pem_password_cb *cb, void *u); RSA *PEM_read_bio_RSAPrivateKey(BIO *bp, RSA **x, pem_password_cb *cb, void *u); int RSA_size(const RSA *r); void RSA_free(RSA *r); ]] local RSA_PKCS1_PADDING = 1 local function init_public_key(pem_key) local bio = crypto.BIO_new_mem_buf(ffi.cast("unsigned char *", pem_key), -1) local rsa = crypto.PEM_read_bio_RSA_PUBKEY(bio, nil, nil, nil) crypto.BIO_free(bio) if rsa == nil then return nil, "parse public key fail" end return rsa, nil end local function init_private_key(pem_key) local bio = crypto.BIO_new_mem_buf(ffi.cast("unsigned char *", pem_key), -1) local rsa = crypto.PEM_read_bio_RSAPrivateKey(bio, nil, nil, nil) crypto.BIO_free(bio) if rsa == nil then return nil, "parse private key fail" end return rsa, nil end local function public_decrypt(key, data) local rsa, err = init_public_key(key) if err ~= nil then return nil, err end local size = tonumber(crypto.RSA_size(rsa)) local decrypted = ffi.new("unsigned char[?]", size) data = ffi.cast("const unsigned char *" ,data) local len = crypto.RSA_public_decrypt(size, data, decrypted, rsa, RSA_PKCS1_PADDING) crypto.RSA_free(rsa) if len <= 0 then return nil, "decrypt fail" end return ffi.string(decrypted, len), nil end local function private_encrypt(key, data) local rsa, err = init_private_key(key) if err ~= nil then return nil, err end local size = tonumber(crypto.RSA_size(rsa)) local encrypted = ffi.new("unsigned char[?]", size) local len = crypto.RSA_private_encrypt(#data, data, encrypted, rsa, RSA_PKCS1_PADDING) crypto.RSA_free(rsa) if len ~= size then return nil, "encrypt fail" end return ffi.string(encrypted, len), nil end return { public_decrypt = public_decrypt, private_encrypt = private_encrypt, }
--[[ GloopBlocks Originally written by GloopMaster Licensed under WTFPL. Maintained by VanessaE. --]] -- Boilerplate to support localized strings if intllib mod is installed. local S if minetest.get_modpath("intllib") then S = intllib.Getter() else S = function(s) return s end end -- misc stuff local colorlist = { {"white", "White"}, {"grey", "Grey"}, {"black", "Black"}, {"red", "Red"}, {"yellow", "Yellow"}, {"green", "Green"}, {"cyan", "Cyan"}, {"blue", "Blue"}, {"magenta", "Magenta"}, {"orange", "Orange"}, {"violet", "Violet"}, {"brown", "Brown"}, {"pink", "Pink"}, {"dark_grey", "Dark Grey"}, {"dark_green", "Dark Green"}, } -- Nodes minetest.register_node("gloopblocks:rainbow_block", { description = S("Rainbow Block"), tiles = {"gloopblocks_rainbow_block.png"}, is_ground_content = true, groups = {cracky=3}, sounds = default.node_sound_defaults(), }) minetest.register_node("gloopblocks:cement", { description = S("Cement"), tiles = {"gloopblocks_cement.png"}, is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("gloopblocks:evil_block", { description = S("Evil Block"), tiles = {"gloopblocks_evil_block.png"}, light_source = 5, is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("gloopblocks:basalt", { description = S("Basalt"), tiles = {"gloopblocks_basalt.png"}, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("gloopblocks:pumice", { description = S("Pumice"), tiles = {"gloopblocks_pumice.png"}, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("gloopblocks:pavement", { description = S("Pavement"), tiles = {"gloopblocks_pavement.png"}, groups = {cracky=3, oddly_breakable_by_hand=3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("gloopblocks:oerkki_block", { drawtype = "nodebox", description = S("Oerkki Block"), paramtype = "light", paramtype2 = "facedir", tiles = { "gloopblocks_oerkkiblock_tb.png", "gloopblocks_oerkkiblock_tb.png", "gloopblocks_oerkkiblock_sides.png", "gloopblocks_oerkkiblock_sides.png", "gloopblocks_oerkkiblock_sides.png", "gloopblocks_oerkkiblock_front.png" }, groups = {cracky=3, oddly_breakable_by_hand=3}, sounds = default.node_sound_stone_defaults(), selection_box = { type = "fixed", fixed = { -0.5, -0.5, -0.5, 0.5, 0.5, 0.5 } }, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.1875, 0.5, 0.5, 0.1875}, -- NodeBox1 {-0.5, -0.5, -0.5, -0.4375, 0.5, 0.5}, -- NodeBox2 {0.4375, -0.5, -0.5, 0.5, 0.5, 0.5}, -- NodeBox3 {-0.5, 0.4375, -0.5, 0.5, 0.5, 0.5}, -- NodeBox4 {-0.5, -0.5, -0.5, 0.5, -0.4375, 0.5}, -- NodeBox5 {-0.5, -0.0625, -0.5, 0.5, 0.0625, 0.5}, -- NodeBox6 } } }) minetest.register_node("gloopblocks:stone_brick_mossy", { description = S("Mossy Stone Brick"), tiles = {"gloopblocks_stone_brick_mossy.png"}, groups = {cracky=3, stone=1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("gloopblocks:stone_mossy", { description = S("Mossy Stone"), tiles = {"gloopblocks_stone_mossy.png"}, groups = {cracky=3, stone=1}, sounds = default.node_sound_stone_defaults(), drop = "default:mossycobble" }) minetest.register_node("gloopblocks:cobble_road", { description = S("Cobblestone Road Bed"), tiles = {"gloopblocks_cobble_road.png"}, groups = {cracky=3, stone=1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("gloopblocks:cobble_road_mossy", { description = S("Mossy Cobblestone Road Bed"), tiles = {"gloopblocks_cobble_road_mossy.png"}, groups = {cracky=3, stone=1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("gloopblocks:scaffolding", { description = S("Wooden Scaffold"), drawtype = "allfaces", paramtype = "light", sunlight_propagates = true, tiles = {"gloopblocks_scaffold.png"}, groups = {choppy=3, oddly_breakable_by_hand=3}, sounds = default.node_sound_wood_defaults(), on_rightclick = function(pos, node, clicker, itemstack) if itemstack and itemstack:get_name() == node.name then for i = 1,19 do if minetest.get_node({x=pos.x,y=pos.y-i,z=pos.z}).name == "gloopblocks:scaffolding" and scafffound ~= 0 and scafffound ~= 1 then local scafffound = 1 return itemstack else break end end for i = 1,19 do if minetest.get_node({x=pos.x,y=pos.y+i,z=pos.z}).name == "air" and scaffworked ~= 1 and scaffworked ~= 0 then minetest.set_node({x=pos.x,y=pos.y+i,z=pos.z}, {name="gloopblocks:scaffolding"}) local scaffworked = 1 return ItemStack(tostring(itemstack:get_name().." "..tostring(itemstack:get_count()-1))) elseif minetest.get_node({x=pos.x,y=pos.y+i,z=pos.z}).name == "gloopblocks:scaffolding" then else local scaffworked = 0 end end if scaffworked == 1 then return ItemStack(tostring(itemstack:get_name().." "..tostring(itemstack:get_count()-1))) else return itemstack end else return itemstack end end, }) minetest.register_alias("moreblocks:oerkkiblock", "gloopblocks:oerkki_block") minetest.register_alias("gloopblocks:obsidian", "default:obsidian") -- Stairs/slabs defs, conversion of normal -> mossy items if minetest.setting_getbool("gloopblocks_mossy_conversion") ~= false then function gloopblocks_register_mossy_conversion(mossyobjects) for i in ipairs(mossyobjects) do minetest.register_abm({ nodenames = { mossyobjects[i][1] }, neighbors = {"default:water_source", "default:water_flowing"}, interval = 120, chance = 50, action = function(pos, node) if minetest.find_node_near(pos, 2, "air") then local fdir = node.param2 minetest.add_node(pos, {name = mossyobjects[i][2], param2 = fdir}) end end, }) end end end if minetest.get_modpath("moreblocks") then stairsplus:register_all("gloopblocks", "oerkki_block", "gloopblocks:oerkki_block", { description = "Oerkki Block", tiles = { "gloopblocks_oerkkiblock_tb.png", "gloopblocks_oerkkiblock_tb.png", "gloopblocks_oerkkiblock_sides.png", "gloopblocks_oerkkiblock_sides.png", "gloopblocks_oerkkiblock_sides.png", "gloopblocks_oerkkiblock_front.png" }, groups = {cracky=2, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), sunlight_propagates = true, }) stairsplus:register_all("gloopblocks", "stone_brick_mossy", "gloopblocks:stone_brick_mossy", { description = "Mossy Stone Brick", tiles = {"gloopblocks_stone_brick_mossy.png"}, groups = {cracky=1, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), sunlight_propagates = true, }) stairsplus:register_all("gloopblocks", "stone_mossy", "gloopblocks:stone_mossy", { description = "Mossy Stone", tiles = {"gloopblocks_stone_mossy.png"}, groups = {cracky=1, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), sunlight_propagates = true, }) stairsplus:register_all("gloopblocks", "cobble_road", "gloopblocks:cobble_road", { description = "Cobblestone Roadbed", tiles = {"gloopblocks_cobble_road.png"}, groups = {cracky=3, stone=1, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), sunlight_propagates = true, }) stairsplus:register_all("gloopblocks", "cobble_road_mossy", "gloopblocks:cobble_road_mossy", { description = "Mossy Cobblestone Roadbed", tiles = {"gloopblocks_cobble_road_mossy.png"}, groups = {cracky=3, stone=1, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), sunlight_propagates = true, }) stairsplus:register_all("gloopblocks", "cement", "gloopblocks:cement", { description = "Cement", tiles = {"gloopblocks_cement.png"}, groups = {cracky=2, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), sunlight_propagates = true, }) stairsplus:register_all("gloopblocks", "pavement", "gloopblocks:pavement", { description = "Pavement", tiles = {"gloopblocks_pavement.png"}, groups = {cracky=2, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), sunlight_propagates = true, }) stairsplus:register_all("gloopblocks", "rainbow_block", "gloopblocks:rainbow_block", { description = "Rainbow Block", tiles = {"gloopblocks_rainbow_block.png"}, groups = {cracky=3, not_in_creative_inventory=1}, sounds = default.node_sound_defaults(), sunlight_propagates = true, }) stairsplus:register_all("gloopblocks", "evil_block", "gloopblocks:evil_block", { description = "Evil Block", tiles = {"gloopblocks_evil_block.png"}, groups = {cracky=3, not_in_creative_inventory=1}, sounds = default.node_sound_defaults(), light_source = 5, sunlight_propagates = true, }) stairsplus:register_all("gloopblocks", "basalt", "gloopblocks:basalt", { description = "Basalt", tiles = {"gloopblocks_basalt.png"}, groups = {cracky=2, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), sunlight_propagates = true, }) stairsplus:register_all("gloopblocks", "pumice", "gloopblocks:pumice", { description = "Pumice", tiles = {"gloopblocks_pumice.png"}, groups = {cracky=3, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), sunlight_propagates = true, }) for i in ipairs(colorlist) do local color = colorlist[i][1] local colordesc = colorlist[i][2] stairsplus:register_all("wool", color, "wool:"..color, { description = colordesc.." Wool", tiles = {"wool_"..color..".png"}, groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1,not_in_creative_inventory=1}, sounds = default.node_sound_defaults(), sunlight_propagates = true, }) end -- ABMs for mossy objects if minetest.setting_getbool("gloopblocks_mossy_conversion") ~= false then gloopblocks_register_mossy_conversion({ { "default:cobble", "default:mossycobble" }, { "default:stair_cobble", "default:stair_mossycobble" }, { "default:slab_cobble", "default:slab_mossycobble" }, { "moreblocks:stair_cobble", "moreblocks:stair_mossycobble" }, { "moreblocks:stair_cobble_inner", "moreblocks:stair_mossycobble_inner" }, { "moreblocks:stair_cobble_outer", "moreblocks:stair_mossycobble_outer" }, { "moreblocks:stair_cobble_half", "moreblocks:stair_mossycobble_half" }, { "moreblocks:slab_cobble_quarter", "moreblocks:slab_mossycobble_quarter" }, { "moreblocks:slab_cobble", "moreblocks:slab_mossycobble" }, { "moreblocks:slab_cobble_three_quarter", "moreblocks:slab_mossycobble_three_quarter" }, { "moreblocks:panel_cobble", "moreblocks:panel_mossycobble" }, { "moreblocks:micro_cobble", "moreblocks:micro_mossycobble" }, { "moreblocks:stair_cobble_alt", "moreblocks:stair_mossycobble_alt" }, { "gloopblocks:cobble_road", "gloopblocks:cobble_road_mossy" }, { "gloopblocks:stair_cobble_road", "gloopblocks:stair_cobble_road_mossy" }, { "gloopblocks:slab_cobble_road", "gloopblocks:slab_cobble_road_mossy" }, { "gloopblocks:stair_cobble_road", "gloopblocks:stair_cobble_road_mossy" }, { "gloopblocks:stair_cobble_road_inner", "gloopblocks:stair_cobble_road_mossy_inner" }, { "gloopblocks:stair_cobble_road_outer", "gloopblocks:stair_cobble_road_mossy_outer" }, { "gloopblocks:stair_cobble_road_half", "gloopblocks:stair_cobble_road_mossy_half" }, { "gloopblocks:slab_cobble_road_quarter", "gloopblocks:slab_cobble_road_mossy_quarter" }, { "gloopblocks:slab_cobble_road", "gloopblocks:slab_cobble_road_mossy" }, { "gloopblocks:slab_cobble_road_three_quarter", "gloopblocks:slab_cobble_road_mossy_three_quarter" }, { "gloopblocks:panel_cobble_road", "gloopblocks:panel_cobble_road_mossy" }, { "gloopblocks:micro_cobble_road", "gloopblocks:micro_cobble_road_mossy" }, { "gloopblocks:stair_cobble_road_alt", "gloopblocks:stair_cobble_road_mossy_alt" }, { "default:stonebrick", "gloopblocks:stone_brick_mossy" }, { "default:stair_stonebrick", "gloopblocks:stair_stone_brick_mossy" }, { "default:slab_stonebrick", "gloopblocks:slab_stone_brick_mossy" }, { "moreblocks:stair_stonebrick", "gloopblocks:stair_stone_brick_mossy" }, { "moreblocks:stair_stonebrick_inner", "gloopblocks:stair_stone_brick_mossy_inner" }, { "moreblocks:stair_stonebrick_outer", "gloopblocks:stair_stone_brick_mossy_outer" }, { "moreblocks:stair_stonebrick_half", "gloopblocks:stair_stone_brick_mossy_half" }, { "moreblocks:slab_stonebrick_quarter", "gloopblocks:slab_stone_brick_mossy_quarter" }, { "moreblocks:slab_stonebrick", "gloopblocks:slab_stone_brick_mossy" }, { "moreblocks:slab_stonebrick_three_quarter", "gloopblocks:slab_stone_brick_mossy_three_quarter" }, { "moreblocks:panel_stonebrick", "gloopblocks:panel_stone_brick_mossy" }, { "moreblocks:micro_stonebrick", "gloopblocks:micro_stone_brick_mossy" }, { "moreblocks:stair_stonebrick_alt", "gloopblocks:stair_stone_brick_mossy_alt" }, { "default:stone", "gloopblocks:stone_mossy" }, { "default:stair_stone", "gloopblocks:stair_stone_mossy" }, { "default:slab_stone", "gloopblocks:slab_stone_mossy" }, { "moreblocks:stair_stone", "gloopblocks:stair_stone_mossy" }, { "moreblocks:stair_stone_inner", "gloopblocks:stair_stone_mossy_inner" }, { "moreblocks:stair_stone_outer", "gloopblocks:stair_stone_mossy_outer" }, { "moreblocks:stair_stone_half", "gloopblocks:stair_stone_mossy_half" }, { "moreblocks:slab_stone_quarter", "gloopblocks:slab_stone_mossy_quarter" }, { "moreblocks:slab_stone", "gloopblocks:slab_stone_mossy" }, { "moreblocks:slab_stone_three_quarter", "gloopblocks:slab_stone_mossy_three_quarter" }, { "moreblocks:panel_stone", "gloopblocks:panel_stone_mossy" }, { "moreblocks:micro_stone", "gloopblocks:micro_stone_mossy" }, { "moreblocks:stair_stone_alt", "gloopblocks:stair_stone_mossy_alt" }, }) end elseif minetest.get_modpath("stairs") then --stairs.register_stair(subname, recipeitem, groups, images, description, sounds) -- stairs:xxxx_stone_mossy ; xxxx = stair or slab stairs.register_stair_and_slab("stone_mossy", "gloopblocks:stone_mossy", {cracky=3}, {"gloopblocks_stone_mossy.png"}, S("Mossy Stone Stair"), S("Mossy Stone Slab"), default.node_sound_stone_defaults()) -- stairs:xxxx_mossycobble stairs.register_stair_and_slab("mossycobble", "default:mossycobble", {cracky=3}, {"default_mossycobble.png"}, S("Mossy Cobble Stair"), S("Mossy Cobble Slab"), default.node_sound_stone_defaults()) -- stairs:xxxx_stone_brick_mossy stairs.register_stair_and_slab("stone_brick_mossy", "gloopblocks:stone_brick_mossy", {cracky=3}, {"gloopblocks_stone_brick_mossy.png"}, S("Mossy Stone Brick Stair"), S("Mossy Stone Brick Slab"), default.node_sound_stone_defaults()) -- stairs:xxxx_cobble_road stairs.register_stair_and_slab("cobble_road", "gloopblocks:cobble_road", {cracky=3}, {"gloopblocks_cobble_road.png"}, S("Cobble Roadbed Stair"), S("Cobble Roadbed Slab"), default.node_sound_stone_defaults()) -- stairs:xxxx_cobble_road_mossy stairs.register_stair_and_slab("cobble_road_mossy", "gloopblocks:cobble_road_mossy", {cracky=3}, {"gloopblocks_cobble_road_mossy.png"}, S("Mossy Cobble Roadbed Stair"), S("Mossy Cobble Roadbed Slab"), default.node_sound_stone_defaults()) -- stairs:xxxx_cement stairs.register_stair_and_slab("cement", "gloopblocks:cement", {cracky=2}, {"gloopblocks_cement.png"}, S("Cement Stair"), S("Cement Slab"), default.node_sound_stone_defaults()) -- stairs:xxxx_pavement stairs.register_stair_and_slab("pavement", "gloopblocks:pavement", {cracky=3, oddly_breakable_by_hand=3}, {"gloopblocks_pavement.png"}, S("Pavement Stair"), S("Pavement Slab"), default.node_sound_stone_defaults()) stairs.register_stair_and_slab("basalt", "gloopblocks:basalt", {cracky=2}, {"gloopblocks_basalt.png"}, "Basalt Stair", "Basalt Slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("pumice", "gloopblocks:pumice", {cracky=3}, {"gloopblocks_pumice.png"}, "Pumice Stair", "Pumice Slab", default.node_sound_stone_defaults()) stairs.register_stair_and_slab("rainbow_block", "gloopblocks:rainbow_block", {cracky=3}, {"gloopblocks_rainbow_block.png"}, "Rainbow Block Stair", "Rainbow Block Slab", default.node_sound_defaults()) for i in ipairs(colorlist) do local color = colorlist[i][1] local colordesc = colorlist[i][2] stairs.register_stair_and_slab("wool_"..color, "wool:"..color, {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3,wool=1}, {"wool_"..color..".png"}, "Wool Stair ("..colordesc..")", "Wool Slab ("..colordesc..")", default.node_sound_defaults()) end if minetest.setting_getbool("gloopblocks_mossy_conversion") ~= false then gloopblocks_register_mossy_conversion({ { "default:cobble", "default:mossycobble" }, { "stairs:stair_cobble", "stairs:stair_mossycobble" }, { "stairs:slab_cobble", "stairs:slab_mossycobble" }, { "gloopblocks:cobble_road", "gloopblocks:cobble_road_mossy" }, { "stairs:stair_cobble_road", "stairs:stair_cobble_road_mossy" }, { "stairs:slab_cobble_road", "stairs:slab_cobble_road_mossy" }, { "default:stonebrick", "gloopblocks:stone_brick_mossy" }, { "stairs:stair_stonebrick", "stairs:stair_stone_brick_mossy" }, { "stairs:slab_stonebrick", "stairs:slab_stone_brick_mossy" }, { "default:stone", "gloopblocks:stone_mossy" }, { "stairs:stair_stone", "stairs:stair_stone_mossy" }, { "stairs:slab_stone", "stairs:slab_stone_mossy" }, }) end minetest.register_alias("default:stair_mossycobble", "stairs:stair_mossycobble") minetest.register_alias("default:slab_mossycobble", "stairs:slab_mossycobble") minetest.register_alias("gloopblocks:stair_cobble_road", "stairs:stair_cobble_road") minetest.register_alias("gloopblocks:slab_cobble_road", "stairs:slab_cobble_road") minetest.register_alias("gloopblocks:stair_cobble_road_mossy", "stairs:stair_cobble_road_mossy") minetest.register_alias("gloopblocks:slab_cobble_road_mossy", "stairs:slab_cobble_road_mossy") minetest.register_alias("gloopblocks:stair_stone_brick_mossy", "stairs:stair_stone_brick_mossy") minetest.register_alias("gloopblocks:slab_stone_brick_mossy", "stairs:slab_stone_brick_mossy") minetest.register_alias("gloopblocks:stair_stone_mossy", "stairs:stair_stone_mossy") minetest.register_alias("gloopblocks:slab_stone_mossy", "stairs:slab_stone_mossy") minetest.register_alias("gloopblocks:stair_cement", "stairs:stair_cement") minetest.register_alias("gloopblocks:slab_cement", "stairs:slab_cement") minetest.register_alias("gloopblocks:stair_pavement", "stairs:stair_pavement") minetest.register_alias("gloopblocks:slab_pavement", "stairs:slab_pavement") minetest.register_alias("gloopblocks:stair_pumice", "stairs:stair_pumice") minetest.register_alias("gloopblocks:slab_pumice", "stairs:slab_pumice") minetest.register_alias("gloopblocks:stair_basalt", "stairs:stair_basalt") minetest.register_alias("gloopblocks:slab_basalt", "stairs:slab_basalt") minetest.register_alias("gloopblocks:stair_rainbow_block", "stairs:stair_rainbow_block") minetest.register_alias("gloopblocks:slab_rainbow_block", "stairs:slab_rainbow_block") end -- Tools minetest.register_tool("gloopblocks:pick_cement", { description = S("Cement Pickaxe"), inventory_image = "gloopblocks_cement_pick.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ cracky={times={[1]=3.50, [2]=1.40, [3]=0.90}, uses=25, maxlevel=2} }, damage_groups = {fleshy=4}, }, }) minetest.register_tool("gloopblocks:shovel_cement", { description = S("Cement Shovel"), inventory_image = "gloopblocks_cement_shovel.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ crumbly={times={[1]=1.50, [2]=0.60, [3]=0.45}, uses=25, maxlevel=2} }, damage_groups = {fleshy=4}, }, }) minetest.register_tool("gloopblocks:axe_cement", { description = S("Cement Axe"), inventory_image = "gloopblocks_cement_axe.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ choppy={times={[1]=3.00, [2]=1.30, [3]=0.80}, uses=25, maxlevel=2}, fleshy={times={[2]=1.20, [3]=0.65}, uses=30, maxlevel=1} }, damage_groups = {fleshy=4}, }, }) minetest.register_tool("gloopblocks:sword_cement", { description = S("Cement Sword"), inventory_image = "gloopblocks_cement_sword.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ fleshy={times={[1]=1.60, [2]=0.80, [3]=0.40}, uses=15, maxlevel=2}, snappy={times={[2]=0.75, [3]=0.35}, uses=30, maxlevel=1}, choppy={times={[3]=0.80}, uses=30, maxlevel=0} }, damage_groups = {fleshy=6}, } }) minetest.register_tool("gloopblocks:pick_evil", { description = S("Evil Pickaxe"), inventory_image = "gloopblocks_evil_pick.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=3, groupcaps={ cracky={times={[1]=0.10, [2]=0.10, [3]=0.10}, uses=10, maxlevel=2} }, damage_groups = {fleshy=6}, }, }) minetest.register_tool("gloopblocks:shovel_evil", { description = S("Evil Shovel"), inventory_image = "gloopblocks_evil_shovel.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=3, groupcaps={ crumbly={times={[1]=0.05, [2]=0.05, [3]=0.05}, uses=10, maxlevel=2} }, damage_groups = {fleshy=6}, }, }) minetest.register_tool("gloopblocks:axe_evil", { description = S("Evil Axe"), inventory_image = "gloopblocks_evil_axe.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=3, groupcaps={ choppy={times={[1]=0.15, [2]=0.15, [3]=0.15}, uses=10, maxlevel=2}, fleshy={times={[1]=0.15, [2]=0.15, [3]=0.15}, uses=10, maxlevel=2} }, damage_groups = {fleshy=6}, }, }) minetest.register_tool("gloopblocks:sword_evil", { description = S("Evil Sword"), inventory_image = "gloopblocks_evil_sword.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=3, groupcaps={ fleshy={times={[1]=0.20, [2]=0.20, [3]=0.20}, uses=10, maxlevel=2}, snappy={times={[1]=0.20, [2]=0.20, [3]=0.20}, uses=10, maxlevel=2}, choppy={times={[1]=0.20, [2]=0.20, [3]=0.20}, uses=10, maxlevel=2} }, damage_groups = {fleshy=8}, } }) -- Other items minetest.register_craftitem("gloopblocks:wet_cement", { description = S("Wet Cement"), inventory_image = "gloopblocks_wet_cement.png", }) minetest.register_craftitem("gloopblocks:evil_stick", { description = S("Evil Stick"), inventory_image = "gloopblocks_evil_stick.png", }) -- define lava-cooling-based nodes and hook into the default lavacooling -- functions to generate basalt, pumice, and obsidian if minetest.setting_getbool("gloopblocks_lavacooling") ~= false then minetest.register_node("gloopblocks:obsidian_cooled", { description = S("Obsidian"), tiles = {"default_obsidian.png"}, is_ground_content = true, sounds = default.node_sound_stone_defaults(), groups = {cracky=1, level=2, not_in_creative_inventory=1}, drop = "default:obsidian", after_place_node = function(pos, placer, itemstack, pointed_thing) minetest.add_node(pos, {name = "default:obsidian"}) end }) minetest.register_node("gloopblocks:basalt_cooled", { description = S("Basalt"), tiles = {"gloopblocks_basalt.png"}, groups = {cracky=2, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), drop = "gloopblocks:basalt", after_place_node = function(pos, placer, itemstack, pointed_thing) minetest.add_node(pos, {name = "gloopblocks:basalt"}) end }) minetest.register_node("gloopblocks:pumice_cooled", { description = S("Pumice"), tiles = {"gloopblocks_pumice.png"}, groups = {cracky=3, not_in_creative_inventory=1}, sounds = default.node_sound_stone_defaults(), drop = "gloopblocks:pumice", after_place_node = function(pos, placer, itemstack, pointed_thing) minetest.add_node(pos, {name = "gloopblocks:pumice"}) end }) local gloopblocks_search_nearby_nodes = function(pos, node) if minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z}).name == node then return true end if minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z}).name == node then return true end if minetest.get_node({x=pos.x, y=pos.y-1, z=pos.z}).name == node then return true end if minetest.get_node({x=pos.x, y=pos.y+1, z=pos.z}).name == node then return true end if minetest.get_node({x=pos.x, y=pos.y, z=pos.z-1}).name == node then return true end if minetest.get_node({x=pos.x, y=pos.y, z=pos.z+1}).name == node then return true end return false end default.cool_lava_source = function(pos) if gloopblocks_search_nearby_nodes(pos,"default:water_source") or gloopblocks_search_nearby_nodes(pos,"default:water_flowing") then minetest.set_node(pos, {name="gloopblocks:obsidian_cooled"}) end end default.cool_lava_flowing = function(pos) if gloopblocks_search_nearby_nodes(pos,"default:water_source") then minetest.set_node(pos, {name="gloopblocks:basalt_cooled"}) elseif gloopblocks_search_nearby_nodes(pos,"default:water_flowing") then minetest.set_node(pos, {name="gloopblocks:pumice_cooled"}) end end end dofile(minetest.get_modpath("gloopblocks").."/crafts.lua") print(S("Gloopblocks Loaded!"))
--[[ Copyright (C) 2014-2017 - Eloi Carbo This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] module("luci.controller.bird4", package.seeall) function index() entry({"admin", "network", "bird4",}, alias("admin", "network", "bird4", "status"), _("Bird4"), 0) entry({"admin", "network", "bird4", "status"}, cbi("bird4/status"), _("Status"), 0).leaf = true entry({"admin","network","bird4","log"}, template("bird4/log"), _("Log"), 1).leaf = true entry({"admin", "network", "bird4", "overview"}, cbi("bird4/overview"), _("Overview"), 2).leaf = true entry({"admin","network","bird4","proto_general"}, cbi("bird4/gen_proto"), _("General protocols"), 3).leaf = true entry({"admin","network","bird4","proto_bgp"}, cbi("bird4/bgp_proto"), _("BGP Protocol"), 4).leaf = true entry({"admin","network","bird4","filters"}, cbi("bird4/filters"), _("Filters"), 5).leaf = true entry({"admin","network","bird4","functions"}, cbi("bird4/functions"), _("Functions"), 6).leaf = true end
return {'wysiwyg'}
local abilitydefs = include( "sim/abilitydefs" ) local simdefs = include( "sim/simdefs" ) local simquery = include( "sim/simquery" ) local btree = include("sim/btree/btree") local util = include( "modules/util" ) local mathutil = include( "modules/mathutil" ) local abilitydefs = include( "sim/abilitydefs" ) local speechdefs = include( "sim/speechdefs" ) local inventory = include("sim/inventory") local function checkForDeployedItem(unit) local cell = unit:getSim():getCell(unit:getLocation() ) local units = {} for i,checkUnit in ipairs(cell.units) do if checkUnit ~= unit and checkUnit:getTraits().deployed and inventory.canCarry(unit, checkUnit) then table.insert(units,checkUnit) end end return units end local function doTrackerAlert(sim, unit) if unit:getTraits().trackerAlert then local tracker, text, x0, y0 = unpack( unit:getTraits().trackerAlert ) sim:dispatchEvent( simdefs.EV_UNIT_FLOAT_TXT, {txt=util.sformat( STRINGS.UI.ALARM_ADD, tracker ),x=x0,y=y0,color={r=255/255,g=10/255,b=10/255,a=1}} ) sim:trackerAdvance( tracker, text ) unit:getTraits().trackerAlert = nil end end local Actions = {} --[[ Actions are the nodes of a behaviour tree that make changes in the world. There are two types: Simple actions use the btree.Action class to create a node that has a function to call when the action should happen. They are just functions that get passed a sim, the current unit and the current memory and can then do something with it. Action functions should return what behaviour state they are in: BSTATE_COMPLETE if the action happens successfully, BSTATE_FAILED if the action could not be completed , BSTATE_WAITING if the action should be tried again later and BSTATE_RUNNING if the action should be called again immediately. Class actions are classes based on the btree.BaseAction class. They can define onInitialise, update and onTerminate functions, and save their own state. Generally, it's preferable to save state in the persistent memory that inside the action itself, and so simple actions should be used most of the time ]]-- --Simple Actions function Actions.MeleeTarget(sim, unit) if not unit:getBrain():getTarget() then return simdefs.BSTATE_FAILED end local abilityDef = unit:ownsAbility( "melee" ) if unit:canUseAbility( sim, abilityDef, unit, unit:getBrain():getTarget():getID() ) then abilityDef:executeAbility( sim, unit, unit, unit:getBrain():getTarget():getID() ) return simdefs.BSTATE_COMPLETE end end function Actions.ShootAtTarget(sim, unit) if not unit:getBrain():getTarget() then return simdefs.BSTATE_FAILED end local target = unit:getBrain():getTarget() --we should only have the target if we can see them local canShoot = unit:canReact() or unit:getBrain():getSenses():hasLostTarget(target) --if they run into cover and then back out, they need to get shot if canShoot and unit:isAiming() and target:isValid() then local abilityDef = unit:ownsAbility( "shootSingle" ) if abilityDef and abilityDef:canUseAbility( sim, unit, unit, target:getID() ) then abilityDef:executeAbility( sim, unit, unit, target:getID() ) --This could result in getting overwatch shot in return if not unit:isValid() then return simdefs.BSTATE_FAILED end if target:isDead() or target:isKO() or not target:isValid() then if target:getTraits().mainframe_turret then unit:getSim():emitSpeech( unit, speechdefs.COMBAT_TURRETDESTROYED ) else unit:getSim():emitSpeech( unit, speechdefs.COMBAT_TARGETDESTROYED ) end end return simdefs.BSTATE_COMPLETE end else if not unit:isAiming() then local abilityDef = unit:ownsAbility("overwatch") if abilityDef then abilityDef:executeAbility(sim, unit, unit, target:getID()) doTrackerAlert(sim, unit) if sim:getCurrentPlayer() == unit:getPlayerOwner() then return simdefs.BSTATE_WAITINGFORPCTURN end end end end return simdefs.BSTATE_WAITINGFORCORPTURN end function Actions.MarkInterestInvestigated(sim, unit) if not unit:getBrain():getInterest() then return simdefs.BSTATE_FAILED end sim:dispatchEvent( simdefs.EV_UNIT_DEL_INTEREST, {unit = unit, interest = unit:getBrain():getInterest()} ) if unit:getBrain():getSituation().ClassType == simdefs.SITUATION_HUNT then unit:getBrain():getSituation():markHuntTargetSearched(unit) elseif unit:getBrain():getSituation().ClassType == simdefs.SITUATION_INVESTIGATE then unit:getBrain():getSituation():markInterestInvestigated(unit) end local units = checkForDeployedItem(unit) if #units > 0 then local pickedUpUnit local destroyedUnit = false for i,pickUpUnit in ipairs(units) do local abilityDef = pickUpUnit:ownsAbility( "carryable" ) if abilityDef and abilityDef:canUseAbility( sim, pickUpUnit, unit) then abilityDef:executeAbility( sim, pickUpUnit, unit ) pickedUpUnit = pickUpUnit elseif unit:getTraits().isDrone then sim:warpUnit( pickUpUnit ) sim:despawnUnit( pickUpUnit ) destroyedUnit = true end end if destroyedUnit then local params = {color ={{symbol="inner_line",r=1,g=0,b=0,a=0.75},{symbol="wall_digital",r=1,g=0,b=0,a=0.75},{symbol="boxy_tail",r=1,g=0,b=0,a=0.75},{symbol="boxy",r=1,g=0,b=0,a=0.75}} } sim:dispatchEvent( simdefs.EV_UNIT_ADD_FX, { unit = unit, kanim = "fx/emp_effect", symbol = "character", anim="idle", above=true, params=params} ) local x1, y1 = unit:getLocation() sim:dispatchEvent( simdefs.EV_PLAY_SOUND, {sound="SpySociety/HitResponse/hitby_tazer_flesh", x=x1,y=y1} ) end end return simdefs.BSTATE_COMPLETE end function Actions.RemoveInterest(sim, unit) if not unit:getBrain():getInterest() then return simdefs.BSTATE_FAILED end sim:dispatchEvent( simdefs.EV_UNIT_DEL_INTEREST, {unit = unit, interest = unit:getBrain():getInterest()} ) sim:triggerEvent( simdefs.TRG_DEL_INTEREST, {unit = unit, interest = unit:getBrain():getInterest()} ) return simdefs.BSTATE_COMPLETE end function Actions.FinishSearch(sim, unit) sim:emitSpeech(unit, speechdefs.INVESTIGATE_FINISH ) sim:dispatchEvent( simdefs.EV_UNIT_DONESEARCHING, {unit = unit} ) return simdefs.BSTATE_COMPLETE end local function checkLookaround( sim, unit, delta ) local x0, y0 = unit:getLocation() local dir = unit:getFacing() local probeCells = {} if unit:getTraits().no_look_around then -- reserved for units that don't peek or drone scan elseif unit:getTraits().lookaroundRange then local fillCells = simquery.fillCircle( sim, x0, y0, unit:getTraits().lookaroundRange, 0) for i, cell in ipairs(fillCells) do if cell.x ~= x0 or cell.y ~= y0 then local raycastX, raycastY = sim:getLOS():raycast(x0, y0, cell.x, cell.y) if raycastX == cell.x and raycastY == cell.y then table.insert(probeCells, cell) end end end else local cell = sim:getCell( x0, y0 ) if (dir % 2) == 0 then local dx, dy = simquery.getDeltaFromDirection( dir ) local facing = (dir + delta*2) % simdefs.DIR_MAX if simquery.isOpenExit( cell.exits[ dir ] ) then -- If possible, probe orthogonally to our current facing. probeCells = sim:getLOS():probeLOS( x0 + dx, y0 + dy, facing, unit:getTraits().LOSrange ) end if #probeCells == 0 and simquery.isOpenExit( cell.exits[ facing ] ) then -- If you can't probe that way, probe a cell over down the axis of our actual facing. local dx, dy = simquery.getDeltaFromDirection( facing ) probeCells = sim:getLOS():probeLOS( x0 + dx, y0 + dy, dir, unit:getTraits().LOSrange ) end else -- On a diagonal, probe a cell in front down the cardinal axis to the left/right local dx, dy = simquery.getDeltaFromDirection( dir ) if simquery.isConnected( sim, cell, sim:getCell( x0 + dx, y0 + dy )) then local facing = (dir + delta) % simdefs.DIR_MAX probeCells = sim:getLOS():probeLOS( x0 + dx, y0 + dy, facing, unit:getTraits().LOSrange ) end end end if sim:isVersion( "0.17.9" ) then sim:dispatchEvent( simdefs.EV_PULSE_SCAN, {unit=unit, cells=probeCells, range=unit:getTraits().lookaroundRange} ) end for i, cell in ipairs(probeCells) do if sim:isVersion( "0.17.9" ) and unit:getTraits().lookaroundRange then sim:scanCell( unit, cell, true ) else for j, targetUnit in ipairs(cell.units) do -- it the looker is a drone, it's scanning and should find disguised targets. local ingnoreDisguise = false -- if sim:isVersion( "0.17.9" ) and unit:getTraits().lookaroundRange then -- ingnoreDisguise = true -- end if simquery.isEnemyAgent(unit:getPlayerOwner(), targetUnit, ingnoreDisguise) and simquery.couldUnitSee(sim, unit, targetUnit, true) then if not sim:canUnitSeeUnit(unit, targetUnit) then unit:getBrain():getSenses():addInterest(cell.x, cell.y, simdefs.SENSE_PERIPHERAL, simdefs.REASON_NOTICED, targetUnit, ingnoreDisguise) end end end end end return probeCells end local function overrideUnitLOS(sim, unit, facingRad, losArc, delta ) local oldRads = unit:getTraits().LOSrads local oldArc = unit:getTraits().LOSarc local oldPeripheralArc = unit:getTraits().LOSperipheralArc local oldRange = unit:getTraits().LOSrange unit:getTraits().LOSrads = facingRad unit:getTraits().LOSarc = losArc unit:getTraits().LOSperipheralArc = nil sim:refreshUnitLOS( unit ) checkLookaround( sim, unit, delta ) sim:processReactions(unit) unit:getTraits().LOSrads = oldRads unit:getTraits().LOSarc = oldArc unit:getTraits().LOSperipheralArc = oldPeripheralArc end function Actions.DoLookAround(sim, unit ) if unit:getTraits().no_look_around then return simdefs.BSTATE_COMPLETE end local cell = sim:getCell(unit:getLocation()) local exitDir = unit:getFacing() local exit = cell.exits[exitDir] if exit and exit.door and exit.closed and not exit.locked then sim:modifyExit(cell, exitDir, simdefs.EXITOP_OPEN, unit) end if unit:isValid() and not unit:isKO() then if unit:isAlerted() then sim:emitSpeech( unit, speechdefs.HUNT_SEARCH ) else sim:emitSpeech( unit, speechdefs.INVESTIGATE_SEARCH ) end unit:setAiming( false ) unit:getTraits().lookingAround = true if unit:getTraits().lookaroundRange then local cells = checkLookaround( sim, unit ) if #cells > 0 then sim:dispatchEvent( simdefs.EV_UNIT_LOOKAROUND, { unit = unit, part="scan", cells=cells} ) end sim:processReactions(unit) else -- Quarter circle, minus half the default guard's LOS arc, so that its edge aligns with 180. local FACING_OFFSET = unit:getTraits().lookaroundOffset or (math.pi/4 - math.pi/16) local lookaroundArc = unit:getTraits().lookaroundArc or (math.pi/2 + math.pi/8) local dir = unit:getFacing() sim:dispatchEvent( simdefs.EV_UNIT_LOOKAROUND, { unit = unit, part="right" } ) overrideUnitLOS( sim, unit, unit:getFacingRad() - FACING_OFFSET, lookaroundArc, -1) if unit:isValid() and not unit:getTraits().interrupted then sim:dispatchEvent( simdefs.EV_UNIT_LOOKAROUND, { unit = unit, part="right_post" } ) end if unit:isValid() and not unit:getTraits().interrupted then sim:dispatchEvent( simdefs.EV_UNIT_LOOKAROUND, { unit = unit, part="left" } ) overrideUnitLOS( sim, unit, unit:getFacingRad() + FACING_OFFSET, lookaroundArc, 1) end if unit:isValid() then if not unit:getTraits().interrupted then sim:dispatchEvent( simdefs.EV_UNIT_LOOKAROUND, { unit = unit, part="left_post" } ) sim:dispatchEvent( simdefs.EV_UNIT_LOOKAROUND, { unit = unit, part="post" } ) end sim:refreshUnitLOS(unit) --return to normal LOS if not unit:getTraits().interrupted then sim:processReactions(unit) end end end unit:getTraits().lookingAround = nil if unit:getTraits().interrupted then -- ccc: don't want to walk any further if we saw something, so consume all MP. --- (but shouldn't there a way to prevent further behaviours just by returning the correct BSTATE_FAILED?) if unit:isValid() then unit:useMP( unit:getMP(), sim ) end return simdefs.BSTATE_FAILED end return simdefs.BSTATE_COMPLETE end end function Actions.ReactToTarget(sim, unit) local target = unit:getBrain():getTarget() if not target or not target:isValid() then return simdefs.BSTATE_FAILED end local x0,y0 = unit:getLocation() local x1,y1 = target:getLocation() if not x1 or not y1 then --it's possible our target is in someone's inventory return simdefs.BSTATE_FAILED end unit:turnToFace(x1, y1) --turning could change our target target = unit:getBrain():getTarget() if unit:isValid() and target and target:isValid() and target:getLocation() and unit:getTraits().camera_drone then sim:dispatchEvent( simdefs.EV_UNIT_ALERTED, { unitID = unit:getID() } ) sim:triggerEvent( simdefs.TRG_NEW_INTEREST, { x=x0, y=y0, range=0, target=target, interest={x=x1, y=y1, sourceUnit=unit} }) target:interruptMove(sim, unit) elseif unit:isValid() and target and target:isValid() and target:getLocation() then sim:dispatchEvent( simdefs.EV_UNIT_ALERTED, { unitID = unit:getID() } ) if target:getTraits().mainframe_turret then unit:getSim():emitSpeech( unit, speechdefs.COMBAT_NEWTURRET ) else unit:getSim():emitSpeech( unit, speechdefs.COMBAT_NEWTARGET ) end sim:triggerEvent( simdefs.TRG_NEW_INTEREST, { x=x0, y=y0, range=simdefs.SOUND_RANGE_2, target=target, interest={x=x1, y=y1, sourceUnit=unit} }) target:interruptMove(sim, unit) sim:dispatchEvent( simdefs.EV_UNIT_ENGAGED, unit ) end return simdefs.BSTATE_COMPLETE end function Actions.WatchTarget(sim, unit) if not unit:getBrain():getTarget() then return simdefs.BSTATE_FAILED end local x1,y1 = unit:getBrain():getTarget():getLocation() unit:turnToFace(x1, y1) doTrackerAlert(sim, unit) if not unit:canReact() then return simdefs.BSTATE_WAITINGFORCORPTURN end return simdefs.BSTATE_COMPLETE end function Actions.MarkHuntTargetSearched(sim, unit) if unit:getBrain():getSituation().ClassType ~= simdefs.SITUATION_HUNT then return simdefs.BSTATE_FAILED end sim:dispatchEvent( simdefs.EV_UNIT_DEL_INTEREST, {unit = unit, interest = unit:getBrain():getInterest()} ) sim:triggerEvent( simdefs.TRG_DEL_INTEREST, {unit = unit, interest = unit:getBrain():getInterest()} ) unit:getBrain():getSituation():markHuntTargetSearched(unit) return simdefs.BSTATE_COMPLETE end function Actions.RequestNewHuntTarget(sim, unit) if unit:getBrain():getSituation().ClassType ~= simdefs.SITUATION_HUNT then return simdefs.BSTATE_FAILED end local rememberedInterest = unit:getBrain():getSenses():getRememberedInterest() if rememberedInterest then unit:getBrain():getSituation():overrideHuntTarget(unit, rememberedInterest) else unit:getBrain():getSituation():requestNewHuntTarget(unit) end return simdefs.BSTATE_COMPLETE end function Actions.ReactToInterest(sim, unit) local interest = unit:getBrain():getInterest() if not interest then return simdefs.BSTATE_FAILED end if interest.noticed then --we already reacted! return simdefs.BSTATE_COMPLETE end sim:dispatchEvent( simdefs.EV_UNIT_ALERTED, { unitID = unit:getID() } ) if interest.reason == simdefs.REASON_WITNESS then if not interest.sourceUnit:getPlayerOwner() or interest.sourceUnit:getPlayerOwner() == unit:getPlayerOwner() then unit:getSim():emitSpeech( unit, speechdefs.HUNT_SAW ) end elseif interest.reason == simdefs.REASON_KO then --no need for speech, they already spoke when they woke up elseif interest.reason == simdefs.REASON_PATROLCHANGED then --no need to say anything, Central talks about it elseif interest.reason == simdefs.REASON_REINFORCEMENTS then if unit:isAlerted() then unit:getSim():emitSpeech( unit, speechdefs.HUNT_REINFORCEMENT ) else unit:getSim():emitSpeech( unit, speechdefs.INVESTIGATE_REINFORCEMENT ) end elseif interest.reason == simdefs.REASON_NOISE then if unit:isAlerted() then unit:getSim():emitSpeech( unit, speechdefs.HUNT_NOISE) else unit:getSim():emitSpeech( unit, speechdefs.INVESTIGATE_NOISE ) end elseif interest.reason == simdefs.REASON_FOUNDCORPSE then if interest.sourceUnit:getPlayerOwner() and interest.sourceUnit:getPlayerOwner() ~= unit:getPlayerOwner() then if interest.sourceUnit:getTraits().mainframe_turret then unit:getSim():emitSpeech( unit, speechdefs.COMBAT_TURRETDESTROYED ) else unit:getSim():emitSpeech( unit, speechdefs.COMBAT_TARGETDESTROYED ) end if unit:isAiming() then unit:setAiming(false) unit:getSim():dispatchEvent(simdefs.EV_UNIT_OVERWATCH, { cancel=true, unit = unit} ) end else if interest.sourceUnit:getTraits().wasDrone then unit:getSim():emitSpeech( unit, speechdefs.HUNT_DRONE) else unit:getSim():emitSpeech( unit, speechdefs.HUNT_CORPSE ) end end elseif interest.reason == simdefs.REASON_FOUNDDRONE then if unit:isAlerted() then unit:getSim():emitSpeech( unit, speechdefs.HUNT_DRONE) else unit:getSim():emitSpeech( unit, speechdefs.INVESTIGATE_DRONE) end elseif interest.reason == simdefs.REASON_DOOR then if unit:isAlerted() then unit:getSim():emitSpeech( unit, speechdefs.HUNT_SAW) else unit:getSim():emitSpeech( unit, speechdefs.INVESTIGATE_SAW ) end elseif interest.reason == simdefs.REASON_LOSTTARGET then --a bit of wizardry! Guards will magically know if a target is down and not say anything if not interest.sourceUnit:isKO() and not interest.sourceUnit:isDead() then if not sim:hasTag("lostTargetSpeech") then unit:getSim():emitSpeech( unit, speechdefs.HUNT_LOSTTARGET ) sim:getTags().lostTargetSpeech = true end end elseif interest.reason == simdefs.REASON_FOUNDOBJECT or interest.reason == simdefs.REASON_SMOKE then unit:getSim():emitSpeech( unit, speechdefs.HUNT_FOUNDOBJECT) else --generic if unit:isAlerted() then local speak = true local situation = unit:getBrain():getSituation() if situation.ClassType == simdefs.SITUATION_HUNT and sim:isVersion( "0.17.9" ) then util.tprint(situation.huntTargets) for i,target in pairs(situation.huntTargets)do if type(target) == "table" then targetUnit = sim:getUnit(i) local x1,y1 = unit:getLocation() local x2,y2 = targetUnit:getLocation() local cell = sim:getCell( x2,y2 ) local interest = unit:getBrain():getInterest() if i ~= unit:getID() and target.noticed == true and cell and interest.x == x2 and interest.y == y2 and simquery.couldUnitSeeCell(sim, unit, cell ) then print("block speech") speak = false end end end end if speak then unit:getSim():emitSpeech( unit, speechdefs.HUNT_GENERIC ) end else unit:getSim():emitSpeech( unit, speechdefs.INVESTIGATE_GENERIC ) end end if unit:canReact() then unit:turnToFace(interest.x, interest.y) end interest.noticed = true doTrackerAlert(sim, unit) return simdefs.BSTATE_COMPLETE end function Actions.FaceNextPatrolPoint(sim, unit) local patrolPoint = unit:getBrain():getPatrolPoint() if patrolPoint then unit:turnToFace(patrolPoint.x, patrolPoint.y) return simdefs.BSTATE_COMPLETE end end function Actions.Panic(sim, unit) sim:dispatchEvent( simdefs.EV_UNIT_ALERTED, { unitID = unit:getID() } ) if unit:getBrain():getTarget() then unit:getSim():emitSpeech( unit, speechdefs.FLEE_STARTLED ) elseif unit:getBrain():getInterest() and not unit:getBrain():getInterest().noticed then unit:getSim():emitSpeech( unit, speechdefs.FLEE_PANIC ) unit:getBrain():getInterest().noticed = true end sim:dispatchEvent( simdefs.EV_UNIT_REFRESH, { unit = unit } ) doTrackerAlert(sim, unit) return simdefs.BSTATE_COMPLETE end function Actions.Cower(sim, unit) unit:getSim():emitSpeech( unit, speechdefs.FLEE_COWER ) if unit:getBrain():getInterest() then unit:getBrain():getInterest().investigated = true end return simdefs.BSTATE_COMPLETE end function Actions.ExitLevel(sim, unit) local cell = sim:getCell(unit:getLocation() ) if not cell then return simdefs.BSTATE_FAILED end if not simquery.cellHasTag(sim, cell, "guard_spawn") then return simdefs.BSTATE_FAILED end if unit:getTraits().vip then local units = {unit} sim:dispatchEvent( simdefs.EV_TELEPORT, { units=units, warpOut =true } ) sim:triggerEvent( "vip_escaped" , {unit=unit} ) end sim:warpUnit( unit, nil ) sim:despawnUnit( unit ) return simdefs.BSTATE_COMPLETE end -------------------------------------------------------------------------------------------------------------------- -- Class actions ------------------------------------------------------------------------------------------------- Actions.UseAbility = class(btree.BaseAction, function(self, abilityID) local abilityDef = abilitydefs.lookupAbility( abilityID ) local name = abilityDef and abilityDef.name if name then --some actions have an unnecessary addition to them name = name:gsub("\nACTION", "") end btree.BaseAction.init(self, name or "Unknown Ability") self.ability = abilityID end) function Actions.UseAbility:update() local abilityDef = self.unit:hasAbility( self.ability ) if abilityDef and self.unit:canUseAbility( self.sim, abilityDef, self.unit ) then abilityDef:executeAbility( self.sim, self.unit, self.unit ) return simdefs.BSTATE_COMPLETE end return simdefs.BSTATE_FAILED end ------------------------------------------------------------------------------------------------------ Actions.MoveTo = class(btree.BaseAction, function(self, name) btree.BaseAction.init(self, name or "Base Move Action") end) function Actions.MoveTo:calculatePath(unit) unit:getPather():calculatePath(unit) local path = unit:getPather():getPath(unit) if path and path.path then if unit:getTraits().dynamicImpass then unit:getPather():reservePath(path) end else if self.onNoPath then return self:onNoPath() end end unit:getSim():dispatchEvent( simdefs.EV_UNIT_GOALS_UPDATED, {unitID = unit:getID()} ) return simdefs.BSTATE_RUNNING end function Actions.MoveTo:executePath(unit) local path = unit:getPather():getPath(unit) if not path then return simdefs.BSTATE_FAILED end if not path.path then return simdefs.BSTATE_WAITING end simlog(simdefs.LOG_PATH, "(%d) - Executing Path", unit:getID() ) local sim = unit:getSim() path.iter = path.iter + 1 if not unit or not unit:isValid() or unit:isKO() or unit:isDead() then -- Unit must have perished during path execution. path.result = simdefs.CANMOVE_FAILED elseif path.result then -- Path already has a result, fuck it. Probably failed early. -- ccc: this clause is dumb, why is there a path.result and yet we are in the processing list? Should be mutually exclusive. -- Currently it's because of the else clause of 'if #moveTable > 0' assert( false, string.format( "[%d] PATH has result %s", unit:getID(), path.result )) elseif path.iter > 10 then log:write("%d] PATH - bailing; not complete after %d iterations", unit:getID(), path.iter) path.result = simdefs.CANMOVE_FAILED unit:getPather():unreservePath(path) else local x0, y0 = unit:getLocation() local nodes = path.path:getNodes() local actions = path.actions --simlog( simdefs.LOG_PATH, "%d] EXECUTE PATH from (%d, %d) -> (%d, %d) [%d nodes]", unit:getID(), x0, y0, path.goalx, path.goaly, #nodes ) -- Assume success; if an error occurs, path.result will be overwritten with the reason. path.result = simdefs.CANMOVE_OK local moveTable = {} local moveAction = nil assert( #nodes > 0 ) while #nodes > 0 do local pathNode = table.remove( nodes, 1 ) -- is already reserved at pathNode's location, but at a lower t? then wait if pathNode.location.x == path.currentNode.location.x and pathNode.location.y == path.currentNode.location.y then -- If this path node is a PAUSE (same location as the previous node) then don't bother checking for reservations, -- or we'll HALT on ourselves. else for i = 0, pathNode.t-1 do local reservation = unit:getPather():checkPathReservation(pathNode.location.x, pathNode.location.y, i) if reservation then --simlog( simdefs.LOG_PATH, "\tHALTING -- for reservation at (%d, %d, t = %d > %d)", pathNode.location.x, pathNode.location.y, pathNode.t, i ) table.insert( nodes, 1, pathNode ) path.result = nil -- Clear result, otherwise this path will bail on reprocessing. pathNode = nil break end end end if pathNode then local action = unit:getPather():getActionForNode(path, path.currentNode) if action then table.insert( nodes, 1, pathNode ) path.actions[path.currentNode.lid] = nil moveAction = action if moveAction.keepPathing then path.result = nil end break end local prevx, prevy = x0, y0 if #moveTable > 0 then prevx, prevy = moveTable[ #moveTable ].x, moveTable[ #moveTable ].y end if pathNode.location.x ~= prevx or pathNode.location.y ~= prevy then table.insert( moveTable, { x = pathNode.location.x, y = pathNode.location.y, lid = pathNode.lid } ) end -- Unreserve the previous node immediately, even before we know whether the move can be completed. -- If the movement fails below, we still unreserve the entire path anyways (no point in keeping -- reservations we can't honor!) unit:getPather():unreserveNode(path, path.currentNode) path.currentNode = pathNode else break end end if #moveTable > 0 then if path.goaldir then moveTable[#moveTable].facing = path.goaldir end local canMoveReason, end_cell = sim:moveUnit( unit, moveTable) x0, y0 = unit:getLocation() if not unit:isValid() or unit:getPather():getPath(unit) ~= path then -- The movement resulted in this path being eradicated, so we literally care about nothing from here on out, and it has -- already been cleaned up. -- simlog("\tPATH [%d] REMOVED (aborting)", path.unit:getID() ); return simdefs.BSTATE_FAILED elseif canMoveReason ~= simdefs.CANMOVE_OK then assert( canMoveReason ) --simlog( simdefs.LOG_PATH, "\tFAIL: (%d, %d) -> (%d, %d) (reason = %s)", x0, y0, moveTable[ #moveTable ].x, moveTable[ #moveTable ].y, canMoveReason ) path.result = canMoveReason -- Unreserve the rest of the nodes, if they're still valid unit:getPather():unreservePath(path) if canMoveReason == simdefs.CANMOVE_NOMP then --ran out of MP return self:onPathNoMP() elseif canMoveReason == simdefs.CANMOVE_DYNAMIC_IMPASS then -- Only continue behaviours if i was blocked by an enemy. If I'm blocked by a friendly, presumably something has -- gone wrong with co-op pathfinding and I need to stop. local blocker = simquery.findUnit(end_cell.units, function( u ) return u:getTraits().dynamicImpass end) if blocker then return self:onPathBlocked(blocker) end end return simdefs.BSTATE_FAILED elseif #nodes == 0 then -- Consumed the entire path! -- Not necessarily at the FINAL goal, as we will return partial results (the cooperative astar has a bounded search depth). unit:getPather():unreserveNode(path, path.currentNode) path.currentNode = nil if moveAction then local abilityDef = abilitydefs.lookupAbility(moveAction.ability) if abilityDef and abilityDef:canUseAbility( sim, moveAction.owner, moveAction.user, unpack(moveAction.params) ) then abilityDef:executeAbility(sim, moveAction.owner, moveAction.user, unpack(moveAction.params) ) end if unit:getTraits().interrupted then return simdefs.BSTATE_FAILED end if not moveAction.keepPathing then return simdefs.BSTATE_WAITINGFORPCTURN end end if path.goalx == x0 and path.goaly == y0 then path.result = simdefs.CANMOVE_OK self.unit:getBrain():setDestination(nil) return simdefs.BSTATE_COMPLETE else path.result = simdefs.CANMOVE_PARTIAL_PATH return simdefs.BSTATE_WAITING end else if moveAction then local abilityDef = abilitydefs.lookupAbility(moveAction.ability) if abilityDef and abilityDef:canUseAbility( sim, moveAction.owner, moveAction.user, unpack(moveAction.params) ) then abilityDef:executeAbility(sim, moveAction.owner, moveAction.user, unpack(moveAction.params) ) end if unit:getTraits().interrupted then return simdefs.BSTATE_FAILED end if moveAction.keepPathing then return simdefs.BSTATE_RUNNING else return simdefs.BSTATE_WAITINGFORPCTURN end end simlog( simdefs.LOG_PATH, "(%d) - waiting for path to clear", path.unit:getID(), path.result ) -- Still have path to process. This can only happen if we are waiting for a path reservation; -- Read ourselves for reprocessing (the blocking path should hopefully have processed itself and unreserved by then) return simdefs.BSTATE_WAITING end else if #nodes > 0 then if moveAction then local abilityDef = abilitydefs.lookupAbility(moveAction.ability) if abilityDef and abilityDef:canUseAbility( sim, moveAction.owner, moveAction.user, unpack(moveAction.params) ) then abilityDef:executeAbility(sim, moveAction.owner, moveAction.user, unpack(moveAction.params) ) end if unit:getTraits().interrupted then return simdefs.BSTATE_FAILED end if moveAction.keepPathing then return simdefs.BSTATE_RUNNING else --get rid of the rest of our path path.result = simdefs.CANMOVE_PARTIAL_PATH unit:getPather():unreservePath(path) return simdefs.BSTATE_WAITINGFORPCTURN end end return simdefs.BSTATE_WAITING else assert( path.currentNode, unit:getID().."\n"..util.stringize(path, 3)) unit:getPather():unreserveNode(path, path.currentNode) path.currentNode = nil self.unit:getBrain():setDestination(nil) if path.goaldir then unit:updateFacing( path.goaldir ) end return simdefs.BSTATE_COMPLETE end end end return simdefs.BSTATE_FAILED end function Actions.MoveTo:shouldRecalculate() local path = self.unit:getPather():getPath(self.unit) local dest = self.unit:getBrain():getDestination() if path then if path.result ~= nil then simlog( simdefs.LOG_PATH, "(%d) - recalculating path with existing result (%s)", path.unit:getID(), path.result ) return true end if dest and (path.goalx ~= dest.x or path.goaly ~= dest.y) then simlog( simdefs.LOG_PATH, "(%d) - recalculating path after destination changed", path.unit:getID(), path.result ) return true end if path.path then local startNode = path.path:getStartNode() local currentNode = path.currentNode local x,y = self.unit:getLocation() if not (x == startNode.location.x and y == startNode.location.y) and not (x == currentNode.location.x and y == currentNode.location.y) then simlog( simdefs.LOG_PATH, "(%d) - recalculating path after starting location changed", path.unit:getID(), path.result ) return true end end end return false end function Actions.MoveTo:onPathBlocked(blocker) local x0, y0 = self.unit:getLocation() local x1, y1 = blocker:getLocation() if simquery.isEnemyTarget(self.unit:getPlayerOwner(), blocker) then if mathutil.distSqr2d(x0, y0, x1, y1) <= 1 or not simquery.checkCover(self.unit:getSim(), self.unit, x1, y1) then self.unit:getBrain():getSenses():addInterest(x0, y0, simdefs.SENSE_PERIPHERAL, simdefs.REASON_NOTICED) end return simdefs.BSTATE_RUNNING -- Keep trying end return simdefs.BSTATE_FAILED end function Actions.MoveTo:onPathNoMP() return simdefs.BSTATE_WAITINGFORPCTURN end function Actions.MoveTo:update() if not self:isRunning() or self:shouldRecalculate() then self.status = simdefs.BSTATE_RUNNING if self.getDestination then local dest = self:getDestination(self.unit) if not dest then if self.onNoDestination then self.status = self:onNoDestination() else local x,y = self.unit:getLocation() --by default we just try to path to where we're standing local facing = self.unit:getFacing() dest = {x=x, y=y, facing=facing} end end if dest then self.unit:getBrain():setDestination(dest) self.status = self:calculatePath(self.unit) end end end if self:isRunning() then if self.unit:canReact() then self.status = self:executePath(self.unit) else self.status = simdefs.BSTATE_WAITINGFORCORPTURN end end return self.status end function Actions.MoveTo:cancel() self.unit:interruptMove(self.unit:getSim() ) self.unit:getBrain():setDestination(nil) --cancel our path self.unit:getPather():removePath(self.unit) end ----------------------------------------------------------------------------------------- Actions.MoveToTarget = class(Actions.MoveTo, function(self, name) btree.BaseAction.init(self, name or "MoveToTarget") end) function Actions.MoveToTarget:getDestination() local target = self.unit:getBrain():getTarget() local x, y = target:getLocation() local dest = { x = x, y = y, unit = target} return dest end ----------------------------------------------------------------------------------------- Actions.MoveBesideTarget = class(Actions.MoveTo, function(self, name) btree.BaseAction.init(self, name or "MoveBesideTarget") end) function Actions.MoveBesideTarget:getDestination() local target = self.unit:getBrain():getTarget() local x, y = target:getLocation() if simquery.canUnitReach(self.sim, self.unit, x, y) then --already close enough return nil end local neighbour = simquery.findNearestEmptyReachableCell(self.sim, x, y, self.unit ) if neighbour then local facing = simquery.getDirectionFromDelta(x - neighbour.x, y - neighbour.y) return {x = neighbour.x, y = neighbour.y, facing=facing, unit=target} end end ----------------------------------------------------------------------------------------- Actions.MoveToInterest = class(Actions.MoveTo, function(self, name) btree.BaseAction.init(self, name or "MoveToInterest") end) function Actions.MoveToInterest:getDestination() local interest = self.unit:getBrain():getInterest() local situation = self.unit:getBrain():getSituation() local path = self.unit:getPather():getPath(self.unit) if path and path.result == simdefs.CANMOVE_NOPATH and interest == self.unit:getBrain():getDestination() then if situation.ClassType == simdefs.SITUATION_HUNT then situation:requestNewHuntTarget(self.unit) end local x, y = self.unit:getLocation() return {x=x, y=y, reason="Could not path"} end return interest end function Actions.MoveToInterest:onPathBlocked(blocker) local interest = self.unit:getBrain():getInterest() if blocker:getPlayerOwner() == self.unit:getPlayerOwner() and self.unit:getBrain():getDestination() == interest then local x, y = self.unit:getLocation() local x1, y1 = blocker:getLocation() local sim = self.unit:getSim() if x1==interest.x and y1==interest.y and simquery.canPathBetween(sim, self.unit, sim:getCell(x,y), sim:getCell(x1,y1) ) then --close enough! self:cancel() return simdefs.BSTATE_COMPLETE end -- if interest.reason == simdef.REASON_FOUNDCORPSE and simquery.isEnemyAgent(self.unit:getPlayerOwner(), interest.sourceUnit) -- and (interest.sourceUnit:isDead() or interest.sourceUnit:getTraits().iscorpse or simquery.isUnitPinned(sim, interest.sourceUnit) if interest.sourceUnit and sim:canUnitSeeUnit(self.unit, interest.sourceUnit) then --also close enough! self:cancel() return simdefs.BSTATE_COMPLETE end end return Actions.MoveTo.onPathBlocked(self, blocker) end function Actions.MoveToInterest:onPathNoMP() local interest = self.unit:getBrain():getInterest() local x0, y0 = self.unit:getLocation() if interest and self.unit:isAlerted() and (interest.x ~= x0 or interest.y ~= y0) then local interestCell = self.unit:getSim():getCell(interest.x, interest.y) local dir = simquery.getDirectionFromDelta(interest.x - x0, interest.y - y0) if interestCell and self.unit:getFacing() ~= dir and simquery.couldUnitSeeCell(self.unit:getSim(), self.unit, interestCell) then self.unit:turnToFace(interest.x, interest.y) return simdefs.BSTATE_RUNNING end end return Actions.MoveTo.onPathNoMP(self) end function Actions.MoveToInterest:addDoorBreakActions(sim, path) local abilityDef = self.unit:ownsAbility("breakDoor") if not abilityDef then return end if not self.unit:isAlerted() then return end local interest = self.unit:getBrain():getInterest() if self.unit:getBrain():getDestination() ~= interest then return end --don't kick doors down for these reasons if interest.reason == simdefs.REASON_HUNTING or interest.reason == simdefs.REASON_PATROLCHANGED then return end local finalNode = path.path:getNodes()[#path.path:getNodes()] local finalCell = sim:getCell(finalNode.location.x, finalNode.location.y) --don't kick doors down if our interest doesn't lie on the other side of it if finalCell.x ~= interest.x or finalCell.y ~= interest.y then return end local secondLastNode = path.path:getStartNode() if #path.path:getNodes() > 1 then --step back through the path trying to find a node that isn't the finish for i = #path.path:getNodes(), 1, -1 do local node = path.path:getNodes()[i] if node.location ~= finalNode.location then secondLastNode = node break end end end if not secondLastNode then simlog( simdefs.LOG_PATH, "(%d) path not long enough to break door", path.unit:getID()) return end local secondLastCell = sim:getCell(secondLastNode.location.x, secondLastNode.location.y) local doorDir = simquery.getDirectionFromDelta(finalCell.x-secondLastCell.x, finalCell.y-secondLastCell.y) if simquery.checkIsDoor(sim, secondLastCell, doorDir) and abilityDef:canUseAbility(sim, self.unit, self.unit, secondLastCell, doorDir) then --add a breakDoor action to the path simlog( simdefs.LOG_PATH, "(%d) path adding breakDoor action at (%d, %d) %s", path.unit:getID(), secondLastCell.x, secondLastCell.y, simdefs:stringForDir(doorDir)) self.unit:getPather():addActionToPath(path, secondLastNode, {ability="breakDoor", owner=self.unit, user=self.unit, params={}, keepPathing=true } ) end end function Actions.MoveToInterest:addThrowGrenadeActions(sim, path) local abilityDef, grenadeUnit = self.unit:ownsAbility("throw") if not abilityDef or not grenadeUnit then return end local x0, y0 = self.unit:getLocation() local destination = self.unit:getBrain():getDestination() if destination ~= self.unit:getBrain():getInterest() then return end if destination.x == x0 and destination.y == y0 then return end if self.unit:getBrain():getInterest().grenadeHit then return end --find the first part of the path that gives us LOS to the interest local throwRange = self.unit:getTraits().maxThrow or 0 local minThrowRange = self.unit:getTraits().minThrow or 0 local targetCell = sim:getCell(path.goalx, path.goaly) local cellsInRange = {} table.insert(cellsInRange, targetCell) local aimRange = grenadeUnit:getTraits().aimRange or grenadeUnit:getTraits().range if aimRange and aimRange > 0 then --only cells in range with LOS to the targetcell should be considered for i,testCell in ipairs(simquery.fillCircle( sim, targetCell.x, targetCell.y, aimRange, 0) ) do if testCell ~= targetCell then local raycastX, raycastY = sim:getLOS():raycast(testCell.x, testCell.y, targetCell.x, targetCell.y) if raycastX == targetCell.x and raycastY == targetCell.y then table.insert(cellsInRange, testCell) end end end end local node = path.path:getStartNode() local i = 1 repeat local startCell = sim:getCell(node.location.x, node.location.y) local closestCell, closestDist if startCell ~= targetCell then for k, endCell in ipairs(cellsInRange) do local throwDistSq = mathutil.distSqr2d(startCell.x, startCell.y, endCell.x, endCell.y) if throwDistSq < throwRange*throwRange and throwDistSq > minThrowRange*minThrowRange then local raycastX, raycastY = sim:getLOS():raycast(startCell.x, startCell.y, endCell.x, endCell.y) if raycastX == endCell.x and raycastY == endCell.y then --it's a valid cell to throw to local distSqFromTarget = mathutil.distSqr2d(endCell.x, endCell.y, targetCell.x, targetCell.y) if not closestCell or distSqFromTarget < closestDist then closestCell = endCell closestDist = distSqFromTarget end end end end end if closestCell then --add a ThrowGrenade action to the path local target = {closestCell.x, closestCell.y} simlog( simdefs.LOG_PATH, "(%d) path adding throw action from (%d, %d) to (%d, %d)", path.unit:getID(), node.location.x, node.location.y, closestCell.x, closestCell.y) self.unit:getPather():addActionToPath(path, node, {ability="throw", owner=grenadeUnit, user=self.unit, params={target}, keepPathing = grenadeUnit:getTraits().keepPathing } ) break end node = path.path:getNodes()[i] i = i + 1 until not node end ----------------------------------------------------------------------------------------- Actions.MoveToNextPatrolPoint = class(Actions.MoveTo, function(self, name) btree.BaseAction.init(self, name or "MoveToNextPatrolPoint") end) function Actions.MoveToNextPatrolPoint:getDestination() return self.unit:getBrain():getPatrolPoint() end ----------------------------------------------------------------------------------------- Actions.MoveToNearestExit = class(Actions.MoveTo, function(self, name) btree.BaseAction.init(self, name or "MoveToNearestExit") end) function Actions.MoveToNearestExit:getDestination() local sim = self.unit:getSim() local startCell = sim:getCell(self.unit:getLocation() ) local guardCells = sim:getCells("guard_spawn") --to do: reduce the cells we path to down to just the closest ones for each guard elevator local astar = include ("modules/astar" ) local astar_handlers = include("sim/astar_handlers") local pather = astar.AStar:new(astar_handlers.aihandler:new(self.unit) ) local closestCell, closestPathDist for i, cell in ipairs(guardCells) do local path = pather:findPath( startCell, cell ) if path then --make sure our path doesn't go through local pathDist = path:getTotalMoveCost() if not closestCell or pathDist < closestPathDist then closestCell = cell closestPathDist = pathDist end end end if closestCell then return {x=closestCell.x, y=closestCell.y} end end ----------------------------------------------------------------------------------------- Actions.MoveAwayFromAgent = class(Actions.MoveTo, function(self, name) btree.BaseAction.init(self, name or "MoveAwayFromAgent") end) function Actions.MoveAwayFromAgent:onNoDestination() return simdefs.BSTATE_FAILED end function Actions.MoveAwayFromAgent:onNoPath() return simdefs.BSTATE_FAILED end function Actions.MoveAwayFromAgent:getDestination() local sim = self.unit:getSim() local x0, y0 = self.unit:getLocation() local target = self.unit:getBrain():getTarget() if not target and self.unit:getBrain():getInterest() and self.unit:getBrain():getInterest().reason == simdefs.REASON_LOSTTARGET and not self.unit:getBrain():getInterest().investigated then target = self.unit:getBrain():getInterest().sourceUnit end if target then local x1, y1 = target:getLocation() local deltaX, deltaY = x0-x1, y0-y1 local raycastX, raycastY = sim:getLOS():raycast(x1, y1, x1+20*deltaX, y1+20*deltaY) raycastX = deltaX < 0 and math.ceil(raycastX) or math.floor(raycastX) raycastY = deltaY < 0 and math.ceil(raycastY) or math.floor(raycastY) local cell = sim:getCell(raycastX, raycastY) if cell and not (cell.x == x0 and cell.y == y0) then if cell.impass == 0 then return {x=cell.x, y=cell.y} else --check all the nearby cells for ones we can hide in for i, v in ipairs(cell.exits) do if not v.door and v.cell.impass == 0 then return {x=v.cell.x, y=v.cell.y} end end end end end end ----------------------------------------------------------------------------------------- Actions.MoveAroundTarget = class(Actions.MoveTo, function(self, name) btree.BaseAction.init(self, name or "MoveAroundTarget") end) function Actions.MoveAroundTarget:getDestination() local x, y = self.unit:getBrain():getTarget():getLocation() local sim = self.unit:getSim() local neighbour = simquery.findNearestEmptyCell( sim, x, y, self.unit) if neighbour then local facing = simquery.getDirectionFromDelta(x - neighbour.x, y - neighbour.y) return {x = neighbour.x, y = neighbour.y, facing=facing} end end ----------------------------------------------------------------------------------------- return Actions
require "config" require "utils" require("plugins").setup()
local events = {} events.navigate_up = "navigate_up" events.navigate_down = "navigate_down" events.navigate_left = "navigate_left" events.navigate_right = "navigate_right" events.change_path = "change_path" events.command_prompt = "command_prompt" events.cancel = "cancel" events.execute = "execute" events.quit = "quit" events.suspend = "suspend" return events
local name, addon = ...; local media = LibStub("LibSharedMedia-3.0"); --[[---------------------------------------------------------------------------- Strings & Patterns ------------------------------------------------------------------------------]] local pattern_title = "%s"; local pattern_left = "Intellect\n" .. "Critical Strike%s\n" .. "Haste%s\n" .. "Versatility%s\n" .. "Mastery%s\n" .. "Leech"; local pattern_right = "%.2f\n" .. "%.2f\n" .. "%.2f\n" .. "%.2f\n" .. "%.2f\n" .. "%.2f"; local haste_hpct = " (HPCT)"; local haste_hpm = ""; local vers_dr = " (DR)"; local crit_resurg = " (R)"; local pawn_pattern = [[( Pawn: v1: "%s": Class=%s, Spec=%s, Intellect=%.2f, CritRating=%.2f, HasteRating=%.2f, Versatility=%.2f, MasteryRating=%.2f, Leech=%.2f)]]; local pawn_str_name = "%s-HSW-%s"; local pawn_title = "Pawn String (Ctrl+A to select all, Ctrl+C to copy):"; local pawn_dialog_name = "HSW_GETPAWNSTRING"; local clearsegments_dialog_name = "HSW_CLEARALLSEGMENTS"; local clearsegments_title = "Clear all segments?"; local qelive_title = "QE Live Website (Ctrl+A to select all, Ctrl+C to copy):"; local qelive_pattern = "https://questionablyepic.com/live/?import=HSW&spec=%s&pname=%s&realm=%s&region=%s&CriticalStrike=%.2f&HasteHPCT=%.2f&HasteHPM=%.2f&Mastery=%.2f&Versatility=%.2f&Leech=%.2f&content=%s"; local qelive_noname_pattern = "https://questionablyepic.com/live/?import=HSW&spec=%s&CriticalStrike=%.2f&HasteHPCT=%.2f&HasteHPM=%.2f&Mastery=%.2f&Versatility=%.2f&Leech=%.2f&content=%s"; --[[---------------------------------------------------------------------------- UpdateDisplayStats - update the display to show the given stats ------------------------------------------------------------------------------]] function addon:UpdateDisplayStats() local int,crt,hst,vrs,mst,lee = addon:GetStatsForDisplay(); self.frame.textR:SetFormattedText(pattern_right,int,crt,hst,vrs,mst,lee); end --[[---------------------------------------------------------------------------- UpdateDisplayTitle - update the title of the display ------------------------------------------------------------------------------]] function addon:UpdateDisplayTitle(title) self.frame.textTitle:SetFormattedText(pattern_title,title); end --[[---------------------------------------------------------------------------- UpdateDisplayLabels - update the display to reflect current filter settings ------------------------------------------------------------------------------]] function addon:UpdateDisplayLabels() local crit_suffix = (self.hsw.db.global.useCritResurg and self:IsRestoShaman()) and crit_resurg or ""; local haste_suffix = self.hsw.db.global.useHPMoverHPCT and haste_hpm or haste_hpct; local vers_suffix = self.hsw.db.global.useVersDR and vers_dr or ""; local mastery_suffix = ""; self.frame.textL:SetFormattedText( pattern_left, crit_suffix, haste_suffix, vers_suffix, mastery_suffix ); end --[[---------------------------------------------------------------------------- SetCurrentSegment - Change the currently-displayed segment ------------------------------------------------------------------------------]] function addon:SetCurrentSegment(segmentID) self.currentSegment = segmentID; local id; if ( segmentID == 0 ) then id = "Current Fight"; elseif ( segmentID == "Total" ) then id = "Total"; else local segment = self.SegmentManager:Get(self.currentSegment); id = segment.id; end self:UpdateDisplayLabels(); self:UpdateDisplayStats(); self:UpdateDisplayTitle(id); end --[[---------------------------------------------------------------------------- GetStatsForDisplay ------------------------------------------------------------------------------]] function addon:GetStatsForDisplay() local segment = self.SegmentManager:Get(self.currentSegment); if ( not segment ) then return 1,0,0,0,0,0; end local t = segment.t; if ( t.int == 0 ) then return 1,0,0,0,0,0; end local usingHPCT = not self.hsw.db.global.useHPMoverHPCT; local usingVersDR = self.hsw.db.global.useVersDR; local usingCritResurg = self:IsRestoShaman() and self.hsw.db.global.useCritResurg; local INT = 1; local CRIT = (usingCritResurg and (segment:GetManaRestoreValue()/addon.CritConv + t.crit) or t.crit) / t.int; local HASTE = (usingHPCT and segment:GetHasteHPCT() or segment:GetHaste()) / t.int; local VERS = (usingVersDR and t.vers_dr or t.vers) / t.int; local MAST = t.mast / t.int; local LEECH = t.leech / t.int; local MP5 = segment:GetMP5(); return INT,CRIT,HASTE,VERS,MAST,LEECH,MP5; end --[[---------------------------------------------------------------------------- SegmentMenu - Create & Display a segment selection dropdown menu ------------------------------------------------------------------------------]] function addon:SegmentMenu() local menu = { { text = "Select a Segment", isTitle = true}, { text = "Total", func = function() addon:SetCurrentSegment("Total") end }, { text = "Current Fight", func = function() addon:SetCurrentSegment(0) end} }; for i=1,self.SegmentManager:Size()-1,1 do local segment = self.SegmentManager:Get(i); table.insert(menu,{ text = segment.id, func = function() addon:SetCurrentSegment(i) end }); end if ( self.currentSegment == "Total" ) then menu[2].checked = true; elseif ( self.currentSegment == "Current" ) then menu[3].checked = true; else menu[3+(self.currentSegment or 0)].checked = true; end local menuFrame = CreateFrame("Frame", "HSW_SegmentMenu_Frame", UIParent, "UIDropDownMenuTemplate"); EasyMenu(menu, menuFrame, "cursor", 0 , 0, "MENU"); end --[[---------------------------------------------------------------------------- Show - Display the stats panel ------------------------------------------------------------------------------]] function addon:Show() addon.frameVisible = true; self:SetCurrentSegment(self.currentSegment or "Total"); if ( self.frame ) then self.frame:Show(); end end --[[---------------------------------------------------------------------------- Hide - Hide the stats panel ------------------------------------------------------------------------------]] function addon:Hide() addon.frameVisible = false; if ( self.frame ) then self.frame:Hide(); end end --[[---------------------------------------------------------------------------- Msg - print a message to chat ------------------------------------------------------------------------------]] function addon:Msg(s) if s then DEFAULT_CHAT_FRAME:AddMessage("|cff00fbf6[HSW]|r "..tostring(s),1,1,1); end end --[[---------------------------------------------------------------------------- Enabled - Check if the addon should be enabled. ------------------------------------------------------------------------------]] function addon:Enabled() if ( self.StatParser:IsCurrentSpecSupported() ) then if ( HSW_ENABLE_FOR_TESTING ) then return true; end local _,_,id = GetInstanceInfo(); if (( id == 1 and self.hsw.db.global.enabledInNormalDungeons ) or ( id == 2 and self.hsw.db.global.enabledInHeroicDungeons ) or ( id == 23 and self.hsw.db.global.enabledInMythicDungeons ) or ( id == 8 and self.hsw.db.global.enabledInMythicPlusDungeons ) or ( id == 14 and self.hsw.db.global.enabledInNormalRaids ) or ( id == 15 and self.hsw.db.global.enabledInHeroicRaids ) or ( id == 16 and self.hsw.db.global.enabledInMythicRaids ) or ( id == 17 and self.hsw.db.global.enabledInLfrRaids )) then return true; elseif self.hsw.db.global.alwaysEnabled then return true; end end return false; end --[[---------------------------------------------------------------------------- InRaidInstance - Check if we are in a raid instance ------------------------------------------------------------------------------]] function addon:InRaidInstance() local _,_,id = GetInstanceInfo(); return id and (id >= 14 and id <= 17); end --[[---------------------------------------------------------------------------- InMythicPlus - Check if we are in a mythic+ instance ------------------------------------------------------------------------------]] function addon:InMythicPlus() local _,_,id = GetInstanceInfo(); return id and (id == 8); end --[[---------------------------------------------------------------------------- AdjustVisibility - Show or hide the frame ------------------------------------------------------------------------------]] function addon:AdjustVisibility() if ( not self.hsw.db.global.neverShow and (self:Enabled() or self.hsw.db.global.alwaysShow) ) then self:Show(); else self:Hide(); end end --[[---------------------------------------------------------------------------- Lock - lock the stats panel ------------------------------------------------------------------------------]] function addon:Lock() self:Msg("Healer Stat Weights frame locked.") self.hsw.db.global.frameLocked = true; self.frame:EnableMouse(not self.hsw.db.global.frameLocked); self.frame:SetMovable(not self.hsw.db.global.frameLocked); end --[[---------------------------------------------------------------------------- Unlock - unlock the stats panel ------------------------------------------------------------------------------]] function addon:Unlock() self:Msg("Healer Stat Weights frame unlocked.") self.hsw.db.global.frameLocked = false; self.frame:EnableMouse(not self.hsw.db.global.frameLocked); self.frame:SetMovable(not self.hsw.db.global.frameLocked); end --[[---------------------------------------------------------------------------- Pawn String - Dialog to display pawn string for current segment ------------------------------------------------------------------------------]] function addon:GetPawnString() local segment = self.SegmentManager:Get(self.currentSegment); local int,crt,hst,vrs,mst,lee = addon:GetStatsForDisplay(); local class = UnitClass("Player"); local specId = GetSpecialization(); local title = string.format(pawn_str_name,class,(segment and segment.id or "Unknown")); return self:GetPawnStringRaw(title,class,specId,int,crt,hst,vrs,mst,lee); end function addon:GetPawnStringRaw(title,class,specId,int,crt,hst,vrs,mst,lee) return string.format(pawn_pattern,title,class,specId,int,crt,hst,vrs,mst,lee); end addon.PawnHistoryDialogName = pawn_dialog_name.."_HISTORY"; StaticPopupDialogs[addon.PawnHistoryDialogName] = { text = pawn_title, button1 = OKAY, button2 = CANCEL, hasEditBox = true, editBoxWidth = 600, maxLetters = 9999, OnShow = function (self, data) local s = addon:GetPawnStringFromHistory(); print(s); self.editBox:SetText(s) end, timeout = 0, exclusive = 1, hideOnEscape = 1, whileDead = 1 } StaticPopupDialogs[pawn_dialog_name] = { text = pawn_title, button1 = OKAY, button2 = CANCEL, hasEditBox = true, editBoxWidth = 600, maxLetters = 9999, OnShow = function (self, data) local s = addon:GetPawnString(); print(s); self.editBox:SetText(s) end, timeout = 0, exclusive = 1, hideOnEscape = 1, whileDead = 1 } --[[---------------------------------------------------------------------------- QE Live String - Dialog to display link to questionably epic website for current segment ------------------------------------------------------------------------------]] function addon:GetQELiveStringRaw(specid,name,realm,regionLetters,crt,hstHPCT,hstHPM,mst,vrs,lee,isDungeon) local s; local contentStr = isDungeon and "dungeon" or "raid"; if ( name and realm and regionLetters ) then s = string.format(qelive_pattern,specid,name,realm,regionLetters,crt,hstHPCT,hstHPM,mst,vrs,lee,contentStr); else s = string.format(qelive_noname_pattern,specid,crt,hstHPCT,hstHPM,mst,vrs,lee,contentStr); end s = string.gsub(s,"%'","%%27"); s = string.gsub(s," ","%%20"); return s; end addon.QELiveDialogName = pawn_dialog_name.."_QELIVE"; StaticPopupDialogs[addon.QELiveDialogName] = { text = qelive_title, button1 = OKAY, button2 = CANCEL, hasEditBox = true, editBoxWidth = 600, maxLetters = 9999, OnShow = function (self, data) local s = addon:GetQELiveStringFromHistory(); print(s); self.editBox:SetText(s) end, timeout = 0, exclusive = 1, hideOnEscape = 1, whileDead = 1 } --[[---------------------------------------------------------------------------- Clear All Segments - Dialog to clear segments ------------------------------------------------------------------------------]] StaticPopupDialogs[clearsegments_dialog_name] = { text = clearsegments_title, button1 = YES, button2 = NO, OnAccept = function () addon.SegmentManager:ResetAllSegments(); addon:SetCurrentSegment(0); end, timeout = 0, exclusive = 1, hideOnEscape = 1, whileDead = 1 } --[[---------------------------------------------------------------------------- StartFight - Start a new combat segment ------------------------------------------------------------------------------]] function addon:StartFight(id) if ( self:Enabled() ) then if ( not self.inCombat ) then self:UpdatePlayerStats(); self.UnitManager:Cache(); if ( self:IsHolyPaladin() ) then self:CountBeaconsAtStartOfFight(); elseif ( self:IsDiscPriest() ) then self.DiscPriest.PWSTracker:EncounterStart(); self.DiscPriest.LBTracker:EncounterStart(); self.DiscPriest.AtonementTracker:EncounterStart(); elseif ( self:IsHolyPriest() ) then self.HolyPriest.EOLTracker:EncounterStart(); end self.SegmentManager:Enqueue(id); --Set start time of total segment to match current segment local cur_seg = self.SegmentManager:Get(0); local ttl_seg = self.SegmentManager:Get("Total"); if ( ttl_seg and cur_seg ) then ttl_seg.startTime = cur_seg.startTime; end self.inCombat = true; self:AdjustVisibility(); end end end --[[---------------------------------------------------------------------------- EndFight - End current combat segment ------------------------------------------------------------------------------]] function addon:EndFight(encounter_end) if ( self.inCombat ) then self.inCombat = false; local cur_seg = self.SegmentManager:Get(0); local ttl_seg = self.SegmentManager:Get("Total"); if ( cur_seg ) then cur_seg:End(); self:AddHistoricalSegment(cur_seg); end if ( ttl_seg ) then ttl_seg:End(); end end end --[[---------------------------------------------------------------------------- makeButton - Helper function used by SetupFrame ------------------------------------------------------------------------------]] local function makeButton(parent, title, description, tex, clickfunc) local btn = CreateFrame("Button", nil, parent) btn.title = title btn:SetFrameLevel(5) btn:ClearAllPoints() btn:SetHeight(16) btn:SetWidth(16) btn:SetNormalTexture(tex) btn:SetHighlightTexture(tex, 1.0) btn:SetAlpha(0.35) btn:RegisterForClicks("LeftButtonUp", "RightButtonUp") btn:SetScript("OnClick", clickfunc) btn:SetScript("OnEnter", function(this) GameTooltip_SetDefaultAnchor(GameTooltip, this) GameTooltip:SetText(title) GameTooltip:AddLine(description, 1, 1, 1, true) GameTooltip:Show() end) btn:SetScript("OnLeave", function() GameTooltip:Hide() end) btn:Show() -- Add to our list of buttons. table.insert(parent.buttons,btn); end --[[---------------------------------------------------------------------------- AdjustFontSizes - Change the font sizes on the stat weights frame ------------------------------------------------------------------------------]] function addon:AdjustFontSizes() local p,s,f; p,s,f = self.frame.textL:GetFont(); self.frame.textL:SetFont(p,self.hsw.db.global.fontSize,"OUTLINE"); p,s,f = self.frame.textR:GetFont(); self.frame.textR:SetFont(p,self.hsw.db.global.fontSize,"OUTLINE"); p,s,f = self.frame.textTitle:GetFont(); self.frame.textTitle:SetFont(p,self.hsw.db.global.fontSize+2,"OUTLINE"); end function addon:AdjustFontColor() local color = self.hsw.db.global.fontColor; self.frame.textL:SetTextColor(color.r,color.g,color.b,color.a); self.frame.textR:SetTextColor(color.r,color.g,color.b,color.a); self.frame.textTitle:SetTextColor(color.r,color.g,color.b,color.a); end --[[---------------------------------------------------------------------------- AdjustWidth - Change the width of the stat weights frame ------------------------------------------------------------------------------]] local btn_size = 16; function addon:AdjustWidth(newWidth) self.frame:SetWidth(newWidth); self.frame.textTitle:SetWidth(newWidth-btn_size*4); end --[[---------------------------------------------------------------------------- AdjustFonts - Change the font used by the stat weights frame ------------------------------------------------------------------------------]] function addon:AdjustFonts() local p,s,f = self.frame.textL:GetFont(); local str = addon.hsw.db.global.fontStr; local path = p; if ( str ) then path = media:Fetch("font", str); end self.frame.textL:SetFont(path,s,f); p,s,f = self.frame.textR:GetFont(); self.frame.textR:SetFont(path,s,f); p,s,f = self.frame.textTitle:GetFont(); self.frame.textTitle:SetFont(path,s,f); end --[[---------------------------------------------------------------------------- ResetFramePosition - Reset the frame's position to center of screen ------------------------------------------------------------------------------]] function addon:ResetFramePosition() self.hsw.db.global.frameX = nil; self.frame:ClearAllPoints(); self.frame:SetPoint("CENTER",0,0); end --[[---------------------------------------------------------------------------- SetupFrame - Set up the main display panel ------------------------------------------------------------------------------]] function addon:SetupFrame() if ( not self.frame ) then local W = self.hsw.db.global.frameWidth or 192; local H = 128; local frame = CreateFrame("Frame", nil, UIParent); frame:SetWidth(W); frame:SetHeight(H); frame:ClearAllPoints(); if ( self.hsw.db.global.frameX ) then frame:SetPoint("BOTTOMLEFT",self.hsw.db.global.frameX or 0,self.hsw.db.global.frameY or 0); else frame:SetPoint("CENTER",0,0); end frame:EnableMouse(not self.hsw.db.global.frameLocked); frame:SetMovable(not self.hsw.db.global.frameLocked); frame:RegisterForDrag("LeftButton"); frame:SetScript("OnDragStart",frame.StartMoving); frame:SetScript("OnDragStop",function(f) f:StopMovingOrSizing(); self.hsw.db.global.frameX = f:GetLeft(); self.hsw.db.global.frameY = f:GetBottom(); end); local text = frame:CreateFontString(nil,"OVERLAY",GameFontNormal); text:SetPoint("TOPLEFT", frame ,"TOPLEFT", 0, -btn_size) text:SetPoint("BOTTOMRIGHT", frame ,"BOTTOMRIGHT", 0, 0) text:SetJustifyH("LEFT"); text:SetJustifyV("TOP"); text:SetFontObject(GameFontWhite); text:SetShadowColor(0,0,0,.7); text:SetShadowOffset(1,1); local p,s,f = text:GetFont(); text:SetFont(p,self.hsw.db.global.fontSize,"OUTLINE"); frame.textL = text; text = frame:CreateFontString(nil,"OVERLAY",GameFontNormal); text:SetPoint("TOPLEFT", frame ,"TOPLEFT", 0, -btn_size) text:SetPoint("BOTTOMRIGHT", frame ,"BOTTOMRIGHT", 0, 0) text:SetJustifyH("RIGHT"); text:SetJustifyV("TOP"); text:SetFontObject(GameFontWhite); local p,s,f = text:GetFont(); text:SetFont(p,self.hsw.db.global.fontSize,"OUTLINE"); frame.textR = text; frame.buttons = {}; makeButton(frame,"Clear","Clear out all segments.","Interface\\Buttons\\UI-StopButton",function() if ( not addon.inCombat ) then StaticPopup_Show(clearsegments_dialog_name); else addon:Msg("[HSW] Cannot clear segments while in combat."); end end); makeButton(frame,"Configure","Open the options menu","Interface\\Buttons\\UI-OptionsButton", function() InterfaceOptionsFrame_OpenToCategory(self.hsw.optionsFrame) InterfaceOptionsFrame_OpenToCategory(self.hsw.optionsFrame) end); makeButton(frame,"Export","Get the pawn string for the current statweights.","Interface\\Buttons\\UI-GuildButton-MOTD-Up",function() StaticPopup_Show(pawn_dialog_name); end); makeButton(frame,"Segment","Select a segment","Interface\\Buttons\\UI-GuildButton-PublicNote-Up",function() self:SegmentMenu() end); --[[local bg = frame:CreateTexture(nil, "BACKGROUND"); bg:SetAllPoints(true); bg:SetColorTexture(0.1,0.1,0.1,0.3); frame.texture = bg;]] text = frame:CreateFontString(nil,"OVERLAY",GameFontNormal); text:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0); text:SetJustifyH("LEFT"); text:SetFontObject(GameFontWhite); local p,s,f = text:GetFont(); text:SetFont(p,self.hsw.db.global.fontSize+2,"OUTLINE"); text:SetWidth(W-btn_size*4); text:SetHeight(16); frame.textTitle = text; local h = -btn_size; for i=1,#frame.buttons,1 do frame.buttons[i]:SetPoint("TOPRIGHT",frame,"TOPRIGHT",h*(i-1),0); end self.frame = frame; self:AdjustFontColor() self:AdjustFonts() self:SetupUnitEvents(); end end
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetModel("models/props_c17/FurnitureBathtub001a.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetModelScale(self:GetModelScale() * 1, 0) self:SetValor(57) self:SetDiez(0) self:SetCinco(0) self:SetDos(0) self:SetUno(0) local phys = self:GetPhysicsObject() if phys:IsValid() then phys:Wake() phys:EnableMotion(false) end end --Physgun does not move this entity function ENT:Think() --no entra en esta validacion if self:GetValor() == 0 then print("Enters first IF Valor") print("Valor 10 = " .. self:GetDiez()) print("Valor 5 = " .. self:GetCinco()) print("Valor 2 = " .. self:GetDos()) print("Valor 1 = " .. self:GetUno()) if self:GetDiez() == 5 then if self:GetCinco() == 1 then print("Enters third IF Cinco") if self:GetDos() == 1 then print ("Enters fourth IF Dos") if self:GetUno() == 0 then print ("Enters fifth IF Uno") ents.FindByClass( "invisible-wall-2" )[1]:Remove() for k , v in ipairs(ents.FindByClass("coin-1-10")) do v:Remove() end for k , v in ipairs(ents.FindByClass("coin-2-5")) do v:Remove() end for k , v in ipairs(ents.FindByClass("coin-3-2")) do v:Remove() end for k , v in ipairs(ents.FindByClass("coin-4-1")) do v:Remove() end end end end end end end function ENT:StartTouch(ent) if ent:GetClass() == "coin-1-10" then self:SetValor(self:GetValor() - ent:GetValor()) self:SetDiez(self:GetDiez() + 1) end if ent:GetClass() == "coin-2-5" then self:SetValor(self:GetValor() - ent:GetValor()) self:SetCinco(self:GetCinco() + 1) end if ent:GetClass() == "coin-3-2" then self:SetValor(self:GetValor() - ent:GetValor()) self:SetDos(self:GetDos() + 1) end if ent:GetClass() == "coin-4-1" then self:SetValor(self:GetValor() - ent:GetValor()) self:SetUno(self:GetUno() + 1) end end function ENT:EndTouch(ent) if ent:GetClass() == "coin-1-10" then self:SetValor(self:GetValor() + ent:GetValor()) self:SetDiez(self:GetDiez() - 1) end if ent:GetClass() == "coin-2-5" then self:SetValor(self:GetValor() + ent:GetValor()) self:SetCinco(self:GetCinco() - 1) end if ent:GetClass() == "coin-3-2" then self:SetValor(self:GetValor() + ent:GetValor()) self:SetDos(self:GetDos() - 1) end if ent:GetClass() == "coin-4-1" then self:SetValor(self:GetValor() + ent:GetValor()) self:SetUno(self:GetUno() - 1) end end
Ext.RegisterOsirisListener("DB_Origins_MaxPartySize", 1, "after", function(size) if size == 4 then Osi.DB_Origins_MaxPartySize:Delete(4) local settings = GetSettings() if settings then local partySize = settings.Global:GetVariable("PartySize", 6) or 6 Osi.DB_Origins_MaxPartySize(partySize) else Osi.DB_Origins_MaxPartySize(99) end GlobalClearFlag("GEN_MaxPlayerCountReached") end end)
SSID = "put network name here" PSK = "put network key here" print("Initalizing WIFI...") wifi.setmode(wifi.STATION) wifi.sta.config(SSID,PSK) wifi.sta.connect() print("Your MAC Address is " .. wifi.sta.getmac()) tmr.alarm(1, 1000, 1, function() if wifi.sta.getip()== nil then print("Waiting for IP Address...") else tmr.stop(1) print("Connected to " .. SSID) print("Your IP Address is " .. wifi.sta.getip()) dofile('webtempprobe.lua') end end)
require "lib.classes.class" local BasicScene = require "Cutscenes.model.scenes.BasicScene" -------------------------------------------------------------------------------------------------------- -- class: TimedScene -- param: text:str -> the text asociated to the cutscene -- param: image_path:str -> the path of the scene image -- A timed single scene class local TimedScene = extend(BasicScene, function(self, text, image_path) self.elapsed_time = 0 end) -- updateTime: num -> None -- updates the current time of the scene function TimedScene.updateTime(self, dt) self.elapsed_time = self.elapsed_time + dt end -- resetElapsedTime: None -> None -- resets the elapsed time function TimedScene.resetElapsedTime(self) self.elapsed_time = 0 end return TimedScene
----------------------------------- -- Area: Windurst Walls -- NPC: Ojha Rhawash -- Starts and Finishes Quest: Flower Child -- !pos -209 0 -134 239 ----------------------------------- local ID = require("scripts/zones/Windurst_Walls/IDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); function onTrade(player,npc,trade) count = trade:getItemCount(); gil = trade:getGil(); itemQuality = 0; if (trade:getItemCount() == 1 and trade:getGil() == 0) then if (trade:hasItemQty(956,1)) then -- Lilac itemQuality = 2; elseif (trade:hasItemQty(957,1) or -- Amaryllis trade:hasItemQty(2554,1) or -- Asphodel trade:hasItemQty(948,1) or -- Carnation trade:hasItemQty(1120,1) or -- Casablanca trade:hasItemQty(1413,1) or -- Cattleya trade:hasItemQty(636,1) or -- Chamomile trade:hasItemQty(959,1) or -- Dahlia trade:hasItemQty(835,1) or -- Flax Flower trade:hasItemQty(2507,1) or -- Lycopodium Flower trade:hasItemQty(958,1) or -- Marguerite trade:hasItemQty(1412,1) or -- Olive Flower trade:hasItemQty(938,1) or -- Papaka Grass trade:hasItemQty(1411,1) or -- Phalaenopsis trade:hasItemQty(949,1) or -- Rain Lily trade:hasItemQty(941,1) or -- Red Rose trade:hasItemQty(1725,1) or -- Snow Lily trade:hasItemQty(1410,1) or -- Sweet William trade:hasItemQty(950,1) or -- Tahrongi Cactus trade:hasItemQty(2960,1) or -- Water Lily trade:hasItemQty(951,1)) then -- Wijnruit itemQuality = 1; end end FlowerChild = player:getQuestStatus(WINDURST,tpz.quest.id.windurst.FLOWER_CHILD); if (itemQuality == 2) then if (FlowerChild == QUEST_COMPLETED) then player:startEvent(10000, 0, 239, 4); else player:startEvent(10000, 0, 239, 2); end elseif (itemQuality == 1) then if (FlowerChild == QUEST_COMPLETED) then player:startEvent(10000, 0, 239, 5); elseif (FlowerChild == QUEST_ACCEPTED) then player:startEvent(10000, 0, 239, 3); else player:startEvent(10000, 0, 239, 1); end else player:startEvent(10000, 0, 239, 0); end end; function onTrigger(player,npc) player:startEvent(10000, 0, 239, 10); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 10000 and option == 3002) then player:tradeComplete(); player:completeQuest(WINDURST,tpz.quest.id.windurst.FLOWER_CHILD); player:addFame(WINDURST,120); player:moghouseFlag(4); player:messageSpecial(ID.text.MOGHOUSE_EXIT); elseif (csid == 10000 and option == 1) then player:tradeComplete(); player:addQuest(WINDURST,tpz.quest.id.windurst.FLOWER_CHILD); end end;
----------------------------------------------------------------------------- -- Leda simple single threaded controller -- Author: Tiago Salmito, Noemi Rodriguez, Ana Lucia de Moura ----------------------------------------------------------------------------- local thread_pool=require("leda.controller.thread_pool") local leda=require'leda' local singlethread=thread_pool.get(1) if leda and leda.controller then leda.controller.single_thread=singlethread end return singlethread
function math.clamp(x, min, max) check("n,?n[2]") return min and x < min and min or max and x > max and max or x end function math.round(x, decimals) check("n,?n") local mult = 10^(decimals or 0) x = x * mult return (x >= 0 and math.floor(x + 0.5) or math.ceil(x - 0.5))/mult end
local Upstream = require('apicast.upstream') local match = require('luassert.match') describe('Upstream', function() local valid_url = 'http://localhost:8080/path?query' describe('.new', function() it('returns an error on invalid upstream', function() assert.returns_error('invalid upstream', Upstream.new('invalid uri')) end) it('returns new instance', function() assert(Upstream.new(valid_url)) end) it('returns table with location_name', function() -- @upstream location is defined in the apicast.conf file assert.equal('@upstream', Upstream.new(valid_url).location_name) end) it('returns table with upstream_name', function() -- upstream name is defined in the upstream.conf file assert.equal('upstream', Upstream.new(valid_url).upstream_name) end) it('returns table with resolver', function() assert.equal(require('resty.resolver'), Upstream.new(valid_url).resolver) end) end) describe(':resolve', function() it('uses .resolver', function() local upstream = Upstream.new('http://localhost:8080') local resolver, instance, servers = {'resolver'}, {'instance'}, {'response'} stub(resolver, 'instance').returns(instance) stub(instance, 'get_servers').returns(servers) upstream.resolver = resolver assert.equal(servers, upstream:resolve()) assert.spy(instance.get_servers).was_called_with(instance, 'localhost', match.contains({ port = 8080 })) end) -- this is useful when we want to pre populate resolved servers in tests it('keeps and returns previously resolved servers', function() local upstream = Upstream.new(valid_url) local servers = { 'resolved servers instance' } upstream.servers = servers assert.equal(upstream.servers, upstream:resolve()) assert.equal(upstream.servers, servers) end) end) describe(':port', function() it('returns port from the URI', function() assert.same(8090, Upstream.new('http://host:8090'):port()) end) it('returns default port for the scheme when none is provided', function() assert.same(443, Upstream.new('https://example.com'):port()) end) it('returns nil when port is unknown', function() assert.is_nil(Upstream.new('ftp://example.com'):port()) end) end) describe(':append_path', function() it('return valid path when is not set', function() local up = Upstream.new('http://host:8090') up:append_path("/test") assert.same(up.uri.path, "/test") end) it('leading slash is removed', function() local up = Upstream.new('http://host:8090/') up:append_path("/test/") assert.same(up.uri.path, "/test/") end) it('trailing slash is not appended', function() local up = Upstream.new('http://host:8090/test') up:append_path("") assert.same(up.uri.path, "/test") end) end) local function stub_ngx_request() ngx.var = { } stub(ngx, 'exec') stub(ngx.req, 'set_header') stub(ngx.req, 'set_uri', function(uri) ngx.var.uri = uri end) stub(ngx.req, 'set_uri_args', function(args) ngx.var.args = args ngx.var.query_string = args end) end describe(':rewrite_request', function() before_each(stub_ngx_request) it('sets request Host header to the URI host', function() assert(Upstream.new('http://example.com/')):rewrite_request() assert.spy(ngx.req.set_header).was_called_with('Host', 'example.com') end) it('sets request uri to the upstream path', function() assert(Upstream.new('http://example.com/test-path')):rewrite_request() assert.spy(ngx.req.set_uri).was_called_with('/test-path') end) for url, path in pairs({ ['http://example.com'] = '/', ['http://example.com/path'] = '/path', ['http://example.com/path/'] = '/path/', ['http://example.com/path/foo'] = '/path/foo', ['http://example.com/path/foo/'] = '/path/foo/', ['http://example.com/path?test=value/'] = '/path', }) do it(('/ uses path %s for upstream %s'):format(path, url), function() ngx.var.uri = '/' local upstream = Upstream.new(url) upstream:rewrite_request() assert.same(path, ngx.var.uri) end) end for url, path in pairs({ ['http://example.com'] = '/test', ['http://example.com/path'] = '/path/test', ['http://example.com/path/'] = '/path/test', ['http://example.com/path/foo'] = '/path/foo/test', ['http://example.com/path/foo/'] = '/path/foo/test', ['http://example.com/path?test=value/'] = '/path/test', }) do it(('/test uses path %s for upstream %s'):format(path, url), function() ngx.var.uri = '/test' local upstream = Upstream.new(url) upstream:rewrite_request() assert.same(path, ngx.var.uri) end) end it('sets request query params to the upstream query params', function() assert(Upstream.new('http://example.com/?query=param')):rewrite_request() assert.spy(ngx.req.set_uri_args).was_called_with('query=param') end) it('does not set the request uri when there is no upstream path', function() assert(Upstream.new('http://example.com')):rewrite_request() assert.spy(ngx.req.set_uri).was_not_called() end) for url, host in pairs({ ['http://example.com'] = 'example.com', ['http://example.com:80'] = 'example.com', ['http://example.com:8080'] = 'example.com:8080', ['https://example.com:80'] = 'example.com:80', ['https://example.com:443'] = 'example.com', ['https://example.com:8080'] = 'example.com:8080', }) do it(('upstream %s sets Host header to %s'):format(url, host), function() local upstream = Upstream.new(url) upstream:rewrite_request() assert.spy(ngx.req.set_header).was_called_with('Host', host) end) end end) describe(':call', function() before_each(stub_ngx_request) it('calls :resolve() when needed', function() local upstream = Upstream.new('http://example.com') stub(upstream, 'resolve') upstream:call({}) assert.spy(upstream.resolve).was_called_with(upstream) end) it('does not call :resolve() when not needed', function() local upstream = Upstream.new('http://example.com') stub(upstream, 'resolve') upstream.servers = {} upstream:call({}) assert.spy(upstream.resolve).was_not_called() end) it('stores itself in the context', function() local upstream = Upstream.new('http://localhost') local context = {} upstream:call(context) assert.equal(upstream, context[upstream.upstream_name]) end) it('executes the upstream location when provided', function() local upstream = Upstream.new('http://localhost') upstream:call({}) assert.spy(ngx.exec).was_called_with(upstream.location_name) end) it('skips executing the upstream location when missing', function() local upstream = Upstream.new('http://localhost') upstream.location_name = nil upstream:call({}) assert.spy(ngx.exec).was_not_called() end) it('skips sending the response if it was already sent', function() ngx.headers_sent = true -- already sent response to the client local upstream = Upstream.new(valid_url) local context = { } spy.on(upstream, 'resolve') assert.returns_error('response sent already', upstream:call(context)) assert.is_nil(context[upstream.upstream_name]) assert.spy(upstream.resolve).was_not_called() end) describe('changes ngx.var.proxy_pass to upstream url', function() it('without port', function() local upstream = Upstream.new('http://localhost:8080/path?query') upstream:call({}) assert.equal('http://upstream', ngx.var.proxy_pass) end) it('works with partial url', function() local upstream = Upstream.new('http://example.com') upstream:call({}) assert.equal('http://upstream', ngx.var.proxy_pass) end) it('works with websocket url', function() local upstream = Upstream.new('ws://example.com') upstream:call({}) assert.equal('http://upstream', ngx.var.proxy_pass) upstream = Upstream.new('wss://example.com') upstream:call({}) assert.equal('https://upstream', ngx.var.proxy_pass) end) end) describe("upstream_keepalive_key set", function() it("uses HTTPS, force key", function() assert.falsy(ngx.var.upstream_keepalive_key) upstream = Upstream.new('https://example.com') upstream:call({service={id=10}}) assert.equal(ngx.var.upstream_keepalive_key, "example.com::10") end) it("uses wss, force key", function() assert.falsy(ngx.var.upstream_keepalive_key) upstream = Upstream.new('wss://example.com') upstream:call({service={id=10}}) assert.equal(ngx.var.upstream_keepalive_key, "example.com::10") end) it("uses HTTP skip by now", function() assert.falsy(ngx.var.upstream_keepalive_key) upstream = Upstream.new('http://example.com') upstream:call({service={id=10}}) assert.falsy(ngx.var.upstream_keepalive_key) end) end) end) describe('http proxy', function() local resty_proxy = require('resty.http.proxy') local http_proxy = require('apicast.http_proxy') before_each(stub_ngx_request) describe('is active', function() before_each(function() resty_proxy:reset({ no_proxy = '*' }) end) it('calls :rewrite_request()', function() local upstream = Upstream.new('http://example.com') stub(upstream, 'rewrite_request') upstream:call({}) assert.spy(upstream.rewrite_request).was_called(1) end) end) describe('is not active', function() before_each(function() resty_proxy:reset({ http_proxy = 'http://localhost' }) end) it('calls http_proxy.request()', function() local upstream = Upstream.new('http://example.com') stub(http_proxy, 'request') upstream:call({}) assert.spy(http_proxy.request).was_called(1) end) end) end) describe('.use_host_header', function() before_each(stub_ngx_request) it('allows to set the host used when setting the Host Header', function() local upstream = Upstream.new('http://example.com') local host = 'http://another_host' upstream:use_host_header(host) upstream:rewrite_request() assert.spy(ngx.req.set_header).was_called_with('Host', host) end) end) describe(".set_host_header", function() before_each(stub_ngx_request) it('self.host is defined', function() local host = "test.com" local upstream = Upstream.new('http://example.com') upstream:use_host_header(host) local tmp_host, err = upstream:set_host_header() assert.equal(tmp_host, host) assert.falsy(err) assert.spy(ngx.req.set_header).was_called_with('Host', host) end) it('self.uri is not defined', function() local host = "test.com" local upstream = Upstream.new('http://example.com') upstream.uri = nil local tmp_host, err = upstream:set_host_header() assert.falsy(tmp_host, host) assert.equal(err, "Upstream URI not initialized") end) it('self.uri is defined in a not default port', function() local expected_host = "example.com:10000" local upstream = Upstream.new('http://example.com:10000') local tmp_host, err = upstream:set_host_header() assert.equal(tmp_host, expected_host) assert.falsy(err) assert.spy(ngx.req.set_header).was_called_with('Host', expected_host) end) it('self.uri is defined in a default port', function() local expected_host = "example.com" local upstream = Upstream.new('http://example.com') local tmp_host, err = upstream:set_host_header() assert.equal(tmp_host, expected_host) assert.falsy(err) assert.spy(ngx.req.set_header).was_called_with('Host', expected_host) end) end) end)
local _, ns = ... local E = ns.E if not E:C('progressbars', 'enabled') then return end; local bars = {} local ProgressBars = CreateFrame("Frame", "sInterfaceProgressBars", Minimap) ProgressBars:SetPoint("TOPLEFT", Minimap, "BOTTOMLEFT", 0, -10) ProgressBars:SetPoint("TOPRIGHT", Minimap, "BOTTOMRIGHT", 0, -10) ProgressBars:SetHeight(1) local function getObject(barName) for key, value in pairs(bars) do if key == barName then return value end end return false end -- local function getBar(barName) -- local obj = getObject(barName) -- return obj and obj.bar or false -- end -- local function getEnabled(barName) -- local obj = getObject(barName) -- return obj and obj.enabled or false -- end local function reposition() local prevElement local enabledCount = 0 local totalHeight = 0 for _, element in pairs(bars) do if element.enabled then enabledCount = enabledCount + 1 local something = element.bar totalHeight = totalHeight + something:GetHeight() if (prevElement == nil) then something:SetPoint("TOP", ProgressBars, "TOP") else something:SetPoint("TOP", prevElement, "BOTTOM", 0, -E:C('progressbars', 'spacing')) end prevElement = something end end ProgressBars:SetHeight(totalHeight + (E:C('progressbars', 'spacing') * (enabledCount-1))) end function ProgressBars:CreateBar(barName) if not barName then return end local barHolder = CreateFrame("Frame", "sInterfaceProgressBars_"..barName, ProgressBars) barHolder:SetPoint("LEFT", ProgressBars, "LEFT") barHolder:SetPoint("RIGHT", ProgressBars, "RIGHT") E:ShadowedBorder(barHolder) bars[barName] = { enabled = false, bar = barHolder } return barHolder end function ProgressBars:EnableBar(barName) local obj = getObject(barName) if not obj then return end obj.enabled = true obj.bar:Show() reposition() end function ProgressBars:DisableBar(barName, element) local obj = getObject(barName) if not obj then return end obj.enabled = false obj.bar:Hide() reposition() end ns.sInterfaceProgressBars = ProgressBars
local LIST = TRL.NewObject("CHECKLIST") function LIST:Name() return self.name end function LIST:ID() return self.id end function LIST:AddItem(name,checked,pos,cb) TRL.ProcessAPI("checklists", self:ID(), "checkItems", { name = name, pos = pos, checked = checked, }, cb, "POST") -- POST end function LIST:Items(cb) TRL.ProcessAPI("checklists", self:ID(), "checkItems", { name = name, pos = pos, checked = checked, }, function(items) for _,item in ipairs(items) do items[item.name] = item -- делаем keyvalue end cb(items) end) -- GET end
#! /usr/bin/lua require 'Test.More' plan(5) local mp1 = require 'MessagePack' package.loaded['MessagePack'] = nil -- hack here local mp2 = require 'MessagePack' isnt( mp1, mp2 ) mp1.set_array'without_hole' mp2.set_array'always_as_map' local t = { 10, 20, nil, 40 } is( mp1.pack(t):byte(), 0x80 + 3, "array with hole as map" ) is_deeply( mp1.unpack(mp1.pack(t)), t ) is( mp2.pack(t):byte(), 0x80 + 3, "always_as_map" ) is_deeply( mp2.unpack(mp2.pack(t)), t )
return { HOOK_CHUNK_GENERATING = { CalledWhen = "A chunk is about to be generated. Plugin can override the built-in generator.", DefaultFnName = "OnChunkGenerating", -- also used as pagename Desc = [[ This hook is called before the world generator starts generating a chunk. The plugin may provide some or all parts of the generation, by-passing the built-in generator. The function is given access to the {{cChunkDesc|ChunkDesc}} object representing the contents of the chunk. It may override parts of the built-in generator by using the object's <i>SetUseDefaultXXX(false)</i> functions. After all the callbacks for a chunk have been processed, the server will generate the chunk based on the {{cChunkDesc|ChunkDesc}} description - those parts that are set for generating (by default everything) are generated, the rest are read from the ChunkDesc object.</p> <p> See also the {{OnChunkGenerated|HOOK_CHUNK_GENERATED}} hook. ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world to which the chunk will be added" }, { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" }, { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" }, { Name = "ChunkDesc", Type = "{{cChunkDesc}}", Notes = "Generated chunk data." }, }, Returns = [[ If this function returns true, the server will not call any other plugin with the same chunk. If this function returns false, the server will call the rest of the plugins with the same chunk, possibly overwriting the ChunkDesc's contents. ]], }, -- HOOK_CHUNK_GENERATING }