content
stringlengths
5
1.05M
-- @namespace foundation.com.InventoryPacker local List = assert(foundation.com.List) local apak = foundation.com.apak local pack_list local unpack_list local ascii_pack_list local ascii_unpack_list local ascii_pack_list_state local ascii_unpack_list_state local has_ascii_pack = false local function build_pack_state() return { length = 0, -- item item_id = 0, --- used by pack item_name_to_id = {}, --- used by unpack id_to_item_name = {}, -- meta meta_id = 0, --- used by pack meta_field_name_to_id = {}, --- used by unpack id_to_meta_field_name = {}, -- stacks ids = {}, counts = {}, wears = {}, meta_fields = {}, -- just the key-value fields inventories = {}, -- unused currently } end -- @spec pack_list(ItemStack[]): InventoryPackerState function pack_list(list) local state = build_pack_state() local item_name local item_id local meta local meta_table local meta_fields local meta_field_id for index, item_stack in pairs(list) do state.length = state.length + 1 if not item_stack:is_empty() then meta = item_stack:get_meta() item_name = item_stack:get_name() if not state.item_name_to_id[item_name] then state.item_id = state.item_id + 1 state.item_name_to_id[item_name] = state.item_id state.id_to_item_name[state.item_name_to_id[item_name]] = item_name end item_id = state.item_name_to_id[item_name] state.ids[index] = item_id state.counts[index] = item_stack:get_count() state.wears[index] = item_stack:get_wear() meta_table = meta:to_table() if next(meta_table.fields) then meta_fields = {} for key, value in pairs(meta_table.fields) do if not state.meta_field_name_to_id[key] then state.meta_id = state.meta_id + 1 state.meta_field_name_to_id[key] = state.meta_id state.id_to_meta_field_name[state.meta_field_name_to_id[key]] = key end meta_field_id = state.meta_field_name_to_id[key] meta_fields[meta_field_id] = value end state.meta_fields[index] = meta_fields end else state.counts[index] = 0 end end return state end -- @spec unpack_list(InventoryPackerState): ItemStack[] function unpack_list(state) assert(state, "expected inventory pack state") local list = {} local item_id local item_stack local meta local meta_fields local field_name if state.length > 0 then for index = 1,state.length do if state.counts[index] > 0 then item_id = state.ids[index] item_stack = ItemStack({ name = state.id_to_item_name[item_id], count = state.counts[index], wear = state.wears[index], }) meta_fields = {} if state.meta_fields[index] then for id, value in pairs(state.meta_fields[index]) do field_name = state.id_to_meta_field_name[id] meta_fields[field_name] = value end end meta = item_stack:get_meta() meta:from_table({ fields = meta_fields, }) list[index] = item_stack else list[index] = ItemStack() end end end return list end if apak then has_ascii_pack = true local ascii_pack = assert(apak.pack) local pack_array = assert(apak.pack_array) local pack_int = assert(apak.pack_int) local pack_nil = assert(apak.pack_nil) -- @spec ascii_pack_list_state(InventoryPackerState): String function ascii_pack_list_state(state) local list = List:new() list:push("APAK") -- header list:push(pack_int(1)) -- version list:push("INAM") list:push(pack_array(state.id_to_item_name)) -- pack the item names list:push("MNAM") list:push(pack_array(state.id_to_meta_field_name)) -- pack the meta field names list:push("LIST") list:push(pack_int(state.length)) -- length list:push("ids_") if state.length > 0 then local item_id for index = 1,state.length do item_id = state.ids[index] if item_id then list:push(pack_int(item_id)) else list:push(pack_nil(nil)) end end end list:push("cnt_") if state.length > 0 then local count for index = 1,state.length do count = state.counts[index] if count then list:push(pack_int(count)) else list:push(pack_nil(nil)) end end end list:push("wear") if state.length > 0 then local wear for index = 1,state.length do wear = state.wears[index] if wear then list:push(pack_int(wear)) else list:push(pack_nil(nil)) end end end list:push("mtfl") if state.length > 0 then local fields for index = 1,state.length do fields = state.meta_fields[index] if fields then list:push(ascii_pack(fields)) else list:push(pack_nil(nil)) end end end return list:flatten_iodata():join() end -- @spec ascii_pack_list(ItemStack[]): String function ascii_pack_list(list) return ascii_pack_list_state(pack_list(list)) end local ascii_file_unpack = assert(foundation.com.ascii_file_unpack) local StringBuffer = assert(foundation.com.StringBuffer) -- @spec ascii_unpack_list_state(String): InventoryPackerState function ascii_unpack_list_state(blob) local buffer = StringBuffer:new(blob, 'r') local state = build_pack_state() assert(buffer:read(4) == 'APAK', "expected APAK header") assert(ascii_file_unpack(buffer) == 1, "expected to be version 1") assert(buffer:read(4) == 'INAM', "expected id names section") state.id_to_item_name = ascii_file_unpack(buffer) assert(buffer:read(4) == 'MNAM', "expected meta field names section") state.id_to_meta_field_name = ascii_file_unpack(buffer) assert(buffer:read(4) == 'LIST', "expected list section") state.length = ascii_file_unpack(buffer) assert(buffer:read(4) == 'ids_', "expected ids_ section") if state.length > 0 then for index = 1,state.length do state.ids[index] = ascii_file_unpack(buffer) end end assert(buffer:read(4) == 'cnt_', "expected cnt_ section") if state.length > 0 then for index = 1,state.length do state.counts[index] = ascii_file_unpack(buffer) end end assert(buffer:read(4) == 'wear', "expected wear section") if state.length > 0 then for index = 1,state.length do state.wears[index] = ascii_file_unpack(buffer) end end assert(buffer:read(4) == 'mtfl', "expected mtfl section") if state.length > 0 then for index = 1,state.length do state.meta_fields[index] = ascii_file_unpack(buffer) end end return state end -- @spec ascii_unpack_list_state(String): ItemStack[] function ascii_unpack_list(blob) return unpack_list(ascii_unpack_list_state(blob)) end end foundation.com.InventoryPacker = { pack_list = pack_list, unpack_list = unpack_list, has_ascii_pack = has_ascii_pack, ascii_pack_list = ascii_pack_list, ascii_unpack_list = ascii_unpack_list, ascii_pack_list_state = ascii_pack_list_state, ascii_unpack_list_state = ascii_unpack_list_state, }
----------------------------------- -- Ability: Perfect Dodge -- Allows you to dodge all melee attacks. -- Obtained: Thief Level 1 -- Recast Time: 1:00:00 -- Duration: 0:00:30 ----------------------------------- require("scripts/globals/settings") require("scripts/globals/status") ----------------------------------- function onAbilityCheck(player,target,ability) return 0,0 end function onUseAbility(player,target,ability) local duration = 30 + player:getMod(tpz.mod.PERFECT_DODGE) player:addStatusEffect(tpz.effect.PERFECT_DODGE,1,0,duration) end
require 'cutorch'; require 'cunn'; require 'cudnn' require 'image' require 'utils' require 'DataLoader' require 'hdf5' cutorch.setDevice(1) local snapshotsFolder = '.' local snapshotName = 'resnet-50' local trainMode = 1 -- Load trained model local modelFile = paths.concat(snapshotsFolder,snapshotName..'.t7'); local model = torch.load(modelFile) model:remove(11) model:insert(nn.Normalize(2)) model = model:cuda() local imgEncoder = model:clone() imgEncoder:evaluate() local doCrop = false; local doFlip = false; -- Create data sampler local prodImgsPathFile = 'data/test-product-imgs.txt' local prodLabelsFile = 'data/test-product-labels.txt' local testImgsPathFile = 'data/test-imgs.txt' local testLabelsFile = 'data/test-labels.txt' local dataLoader = DataLoader(prodImgsPathFile,prodLabelsFile,testImgsPathFile,testLabelsFile,doCrop,doFlip,trainMode) -- Save product image features local prodImgFeats = torch.zeros(dataLoader.numProdImgs,2048) local prodImgIdx = 1 for objIdx = 1,dataLoader.numProdClasses do for imgIdx = 1,#dataLoader.prodImgPaths[objIdx] do prodImgFeats[prodImgIdx] = dataLoader.prodImgFeats[objIdx][imgIdx] prodImgIdx = prodImgIdx+1 end end local resultsFile = hdf5.open(paths.concat(snapshotsFolder,'results-'..snapshotName..'.h5'), 'w') resultsFile:write('prodFeat', prodImgFeats:float()) -- Save training image features and class confidence values local testImgPaths = getLinesFromFile(testImgsPathFile) local testImgFeats = torch.ones(#testImgPaths,2048) local testImgClassConf = torch.zeros(#testImgPaths,dataLoader.numTrainClasses) for imgIdx = 1,#testImgPaths do print('Testing: '..imgIdx..'/'..#testImgPaths) local testImg = image.load(testImgPaths[imgIdx]) testImg = image.crop(testImg,120,30,520,430) testImg = image.scale(testImg,224,224) local mean = {0.485,0.456,0.406} local std = {0.229,0.224,0.225} for c=1,3 do testImg[c]:add(-mean[c]) testImg[c]:div(std[c]) end testImgFeats[imgIdx] = imgEncoder:forward(testImg:cuda()):float()[1] end resultsFile:write('testFeat', testImgFeats:float()) resultsFile:close() print('Finished.')
local grid = require "grid_functions" local play_mode = nil play = {} local columns_changed = nil local timer_start = nil local pc -- puyo count local cp -- chain power local cb -- chain bonus local gb -- group bonus play.init = function () play.delay = 0.5 --seconds end play.score = nil play.init_play = false play.update = function (dt) --first update of play mode if play.init_play then play.score = 0 play.init_play = false play_mode = "fall" --set columns_changed to all columns columns_changed = {} for i=grid.min_size().x, grid.size().x do columns_changed[#columns_changed + 1] = i end timer_start = love.timer.getTime() end if timer_start + play.delay < love.timer.getTime() then timer_start = love.timer.getTime() if play_mode == "fall" then play.fall() play_mode = "pop" new_canvas() elseif play_mode == "pop" then if play.pop() then play_mode = "fall" new_canvas() else play_mode = "end" end else --end of chain, do nothing end end end play.fall = function () --could be optimized by using pairs() and finding difference in index instead of checking for nil values for _, x in pairs(columns_changed) do local fall_spaces = 0 local cur_column = grid.column(x) for y = grid.size().y, grid.min_size().y, -1 do local puyo_num = grid.get(x, y) if puyo_num == nil then fall_spaces = fall_spaces + 1 elseif REV_PUYO_ENUM[puyo_num] == "block" then fall_spaces = 0 elseif fall_spaces > 0 then -- if puyo falls cur_column[y + fall_spaces] = cur_column[y] cur_column[y] = nil end end end end play.pop = function () local puyos_to_remove = play.retest_for_chain(columns_changed) if next(puyos_to_remove) == nil then return nil end columns_changed = play.remove_puyos(puyos_to_remove) return true end play.test_for_chain = function (puyo_pos) local check_puyo_num = grid.get(puyo_pos.x, puyo_pos.y) local connecting_puyos = {} local connecting_puyos_len = 0 -- does not count garbage local puyos_to_check = {} puyos_to_check[puyo_pos] = true -- puyos whose adjacent spaces have not been checked tosee if they can join the string of puyos local puyos_unadjecented = {} local puyos_unadjecented_len = 0 --group_bonus = 0 while true do for puyo, _ in pairs(puyos_to_check) do if check_puyo_num == grid.get(puyo.x, puyo.y) then if not puyo_in_table(connecting_puyos, puyo) then connecting_puyos[puyo] = true connecting_puyos_len = connecting_puyos_len + 1 puyos_unadjecented[puyo] = true puyos_unadjecented_len = puyos_unadjecented_len + 1 end elseif REV_PUYO_ENUM[grid.get(puyo.x, puyo.y)] == "garbage" then if not puyo_in_table(connecting_puyos, puyo) then connecting_puyos[puyo] = true end end end puyos_to_check = {} if puyos_unadjecented_len == 0 then break end for puyo, _ in pairs(puyos_unadjecented) do if puyo.x ~= grid.size().x then puyos_to_check[{x = puyo.x + 1, y = puyo.y}] = true end if puyo.x ~= grid.min_size().x then puyos_to_check[{x = puyo.x - 1, y = puyo.y}] = true end if puyo.y ~= grid.size().y then puyos_to_check[{x = puyo.x, y = puyo.y + 1}] = true end if puyo.y ~= grid.min_size().y then puyos_to_check[{x = puyo.x, y = puyo.y - 1}] = true end end puyos_unadjecented = {} puyos_unadjecented_len = 0 end --if len(connecting_puyos) > 4: -- group_bonus = group_bonus_table[len(connecting_puyos) - 4] return connecting_puyos, connecting_puyos_len --, group_bonus #list of puyos the same color as input puyo and touching, as well as group bonus end play.retest_for_chain = function (columns) --columns is a list of ints for columns to check local removing_puyos = {} --group_bonus = 0 --group_bonus_addition = 0 for _, x in pairs(columns) do for y, puyo_num in pairs(grid.column(x)) do local puyo = {x = x, y = y} if is_puyo(puyo_num) and not puyo_in_table(removing_puyos, puyo) then --connecting_puyos, group_bonus_addition = test_for_chain([c, s]) local connecting_puyos, connecting_puyos_len = play.test_for_chain(puyo) --group_bonus += group_bonus_addition if connecting_puyos_len >= 4 then for puyo, _ in pairs(connecting_puyos) do removing_puyos[puyo] = true end end end end end return removing_puyos--, group_bonus end play.remove_puyos = function (puyos_to_remove) local columns_removed_from = {} --local colors = {} for puyo, _ in pairs(puyos_to_remove) do --gets columns and adds them to list, while setting the puyos to 9 if not int_in_table(columns_removed_from, puyo.x) then columns_removed_from[#columns_removed_from + 1] = puyo.x end --if internal_puyo_table[puyo_pos[0]][puyo_pos[1]] not in colors: -- colors.append(internal_puyo_table[puyo_pos[0]][puyo_pos[1]]) grid.remove(puyo.x, puyo.y) end return columns_removed_from--, len(colors) end play.exit = function () if state == "play" then state = "edit" grid.restore() end end function puyo_in_table (parent, puyo) for key_puyo, _ in pairs(parent) do if key_puyo.x == puyo.x and key_puyo.y == puyo.y then return true end end return nil end function int_in_table (table, int) for _, v in ipairs(table) do if v == int then return true end end return nil end function is_puyo (num) return num == PUYO_ENUM.red or num == PUYO_ENUM.green or num == PUYO_ENUM.blue or num == PUYO_ENUM.yellow or num == PUYO_ENUM.purple end function chain_power (chain_num) if chain_num == 1 then return 0 elseif chain_num == 2 then return 8 elseif chain_num == 3 then return 16 else return (chain_num - 3) * 32 end end function color_bonus (color_count) return 3 * (color_count - 1) end function group_bonus (puyo_count) if puyo_count == 4 then return 0 elseif puyo_count < 11 then return puyo_count - 3 else return 10 end end return play
Talk(14, "少侠手下功夫果然了得.", "talkname14", 0); do return end;
local parse = require"cheese" local stream = require"stream.string" parse.open_grammar"rules" aei = (plus(class("a","e","i")) .. pnot(str("ou"))) % function (res) return table.concat(res[1]) end foobar = str("foobar") join = aei / foobar close() local parsers = parse.compile(rules) local ok, res = pcall(parsers.join, stream.new("aei")) print(res) local res = parsers.join(stream.new("foobar")) print(res)
local InventoryFunctions = require "util/inventoryfunctions" local TransformationUnEquips = {} local function Equip(inst) if inst.weremode:value() == 0 then inst:DoTaskInTime(FRAMES * 23, function() for _, invItem in pairs(InventoryFunctions:GetPlayerInventory()) do for _, transformItem in pairs(TransformationUnEquips) do if invItem == transformItem then InventoryFunctions:Equip(transformItem) break end end end TransformationUnEquips = {} end) end end local function UnEquip() if not InventoryFunctions:IsBusyClassified() then local equips = {} for _, item in pairs(InventoryFunctions:GetEquips()) do if not item:HasTag("backpack") then equips[#equips + 1] = item end end for i = #equips, 1, -1 do if InventoryFunctions:HasFreeSlot() then SendRPCToServer(RPC.ControllerUseItemOnSelfFromInvTile, ACTIONS.UNEQUIP.code, equips[i]) TransformationUnEquips[#TransformationUnEquips + 1] = equips[i] end end end end local function IsFullMoon(cycle) return (cycle - 11) % 20 == 0 end local function Init() if not ThePlayer or not ThePlayer:HasTag("werehuman") then return end local InventoryReplica = ThePlayer.replica.inventory if not InventoryReplica then return end local OldUseItemFromInvTile = InventoryReplica.UseItemFromInvTile InventoryReplica.UseItemFromInvTile = function(self, item) if item and item:HasTag("wereitem") then UnEquip() end OldUseItemFromInvTile(self, item) end if TheWorld:HasTag("forest") then TheWorld:ListenForEvent("phasechanged", function(inst, phase) if IsFullMoon(inst.state.cycles + 1) and phase == "dusk" then local timeUntilPhase = inst.net.components.clock:GetTimeUntilPhase("night") ThePlayer:DoTaskInTime(timeUntilPhase - FRAMES, function() if IsFullMoon(inst.state.cycles + 1) then UnEquip() end end) end end) end ThePlayer:ListenForEvent("weremodedirty", function(inst) Equip(inst) end) end return Init
meta.name = 'Jumplunky' meta.version = '2.4' meta.description = 'Challenging platforming puzzles' meta.author = 'JayTheBusinessGoose' local level_sequence = require("LevelSequence/level_sequence") local SIGN_TYPE = level_sequence.SIGN_TYPE local telescopes = require("Telescopes/telescopes") local button_prompts = require("ButtonPrompts/button_prompts") local action_signs = require('action_signs') require('idols') local sound = require('play_sound') local journal = require('journal') local win_ui = require('win') local bottom_hud = require('bottom_hud') local clear_embeds = require('clear_embeds') local save_state = require('save_state') local DIFFICULTY = require('difficulty') local dwelling = require("dwelling") local volcana = require("volcana") local temple = require("temple") local ice_caves = require("ice_caves") local sunken_city = require("sunken_city") level_sequence.set_levels({dwelling, volcana, temple, ice_caves, sunken_city}) telescopes.set_hud_button_insets(0, 0, .1, 0) -- Forward declare local function local update_continue_door_enabledness local force_save local save_data -- Store the save context in a local var so we can save whenever we want. local save_context local initial_bombs = 0 local initial_ropes = 0 local create_stats = require('stats') local function create_saved_run() return { has_saved_run = false, saved_run_attempts = nil, saved_run_time = nil, saved_run_level = nil, saved_run_idol_count = nil, saved_run_idols_collected = {}, } end local game_state = { difficulty = DIFFICULTY.NORMAL, hardcore_enabled = false, hardcore_previously_enabled = false, total_idols = 0, idols_collected = {}, idols = 0, run_idols_collected = {}, -- True if the player has seen ana dead in the sunken city level. has_seen_ana_dead = false, stats = create_stats(), hardcore_stats = create_stats(), legacy_stats = create_stats(true), legacy_hardcore_stats = create_stats(true), easy_saved_run = create_saved_run(), normal_saved_run = create_saved_run(), hard_saved_run = create_saved_run(), } function game_state.stats.current_stats() return game_state.stats.stats_for_difficulty(game_state.difficulty) end function game_state.legacy_stats.current_stats() return game_state.legacy_stats.stats_for_difficulty(game_state.difficulty) end function game_state.hardcore_stats.current_stats() return game_state.hardcore_stats.stats_for_difficulty(game_state.difficulty) end function game_state.legacy_hardcore_stats.current_stats() return game_state.legacy_hardcore_stats.stats_for_difficulty(game_state.difficulty) end -- saved run state for the current difficulty. local function current_saved_run() if game_state.difficulty == DIFFICULTY.EASY then return game_state.easy_saved_run elseif game_state.difficulty == DIFFICULTY.HARD then return game_state.hard_saved_run else return game_state.normal_saved_run end end local function set_hardcore_enabled(enabled) game_state.hardcore_enabled = enabled bottom_hud.update_stats( game_state.hardcore_enabled and game_state.hardcore_stats.current_stats() or game_state.stats.current_stats(), game_state.hardcore_enabled, game_state.difficulty) level_sequence.set_keep_progress(not game_state.hardcore_enabled) update_continue_door_enabledness() end local function set_difficulty(difficulty) game_state.difficulty = difficulty bottom_hud.update_stats( game_state.hardcore_enabled and game_state.hardcore_stats.current_stats() or game_state.stats.current_stats(), game_state.hardcore_enabled, game_state.difficulty) bottom_hud.update_saved_run(current_saved_run()) update_continue_door_enabledness() end local function unique_idols_collected() local unique_idol_count = 0 for i, lvl in ipairs(level_sequence.levels()) do if game_state.idols_collected[lvl.identifier] then unique_idol_count = unique_idol_count + 1 end end return unique_idol_count end local function hardcore_available() return unique_idols_collected() == #level_sequence.levels() end -------------------------------------- ---- SOUNDS -------------------------------------- local function spring_volume_callback() -- Make spring traps quieter. return set_vanilla_sound_callback(VANILLA_SOUND.TRAPS_SPRING_TRIGGER, VANILLA_SOUND_CALLBACK_TYPE.STARTED, function(playing_sound) playing_sound:set_volume(.3) end) end local function sign_mute_callback() -- Mute the vocal sound that was playing on the signs when they "say" something. return set_vanilla_sound_callback(VANILLA_SOUND.UI_NPC_VOCAL, VANILLA_SOUND_CALLBACK_TYPE.STARTED, function(playing_sound) playing_sound:set_volume(0) end) end -------------------------------------- ---- /SOUNDS -------------------------------------- -------------------------------------- ---- CAMP -------------------------------------- local function camp_bounds_callback() return set_callback(function() set_camp_camera_bounds_enabled(true) set_global_timeout(function() if state.theme ~= THEME.BASE_CAMP then return end set_camp_camera_bounds_enabled(false) state.camera.bounds_left = 0 state.camera.bounds_right = 72.5 state.camera.bounds_top = 130.4 - 8 * 6 + 16 state.camera.bounds_bottom = 130.6 - 8 * 6 end, 140) end, ON.CAMP) end local function undo_camp_bounds_callback() return set_callback(function() set_camp_camera_bounds_enabled(true) end, ON.LEVEL) end local continue_door function update_continue_door_enabledness() if not continue_door then return end local saved_run = current_saved_run() continue_door.update_door(saved_run.saved_run_level, saved_run.saved_run_attempts, saved_run.saved_run_time) end -- Spawn an idol that is not interactible in any way. Only spawns the idol if it has been collected -- from the level it is being spawned for. local function spawn_camp_idol_for_level(level, x, y, layer) if not game_state.idols_collected[level.identifier] then return end local idol_uid = spawn_entity(ENT_TYPE.ITEM_IDOL, x, y, layer, 0, 0) local idol = get_entity(idol_uid) idol.flags = clr_flag(idol.flags, ENT_FLAG.THROWABLE_OR_KNOCKBACKABLE) idol.flags = clr_flag(idol.flags, ENT_FLAG.PICKUPABLE) end -- Creates a "room" for the Volcana shortcut, with a door, a sign, and an idol if it has been collected. define_tile_code("volcana_shortcut") local function volcano_shortcut_callback() return set_pre_tile_code_callback(function(x, y, layer) level_sequence.spawn_shortcut(x, y, layer, volcana, SIGN_TYPE.LEFT) spawn_camp_idol_for_level(volcana, x - 1, y, layer) return true end, "volcana_shortcut") end -- Creates a "room" for the Temple shortcut, with a door, a sign, and an idol if it has been collected. define_tile_code("temple_shortcut") local function temple_shortcut_callback() return set_pre_tile_code_callback(function(x, y, layer) level_sequence.spawn_shortcut(x, y, layer, temple, SIGN_TYPE.LEFT) spawn_camp_idol_for_level(temple, x - 1, y, layer) return true end, "temple_shortcut") end -- Creates a "room" for the Ice Caves shortcut, with a door, a sign, and an idol if it has been collected. define_tile_code("ice_shortcut") local function ice_shortcut_callback() return set_pre_tile_code_callback(function(x, y, layer) level_sequence.spawn_shortcut(x, y, layer, ice_caves, SIGN_TYPE.LEFT) spawn_camp_idol_for_level(ice_caves, x - 1, y, layer) return true end, "ice_shortcut") end -- Creates a "room" for the Sunken City shortcut, with a door, a sign, and an idol if it has been collected. define_tile_code("sunken_shortcut") local function sunken_shortcut_callback() return set_pre_tile_code_callback(function(x, y, layer) level_sequence.spawn_shortcut(x, y, layer, sunken_city, SIGN_TYPE.LEFT) spawn_camp_idol_for_level(sunken_city, x - 1, y, layer) return true end, "sunken_shortcut") end -- Creates a "room" for the continue entrance, with a door and a sign. define_tile_code("continue_run") local function continue_run_callback() return set_pre_tile_code_callback(function(x, y, layer) continue_door = level_sequence.spawn_continue_door( x, y, layer, current_saved_run().saved_run_level, current_saved_run().saved_run_attempts, current_saved_run().saved_run_time, SIGN_TYPE.RIGHT) return true end, "continue_run") end -- Spawns an idol if collected from the dwelling level, since there is no Dwelling shortcut. define_tile_code("dwelling_idol") local function dwelling_idol_callback() return set_pre_tile_code_callback(function(x, y, layer) spawn_camp_idol_for_level(dwelling, x, y, layer) return true end, "dwelling_idol") end local tunnel_x, tunnel_y, tunnel_layer -- Spawn tunnel, and spawn the difficulty and mode signs relative to her position. define_tile_code("tunnel_position") local function tunnel_position_callback() return set_pre_tile_code_callback(function(x, y, layer) tunnel_x, tunnel_y, tunnel_layer = x, y, layer -- Hardcore mode sign action_signs.spawn_sign(x + 3, y, layer, button_prompts.PROMPT_TYPE.INTERACT, function() if hardcore_available() then set_hardcore_enabled(not game_state.hardcore_enabled) game_state.hardcore_previously_enabled = true save_data() if game_state.hardcore_enabled then toast("Hardcore mode enabled") else toast("Hardcore mode disabled") end else toast("Collect more idols to unlock hardcore mode") end end, function(sign) cancel_speechbubble() set_timeout(function() if game_state.hardcore_enabled then say(sign.uid, "Hardcore mode (enabled)", 0, true) else say(sign.uid, "Hardcore mode", 0, true) end end, 1) end) -- Easy difficulty sign. action_signs.spawn_sign(x + 6, y, layer, button_prompts.PROMPT_TYPE.INTERACT, function() if game_state.difficulty ~= DIFFICULTY.EASY then set_difficulty(DIFFICULTY.EASY) save_data() toast("Easy mode enabled") end end, function(sign) cancel_speechbubble() set_timeout(function() if game_state.difficulty == DIFFICULTY.EASY then say(sign.uid, "Easy mode (enabled)", 0, true) else say(sign.uid, "Easy mode", 0, true) end end, 1) end) -- Normal difficulty sign. action_signs.spawn_sign(x + 7, y, layer, button_prompts.PROMPT_TYPE.INTERACT, function() if game_state.difficulty ~= DIFFICULTY.NORMAL then if game_state.difficulty == DIFFICULTY.EASY then toast("Easy mode disabled") elseif game_state.difficulty == DIFFICULTY.HARD then toast("Hard mode disabled") end set_difficulty(DIFFICULTY.NORMAL) save_data() end end, function(sign) cancel_speechbubble() set_timeout(function() if game_state.difficulty == DIFFICULTY.NORMAL then say(sign.uid, "Normal mode (enabled)", 0, true) else say(sign.uid, "Normal mode", 0, true) end end, 1) end) -- Hard difficulty sign. action_signs.spawn_sign(x + 8, y, layer, button_prompts.PROMPT_TYPE.INTERACT, function() if game_state.difficulty ~= DIFFICULTY.HARD then set_difficulty(DIFFICULTY.HARD) save_data() toast("Hard mode enabled") end end, function(sign) cancel_speechbubble() set_timeout(function() if game_state.difficulty == DIFFICULTY.HARD then say(sign.uid, "Hard mode (enabled)", 0, true) else say(sign.uid, "Hard mode", 0, true) end end, 1) end) -- Stats sign opens journal. action_signs.spawn_sign(x + 10, y, layer, button_prompts.PROMPT_TYPE.VIEW, function() journal.show(game_state.stats, game_state.hardcore_stats, game_state.difficulty, 6) -- Cancel speech bubbles so they don't show above stats. cancel_speechbubble() -- Hide the prompt so it doesn't show above stats. button_prompts.hide_button_prompts(true) end, function(sign) cancel_speechbubble() set_timeout(function() say(sign.uid, "Stats", 0, true) end, 1) end) if game_state.legacy_stats.normal and game_state.legacy_stats.easy and game_state.legacy_stats.hard and game_state.legacy_hardcore_stats.normal and game_state.legacy_hardcore_stats.easy and game_state.legacy_hardcore_stats.hard then -- Legacy stats sign opens journal; only spawns if legacy stats exist. action_signs.spawn_sign(x + 11, y, layer, button_prompts.PROMPT_TYPE.VIEW, function() journal.show(game_state.legacy_stats, game_state.legacy_hardcore_stats, game_state.difficulty, 6) -- Cancel speech bubbles so they don't show above stats. cancel_speechbubble() -- Hide the prompt so it doesn't show above stats. button_prompts.hide_button_prompts(true) end, function(sign) cancel_speechbubble() set_timeout(function() say(sign.uid, "Legacy Stats", 0, true) end, 1) end) end end, "tunnel_position") end local tunnel local function tunnel_spawn_callback() return set_callback(function() -- Spawn tunnel in the mode room and turn the normal tunnel invisible so the player doesn't see her. if state.theme ~= THEME.BASE_CAMP then return end local tunnels = get_entities_by_type(ENT_TYPE.MONS_MARLA_TUNNEL) if #tunnels > 0 then local tunnel_uid = tunnels[1] local tunnel = get_entity(tunnel_uid) tunnel.flags = set_flag(tunnel.flags, ENT_FLAG.INVISIBLE) tunnel.flags = clr_flag(tunnel.flags, ENT_FLAG.ENABLE_BUTTON_PROMPT) end local tunnel_id = spawn_entity(ENT_TYPE.MONS_MARLA_TUNNEL, tunnel_x, tunnel_y, tunnel_layer, 0, 0) tunnel = get_entity(tunnel_id) tunnel.flags = clr_flag(tunnel.flags, ENT_FLAG.ENABLE_BUTTON_PROMPT) tunnel.flags = set_flag(tunnel.flags, ENT_FLAG.FACING_LEFT) --end end, ON.CAMP) end -- STATS local function journal_button_callback() return set_callback(function() if #players < 1 then return end local player = players[1] local buttons = read_input(player.uid) -- 8 = Journal if test_flag(buttons, 8) and not journal.showing_stats() then journal.show(game_state.stats, game_state.hardcore_stats, game_state.difficulty, 8) -- Cancel speech bubbles so they don't show above stats. cancel_speechbubble() -- Hide the prompt so it doesn't show above stats. button_prompts.hide_button_prompts(true) end end, ON.GAMEFRAME) end journal.set_on_journal_closed(function() button_prompts.hide_button_prompts(false) end) local tunnel_enter_displayed local tunnel_exit_displayed local tunnel_enter_hardcore_state local tunnel_enter_difficulty local tunnel_exit_hardcore_state local tunnel_exit_difficulty local tunnel_exit_ready local function tunnel_text_callback() return set_callback(function() if state.theme ~= THEME.BASE_CAMP then return end if #players < 1 then return end local player = players[1] local x, y, layer = get_position(player.uid) if layer == LAYER.FRONT then -- Reset tunnel dialog states when exiting the back layer so the dialog shows again. tunnel_enter_displayed = false tunnel_exit_displayed = false tunnel_enter_hardcore_state = game_state.hardcore_enabled tunnel_exit_hardcore_state = game_state.hardcore_enabled tunnel_enter_difficulty = game_state.difficulty tunnel_exit_difficulty = game_state.difficulty tunnel_exit_ready = false elseif tunnel_enter_displayed and x > tunnel_x + 2 then -- Do not show Tunnel's exit dialog until the player moves a bit to her right. tunnel_exit_ready = true end -- Speech bubbles for Tunnel and mode signs. if tunnel and player.layer == tunnel.layer and distance(player.uid, tunnel.uid) <= 1 then if not tunnel_enter_displayed then -- Display a different Tunnel text on entering depending on how many idols have been collected and the hardcore state. tunnel_enter_displayed = true tunnel_enter_hardcore_state = game_state.hardcore_enabled tunnel_enter_difficulty = game_state.difficulty if unique_idols_collected() == 0 then say(tunnel.uid, "Looking to turn down the heat?", 0, true) elseif unique_idols_collected() < 2 then say(tunnel.uid, "Come back when you're seasoned for a more difficult challenge.", 0, true) elseif game_state.hardcore_enabled then say(tunnel.uid, "Maybe that was too much. Go back over to disable hardcore mode.", 0, true) elseif game_state.difficulty == DIFFICULTY.HARD then say(tunnel.uid, "Maybe that was too much. Go back over to disable hard mode.", 0, true) elseif game_state.hardcore_previously_enabled then say(tunnel.uid, "Back to try again? Step on over.", 0, true) elseif hardcore_available() then say(tunnel.uid, "This looks too easy for you. Step over there to enable hardcore mode.", 0, true) else say(tunnel.uid, "You're quite the adventurer. Collect the rest of the idols to unlock a more difficult challenge.", 0, true) end elseif (not tunnel_exit_displayed or tunnel_exit_hardcore_state ~= game_state.hardcore_enabled or tunnel_exit_difficulty ~= game_state.difficulty) and tunnel_exit_ready and (hardcore_available() or (game_state.difficulty == DIFFICULTY.EASY and tunnel_exit_difficulty ~=DIFFICULTY.EASY)) then -- On exiting, display a Tunnel dialog depending on whether hardcore mode has been enabled/disabled or the difficulty changed. cancel_speechbubble() tunnel_exit_displayed = true tunnel_exit_hardcore_state = game_state.hardcore_enabled tunnel_exit_difficulty = game_state.difficulty set_timeout(function() if game_state.hardcore_enabled and not tunnel_enter_hardcore_state or game_state.difficulty > tunnel_enter_difficulty then say(tunnel.uid, "Good luck out there!", 0, true) elseif not game_state.hardcore_enabled and tunnel_enter_hardcore_state or game_state.difficulty < tunnel_enter_difficulty then say(tunnel.uid, "Take it easy.", 0, true) elseif game_state.hardcore_enabled or game_state.difficulty == DIFFICULTY.HARD then say(tunnel.uid, "Sticking with it. I like your guts!", 0, true) else say(tunnel.uid, "Maybe another time.", 0, true) end end, 1) end end end, ON.GAMEFRAME) end -- Sorry, Ana... local function remove_ana_callback() return set_post_entity_spawn(function (entity) if game_state.has_seen_ana_dead then if state.screen == 11 then entity.x = 1000 else entity:set_texture(TEXTURE.DATA_TEXTURES_CHAR_CYAN_0) end end end, SPAWN_TYPE.ANY, MASK.ANY, ENT_TYPE.CHAR_ANA_SPELUNKY) end -------------------------------------- ---- /CAMP -------------------------------------- -------------------------------------- ---- LEVEL SEQUENCE -------------------------------------- level_sequence.set_on_level_will_load(function(level) level.set_difficulty(game_state.difficulty) if level == sunken_city then level.set_idol_collected(game_state.idols_collected[level.identifier]) level.set_run_idol_collected(game_state.run_idols_collected[level.identifier]) level.set_ana_callback(function() has_seen_ana_dead = true end) elseif level == ice_caves then level.set_idol_collected(game_state.idols_collected[level.identifier]) level.set_run_idol_collected(game_state.run_idols_collected[level.identifier]) end end) level_sequence.set_on_post_level_generation(function(level) if #players == 0 then return end players[1].inventory.bombs = initial_bombs players[1].inventory.ropes = initial_ropes if players[1]:get_name() == "Roffy D. Sloth" or level == ice_caves then players[1].health = 1 else players[1].health = 2 end end) level_sequence.set_on_completed_level(function(completed_level, next_level) if not next_level then return end -- Update stats for the current difficulty mode. local current_stats = game_state.stats.current_stats() local stats_hardcore = game_state.hardcore_stats.current_stats() local best_level_index = level_sequence.index_of_level(current_stats.best_level) local hardcore_best_level_index = level_sequence.index_of_level(stats_hardcore.best_level) local current_level_index = level_sequence.index_of_level(next_level) -- Update the PB if the new level has not been reached yet. if (not best_level_index or current_level_index > best_level_index) and not level_sequence.took_shortcut() then current_stats.best_level = next_level end if game_state.hardcore_enabled and (not hardcore_best_level_index or current_level_index > hardcore_best_level_index) and not level_sequence.took_shortcut() then stats_hardcore.best_level = next_level end end) level_sequence.set_on_win(function(attempts, total_time) local current_stats = game_state.stats.current_stats() local stats_hardcore = game_state.hardcore_stats.current_stats() if not level_sequence.took_shortcut() then local deaths = attempts - 1 current_stats.completions = current_stats.completions + 1 if game_state.hardcore_enabled then stats_hardcore.completions = stats_hardcore.completions + 1 else -- Clear the saved run for the current difficulty if hardcore is disabled. local saved_run = current_saved_run() saved_run.has_saved_run = false saved_run.saved_run_attempts = nil saved_run.saved_run_idol_count = nil saved_run.saved_run_idols_collected = {} saved_run.saved_run_level = nil saved_run.saved_run_time = nil end local new_time_pb = false if not current_stats.best_time or current_stats.best_time == 0 or total_time < current_stats.best_time then current_stats.best_time = total_time new_time_pb = true if game_state.difficulty ~= DIFFICULTY.EASY then current_stats.best_time_idol_count = game_state.idols end current_stats.best_time_death_count = deaths end if game_state.hardcore_enabled and (not stats_hardcore.best_time or stats_hardcore.best_time == 0 or total_time < stats_hardcore.best_time) then stats_hardcore.best_time = total_time new_time_pb = true if game_state.difficulty ~= DIFFICULTY.EASY then stats_hardcore.best_time_idol_count = game_state.idols end end if game_state.idols == #level_sequence.levels() and game_state.difficulty ~= DIFFICULTY.EASY then current_stats.max_idol_completions = current_stats.max_idol_completions + 1 if not current_stats.max_idol_best_time or current_stats.max_idol_best_time == 0 or total_time < current_stats.max_idol_best_time then current_stats.max_idol_best_time = total_time end if game_state.hardcore_enabled then stats_hardcore.max_idol_completions = stats_hardcore.max_idol_completions + 1 if not stats_hardcore.max_idol_best_time or stats_hardcore.max_idol_best_time == 0 or total_time < stats_hardcore.max_idol_best_time then stats_hardcore.max_idol_best_time = total_time end end end local new_deaths_pb = false if not current_stats.least_deaths_completion or deaths < current_stats.least_deaths_completion or (deaths == current_stats.least_deaths_completion and total_time < current_stats.least_deaths_completion_time) then if not current_stats.least_deaths_completion or deaths < current_stats.least_deaths_completion then new_deaths_pb = true end current_stats.least_deaths_completion = deaths current_stats.least_deaths_completion_time = total_time if attempts == 1 then current_stats.deathless_completions = current_stats.deathless_completions + 1 end end win_ui.win( total_time, deaths, game_state.idols, game_state.difficulty, game_state.stats, game_state.hardcore_stats, game_state.hardcore_enabled, #level_sequence.levels(), new_time_pb, new_deaths_pb) bottom_hud.update_win_state(true) win_ui.set_on_dismiss(function() bottom_hud.update_win_state(false) end) end warp(1, 1, THEME.BASE_CAMP) end) local function pb_update_callback() return set_callback(function () -- Update the PB if the new level has not been reached yet. This is only really for the first time entering Dwelling, -- since other times ON.RESET will not have an increased level from the best_level. local current_stats = game_state.stats.current_stats() local stats_hardcore = game_state.hardcore_stats.current_stats() local best_level_index = level_sequence.index_of_level(current_stats.best_level) local hardcore_best_level_index = level_sequence.index_of_level(stats_hardcore.best_level) local current_level = level_sequence.get_run_state().current_level local current_level_index = level_sequence.index_of_level(current_level) if (not best_level_index or current_level_index > best_level_index) and not level_sequence.took_shortcut() then current_stats.best_level = current_level end if game_state.hardcore_enabled and (not hardcore_best_level_index or current_level_index > hardcore_best_level_index) and not level_sequence.took_shortcut() then stats_hardcore.best_level = current_level end end, ON.RESET) end local function update_hud_run_entry(continuing) local run_state = level_sequence.get_run_state() local took_shortcut = level_sequence.took_shortcut() bottom_hud.update_run_entry(run_state.initial_level, took_shortcut, continuing) end local function update_hud_run_state() local run_state = level_sequence.get_run_state() bottom_hud.update_run(game_state.idols, run_state.attempts, run_state.total_time) end level_sequence.set_on_reset_run(function() game_state.run_idols_collected = {} game_state.idols = 0 update_hud_run_state() end) level_sequence.set_on_prepare_initial_level(function(level, continuing) local saved_run = current_saved_run() if continuing then game_state.idols = saved_run.saved_run_idol_count game_state.run_idols_collected = saved_run.saved_run_idols_collected else game_state.idols = 0 game_state.run_idols_collected = {} end update_hud_run_state() update_hud_run_entry(continuing) end) level_sequence.set_on_level_start(function(level) update_hud_run_state() end) -------------------------------------- ---- /LEVEL SEQUENCE -------------------------------------- -------------------------------------- ---- IDOL -------------------------------------- local function idol_price_callback() return set_post_entity_spawn(function(entity) -- Set the price to 0 so the player doesn't get gold for returning the idol. entity.price = 0 end, SPAWN_TYPE.ANY, 0, ENT_TYPE.ITEM_IDOL, ENT_TYPE.ITEM_MADAMETUSK_IDOL) end local function idol_collected_state_for_level(level) if game_state.run_idols_collected[level.identifier] then return IDOL_COLLECTED_STATE.COLLECTED_ON_RUN elseif game_state.idols_collected[level.identifier] then return IDOL_COLLECTED_STATE.COLLECTED end return IDOL_COLLECTED_STATE.NOT_COLLECTED end define_tile_code("idol_reward") local function idol_tile_code_callback() return set_pre_tile_code_callback(function(x, y, layer) return spawn_idol( x, y, layer, idol_collected_state_for_level(level_sequence.get_run_state().current_level), game_state.difficulty == DIFFICULTY.EASY) end, "idol_reward") end local function idol_sound_callback() return set_vanilla_sound_callback(VANILLA_SOUND.UI_DEPOSIT, VANILLA_SOUND_CALLBACK_TYPE.STARTED, function() -- Consider the idol collected when the deposit sound effect plays. game_state.idols_collected[level_sequence.get_run_state().current_level.identifier] = true game_state.run_idols_collected[level_sequence.get_run_state().current_level.identifier] = true game_state.idols = game_state.idols + 1 game_state.total_idols = game_state.total_idols + 1 update_hud_run_state() end) end -------------------------------------- ---- /IDOL -------------------------------------- -------------------------------------- ---- DO NOT SPAWN GHOST -------------------------------------- set_ghost_spawn_times(-1, -1) -------------------------------------- ---- /DO NOT SPAWN GHOST -------------------------------------- -------------------------------------- ---- SAVE STATE -------------------------------------- -- Manage saving data and keeping the time in sync during level transitions and resets. function save_data() if save_context then force_save(save_context) end end function save_current_run_stats() local run_state = level_sequence.get_run_state() -- Save the current run only if there is a run in progress that did not start from a shorcut, and harcore mode is disabled. if not level_sequence.took_shortcut() and not game_state.hardcore_enabled and state.theme ~= THEME.BASE_CAMP and level_sequence.run_in_progress() then local saved_run = current_saved_run() saved_run.saved_run_attempts = run_state.attempts saved_run.saved_run_idol_count = game_state.idols saved_run.saved_run_level = run_state.current_level saved_run.saved_run_time = run_state.total_time saved_run.saved_run_idols_collected = game_state.run_idols_collected saved_run.has_saved_run = true end end -- Saves the current state of the run so that it can be continued later if exited. local function save_current_run_stats_callback() return set_callback(function() save_current_run_stats() end, ON.FRAME) end -- Since we are keeping track of time for the entire run even through deaths and resets, we must track -- what the time was on resets and level transitions. local function reset_save_callback() return set_callback(function () if state.theme == THEME.BASE_CAMP then return end if level_sequence.run_in_progress() then if not game_state.hardcore_enabled then save_current_run_stats() end save_data() end end, ON.RESET) end local function transition_save_callback() return set_callback(function () if state.theme == THEME.BASE_CAMP then return end if level_sequence.run_in_progress() and not win_ui.won() then save_current_run_stats() save_data() end end, ON.TRANSITION) end -------------------------------------- ---- /SAVE STATE -------------------------------------- -------------------------------------- ---- STATE MANAGEMENT -------------------------------------- -- Leaving these variables set between resets can lead to undefined behavior due to the high likelyhood of entities being reused. local function clear_variables_callback() return set_callback(function() continue_door = nil tunnel_x = nil tunnel_y = nil tunnel_layer = nil tunnel = nil end, ON.PRE_LOAD_LEVEL_FILES) end -------------------------------------- ---- /STATE MANAGEMENT -------------------------------------- -------------------------------------- ---- SAVE DATA -------------------------------------- set_callback(function(ctx) game_state = save_state.load(game_state, level_sequence, ctx) set_difficulty(game_state.difficulty) set_hardcore_enabled(game_state.hardcore_enabled) end, ON.LOAD) function force_save(ctx) save_state.save(game_state, level_sequence, ctx) end local function on_save_callback() return set_callback(function(ctx) save_context = ctx force_save(ctx) end, ON.SAVE) end -------------------------------------- ---- /SAVE DATA -------------------------------------- local active = false local callbacks = {} local vanilla_sound_callbacks = {} local function activate() if active then return end active = true level_sequence.activate() telescopes.activate() button_prompts.activate() action_signs.activate() journal.activate() win_ui.activate() bottom_hud.activate() local function add_callback(callback_id) callbacks[#callbacks+1] = callback_id end local function add_vanilla_sound_callback(callback_id) vanilla_sound_callbacks[#vanilla_sound_callbacks+1] = callback_id end set_journal_enabled(false) add_callback(camp_bounds_callback()) add_callback(undo_camp_bounds_callback()) add_callback(volcano_shortcut_callback()) add_callback(temple_shortcut_callback()) add_callback(ice_shortcut_callback()) add_callback(sunken_shortcut_callback()) add_callback(continue_run_callback()) add_callback(dwelling_idol_callback()) add_callback(tunnel_position_callback()) add_callback(tunnel_spawn_callback()) add_callback(journal_button_callback()) add_callback(tunnel_text_callback()) add_callback(remove_ana_callback()) add_callback(pb_update_callback()) add_callback(idol_price_callback()) add_callback(idol_tile_code_callback()) add_callback(reset_save_callback()) add_callback(transition_save_callback()) add_callback(clear_variables_callback()) add_callback(on_save_callback()) add_callback(save_current_run_stats_callback()) add_vanilla_sound_callback(spring_volume_callback()) add_vanilla_sound_callback(sign_mute_callback()) add_vanilla_sound_callback(idol_sound_callback()) end set_callback(function() activate() end, ON.LOAD) set_callback(function() activate() end, ON.SCRIPT_ENABLE) set_callback(function() if not active then return end active = false level_sequence.deactivate() telescopes.deactivate() button_prompts.deactivate() action_signs.deactivate() journal.deactivate() win_ui.deactivate() bottom_hud.deactivate() set_journal_enabled(true) for _, callback in pairs(callbacks) do clear_callback(callback) end for _, vanilla_sound_callback in pairs(vanilla_sound_callbacks) do clear_vanilla_sound_callback(vanilla_sound_callback) end callbacks = {} vanilla_sound_callbacks = {} end, ON.SCRIPT_DISABLE)
WindowWidth = 800 WindowHeight = 400 love.load = function() love.window.setMode(WindowWidth, WindowHeight) end PosX = 400 PosY = 0 CharacterSize = 20 SpeedX = 120 VelocityY = 0 Gravity = -200 JumpForce = 150 WasPressingStomp = false HasStomp = false StompForce = -320 LifePoints = 3 BlinkTimer = 0 Points = 0 BestCombo = 0 Multiplier = 1 Enemies = {} SpawnRate = 1 SpawnTimer = 0 EnemySize = 15 EnemyMinSpeed,EnemyMaxSpeed = 90 , 180 Labels = {} LabelDisplayTime = 1 LabelSpeed = 30 BestScore = "Loading" WasPressingReset = false reset = function() -- dirty compressed reset PosX,PosY,VelocityY,HasStomp,WasPressingStomp,LifePoints,BlinkTimer,Points,BestCombo,Multiplier,Enemies,Labels = 400,0,0,false,false,3,0,0,0,1,{},{} end love.update = function(dt) if love.keyboard.isDown("escape") then love.event.push('quit') end if not WasPressingReset and love.keyboard.isDown("r") then reset() end WasPressingReset = love.keyboard.isDown("r") if LifePoints > 0 then local directionX = 0 if love.keyboard.isDown("right") then directionX = 1 end if love.keyboard.isDown("left") then directionX = directionX - 1 end -- If the player is pressing both, the character dont move PosX = PosX + directionX * SpeedX * dt PosX = math.min(math.max(PosX,0), WindowWidth - CharacterSize) -- Clamping the character into the window VelocityY = VelocityY + Gravity * dt local isOnGround = PosY <= 1 if isOnGround then HasStomp = false Multiplier = 1 if love.keyboard.isDown("up") then VelocityY = JumpForce end elseif love.keyboard.isDown("down") and not WasPressingStomp and not HasStomp then VelocityY = StompForce HasStomp = true end WasPressingStomp = love.keyboard.isDown("down") PosY = PosY + VelocityY * dt PosY = math.max(PosY , 0) updateEnemies(dt) local hasHit = false for i = #Enemies,1,-1 do if rectangleCollision(PosX,PosY,CharacterSize,CharacterSize,Enemies[i].posX,Enemies[i].posY,EnemySize,EnemySize) then removeElement(Enemies,i) VelocityY = JumpForce if HasStomp then Points = Points + Multiplier Labels[#Labels + 1] = {Text = tostring(Multiplier) , posX = PosX, posY = PosY, time = LabelDisplayTime} BestCombo = math.max(BestCombo,Multiplier) Multiplier = Multiplier + 1 else LifePoints = LifePoints - 1 BlinkTimer = 1 Multiplier = 1 if LifePoints == 0 then onGameOver() end end hasHit = true end end if hasHit then HasStomp = false end if BlinkTimer > 0 then BlinkTimer = BlinkTimer - dt end for i= #Labels,1,-1 do Labels[i].time = Labels[i].time - dt if Labels[i].time <= 0 then removeElement(Labels,i) end end end end love.draw = function() love.graphics.setColor(255,255,20) love.graphics.print("Left/Right to move | Up to jump | Down to stomp you'll crush only if you stomp",305,15) if LifePoints > 0 then love.graphics.print("Life : " .. tostring(LifePoints) , 15,15) love.graphics.print("Points : " .. tostring(Points) .. " Multiplier : " .. tostring(Multiplier) .. " Best Combo : " .. BestCombo, 15 , 35) if not (BlinkTimer > 0) or (math.sin(BlinkTimer * math.pi * 15) > .5) then if HasStomp then love.graphics.setColor(240,240,0) else love.graphics.setColor(240,240,75) end local x,y = getPositionFromCamera(PosX,PosY) love.graphics.rectangle("fill",x, y - CharacterSize,CharacterSize,CharacterSize) end love.graphics.setColor(255,65,40) for i,enemy in ipairs(Enemies) do local x,y = getPositionFromCamera(enemy.posX,enemy.posY) love.graphics.rectangle("fill",x,y - EnemySize,EnemySize,EnemySize) end love.graphics.setColor(25,128,255) for i,label in ipairs(Labels) do local x,y = getPositionFromCamera(label.posX,label.posY + LabelSpeed * (1 - label.time / LabelDisplayTime) + CharacterSize + EnemySize) love.graphics.print(label.Text,x,y) end else love.graphics.print("Congratulation you achieved : " .. tostring(Points) .. " Points! \nYour best combo is " .. BestCombo , 300,185) love.graphics.print("Best score : " .. tostring(BestScore), 335,220) love.graphics.print("Press R to restart", 375,240) love.graphics.print("The 200 lines of codes for this game are here : https://github.com/Redoxee/CompressedGame/blob/master/Game/main.lua",4,380) end end getPositionFromCamera = function(x,y) return x, y*-1 + WindowHeight end updateEnemies = function(dt) SpawnTimer = SpawnTimer - dt if SpawnTimer < 0 then SpawnTimer = SpawnRate local goRight = math.random() > .5 Enemies[#Enemies + 1] = { posY = math.random(0,50), posX = goRight and -EnemySize or WindowWidth , speed = math.random(EnemyMinSpeed,EnemyMaxSpeed) * (goRight and 1 or -1), } end for i = #Enemies, 1, -1 do local enemy = Enemies[i] enemy.posX = enemy.posX + enemy.speed * dt if ((enemy.speed > 0) and enemy.posX > WindowWidth) or (not (enemy.speed > 0) and enemy.posX < -EnemySize) then removeElement(Enemies,i) end end end removeElement = function(list,index) for i = index,#list do list[i] = list[i + 1] end end rectangleCollision = function(x1,y1,width1,height1,x2,y2,width2,height2) -- Simple aabb function local isNotColliding = x1 > (x2 + width2) or (x2 > x1 + width1) or y1 > (y2 + height2) or y2 > (y1 + height1) return not isNotColliding end onGameOver = function() if BestScore == "Loading" or BestScore ~= "Can't load" then local http = require("socket.http") local b, c, h = http.request("http://antonroy.fr/content/CompressedGame/php/HighScore.php?Score=" .. tostring(Points).."&BestCombo="..tostring(BestCombo)) if c == 200 then BestScore = b else BestScore = "Can't load" end end end --[[<?php -- Server Side -- yes it is very easy to cheat but I trust you not to $host = "stub"; $db = "stub"; $dsn = 'stub'.$db.'stub'.$host; $user = "stub"; $pwd = "stub"; $pdo = new PDO($dsn,$user,$pwd); $pdo = new PDO($dsn,$user,$pwd); if (isset($_GET["Score"]) && isset($_GET["BestCombo"])){ $sql = 'SELECT * FROM HighScore WHERE id = 1;'; $rep = $pdo->query($sql); $rep = $rep->fetch(); $_GET["Score"] = max(htmlspecialchars ($_GET["Score"]),$rep['Score']); $_GET["BestCombo"] = max(htmlspecialchars ($_GET["BestCombo"]),$rep['BestCombo']); $sql = 'UPDATE HighScore SET Score='.$_GET["Score"].', BestCombo = '.$_GET["BestCombo"].' WHERE id = 1;'; $pdo->exec($sql); } $sql = 'SELECT Score,BestCombo FROM HighScore;'; $rep = $pdo->query($sql); foreach ($rep as $row) { echo $row['Score'].", ".$row['BestCombo']; } ?>--]] --[[function love.conf(t) -- conf.lua t.version = "0.10.0" -- The LÖVE version this game was made for (string) t.window.title = "CompressedGame" -- The window title (string) t.window.resizable = false -- Let the window be user-resizable (boolean) end--]] -- Thanks for reading :) -- Anton Roy Apache License 2.0 2016
--Image manager --Goal reuse images without using too much memory images ={} function addImage(src,id) image = love.graphics.newImage(src) newImage = {img = image, id=id} table.insert(images,newImage) end function getImage(id) --loop and return img for i, img in ipairs(images) do if img.id == id then return img.img end end return nil end function deleteImage(id) for i, img in ipairs(images) do if img.id == id then return img.img end end return nil end
--[[ Load VGG16 + Body joints predictor + LSTM networks. Classifier type: single lstm. ]] require 'nn' ------------------------------------------------------------------------------------------------------------ local function load_classifier_network(input_size, num_feats, num_activities, num_layers) local lstm = nn.Sequential() lstm:add(nn.Contiguous()) lstm:add(cudnn.LSTM(input_size, num_feats, num_layers, true)) lstm:add(nn.Contiguous()) lstm:add(nn.View(-1, num_feats)) lstm:add(nn.Dropout(opt.dropout)) lstm:add(nn.Linear(num_feats, num_activities)) return lstm end ------------------------------------------------------------------------------------------------------------ --[[ Create VGG16 + LSTM ]]-- local function create_network() local vgg16 = paths.dofile('vgg16_lstm.lua') local hms = paths.dofile('hms_lstm.lua') local vgg16_features, _, vgg16_lstm, vgg16_params = vgg16() local _, hms_features, hms_lstm, hms_params = hms() local hms_feat_size = hms_params.dims[1] * hms_params.dims[2] * hms_params.dims[3] local lstm = load_classifier_network(vgg16_params.feat_size + hms_feat_size, opt.nFeats, opt.num_activities, opt.nLayers) local classifier = nn.Sequential() classifier:add(nn.JoinTable(3)) classifier:add(lstm) return vgg16_features, hms_features, classifier, vgg16_params -- features, hms, classifier, params end ------------------------------------------------------------------------------------------------------------ return create_network
local module = {}function module.argCheck(arg,argType,argIndex,errorCallback)if typeof(argType)~="string"then return error("Argument check error! Incorrect argument #2. Expected string, got "..typeof(argType))end if typeof(argIndex)~="number"then return error("Argument check error! Incorrect argument #3. Expected number, got "..typeof(argType))end if not argIndex or argIndex==nil then argIndex = ""else argIndex = " #"..argIndex end if not errorCallback or errorCallback == nil then if typeof(arg) ~= argType then return error("Incorrect argument"..argIndex..". Expected "..argType..", got "..typeof(arg))else return end elseif typeof(errorCallback)=="function"then return errorCallback()else return error("Argument check error! Incorrect argument #4. errorCallback can be only function or nil.")end end return module
dofile'include.lua' -- Important libraries in the global space local libs = { 'Config', 'Body', 'unix', 'util', 'vector', } -- Load the libraries for _,lib in ipairs(libs) do _G[lib] = require(lib) end -- mp local mp = require'msgpack' local getch=require'getch' local si = require'simple_ipc' require'mcm' require'gcm' -- FSM communicationg local fsm_chs = {} for sm,en in pairs(Config.fsm.enabled) do local fsm_name = sm..'FSM' table.insert(fsm_chs, fsm_name) _G[sm:lower()..'_ch'] = si.new_publisher(fsm_name.."!") end -- RPC engine rpc_ch = si.new_requester(Config.net.reliable_rpc) targetvel={0,0,0} targetvel_new={0,0,0} --Name show_factor value increment local params={ {'tStep',1,'0'}, {'tZMP',1,'0'}, {'stepHeight',1,'0'}, {'torsoX',1,'0'}, {'supportX',1,'0'}, {'supportY',1,'0'}, {'hipRollCompensation',180/math.pi,'0'}, {'ankleRollCompensation',180/math.pi,'0'}, } for i=1,#params do params[i][3]=Config.walk[params[i][1]] or 0 end local selected_param = 1 function process_keyinput() local byte=getch.block(); if byte then if byte==string.byte("i") then targetvel_new[1]=targetvel[1]+0.02; elseif byte==string.byte("j") then targetvel_new[3]=targetvel[3]+0.1; elseif byte==string.byte("k") then targetvel_new[1],targetvel_new[2],targetvel_new[3]=0,0,0; elseif byte==string.byte("l") then targetvel_new[3]=targetvel[3]-0.1; elseif byte==string.byte(",") then targetvel_new[1]=targetvel[1]-0.02; elseif byte==string.byte("h") then targetvel_new[2]=targetvel[2]+0.02; elseif byte==string.byte(";") then targetvel_new[2]=targetvel[2]-0.02; --Cycle through selected params elseif byte==string.byte("w") then selected_param = selected_param%#params + 1 elseif byte==string.byte("q") then selected_param = (selected_param + #params-2) %#params + 1 elseif byte==string.byte("4") then mcm.set_walk_kicktype(1) --this means testing mode (don't run body fsm) mcm.set_walk_kickfoot(1) body_ch:send'kick' elseif byte==string.byte("5") then mcm.set_walk_kickfoot(0) mcm.set_walk_steprequest(1) elseif byte==string.byte("6") then mcm.set_walk_kickfoot(1) mcm.set_walk_steprequest(1) elseif byte==string.byte("7") then motion_ch:send'sit' elseif byte==string.byte("0") then gcm.set_game_state(0) elseif byte==string.byte("8") then motion_ch:send'stand' body_ch:send'stop' if mcm.get_walk_ismoving()>0 then print("requesting stop") mcm.set_walk_stoprequest(1) end elseif byte==string.byte("9") then motion_ch:send'hybridwalk' end local vel_diff = (targetvel_new[1]-targetvel[1])^2+(targetvel_new[2]-targetvel[2])^2+(targetvel_new[3]-targetvel[3])^2 if vel_diff>0 then targetvel[1],targetvel[2],targetvel[3] = targetvel_new[1],targetvel_new[2],targetvel_new[3] mcm.set_walk_vel(targetvel) end end end local t_last = Body.get_time() local tDelay = 0.005*1E6 local role_names={ util.color('Goalie','green'), util.color('Attacker','red'), 'Test'} local gcm_names={ util.color('Initial','green'), util.color('Ready','green'), util.color('Set','green'), util.color('Playing','blue'), util.color('Finished','green'), util.color('Untorqued','red'), util.color('Test','blue'), } local command1='' local command2='' function show_status() os.execute('clear') local outstring='' outstring= outstring..command1 -- outstring=outstring..string.format("Target velocity: %.3f %.3f %.3f\n",unpack(targetvel)) for i=1,#params do local paramstr = string.format('%s : %.2f\n', params[i][1],params[i][2]*params[i][3]) if i==selected_param then paramstr = util.color(paramstr,'green') end outstring=outstring..paramstr end print(outstring) end while 1 do show_status() process_keyinput(); --why nonblocking reading does not work? end
local codec = require('codec') local src = '123456' local privpem = [[-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAwZesbRwWydkPJV9KjDa+OJi5KKBgX8c63GxQORh33mZS+TT/ brp++IVhB0mIqSDtZFoagigXWTe5maQEsJAAivseVwRopWq+ZtmNt6CpPksAsv5w F7MYKmAZuj8TKaNmhwnzkExZPDIPGJgov+njsfD1CRwiT1JOcy1zd4T1Bdo4UPjb zYIBjchUPSO7MzFjRmCEsZ3I8k9M7jrEJtsbVv2IJ6vd6tASqNoT3zxmk5RxUE7v jjgQ9nm2IYS9KQtikkj39YkqnqVdVcfWIJ1HNh23/44SXUvS/nL++kChMAUbuXeP C9gcdS+0fJE8qHlCVWUS21vWtNZrHI9lAEl7XwIDAQABAoIBAF/vZt4nJk/exfey MkIrurZXUKKGX1v3Yf7rmhHBQ12t/X5Lui1INDW5+yxeT1/o1lt9n1dSwMdQqyQt OLm6ktpMuWtL3wPiUvqq4uTVtCkPiAgruKa19MrDFtzJ9xgSRnOzBcVDYJFJCVwZ w0/fexuqGfPqwkHmusOvCWJ4O+gqrx/WTt6ajCUr7oSb0Y46ELYDJYAVsuv/G7b3 ExDtyQ88I+mXJy1QNkcaQ/l/EhIDhfEospUK6M0rzc3IlmSIY9KO6u6PcxAJ2ox2 2KYh+PC4M7UOvnP/7FNhBA7EqajDBLPP/GQZursBm18+0IJ7JJKL2wOa3EGXnIrv atFkLQECgYEA9r/AyPnZcdUViXNBKF9fj9WAy4YzNMPqo0GUYHPNSpfjHUfJwPTa k06U2TO4sttFr99lyAvmIOexzK6/jReTHT0w3FmuBpaDBKC3nJxy7iLpHASH6aZb mDgVhclIsiVw4JHylpaucW2n4TlKJxIz0DdNt3Dv1C313zGTiff7/4ECgYEAyNm8 EX7O0zazGBiOwfLbJL+Q6PeebAe4r0U5rn8X++Mj8j4sWC+r7Oi1+NROWUqODW5N 8y3e9vxe2KNg6b9cCGy6W34iz7l9uUX22569hYTct06hVHbp68gs5+cYjFVSzXqE SHzvGDRC162cdCiu//s7P+TuyBsn6eWLkkE66t8CgYB8t30U2BxNCfvhxmyHoHUn uS1pMYKOR/w/2jTJ754y9sRnl1Jlgh08WXqoshjH5ka51zuVulXuCc33e9f704+b NsOMjJOGZusAGs/Ti8wXi3OxoqSjt18SeD6AqbVhvcTo7TvlW3H+iQNStmdBilTA CEPy1VWTNEvTLTa6hKpNgQKBgFfkaFdjnZByJGdL/9TBuMJZDknUakAuFNSmP3qr 5Uv19vn/2RnyKpMutssf5PVQGd+owHXFQgflIoA85qEDe3u4UMjO5t7t9iWIh2FO EvOF06xnvVOgAfeLDpOg3m4yvFxs28x414xI+mM1dvyh/QrJ3wCz5wYsVAgXyj8D SowTAoGBAMIIULP3lpxzga+CkneuWxeh9L5ZD2hEdhnLvQFPP30o4wezW0dAUGNa zX+7zfFpxp4nwtioYIKzBXAACm8eedEENPDRL4vgvVaW13E8YM2tvGk5BWowPlC5 flYUaiUILjveZDOawmy6Pvsj3vkzyaztJHHK/kwB0kH6qWGM+Aq0 -----END RSA PRIVATE KEY-----]] local bs = codec.rsa_private_sign_sha256withrsa(src, privpem) local sign = codec.base64_encode(bs) print(sign) local dbs = codec.base64_decode(sign) local pubpem = [[-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwZesbRwWyd kPJV9KjDa+OJi5KKBgX8c63GxQORh33mZS+TT/brp++IVhB0mIqSDt ZFoagigXWTe5maQEsJAAivseVwRopWq+ZtmNt6CpPksAsv5wF7MYKm AZuj8TKaNmhwnzkExZPDIPGJgov+njsfD1CRwiT1JOcy1zd4T1Bdo4 UPjbzYIBjchUPSO7MzFjRmCEsZ3I8k9M7jrEJtsbVv2IJ6vd6tASqN oT3zxmk5RxUE7vjjgQ9nm2IYS9KQtikkj39YkqnqVdVcfWIJ1HNh23 /44SXUvS/nL++kChMAUbuXePC9gcdS+0fJE8qHlCVWUS21vWtNZrHI 9lAEl7XwIDAQAB -----END PUBLIC KEY-----]] local ok = codec.rsa_public_verify_sha256withrsa(src, dbs, pubpem, 2) print(ok) assert(ok)
----------------------------------------------------------------------------- -- Fastcgi WSAPI handler -- -- Author: Fabio Mascarenhas -- Copyright (c) 2007 Kepler Project -- ----------------------------------------------------------------------------- local lfcgi = require"lfcgi" local os = require"os" local io = require"io" local common = require"wsapi.common" local ipairs = ipairs local _M = {} io.stdout = lfcgi.stdout io.stderr = lfcgi.stderr io.stdin = lfcgi.stdin -- Runs an WSAPI application for each FastCGI request that comes -- from the FastCGI pipeline function _M.run(app_run) while lfcgi.accept() >= 0 do local headers local function getenv(n) if n == "headers" then if headers then return headers end local env_vars = lfcgi.environ() headers = {} for _, s in ipairs(env_vars) do local name, val = s:match("^([^=]+)=(.*)$") headers[name] = val end return headers else return lfcgi.getenv(n) or os.getenv(n) end end common.run(app_run, { input = lfcgi.stdin, output = lfcgi.stdout, error = lfcgi.stderr, env = getenv }) end end return _M
-- stylua: ignore start function simple_function(a) local test = 1 local test_other = 11 print("simple_function test_other:", vim.inspect(test_other)) for idx = test - 1, test_other do print(idx, a) end end
require 'torch' require 'image' --[[ Reads a flow field from a binary flow file. bytes contents 0-3 tag: "PIEH" in ASCII, which in little endian happens to be the float 202021.25 (just a sanity check that floats are represented correctly) 4-7 width as an integer 8-11 height as an integer 12-end data (width*height*2*4 bytes total) --]] local function flowFileLoader_load(fileName) local flowFile = torch.DiskFile(fileName, 'r') flowFile:binary() flowFile:readFloat() local W = flowFile:readInt() local H = flowFile:readInt() -- image.warp needs 2xHxW, and also expects (y, x) for some reason... local flow = torch.Tensor(2, H, W) local raw_flow = torch.data(flow) local elems_in_dim = H * W local storage = flowFile:readFloat(2 * elems_in_dim) for y=0, H - 1 do for x=0, W - 1 do local shift = y * W + x raw_flow[elems_in_dim + shift] = storage[2 * shift + 1] raw_flow[shift] = storage[2 * shift + 2] end end flowFile:close() return flow end return { load = flowFileLoader_load }
local lizards = require("lizards") local layouts = lizards.layouts_t(lizards.FORMAT_FILE_JS, "../LAYOUT.JS"); local template = lizards.template_t(layouts, lizards.FORMAT_FILE_JS, "../CUST2.JS"); local grid = template:realize(); local output = grid:output(); output:svg('layout.svg', 0); -- $template->setactive('04'); -- $template->save('test.js');
-- =========================== -- BUBBLY.NVIM COC.NVIM BUBBLE -- =========================== -- Created by: datwaft [github.com/datwaft] local bubble_factory = require'bubbly.factories.bubble' return function(inactive) if inactive then return '' end local info = vim.b.coc_diagnostic_info if info == nil or next(info) == nil then return '' end return bubble_factory{ { data = info.error ~= 0 and vim.g.bubbly_symbols.coc.error .. info.error, color = vim.g.bubbly_colors.coc.error, style = vim.g.bubbly_styles.coc.error, }, { data = info.warning ~= 0 and vim.g.bubbly_symbols.coc.warning .. info.warning, color = vim.g.bubbly_colors.coc.warning, style = vim.g.bubbly_styles.coc.warning, }, { data = vim.g.coc_status, color = vim.g.bubbly_colors.coc.status, style = vim.g.bubbly_styles.coc.status, }, } end
ITEM.name = "Cheeze Burger" ITEM.model = "models/food/burger.mdl" ITEM.hungerAmount = 100 ITEM.foodDesc = "A Big Cheeze Burger." ITEM.quantity = 1 ITEM.price = 10 ITEM.iconCam = { ang = Angle(11.135420799255, 269.24069213867, 0), fov = 2.3069860161324, pos = Vector(2.5959460735321, 193.05519104004, 52.177997589111) }
-- Configuration function love.conf(t) t.title = [[B.F. Skinner: Pigeon Herder (LEGITIMATE PIGEON SIMULATOR)]] t.version = "0.10.0" -- This is just the initial window size; it is readjusted in main.lua t.window = { width = 640, height = 480, } -- For Windows debugging t.console = true end
--====================================== --Thlib --====================================== ---------------------------------------- --加载脚本 Include'THlib\\misc\\misc.lua' Include'THlib\\se\\se.lua' Include'THlib\\music\\music.lua' Include'THlib\\item\\item.lua' Include'THlib\\player\\player.lua' Include'THlib\\player\\playersystem.lua' Include'THlib\\enemy\\enemy.lua' Include'THlib\\bullet\\bullet.lua' Include'THlib\\laser\\laser.lua' Include'THlib\\background\\background.lua' Include'THlib\\ext.lua' Include'THlib\\ui\\menu.lua' Include'THlib\\editor.lua' Include'THlib\\ui\\ui.lua' Include'ex\\javastage.lua' Include'ex\\crazystorm.lua' Include'ex\\system.lua' Include'ex\\systems\\act7\\system_act7.lua' --在autorun文件夹下面的lua脚本会自动执行,加载时机为data和mod之间,可能会被mod里面的定义覆盖 local function autorun() local r=FindFiles('autorun\\','lua') for i,v in pairs(r) do local filename=v[1] local packname=v[2] Print('自动加载',filename) Include(''..filename) end end autorun()
-- Singleton Class made by Jusonex (Justus), Permission Granted cSingleton = {} cSingleton.__singletonObjects = {} function cSingleton:derived_constructor() self:init() end function cSingleton:init() end function cSingleton:getInstance(...) if not(self.__singletonObjects[self]) then outputConsole("Singleton not availabe, creating "..tostring(self)) return self:new(...) end return self.__singletonObjects[self] end function cSingleton:isInitialized() return self.__singletonObjects[self] ~= nil end function cSingleton:new(...) if (self.__singletonObjects[self]) then self.__singletonObjects[self] = delete(self) self.__singletonObjects[self] = nil end local obj = {...} self.__singletonObjects[self] = new(self, ...) return self.__singletonObjects[self] end
require "libs.control.entityId" require "libs.logging" -- -------------------------------- -- API V3 -- -------------------------------- --[[ Data used: global.schedule[tick][idEntity] = { entity = $entity, [noTick = true], -- no entity update - used when entity is premined (to remove asap) [clearSchedule = true], -- used when entity is premined (to clear out of ordinary schedule) } global.entityData[idEntity] = { name=$name, ... } global.entities_cleanup_required = boolean(check and remove all old events) global.entityDataVersion = 4 Register custom entity build, tick or remove function: [$entityName] = { build = function(entity, player=nil):dataArr, if returned arr is nil no data is registered (no remove will be called later) Note: tick your entity with scheduleAdd(entity,TICK_SOON) Note: player is empty if this is built by a robot tick = function(entity,data):(nextTick,reason), premine = function(entity,data,player?):manuallyHandle if manuallyHandle is true entity will not be added to schedule (tick for removal) Note: player is empty if removed by a robot orderDeconstruct = function(entity,data,player) remove = function(data), clean up any additional entities from your custom data die = function(entity,data), clean up any additional entities from your custom data, spill items on the floor rotate = function(entity,data), called when an entity is rotated by the player copy = function(source,srcData,target,targetData) coppy settings when shift+rightclick -> shift+leftclick (called on the source entity) copyTo = function(source,srcData,target,targetData) coppy settings when shift+rightclick -> shift+leftclick (called on the target entity) move = function(entity,data,player,start_pos) Called when pickerDolly moves an entity. The method should do the required afterwork to make sure everything works. If the method is not implemented moving the entity will be prevented } Required calls in control: entities_init() entities_load() entities_build(event) entities_tick() entities_pre_mined(event) entities_died(event) entities_rotate(event) entities_settings_pasted(event) entities_marked_for_deconstruction(event) ]]-- entities = {} -- Constants: TICK_ASAP = 0 --game.tick used in migration when game variable is not available yet TICK_SOON = 1 --game.tick used in cleanup when entity should be schedule randomly in next 1s -- ------------------------------------------------- -- init -- ------------------------------------------------- function entities_init() if global.schedule == nil then global.schedule = {} global.entityData = {} global.entityDataVersion = 4 end entities_migration() end function entities_migration() if not global.entityDataVersion then entities_migration_V3() global.entityDataVersion = 3 info("Migrated entity data to v3") end if global.entityDataVersion < 4 then entities_migration_V4() global.entityDataVersion = 4 info("Migrated entity data to v4") end end function entities_load() if remote.interfaces["picker"] and remote.interfaces["picker"]["dolly_moved_entity_id"] then script.on_event(remote.call("picker", "dolly_moved_entity_id"), entities_move) end end -- ------------------------------------------------- -- Copying settings -- ------------------------------------------------- -- Event table contains: -- player_index, The index of the player who moved the entity -- moved_entity, The entity that was moved -- start_pos, The position that the entity was moved from function entities_move(event) local entity = event.moved_entity local name = entity.name if entities[name] ~= nil then if entities[name].move ~= nil then local startPos = event.start_pos local oldId = idOfPosition(entity.surface.index,startPos.x,startPos.y,entity.name) -- update schedule list for tick,list in pairs(global.schedule) do if list[oldId] ~= nil then local scheduledEvent = list[oldId] list[oldId] = nil list[idOfEntity(entity)] = scheduledEvent end end -- update data local data = global.entityData[oldId] info("data while moving: "..serpent.block(data).." for "..idOfEntity(entity)) global.entityData[oldId] = nil global.entityData[idOfEntity(entity)] = data entities[name].move(entity,data,player,startPos) else info("Entity "..name.." does not support dolly-moving") entity.teleport(event.start_pos) end end end -- ------------------------------------------------- -- Copying settings -- ------------------------------------------------- function entities_settings_pasted(event) local source = event.source local target = event.destination if entities[source.name] ~= nil then if entities[source.name].copy ~= nil then local srcData = global.entityData[idOfEntity(source)] local targetData = global.entityData[idOfEntity(target)] entities[source.name].copy(source,srcData,target,targetData) end end if entities[target.name] ~= nil then if entities[target.name].copyTo ~= nil then local srcData = global.entityData[idOfEntity(source)] local targetData = global.entityData[idOfEntity(target)] entities[target.name].copyTo(source,srcData,target,targetData) end end end -- ------------------------------------------------- -- Updating Entities -- ------------------------------------------------- function entities_tick() -- schedule events from migration if global.schedule[TICK_ASAP] ~= nil then if global.schedule[game.tick] == nil then global.schedule[game.tick] = {} end for id,arr in pairs(global.schedule[TICK_ASAP]) do --info("scheduled entity "..id.." for now.") global.schedule[game.tick][id] = arr end global.schedule[TICK_ASAP] = nil end if global.schedule[TICK_SOON] ~= nil then for id,arr in pairs(global.schedule[TICK_SOON]) do local nextTick = game.tick + math.random(60) if global.schedule[nextTick] == nil then global.schedule[nextTick] = {} end global.schedule[nextTick][id] = arr end global.schedule[TICK_SOON] = nil end if global.entities_cleanup_required then entities_cleanup_schedule() global.entities_cleanup_required = false end -- if no updates are scheduled return if global.schedule[game.tick] == nil then return end -- Execute all scheduled events local entityIdsToClear = {} for entityId,arr in pairs(global.schedule[game.tick]) do local entity = arr.entity if entity and entity.valid then if not arr.noTick then local data = global.entityData[entityId] local name = entity.name local nextUpdateInXTicks, reasonMessage if entities[name] ~= nil then if entities[name].tick ~= nil then nextUpdateInXTicks, reasonMessage = entities[name].tick(entity,data) end else warn("updating entity with unknown name: "..name) end if reasonMessage then info(name.." at " .. entity.position.x .. ", " ..entity.position.y .. ": "..reasonMessage) end if nextUpdateInXTicks then scheduleAdd(entity, game.tick + nextUpdateInXTicks) -- if no more update is scheduled, remove it from memory -- nothing to be done here, the entity will just not be scheduled anymore end end elseif entityId == "text" then game.print(entity) else -- if entity was removed, remove it from memory entities_remove(entityId) if arr.clearSchedule then table.insert(entityIdsToClear,entityId) end end end global.schedule[game.tick] = nil if #entityIdsToClear > 0 then for tick,tickSchedule in pairs(global.schedule) do for _,id in pairs(entityIdsToClear) do tickSchedule[id] = nil end end end end function entities_rotate(event) local entity = event.entity local name = entity.name if entities[name] ~= nil then if entities[name].rotate ~= nil then local entityId = idOfEntity(entity) local data = global.entityData[entityId] entities[name].rotate(entity,data) end end end -- ------------------------------------------------- -- Building Entities -- ------------------------------------------------- function entities_build(event) local entity = event.created_entity or event.entity or event.destination local player = nil if event.player_index ~= nil then player = game.players[event.player_index] end if entity == nil then warn("can't build nil entity") return false end local name = entity.name if entities[name] == nil then return false end if entities[name].build then local data = entities[name].build(entity, player) if data ~= nil then data.name = name global.entityData[idOfEntity(entity)] = data return true else info("built entity doesn't use data: "..name) end else warn("no build method available for entity "..name) end return false end -- ------------------------------------------------- -- Premining / deconstruction -- ------------------------------------------------- function entities_pre_mined(event) -- { entity Lua/Entity, name = 9, player_index = 1, tick = 96029 } local entity = event.entity local name = entity.name if entities[name] == nil then return end local manuallyHandle = false if entities[name].premine and event.player_index ~= nil then local data = global.entityData[idOfEntity(entity)] manuallyHandle = entities[name].premine(entity,data,game.players[event.player_index]) elseif entities[name].premine then local data = global.entityData[idOfEntity(entity)] manuallyHandle = entities[name].premine(entity,data,nil) end if not manuallyHandle then local checkEntity = scheduleAdd(entity,TICK_ASAP) checkEntity.noTick = true checkEntity.clearSchedule = true end end function entities_died(event) local entity = event.entity local name = entity.name if entities[name] == nil then return end if entities[name].die then local data = global.entityData[idOfEntity(entity)] entities[name].die(entity,data) end local checkEntity = scheduleAdd(entity,TICK_ASAP) checkEntity.noTick = true checkEntity.clearSchedule = true end function entities_marked_for_deconstruction(event) local entity = event.entity local name = entity.name if entities[name] == nil then return end if entities[name].orderDeconstruct then local data = global.entityData[idOfEntity(entity)] entities[name].orderDeconstruct(entity,data,game.players[event.player_index]) end end -- ------------------------------------------------- -- Utility methods -- ------------------------------------------------- function scheduleAdd(entity, nextTick) if entity == nil then err("scheduleAdd can't be called for nil entity") return nil end if global.schedule[nextTick] == nil then global.schedule[nextTick] = {} end --info("schedule added for entity "..entity.name.." "..idOfEntity(entity).." at tick: "..nextTick) local update = { entity = entity } global.schedule[nextTick][idOfEntity(entity)] = update return update end function entities_remove(entityId) local data = global.entityData[entityId] if not data then return end local name = data.name --info("removing entity: "..name.." at: "..entityId.." with data: "..serpent.block(data)) if entities[name] ~= nil then if entities[name].remove ~= nil then entities[name].remove(data) end else warn("removing unknown entity: "..name.." at: "..entityId) -- .." with data: "..serpent.block(data)) end global.entityData[entityId] = nil end function entities_cleanup_schedule() local count = 0 local toSchedule = {} info("starting cleanup. Expect lag... ") for tick,array in pairs(global.schedule) do if tick < game.tick then for entityId,arr in pairs(array) do if arr.entity.valid then if toSchedule[entityId]==nil then info("found valid entity, scheduling it asap: "..entityId) toSchedule[entityId] = arr.entity end else info("found invalid entity, removing it: "..entityId) entities_remove(entityId) end count = count + 1 end global.schedule[tick] = nil end end -- remove all entities that are already scheduled for _,array in pairs(global.schedule) do for entityId,_ in pairs(array) do toSchedule[entityId] = nil end end for _,entity in pairs(toSchedule) do scheduleAdd(entity, TICK_SOON) end info("Cleanup done. Fixed entities "..count) end -- ------------------------------------------------- -- Migration -- ------------------------------------------------- function entities_migration_V4() entities_rebuild_entityIds() end function entities_migration_V3() entities_rebuild_entityIds() end function entities_migration_V2() for tick,arr in pairs(global.schedule) do for id,entity in pairs(arr) do arr[id] = { entity = entity } end end end function entities_rebuild_entityIds() -- rebuild entityId: -- global.schedule[tick][idEntity] = { entity = $entity, [noTick = true] } -- global.entityData[idEntity] = { name=$name, ... } local newSchedule = {} local newEntityData = {} for tick,scheduleList in pairs(global.schedule) do newSchedule[tick] = {} for oldId,scheduleEntry in pairs(scheduleList) do local data = global.entityData[oldId] local entity = scheduleEntry.entity newSchedule[tick][idOfEntity(entity)] = scheduleEntry newEntityData[idOfEntity(entity)] = data end end global.schedule = newSchedule global.entityData = newEntityData end
require 'nn' require 'cudnn' require 'cunn' local function build(nChannels, nOutChannels, type, bottleneck, bnWidth) local net = nn.Sequential() local innerChannels = nChannels bnWidth = bnWidth or 4 if bottleneck == true then innerChannels = math.min(innerChannels, bnWidth * nOutChannels) net:add(cudnn.SpatialConvolution(nChannels, innerChannels, 1,1, 1,1, 0,0)) net:add(cudnn.SpatialBatchNormalization(innerChannels)) net:add(cudnn.ReLU(true)) end if type == 'normal' then net:add(cudnn.SpatialConvolution(innerChannels, nOutChannels, 3,3, 1,1, 1,1)) elseif type == 'down' then net:add(cudnn.SpatialConvolution(innerChannels, nOutChannels, 3,3, 2,2, 1,1)) elseif type == 'up' then net:add(cudnn.SpatialFullConvolution(innerChannels, nOutChannels, 3,3, 2,2, 1,1, 1,1)) else error("Please implement me: " .. type) end net:add(cudnn.SpatialBatchNormalization(nOutChannels)) net:add(cudnn.ReLU(true)) return net end local function build_net_normal(nChannels, nOutChannels, bottleneck, bnWidth) local net_warp = nn.Sequential() local net = nn.ParallelTable() net:add(nn.Identity()) net:add(build(nChannels, nOutChannels, 'normal', bottleneck, bnWidth)) net_warp:add(net):add(nn.JoinTable(2)) return net_warp end local function build_net_down_normal(nChannels1, nChannels2, nOutChannels, bottleneck, bnWidth1, bnWidth2) local net_warpper = nn.Sequential() local net = nn.ParallelTable() assert(nOutChannels % 2 == 0, 'Growth rate invalid!') net:add(nn.Identity()) net:add(build(nChannels1, nOutChannels/2, 'down', bottleneck, bnWidth1)) net:add(build(nChannels2, nOutChannels/2, 'normal', bottleneck, bnWidth2)) net_warpper:add(net):add(nn.JoinTable(2)) return net_warpper end ---------------- --- MSDNet_Layer_first: --- the input layer of MSDNet --- input: a tensor (orginal image) --- output: a table of nScale tensors ---------------- local MSDNet_Layer_first, parent = torch.class('nn.MSDNet_Layer_first', 'nn.Container') function MSDNet_Layer_first:__init(nChannels, nOutChannels, opt) parent.__init(self) self.train = true self.nChannels = nChannels self.nOutChannels = nOutChannels self.opt = opt self.modules = {} -- transform raw input to first layer self.modules[1] = nn.Sequential() if opt.dataset == 'cifar10' or opt.dataset == 'cifar100' then self.modules[1]:add(cudnn.SpatialConvolution(nChannels, nOutChannels*opt.grFactor[1], 3,3, 1,1, 1,1)) self.modules[1]:add(cudnn.SpatialBatchNormalization(nOutChannels*opt.grFactor[1])) self.modules[1]:add(cudnn.ReLU(true)) elseif opt.dataset == 'imagenet' then self.modules[1]:add(cudnn.SpatialConvolution(nChannels,nOutChannels*opt.grFactor[1], 7,7, 2,2, 3,3)) self.modules[1]:add(nn.SpatialBatchNormalization(nOutChannels*opt.grFactor[1])) self.modules[1]:add(cudnn.ReLU(true)) self.modules[1]:add(nn.SpatialMaxPooling(3,3,2,2,1,1)) end local nIn = nOutChannels * opt.grFactor[1] for i = 2, opt.nScales do self.modules[i] = nn.Sequential() self.modules[i]:add(cudnn.SpatialConvolution(nIn, nOutChannels*opt.grFactor[i], 3,3, 2,2, 1,1)) self.modules[i]:add(cudnn.SpatialBatchNormalization(nOutChannels*opt.grFactor[i])) self.modules[i]:add(cudnn.ReLU(true)) nIn = nOutChannels*opt.grFactor[i] end self.gradInput = torch.CudaTensor() self.output = {} end function MSDNet_Layer_first:updateOutput(input) for i = 1, self.opt.nScales do self.output[i] = self.output[i] or input.new() local tmp_input = (i==1) and input or self.output[i-1] local tmp_output = self:rethrowErrors(self.modules[i], i, 'updateOutput', tmp_input) self.output[i]:resizeAs(tmp_output):copy(tmp_output) end return self.output end function MSDNet_Layer_first:updateGradInput(input, gradOutput) self.gradInput = self.gradInput or input.new() self.gradInput:resizeAs(input):zero() for i = self.opt.nScales-1, 1, -1 do gradOutput[i]:add(self.modules[i+1]:updateGradInput(self.output[i], gradOutput[i+1])) end self.gradInput:resizeAs(input):copy(self.modules[1]:updateGradInput(input, gradOutput[1])) return self.gradInput end function MSDNet_Layer_first:accGradParameters(input, gradOutput, scale) scale = scale or 1 for i = self.opt.nScales, 2, -1 do self.modules[i]:accGradParameters(self.output[i-1], gradOutput[i], scale) end self.modules[1]:accGradParameters(input, gradOutput[1], scale) end function MSDNet_Layer_first:__tostring__() local tab = ' ' local line = '\n' local next = ' |`-> ' local lastNext = ' `-> ' local ext = ' | ' local extlast = ' ' local last = ' ... -> ' local str = 'MSDNet_Layer_first' str = str .. ' {' .. line .. tab .. '{input}' for i=1,#self.modules do if i == #self.modules then str = str .. line .. tab .. lastNext .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast) else str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext) end end str = str .. line .. tab .. last .. '{output}' str = str .. line .. '}' return str end ---------------- --- MSDNet_Layer (without upsampling): --- subsequent layers of MSDNet --- input: a table of `nScales` tensors --- output: a table of `nScales` tensors ---------------- local MSDNet_Layer, parent = torch.class('nn.MSDNet_Layer', 'nn.Container') function MSDNet_Layer:__init(nChannels, nOutChannels, opt, inScales, outScales) parent.__init(self) self.train = true self.nChannels = nChannels self.nOutChannels = nOutChannels self.opt = opt self.inScales = inScales or opt.nScales self.outScales = outScales or opt.nScales self.nScales = opt.nScales self.discard = self.inScales - self.outScales assert(self.discard<=1, 'Double check inScales'..self.inScales..'and outScales: '..self.outScales) local offset = self.nScales - self.outScales self.modules = {} local isTrans = self.outScales<self.inScales if isTrans then local nIn1, nIn2, nOut = nChannels*opt.grFactor[offset], nChannels*opt.grFactor[offset+1], opt.grFactor[offset+1]*nOutChannels self.modules[1] = build_net_down_normal(nIn1, nIn2, nOut, opt.bottleneck, opt.bnFactor[offset], opt.bnFactor[offset+1]) else self.modules[1] = build_net_normal(nChannels*opt.grFactor[offset+1], opt.grFactor[offset+1]*nOutChannels, opt.bottleneck, opt.bnFactor[offset+1]) end for i = 2, self.outScales do local nIn1, nIn2, nOut = nChannels*opt.grFactor[offset+i-1], nChannels*opt.grFactor[offset+i], opt.grFactor[offset+i]*nOutChannels self.modules[i] = build_net_down_normal(nIn1, nIn2, nOut, opt.bottleneck, opt.bnFactor[offset+i-1], opt.bnFactor[offset+i]) end self.real_input = {} self.gradInput = {} self.gIn = {} self.output = {} self.modules = self.modules end function MSDNet_Layer:updateOutput(input) local discard = self.discard if self.inScales == self.outScales then self.real_input[1] = {input[1], input[1]} for i = 2, self.outScales do self.real_input[i] = {input[i], input[i-1], input[i]} end else for i = 1, self.outScales do -- !!! self.real_input[i] = {input[discard+i], input[discard+i-1], input[discard+i]} end end for i = 1, self.outScales do self.output[i] = self:rethrowErrors(self.modules[i], i, 'updateOutput', self.real_input[i]) end return self.output end function MSDNet_Layer:updateGradInput(input, gradOutput) -- self.gradInput = self.gradInput or {} local offset = self.offset self.gIn = self.gIn or {} for i = 1, self.inScales do self.gradInput[i] = self.gradInput[i] or input[i].new() end for i = 1, self.outScales do self.gIn[i] = self.modules[i]:updateGradInput(self.real_input[i], gradOutput[i]) end if self.inScales == self.outScales then if self.outScales == 1 then self.gradInput[1]:resizeAs(self.gIn[1][1]):copy(self.gIn[1][1]) :add(self.gIn[1][2]) else self.gradInput[1]:resizeAs(self.gIn[1][1]):copy(self.gIn[1][1]) :add(self.gIn[1][2]):add(self.gIn[2][2]) end for i = 2, self.inScales-1 do self.gradInput[i]:resizeAs(self.gIn[i][1]):copy(self.gIn[i][1]) :add(self.gIn[i][3]):add(self.gIn[i+1][2]) end else self.gradInput[1]:resizeAs(self.gIn[1][2]):copy(self.gIn[1][2]) for i = 2, self.inScales - 1 do self.gradInput[i]:resizeAs(self.gIn[i-1][1]):copy(self.gIn[i-1][1]) :add(self.gIn[i-1][3]):add(self.gIn[i][2]) end end if self.inScales > 1 then self.gradInput[self.inScales]:resizeAs(self.gIn[self.outScales][1]) :copy(self.gIn[self.outScales][1]):add(self.gIn[self.outScales][3]) end return self.gradInput end function MSDNet_Layer:accGradParameters(input, gradOutput, scale) scale = scale or 1 for i = 1, self.outScales do self.modules[i]:accGradParameters(self.real_input[i], gradOutput[i], scale) end end function MSDNet_Layer:clearState() -- don't call set because it might reset referenced tensors local function clear(f) if self[f] then if torch.isTensor(self[f]) then self[f] = self[f].new() elseif type(self[f]) == 'table' then self[f] = {} else self[f] = nil end end end clear('output') clear('gradInput') clear('real_input') clear('gIn') if self.modules then for i,module in pairs(self.modules) do module:clearState() end end return self end function MSDNet_Layer:__tostring__() local tab = ' ' local line = '\n' local next = ' |`-> ' local lastNext = ' `-> ' local ext = ' | ' local extlast = ' ' local last = ' ... -> ' local str = 'MSDNet_Layer' str = str .. ' {' .. line .. tab .. '{input}' for i = 1,#self.modules do if i == #self.modules then str = str .. line .. tab .. lastNext .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast) else str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext) end end str = str .. line .. tab .. last .. '{output}' str = str .. line .. '}' return str end
mapdata = {} mapdata.__index = mapdata mapdata.__metatable = "None of your business" function mapdata:new() local t = { data = { tile_index = {}, tile_modifier = {} } } return setmetatable(t,mapdata) end function mapdata.addindex(self,d) table.insert(self.data.tile_index,d) end function mapdata.addmodifier(self,d,extra,t) -- d : data , extra : extra data ? : t extra data in table ( ALWAYS a table ) local data = { data = d, additional_data = t } table.insert(self.data.tile_modifier,data) end
object_tangible_tcg_series8_instant_travel_terminal_slave1 = object_tangible_tcg_series8_shared_instant_travel_terminal_slave1:new { } ObjectTemplates:addTemplate(object_tangible_tcg_series8_instant_travel_terminal_slave1, "object/tangible/tcg/series8/instant_travel_terminal_slave1.iff")
DLCore.Commands = {} DLCore.Commands.List = {} DLCore.Commands.Add = function(name, help, arguments, argsrequired, callback, permission) -- [name] = command name (ex. /givemoney), [help] = help text, [arguments] = arguments that need to be passed (ex. {{name="id", help="ID of a player"}, {name="amount", help="amount of money"}}), [argsrequired] = set arguments required (true or false), [callback] = function(source, args) callback, [permission] = rank or job of a player DLCore.Commands.List[name:lower()] = { name = name:lower(), permission = permission ~= nil and permission:lower() or "user", help = help, arguments = arguments, argsrequired = argsrequired, callback = callback, } end DLCore.Commands.Refresh = function(source) local Player = DLCore.Functions.GetPlayer(tonumber(source)) if Player ~= nil then for command, info in pairs(DLCore.Commands.List) do if DLCore.Functions.HasPermission(source, "god") or DLCore.Functions.HasPermission(source, DLCore.Commands.List[command].permission) then TriggerClientEvent('chat:addSuggestion', source, "/"..command, info.help, info.arguments) end end end end
local entry_display = require("telescope.pickers.entry_display") local gh_make_entry = {} function gh_make_entry.gen_from_run(opts) opts = opts or {} local icons = { failed = "X", success = "✓", working = "-", cancelled = "C", } local displayer = entry_display.create({ separator = "|", items = { { width = 2 }, { width = 40 }, { width = 12 }, { remaining = true }, }, }) local status_map = { ["success"] = { icon = icons.success, hl = "TelescopeResultsDiffAdd" }, ["failure"] = { icon = icons.failed, hl = "TelescopeResultsDiffDelete" }, ["startup_failure"] = { icon = icons.failed, hl = "TelescopeResultsDiffDelete" }, ["active"] = { icon = icons.working, hl = "TelescopeResultsDiffChange" }, ["cancelled"] = { icon = icons.cancelled, hl = "TelescopeResultsDiffDelete" }, } local make_display = function(entry) local status_x = {} if entry.active ~= "completed" then status_x = status_map["active"] else status_x = status_map[entry.status] or {} end local empty_space = "" return displayer({ { status_x.icon or empty_space, status_x.hl }, entry.value, entry.workflow, entry.branch, entry.id, }) end return function(entry) if entry == "" then return nil end local tmp_table = vim.split(entry, "\t") local active = tmp_table[1] or "" local status = tmp_table[2] or "" local description = tmp_table[3] or "" local workflow = tmp_table[4] or "" local branch = tmp_table[5] or "" local id = "" if #tmp_table > 8 then id = tmp_table[7] else id = tmp_table[#tmp_table] end return { value = description, active = active, status = status, workflow = workflow, branch = branch, id = id, ordinal = entry, display = make_display, } end end function gh_make_entry.gen_from_gist(opts) opts = opts or {} local displayer = entry_display.create({ separator = "|", items = { { width = 40 }, { width = 2 }, { width = 6 }, { remaining = true }, }, }) local make_display = function(entry) return displayer({ entry.value, entry.files, entry.visibility, entry.age, entry.id, }) end return function(entry) if entry == "" then return nil end local tmp_table = vim.split(entry, "\t") local id = tmp_table[1] or "" local description = tmp_table[2] or "" local files = tmp_table[3] or "" local visibility = tmp_table[4] or "" local age = tmp_table[5] or "" return { age = age, display = make_display, files = files, id = id, ordinal = entry, value = description, visibility = visibility, } end end function gh_make_entry.gen_from_secret(opts) opts = opts or {} -- TODO: pass secret type, so far only repository supported local icons = { repository = "R", environment = "E", organization = "O", user = "U", } local status_map = { ["repository"] = { icon = icons.repository, hl = "TelescopeResultsDiffAdd" }, ["environment"] = { icon = icons.failed, hl = "TelescopeResultsDiffUntracked" }, ["organization"] = { icon = icons.failed, hl = "TelescopeResultsDiffDelete" }, ["user"] = { icon = icons.working, hl = "TelescopeResultsDiffChange" }, } local displayer = entry_display.create({ separator = "|", items = { { width = 2 }, { width = 40 }, { remaining = true }, }, }) local status_x = {} if opts.environment then status_x = status_map["environment"] elseif opts.organization then status_x = status_map["organization"] elseif opts.user then status_x = status_map["user"] else status_x = status_map["repository"] end local make_display = function(entry) return displayer({ { status_x.icon or " ", status_x.hl }, entry.value, entry.age, }) end return function(entry) if entry == "" then return nil end local tmp_table = vim.split(entry, "\t") local name = tmp_table[1] or "" local age = tmp_table[2] or "" return { display = make_display, age = age, value = name, ordinal = entry, } end end return gh_make_entry
local config = require("config") local utils = require("utils") local otii_utils = require("otii_utils") local env_managers_name = utils.get_env_managers_name() return { resource_definitions = function(definitions_params) local settings = function(resource_object) resource_object:set_data_value("turboredis_timeout", 15) resource_object:set_data_value("redfish_redis_key_prefix", { string.format("Redfish:%s:%s:%s", "Managers", env_managers_name, "NtpService"), }) resource_object:set_data_value("redfish_resource_uri_pattern", { string.format("^%s/Managers/([^/]+)/NtpService$", config.SERVICE_PREFIX), }) resource_object:set_data_value("redfish_resource_superordinate", { "ManagersInstance", }) resource_object:set_data_value("redfish_resource_subordinate", nil) end return { settings = settings, } end, property_definitions = function(definitions_params) local endpoint_settings = { ["ServiceEnabled"] = function(property_object) property_object:set_data_value("redis_lua_access_cache_enabled", false) property_object:set_data_value("redis_lua_access_prehook", { GET = function(prehook_params) prehook_params.pl:get(string.format("%s:ServiceEnabled", prehook_params.redis_key_prefix)) end, }) property_object:set_data_value("redis_lua_access_posthook", { GET = function(posthook_params) return otii_utils.toboolean(posthook_params.pl_replies[1]) end, }) property_object:set_data_value("readonly", false) property_object:set_data_value("property_type", {"boolean"}) property_object:set_data_value("turboredis_access_prehook", { PATCH = function(prehook_params) if prehook_params.request_body_value ~= nil then prehook_params.pl:set(string.format("PATCH:%s", prehook_params.redis_key_prefix), prehook_params.request_body_value) table.insert(prehook_params.redis_keys_to_watch, string.format("PATCH_FINISH:%s", prehook_params.redis_key_prefix)) end end, }) end, } return { endpoint_settings = endpoint_settings, } end, operation_definitions = function(definitions_params) local operation = { GET = function(operations_params) local response_body = operations_params.response_body local db_access_clients = operations_params.db_access_clients local response_data = db_access_clients:redis_lua_access() utils.copy_table_endpoint(response_body, response_data, {"ServiceEnabled"}) end, } return { operation = operation, } end, }
WINDOW_WIDTH = 1280 WINDOW_HEIGHT = 720 VIRTUAL_WIDTH = 432 VIRTUAL_HEIGHT = 243 PADDLE_SPEED = 200
function fact (n) if n == 0 then return 1 else return n * fact(n-1) end end print("enter a number:") a = io.read("num") -- any string is okay (maybe) print(fact(a))
return { coruwmmm = { acceleration = 0, activatewhenbuilt = true, brakerate = 0, buildangle = 8192, buildcostenergy = 31258, buildcostmetal = 929, builder = false, buildinggrounddecaldecayspeed = 30, buildinggrounddecalsizex = 8, buildinggrounddecalsizey = 8, buildinggrounddecaltype = "coruwmmm_aoplane.dds", buildpic = "coruwmmm.dds", buildtime = 35000, category = "ALL UNDERWATER", collisionvolumeoffsets = "0 0 0", collisionvolumescales = "120 120 120", collisionvolumetype = "Ell", corpse = "dead", damagemodifier = 0.25, description = "Converts upto 1280 Energy to Metal", explodeas = "CRAWL_BLASTSML", footprintx = 5, footprintz = 5, icontype = "building", idleautoheal = 5, idletime = 1800, losemitheight = 31, mass = 1650, maxdamage = 915, maxslope = 16, maxvelocity = 0, minwaterdepth = 15, name = "Underwater Moho Metal Maker", noautofire = false, objectname = "CORUWMMM", radaremitheight = 31, seismicsignature = 0, selfdestructas = "CRAWL_BLAST", sightdistance = 143, turninplaceanglelimit = 140, turninplacespeedlimit = 0, turnrate = 0, unitname = "coruwmmm", usebuildinggrounddecal = true, yardmap = "ooooooooooooooooooooooooo", customparams = { buildpic = "coruwmmm.dds", faction = "CORE", }, featuredefs = { dead = { blocking = true, collisionvolumeoffsets = "0.0 -2.2497558593e-05 -0.0", collisionvolumescales = "60.0 29.4457550049 60.0", collisionvolumetype = "Box", damage = 1371, description = "Underwater Moho Metal Maker Wreckage", energy = 0, featuredead = "heap", footprintx = 5, footprintz = 5, metal = 1237, object = "CORUWMMM_DEAD", reclaimable = true, customparams = { fromunit = 1, }, }, heap = { blocking = false, damage = 1714, description = "Underwater Moho Metal Maker Debris", energy = 0, footprintx = 5, footprintz = 5, metal = 660, object = "5X5A", reclaimable = true, customparams = { fromunit = 1, }, }, }, sfxtypes = { pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { activate = "metlon2", canceldestruct = "cancel2", deactivate = "metloff2", underattack = "warning1", working = "metlrun2", count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, select = { [1] = "metlon2", }, }, }, }
require "resty.nettle.types.ed25519-sha512" local types = require "resty.nettle.types.common" local hogweed = require "resty.nettle.hogweed" local ffi = require "ffi" local ffi_str = ffi.string local ed25519 = {} function ed25519.public_key(pri) if not pri then return nil, "the EdDSA25519 SHA-512 public key cannot be extracted without private key" end if #pri ~= 32 then return nil, "the EdDSA25519 SHA-512 supported private key size is 256 bits" end hogweed.nettle_ed25519_sha512_public_key(types.uint8_t_32, pri) return ffi_str(types.uint8_t_32, 32) end function ed25519.sign(pub, pri, msg) if not pri then return nil, "the EdDSA25519 SHA-512 signing is not possible without private key" end if not pub then local err pub, err = ed25519.public_key(pri) if not pub then return nil, err end end if #pub ~= 32 then return nil, "the EdDSA25519 SHA-512 supported public key size is 256 bits" end if #pri ~= 32 then return nil, "the EdDSA25519 SHA-512 supported private key size is 256 bits" end hogweed.nettle_ed25519_sha512_sign(pub, pri, #msg, msg, types.uint8_t_64) return ffi_str(types.uint8_t_64, 64) end function ed25519.verify(pub, msg, sig) if not pub then return nil, "the EdDSA25519 SHA-512 signature verification is not possible without public key" end if not sig then return nil, "the EdDSA25519 SHA-512 signature verification is not possible without signature" end if #pub ~= 32 then return nil, "the EdDSA25519 SHA-512 supported public key size is 256 bits" end if #sig ~= 64 then return nil, "the EdDSA25519 SHA-512 supported signature size is 512 bits" end if hogweed.nettle_ed25519_sha512_verify(pub, #msg, msg, sig) ~= 1 then return nil, "unable to EdDSA25519 SHA-512 verify" end return true end return ed25519
local BEGIN = 1 local FINISH_CONSTRUCTION = 2 local REQUEST_LOCATION = 3 local AWAIT_RESIDENCE = 6 return { plan = function(char, state) state.state = BEGIN end, perform = function(char, state) if state.state == BEGIN then -- find the closest municipality local site = Site.get_closest(char:get_position(), function(x) return x.type == char:get_race().municipality_type end) if not site then -- there's no where to go, better start our own char:push_task('establish_municipality') state.state = BEGIN return end -- help build the municipality if it is not complete yet char.municipality = site.id char:push_task('construct_site', { site = site.id }) state.state = FINISH_CONSTRUCTION elseif state.state == FINISH_CONSTRUCTION then if char.last_task_result ~= true then return false end state.state = REQUEST_LOCATION elseif state.state == REQUEST_LOCATION then -- when complete, ask for a place to build a home local residence = Site.new() residence.type = Race.get(char.race).residence_type local size = residence:pick_style() local found_space = Site.get(char.municipality):request_space(residence, size) if not found_space then return false end residence:create_initial_build_orders() Site.register(residence) char.residence = residence.id char:push_task('construct_site', { site = residence.id }) state.state = AWAIT_RESIDENCE elseif state.state == AWAIT_RESIDENCE then return char.last_task_result end end }
-- Copyright 2017-2022 Jason Tackaberry -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local rtk = require('rtk.core') local log = require('rtk.log') --- Single-line editable text entry with text selection and copy/paste support. -- -- rtk.Entry implements most (all?) of the usual keyboard shortcuts and UX -- idioms for cursor (`caret`) navigation, selection, and clipboard management, and -- so it should feel relatively intuitive for most users. -- -- Undo is also supported, both programmatically as well as via the default -- user-accessible context menu. -- -- @example -- local entry = box:add(rtk.Entry{icon='18-search', placeholder='Search', textwidth=15}) -- entry.onkeypress = function(self, event) -- if event.keycode == rtk.keycodes.ESCAPE then -- self:clear() -- self:animate{'bg', dst=rtk.Attribute.DEFAULT} -- elseif event.keycode == rtk.keycodes.ENTER then -- self:animate{'bg', dst='hotpink'} -- end -- end -- -- @class rtk.Entry -- @inherits rtk.Widget rtk.Entry = rtk.class('rtk.Entry', rtk.Widget) -- Popup menu created on-demand in _handle_mousedown(). Menu item ids map to -- the corresponding method names. rtk.Entry.static.contextmenu = { {'Undo', id='undo'}, rtk.NativeMenu.SEPARATOR, {'Cut', id='cut'}, {'Copy', id='copy'}, {'Paste', id='paste'}, {'Delete', id='delete'}, rtk.NativeMenu.SEPARATOR, {'Select All', id='select_all'}, } rtk.Entry.register{ --- The current (or desired if setting) value of the text entry (default is the empty -- string). As the user interacts with the entry, this value is updated to reflect -- current state, or you can set the value programmatically via `attr()` one of the -- rtk.Entry-specific methods below. -- -- The value is never nil. If no text is inputted, it is represented by the -- empty string. -- -- @meta read/write -- @type string value = rtk.Attribute{ default='', reflow=rtk.Widget.REFLOW_NONE, calculate=function(self, attr, value, target) -- Ensure value is always a string. return value and tostring(value) or '' end, }, --- Defines the width of the entry widget to hold this many characters based on the -- current `font` when `w` is not defined (default nil). The `w` attribute will -- override `textwidth`. -- @meta read/write -- @type number|nil textwidth = rtk.Attribute{reflow=rtk.Widget.REFLOW_FULL}, --- Optional icon for the left edge of the entry box (default nil). If a string is -- provided, `rtk.Image.icon()` will be called to fetch the image, otherwise an -- `rtk.Image` object can be used directly. -- -- @type rtk.Image|string|nil -- @meta read/write icon = rtk.Attribute{ reflow=rtk.Widget.REFLOW_FULL, calculate=function(self, attr, value, target) if type(value) == 'string' then local icon = self.calc.icon local style = rtk.color.get_icon_style(self.calc.bg or rtk.theme.bg, rtk.theme.bg) if icon and icon.style == style then -- Style didn't change. return icon end local img = rtk.Image.icon(value, style) if not img then img = rtk.Image.make_placeholder_icon(24, 24, style) end return img else return value end end }, --- The opacity of `icon` (default 0.6). -- @meta read/write -- @type number icon_alpha = 0.6, --- The amount of space in pixels between the `icon` and the text (default 5). -- @meta read/write -- @type number spacing = rtk.Attribute{ default=5, reflow=rtk.Widget.REFLOW_FULL }, --- Placeholder text that is drawn with a low opacity as long as `value` is empty (default nil). -- If nil, the placeholder text is not drawn. The color (including opacity) of the placeholder -- is defined by the current theme's @{rtk.themes.entry_placeholder|`entry_placeholder`}. -- @meta read/write -- @type string placeholder = rtk.Attribute{ default=nil, reflow=rtk.Widget.REFLOW_FULL, }, --- Color of text value, which defaults to the theme's @{rtk.themes.text|`text`} value if -- nil (default). -- -- @type colortype|nil -- @meta read/write textcolor = rtk.Attribute{ default=function(self, attr) return rtk.theme.text end, calculate=rtk.Reference('bg') }, --- Color of border when the mouse is `hovering` over the rtk.Entry region, which -- defaults to the theme's @{rtk.themes.entry_border_hover|`entry_border_hover`} -- value if nil (default). -- -- @type colortype|nil -- @meta read/write border_hover = rtk.Attribute{ default=function(self, attr) return {rtk.theme.entry_border_hover, 1} end, reflow=rtk.Widget.REFLOW_FULL, calculate=function(self, attr, value, target) return rtk.Widget.static._calc_border(self, value) end, }, --- Color of border when the widget is `focused`, which defaults to the theme's -- @{rtk.themes.entry_border_focused|`entry_border_focused`} value if nil (default). -- -- @type colortype|nil -- @meta read/write border_focused = rtk.Attribute{ default=function(self, attr) return {rtk.theme.entry_border_focused, 1} end, reflow=rtk.Widget.REFLOW_FULL, calculate=rtk.Reference('border_hover'), }, --- Controls whether the cursor will blink when the widget is focused (default true). -- @type boolean -- @meta read/write blink = true, --- The current caret (or cursor) position which is immediately in front of the -- character defined by this index (default 1). -- @type number -- @meta read/write caret = rtk.Attribute{ type='number', default=1, -- Priority ensures this gets calculated after value, as the caret bounds depends -- on the current value. priority=true, reflow=rtk.Widget.REFLOW_NONE, -- We don't need to reflow, but we do need to redraw. redraw=true, calculate=function(self, attr, value, target) return rtk.clamp(value, 1, #(target.value or '') + 1) end, }, --- The name of the font face (e.g. `'Calibri`'), which uses the @{rtk.themes.entry_font|global -- text entry default} if nil (default nil). -- @type string|nil -- @meta read/write font = rtk.Attribute{ reflow=rtk.Widget.REFLOW_FULL, default=function(self, attr) return self._theme_font[1] end }, --- The pixel size of the entry font (e.g. 18), which uses the @{rtk.themes.entry_font|global -- text entry default} if nil (default nil). -- @type number|nil -- @meta read/write fontsize = rtk.Attribute{ reflow=rtk.Widget.REFLOW_FULL, default=function(self, attr) return self._theme_font[2] end }, --- Scales `fontsize` by the given multiplier (default 1.0). This is a convenient way to adjust -- the relative font size without specifying the exact size. -- @type number -- @meta read/write fontscale = rtk.Attribute{ default=1.0, reflow=rtk.Widget.REFLOW_FULL }, --- A bitmap of @{rtk.font|font flags} to alter the text appearance (default nil). Nil -- (or 0) does not style the font. -- @type number|nil -- @meta read/write fontflags = rtk.Attribute{ default=function(self, attr) return self._theme_font[3] end }, -- -- Widget overrides -- bg = rtk.Attribute{ default=function(self, attr) return rtk.theme.entry_bg end }, tpadding = 4, rpadding = 10, bpadding = 4, lpadding = 10, cursor = rtk.mouse.cursors.BEAM, autofocus = true, } --- Create a new text entry widget with the given attributes. -- @display rtk.Entry function rtk.Entry:initialize(attrs, ...) self._theme_font = rtk.theme.entry_font or rtk.theme.default_font rtk.Widget.initialize(self, attrs, self.class.attributes.defaults, ...) -- Array mapping character index to x offset self._positions = {0} -- Initialized in _reflow() self._backingstore = nil self._font = rtk.Font() self._caretctr = 0 -- Character position where selection was started self._selstart = nil -- Character position where where selection ends (which may be less than or -- greater than the anchor) self._selend = nil -- The left offset in pixels of the rendered text. If this value is e.g. 50, -- it means that the left edge of the backing store corresponds to 50px -- inside the text. self._loffset = 0 self._blinking = false -- If true, the backingstore will be rendered on next _draw() self._dirty_text = false -- If not nil, is the index of the current value attribute that we need to start -- recalculate character positions on next _draw() self._dirty_positions = nil -- If true, we need to run _calcview() on next draw, which may in turn set -- _dirty_text to true if _loffset has changed. self._dirty_view = false -- A table of prior states for ctrl-z undo. Each entry is is an array -- of {text, caret, selstart, selend} self._history = nil self._last_doubleclick_time = 0 self._num_doubleclicks = 0 end function rtk.Entry:_handle_attr(attr, value, oldval, trigger, reflow) local calc = self.calc local ok = rtk.Widget._handle_attr(self, attr, value, oldval, trigger, reflow) if ok == false then return ok end if attr == 'value' then self._dirty_text = true if not self._dirty_positions then -- If this was already set, it's because sync() was called internally and an -- intelligent value was set first. Otherwise, if we're here, the new value -- came from the user. Given the cost of calculating character positions, -- it's worth the effort to loop through the old and new strings to find the -- first difference. local diff = math.min(#value, #oldval) for i = 1, diff do if value:sub(i, i) ~= oldval:sub(i, i) then diff = i break end end self._dirty_positions = diff end -- Updating the text clears selection self._selstart = nil -- After setting value, ensure caret does not extend past end of value. local caret = rtk.clamp(calc.caret, 1, #value + 1) if caret ~= calc.caret then self:sync('caret', caret) end if trigger then self:_handle_change() end elseif attr == 'caret' then -- Ensure we recalculate offset on next draw, which will rerender text -- if necessary. self._dirty_view = true elseif attr == 'bg' and type(self.icon) == 'string' then -- We're (potentially) changing the color but, because the user-provided attribute -- is a string it means we loaded the icon based on its name. Recalculate the icon -- attr so that the light vs dark style gets recalculated based on this new -- background color. self:attr('icon', self.icon, true) elseif attr == 'icon' and value then -- Ensure next reflow calls refresh_scale() on the icon. self._last_reflow_scale = nil end return true end function rtk.Entry:_reflow(boxx, boxy, boxw, boxh, fillw, fillh, clampw, clamph, uiscale, viewport, window) local calc = self.calc local maxw, maxh = nil, nil if self._font:set(calc.font, calc.fontsize, calc.fontscale, calc.fontflags) then -- Font changed, so ensure we recalculate all character positions. self._dirty_positions = 1 end if calc.icon and uiscale ~= self._last_reflow_scale then calc.icon:refresh_scale() self._last_reflow_scale = uiscale end if calc.textwidth and not self.w then -- Compute dimensions based on font and given textwidth. Choose a character -- that's big enough to ensure we can safely support textwidth worth of any -- character. local charwidth, _ = gfx.measurestr('W') maxw, maxh = charwidth * calc.textwidth, self._font.texth else -- No hints given on dimensions, so make something up from whole cloth for our -- intrinsic size. maxw, maxh = gfx.measurestr("Dummy string!") end calc.x, calc.y = self:_get_box_pos(boxx, boxy) local w, h, tp, rp, bp, lp = self:_get_content_size(boxw, boxh, fillw, fillh, clampw, clamph) calc.w = (w or maxw) + lp + rp calc.h = (h or maxh) + tp + bp -- Remember calculated padding as we use that in many functions. self._ctp, self._crp, self._cbp, self._clp = tp, rp, bp, lp -- We use the backingstore to implement left-clipping, which REAPER doesn't natively -- support. if not self._backingstore then self._backingstore = rtk.Image() end self._backingstore:resize(calc.w, calc.h, false) self._dirty_text = true end function rtk.Entry:_unrealize() rtk.Widget._unrealize(self) self._backingstore = nil end -- Measure the x position of each character in the string. This allows us to support -- proportional fonts. function rtk.Entry:_calcpositions(startfrom) startfrom = startfrom or 1 local value = self.calc.value self._font:set() -- Ok, this isn't exactly efficient, but it should be fine for sensibly sized strings. for i = startfrom, #value + 1 do local w, _ = gfx.measurestr(value:sub(1, i)) self._positions[i + 1] = w end self._dirty_positions = nil end function rtk.Entry:_calcview() local calc = self.calc local curx = self._positions[calc.caret] local curoffset = curx - self._loffset local innerw = calc.w - (self._clp + self._crp) if calc.icon then innerw = innerw - (calc.icon.w * rtk.scale.value / calc.icon.density) - calc.spacing end local loffset = self._loffset if curoffset < 0 then loffset = curx elseif curoffset > innerw then loffset = curx - innerw end local last = self._positions[#calc.value+1] if last > innerw then -- The rendered value doesn't fit within our inner width. Ensure we aren't leaving -- any gap on the right of the caret to keep the text right justified. local gap = innerw - (last - loffset) if gap > 0 then loffset = loffset - gap end else -- Last character in value finishes rendering within our inner width, so there's -- no reason we should have any left offset at all. loffset = 0 end -- If the offset changed we need to rerender the backing store. if loffset ~= self._loffset then self._dirty_text = true self._loffset = loffset end self._dirty_view = false end function rtk.Entry:_handle_focus(event, context) local ok = rtk.Widget._handle_focus(self, event, context) -- Force a redraw if there is a selection self._dirty_text = self._dirty_text or (ok and self._selstart) return ok end function rtk.Entry:_handle_blur(event, other) local ok = rtk.Widget._handle_blur(self, event, other) -- Force a redraw if there is a selection self._dirty_text = self._dirty_text or (ok and self._selstart) return ok end function rtk.Entry:_blink() if self.calc.blink and self:focused() then self._blinking = true local ctr = self._caretctr % 16 self._caretctr = self._caretctr + 1 if ctr == 0 then self:queue_draw() end rtk.defer(self._blink, self) end end -- Given absolute coords of the text area, determine the caret position from -- the mouse down event. function rtk.Entry:_caret_from_mouse_event(event) local calc = self.calc local iconw = calc.icon and (calc.icon.w * rtk.scale.value / calc.icon.density + calc.spacing) or 0 local relx = self._loffset + event.x - self.clientx - iconw - self._clp for i = 2, calc.value:len() + 1 do local pos = self._positions[i] local width = pos - self._positions[i-1] if relx <= self._positions[i] - width/2 then return i - 1 end end return calc.value:len() + 1 end local function is_word_break_character(value, pos) local c = value:sub(pos, pos) -- Control characters, punctuation, and whitespace, but excluding underscores. return c ~= '_' and c:match('[%c%p%s]') end function rtk.Entry:_get_word_left(spaces) local value = self.calc.value local caret = self.calc.caret if spaces then while caret > 1 and is_word_break_character(value, caret - 1) do caret = caret - 1 end end while caret > 1 and not is_word_break_character(value, caret - 1) do caret = caret - 1 end return caret end function rtk.Entry:_get_word_right(spaces) local value = self.calc.value local caret = self.calc.caret local len = value:len() while caret <= len and not is_word_break_character(value, caret) do caret = caret + 1 end if spaces then while caret <= len and is_word_break_character(value, caret) do caret = caret + 1 end end return caret end --- Selects all text. function rtk.Entry:select_all() self._selstart = 1 self._selend = self.calc.value:len() + 1 self._dirty_text = true self:queue_draw() end --- Selects a region of text between two character positions. -- -- Each parameter refers to an index within the `value` string, where the first -- character in `value` is index `1`, as usual for Lua. -- -- The range works like Lua's native `string.sub()` in that the range is inclusive (i.e. -- includes the characters at both `a` and `b` indexes), and also suports negative end -- indices, such that -1 refers to the end of the string, -2 is the second last character, -- etc. -- -- @tparam number a the starting character index -- @tparam number b the ending character index (inclusive within the region), or negative to -- slice from the end of the string, where -1 will extend to the end of `value`. function rtk.Entry:select_range(a, b) local len = #self.calc.value if len == 0 or not a then -- Regardless of what was asked, there is nothing to select. self._selstart = nil else b = b or a self._selstart = math.max(1, a) self._selend = b > 0 and math.min(len + 1, b + 1) or math.max(self._selstart, len+b+2) end self._dirty_text = true self:queue_draw() end --- Returns the selection range. -- -- @treturn number the index within `value` of the start of the selection, or nil if nothing -- was selected. -- @treturn number the index within `value` of the end of the selection (inclusive), or nil if nothing -- was selected. function rtk.Entry:get_selection_range() if self._selstart then return math.min(self._selstart, self._selend), math.max(self._selstart, self._selend) end end function rtk.Entry:_edit(insert, delete_selection, dela, delb, caret) local calc = self.calc local value = calc.value if delete_selection then dela, delb = self:get_selection_range() if dela and delb then local ndeleted = delb - dela caret = rtk.clamp(dela, 1, #value) end end caret = caret or calc.caret if dela and delb then dela = rtk.clamp(dela, 1, #value) delb = rtk.clamp(delb, 1, #value+1) value = value:sub(1, dela - 1) .. value:sub(delb) self._dirty_positions = math.min(dela - 1, self._dirty_positions or math.inf) end if insert then self._dirty_positions = math.min(caret - 1, self._dirty_positions or math.inf) value = value:sub(0, caret - 1) .. insert .. value:sub(caret) caret = caret + insert:len() end if value ~= calc.value then caret = rtk.clamp(caret, 1, #value + 1) self:sync('value', value) if caret ~= calc.caret then self:sync('caret', caret) end self._dirty_view = true end end --- Deletes a specific range from the text entry. -- -- The original value is added to undo history. -- -- @tparam number a the starting character index -- @tparam number b the ending character index (inclusive within the region) function rtk.Entry:delete_range(a, b) self:push_undo() self:_edit(nil, nil, a, b) end --- Deletes the current selected range from `value` and resets the selection. -- -- The original value is added to undo history. -- -- @treturn number the number of characters that were deleted from `value`, or -- 0 if there was no selection. function rtk.Entry:delete() if self._selstart then self:push_undo() end self:_edit(nil, true) end --- Erases all contents from the entry. -- -- This is different from directly setting the `value` attribute to the empty string -- in that it also pushes the current value onto the undo history. function rtk.Entry:clear() if self.calc.value ~= '' then self:push_undo() self:sync('value', '') end end --- Copies the selected range to the system clipboard. -- -- The original value is added to undo history. -- -- This uses `rtk.clipboard.set()` and so requires the SWS extension to work properly. -- -- @treturn string|nil the text that was copied to clipboard, or nil if nothing was selected, or -- if the SWS extension isn't available. function rtk.Entry:copy() if self._selstart then local a, b = self:get_selection_range() local text = self.calc.value:sub(a, b - 1) if rtk.clipboard.set(text) then return text end end end --- Copies the selected text to the clipboard and deletes it from `value`, -- resetting the selection. -- -- The original value is added to undo history. -- -- @treturn string|nil the string that was cut from `value`, or nil if nothing -- was selected, or if the SWS extension wasn't available. function rtk.Entry:cut() local copied = self:copy() if copied then self:delete() end return copied end --- Pastes text from the clipboard into the text entry at the current `caret` position. -- -- The original value is added to undo history. -- -- @tparam string|nil the string that was pasted into the text entry, or nil if nothing -- was in the clipboard, or if the SWS extension wasn't available. function rtk.Entry:paste() local str = rtk.clipboard.get() if str and str ~= '' then self:push_undo() self:_edit(str, true) return str end end --- Inserts the given text at the current `caret` position. -- -- The original value is added to undo history. -- -- @tparam string text the text to insert at `caret` function rtk.Entry:insert(text) self:push_undo() self:_edit(text) end --- Reverts to the last state in the undo history. -- -- All APIs that mutate `value` add undo state to the undo history. However, -- individual character presses by the user within the entry do not generate -- undo state. -- -- @treturn boolean true if undo state was restored, or false if there was no -- undo state. function rtk.Entry:undo() local calc = self.calc if self._history and #self._history > 0 then local state = table.remove(self._history, #self._history) local value, caret value, caret, self._selstart, self._selend = table.unpack(state) self:sync('value', value) self:sync('caret', caret) return true else return false end end --- Pushes current state to the undo history for future `undo()`. function rtk.Entry:push_undo() if not self._history then self._history = {} end local calc = self.calc self._history[#self._history + 1] = {calc.value, calc.caret, self._selstart, self._selend} end function rtk.Entry:_handle_mousedown(event) local ok = rtk.Widget._handle_mousedown(self, event) if ok == false then return ok end if event.button == rtk.mouse.BUTTON_LEFT then local caret = self:_caret_from_mouse_event(event) self._selstart = nil self._dirty_text = true self:sync('caret', caret) self:queue_draw() elseif event.button == rtk.mouse.BUTTON_RIGHT then if not self._popup then self._popup = rtk.NativeMenu(rtk.Entry.contextmenu) end local clipboard = rtk.clipboard.get() self._popup:item('undo').disabled = not self._history or #self._history == 0 self._popup:item('cut').disabled = not self._selstart self._popup:item('copy').disabled = not self._selstart self._popup:item('delete').disabled = not self._selstart self._popup:item('paste').disabled = not clipboard or clipboard == '' self._popup:item('select_all').disabled = #self.calc.value == 0 self._popup:open_at_mouse():done(function(item) if item then -- We named menu item ids after method names, so this is a simple dispatcher. self[item.id](self) end end) end return true end function rtk.Entry:_handle_keypress(event) local ok = rtk.Widget._handle_keypress(self, event) if ok == false then return ok end local calc = self.calc local newcaret = nil local len = calc.value:len() local orig_caret = calc.caret local selecting = event.shift if event.keycode == rtk.keycodes.LEFT then if not selecting and self._selstart then newcaret = self._selstart elseif event.ctrl then newcaret = self:_get_word_left(true) else newcaret = math.max(1, calc.caret - 1) end elseif event.keycode == rtk.keycodes.RIGHT then if not selecting and self._selstart then newcaret = self._selend elseif event.ctrl then newcaret = self:_get_word_right(true) else newcaret = math.min(calc.caret + 1, len + 1) end elseif event.keycode == rtk.keycodes.HOME then newcaret = 1 elseif event.keycode == rtk.keycodes.END then newcaret = calc.value:len() + 1 elseif event.keycode == rtk.keycodes.DELETE then if self._selstart then self:delete() else if event.ctrl then self:push_undo() self:_edit(nil, false, calc.caret, self:_get_word_right(true) - 1) elseif calc.caret <= len then self:_edit(nil, false, calc.caret, calc.caret+1) end end elseif event.keycode == rtk.keycodes.BACKSPACE then if calc.caret >= 1 then if self._selstart then self:delete() else if event.ctrl then self:push_undo() local caret = self:_get_word_left(true) self:_edit(nil, false, caret, calc.caret, caret) elseif calc.caret > 1 then local caret = calc.caret - 1 self:_edit(nil, false, caret, caret+1, caret) end end end elseif event.char and not event.ctrl then if self._selstart then self:push_undo() end self:_edit(event.char, true) selecting = false elseif event.ctrl and event.char and not event.shift then if event.char == 'a' and len > 0 then self:select_all() -- Ensure selection doesn't get reset below because shift isn't pressed. selecting = nil elseif event.char == 'c' then self:copy() return true elseif event.char == 'x' then self:cut() elseif event.char == 'v' then self:paste() elseif event.char == 'z' then self:undo() selecting = nil end else return ok end if newcaret then self:sync('caret', newcaret) end if selecting then if not self._selstart then self._selstart = orig_caret end self._selend = calc.caret self._dirty_text = true elseif selecting == false and self._selstart then self._selstart = nil self._dirty_text = true end -- Reset blinker self._caretctr = 0 log.debug2( 'keycode=%s char=%s caret=%s ctrl=%s shift=%s meta=%s alt=%s sel=%s-%s', event.keycode, event.char, calc.caret, event.ctrl, event.shift, event.meta, event.alt, self._selstart, self._selend ) return true end function rtk.Entry:_get_touch_activate_delay(event) if self:focused() then -- If focused, don't delay touch activation, otherwise it frustrates drag-selections. return 0 else return rtk.Widget._get_touch_activate_delay(self, event) end end function rtk.Entry:_handle_dragstart(event) if not self:focused() or event.button ~= rtk.mouse.BUTTON_LEFT then return end -- Superclass method disables dragging so don't call it. local draggable, droppable = self:ondragstart(self, event) if draggable == nil then self._selstart = self.calc.caret self._selend = self.calc.caret return true, false end return draggable, droppable end function rtk.Entry:_handle_dragmousemove(event) local ok = rtk.Widget._handle_dragmousemove(self, event) if ok == false then return ok end local selend = self:_caret_from_mouse_event(event) if selend == self._selend then return ok end self._selend = selend -- This will queue a redraw of the widget. self:sync('caret', selend) -- Ensure text is rerendered as we've changed the selection area. self._dirty_text = true return ok end function rtk.Entry:_handle_click(event) local ok = rtk.Widget._handle_click(self, event) if ok == false or event.button ~= rtk.mouse.BUTTON_LEFT then return ok end if event.time - self._last_doubleclick_time < 0.7 then -- Triple click selects all text self:select_all() self._last_doubleclick_time = 0 elseif rtk.dnd.dragging ~= self then self:select_range(nil) rtk.Widget.focus(self) end return ok end function rtk.Entry:_handle_doubleclick(event) local ok = rtk.Widget._handle_doubleclick(self, event) if ok == false or event.button ~= rtk.mouse.BUTTON_LEFT then return ok end self._last_doubleclick_time = event.time local left = self:_get_word_left(false) local right = self:_get_word_right(true) self:sync('caret', right) self:select_range(left, right-1) return true end function rtk.Entry:_rendertext(x, y) self._font:set() -- Drawing text onto a fully transparent image, and then blending that image over the -- current drawing target looks really janky. There is almost certainly some bug with -- REAPER here. We solve this problem by drawing the region from the current drawing -- target onto our backing store, and then drawing the text on top of that. self._backingstore:blit{ src=gfx.dest, sx=x + self._clp, sy=y + self._ctp, mode=rtk.Image.FAST_BLIT } self._backingstore:pushdest() if self._selstart and self:focused() then local a, b = self:get_selection_range() self:setcolor(rtk.theme.entry_selection_bg) gfx.rect( self._positions[a] - self._loffset, 0, self._positions[b] - self._positions[a], self._backingstore.h, 1 ) end self:setcolor(self.calc.textcolor) self._font:draw(self.calc.value, -self._loffset, 0) self._backingstore:popdest() self._dirty_text = false end function rtk.Entry:_draw(offx, offy, alpha, event, clipw, cliph, cltargetx, cltargety, parentx, parenty) local calc = self.calc -- Must do this before calling rtk.Widget._draw() since we're checking our saved offset. if offy ~= self.offy or offx ~= self.offx then -- If we've scrolled within a viewport since last draw, force _rendertext() to -- repaint the background into the Entry's local backing store. self._dirty_text = true end rtk.Widget._draw(self, offx, offy, alpha, event, clipw, cliph, cltargetx, cltargety, parentx, parenty) local x, y = calc.x + offx, calc.y + offy local focused = self:focused() if (y + calc.h < 0 or y > cliph or calc.ghost) and not focused then -- Widget would not be visible on current drawing target return false end if self.disabled then alpha = alpha * 0.5 end local scale = rtk.scale.value local tp, rp, bp, lp = self._ctp, self._crp, self._cbp, self._clp self:_handle_drawpre(offx, offy, alpha, event) -- Paint background first because _rendertext() will copy to the backing store and -- render the text over top it. self:_draw_bg(offx, offy, alpha, event) if self._dirty_positions then self:_calcpositions(self._dirty_positions) end if self._dirty_view or self._dirty_text then self:_calcview() end if self._dirty_text then self:_rendertext(x, y) end local amul = calc.alpha * alpha local icon = calc.icon if icon then local a = math.min(1, calc.icon_alpha * alpha + (focused and 0.2 or 0)) -- TODO: clip icon:draw( x + lp, y + ((calc.h + tp - bp) - icon.h * scale / icon.density) / 2, a * amul, scale ) lp = lp + icon.w*scale/icon.density + calc.spacing end self._backingstore:blit{ sx=0, sy=0, sw=calc.w - lp - rp, sh=calc.h - tp - bp, dx=x + lp, dy=y + tp, alpha=amul, mode=rtk.Image.FAST_BLIT } if calc.placeholder and #calc.value == 0 then self._font:set() self:setcolor(rtk.theme.entry_placeholder, alpha) self._font:draw(calc.placeholder, x + lp, y + tp, calc.w - lp, calc.h - tp) end if focused then local showcursor = not self._selstart or (self._selend - self._selstart) == 0 if not self._blinking and showcursor then -- Run a "timer" in the background to queue a redraw when the -- cursor needs to blink. self:_blink() end self:_draw_borders(offx, offy, alpha, calc.border_focused) if self._caretctr % 32 < 16 and showcursor then -- Draw caret local curx = x + self._positions[calc.caret] + lp - self._loffset self:setcolor(calc.textcolor, alpha) gfx.line(curx, y + tp, curx, y + calc.h - bp, 0) end else self._blinking = false if self.hovering then self:_draw_borders(offx, offy, alpha, calc.border_hover) else self:_draw_borders(offx, offy, alpha) end end self:_handle_draw(offx, offy, alpha, event) end --- Event Handlers. -- -- See also @{widget.handlers|handlers for rtk.Widget}. -- -- @section entry.handlers --- Called whenever `value` has changed, either by the user changing the value in -- the UI, or when it changes programmatically via the API. -- -- @tparam rtk.Event|nil event an `rtk.Event.KEY` event if available, or nil if -- the entry was changed programmatically. -- @treturn nil Return value has no significance. This is a notification event only. function rtk.Entry:onchange(event) end function rtk.Entry:_handle_change(event) return self:onchange(event) end
object_static_worldbuilding_vegitation_fngi_mushroom_clump_a2 = object_static_worldbuilding_vegitation_shared_fngi_mushroom_clump_a2:new { } ObjectTemplates:addTemplate(object_static_worldbuilding_vegitation_fngi_mushroom_clump_a2, "object/static/worldbuilding/vegitation/fngi_mushroom_clump_a2.iff")
local get_item get_item = function(t, param, key, recursive, result_number, current_found) if t == nil then return nil end recursive = recursive == nil and true or false if result_number == nil then result_number = 1 end if current_found == nil then current_found = 0 end if t[param] == key then return t end for k, _ in ipairs(t) do if t[k][param] == key then current_found = current_found + 1 if current_found >= result_number then return t[k] end end end if not recursive then return nil end local result = nil for _, v in ipairs(t) do if type(v) == 'table' then result = get_item(v, param, key, result_number, current_found) if (result) then current_found = current_found + 1 if current_found >= result_number then return result end end end end return result end local get_item_with_id = function(match, id) return get_item(match, 'id', id) end local id_exists = function(match, id) return get_item(match, 'id', id, false) ~= nil end local get_result = function(generator, match) if match == nil then return nil end local match_id = match.id assert(match_id, string.format("%s:%s malformed object", match_id, match)) -- Hmm... wonder if I could just use _ret_value for a lot of stuff. assert(generator.match[match_id], string.format("%s: missing generator", match_id)) return generator.match[match_id](match) end return { get_item = get_item, get_item_with_id = get_item_with_id, id_exists = id_exists, get_result = get_result, }
modifier_passive_walk = class({}) function modifier_passive_walk:OnCreated(params) if IsServer() then self.direction = Vector(1, 0, 0) self:StartIntervalThink(3.0) end end function modifier_passive_walk:OnIntervalThink() local new_origin = self:GetParent():GetAbsOrigin() + self.direction * 500 self:GetParent():MoveToPosition(new_origin) self.direction = Vector(self.direction.x * -1, self.direction.y, self.direction.z) end
function joinThread(pid) --coroutine.yield("yield", 0) while true do local dead = coroutine.yield("kill") if pid == dead then break end end end function getThreadInfo() local info = {} kernel.modules.threading.eachThread(function(thread) info[thread.pid] = { pid = thread.pid, uid = thread.uid, name = thread.name, parent = thread.parent and thread.parent.pid or nil } end) return info end function userKill(pid, signal, ...) if not kernel.modules.threading.threads[pid] or not kernel.modules.threading.threads[pid].coro then return nil, "Thread does not exists" end if not kernel.modules.threading.threads[pid].kill[signal] then return nil, "Unknown signal" end local args = {...} local thread = kernel.modules.threading.threads[pid] kernel.modules.manageg.protect(thread.sandbox) --TODO: probably set threading.currentThread here local res, reason = pcall(function() thread.kill[signal](table.unpack(args)) end) kernel.modules.manageg.unprotect() if not res then kernel.modules.threading.kill(pid) end return true end function select(timeout, ...) checkArg(1, timeout, "number") local funcs = {} for n, f in ipairs(...) do checkArg(n + 1, f, "function") funcs[n] = coroutine.create(f) end end function setKillHandler(signal, handler) --WAT if not kernel.modules.threading.threads[pid] or not kernel.modules.threading.threads[pid].coro then return nil, "Thread does not exists" end if signal == "kill" then return nil, "Cannot override kill" end kernel.modules.threading.threads[pid].kill[signal] = handler return true end
local Selection = game:GetService("Selection") local src = script.parent.parent local Roact = require(src.Parent.vendor.Roact) local Parse = require(src.Parse) local e = Roact.createElement local App = Roact.Component:extend("App") function App:render() return e("Frame", { Size = UDim2.fromScale(1,1), BackgroundColor3 = Color3.fromRGB(52,52,52), }, { StartButton = e("TextButton", { AnchorPoint = Vector2.new(0.5,0.5), BackgroundColor3 = Color3.fromRGB(78,170,255), Position = UDim2.fromScale(0.5,0.5), Size = UDim2.fromScale(0.6,0.2), Font = Enum.Font.SourceSansBold, TextScaled = true, TextColor3 = Color3.fromRGB(255,255,255), Text = "Start", [Roact.Event.Activated] = function() for _,v in pairs(Selection:Get()) do if v:IsA("Model") then Parse:StartParse(v) end end end }, { UICorner = e("UICorner", { CornerRadius = UDim.new(0.2,0), }) }) }) end return App
function main() turtle.select(1) turtle.refuel(5) level() forward() turtle.turnRight() strip() forward() turtle.turnRight() forward() strip() forward() turtle.turnRight() forward() strip() turtle.turnRight() forward() stairs() end function stairs() for i = 1, 6 do forward() turtle.digUp() turtle.digDown() turtle.down() if i% 2 == 0 then turtle.turnLeft() end end turtle.turnRight() end function level() for j = 1, 3 do for i = 1, 2 do dig3High() end if j == 1 then turtle.turnLeft() dig3High() turtle.turnLeft() end if j == 2 then turtle.turnRight() dig3High() turtle.turnRight() end if j == 3 then turtle.turnRight() forward() forward() turtle.turnRight() forward() forward() turn() end end end function strip() for i = 1, 15 do dig2High() if i%4 == 0 then turtle.turnRight() miniStrip() turtle.turnLeft() end end turn() for i = 1, 15 do forward() end end function miniStrip() for j = 1, 7 do dig2High() end turn() for j = 1, 7 do forward() end for j = 1, 7 do dig2High() end turn() for j = 1, 7 do forward() end end function dig2High() forward() turtle.digUp() end function dig3High() turtle.digUp() turtle.up() forward() turtle.digUp() turtle.digDown() turtle.down() end local torchCount = 0 function forward() while not turtle.forward() do turtle.dig() turtle.attack() end torchCount = torchCount + 1 if torchCount == 4 then turtle.select(16) turtle.placeUp() torchCount = 0 end end function turn() turtle.turnLeft() turtle.select(16) turtle.placeUp() turtle.turnLeft() end main()
utf8 = utf8 or require 'utf8' Codec = { codec = {}, codec_inv = {}, codec_size = 0 } setmetatable(Codec, { __call = function (cls, ...) return cls:new(...) end }) function Codec:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function Codec:encode(src) local result = {} for _, v, _ in utf8.iter(src) do table.insert(result, self.codec[v]) end return result end function Codec:decode(src) local result = "" for _, v in ipairs(src) do result = result .. self.codec_inv[v] end return result end
if (get_window_name() == "seahorse") then set_window_position(1420, 360); end
return function() local RunService = game:GetService("RunService") local ToastRoot = script.Parent local DialogRoot = ToastRoot.Parent local AppRoot = DialogRoot.Parent local UIBloxRoot = AppRoot.Parent local Packages = UIBloxRoot.Parent local Roact = require(Packages.Roact) local mockStyleComponent = require(UIBloxRoot.Utility.mockStyleComponent) local SlideFromTopToast = require(ToastRoot.SlideFromTopToast) local createSlideFromTopToast = function(props) return mockStyleComponent({ SlideFromTopToast = Roact.createElement(SlideFromTopToast, props) }) end it("should throw on empty toastTitle", function() local element = createSlideFromTopToast({ toastContent = { toastTitle = nil, }, }) expect(function() Roact.mount(element) end).to.throw() end) it("should create and destroy without errors", function() local element = createSlideFromTopToast({ toastContent = { toastTitle = "Test Title", }, }) local instance = Roact.mount(element) Roact.unmount(instance) end) it("should create and destroy without errors when render InformativeToast", function() local element = createSlideFromTopToast({ toastContent = { iconImage = "rbxassetid://4126499279", toastSubtitle = "test test test", toastTitle = "Item on sale", }, }) local instance = Roact.mount(element) Roact.unmount(instance) end) it("should create and destroy without errors when render InteractiveToast with onActivated callback", function() local element = createSlideFromTopToast({ toastContent = { iconImage = "rbxassetid://4126499279", onActivated = function() end, toastSubtitle = "Tap to see more information", toastTitle = "System Outage", }, }) local instance = Roact.mount(element) Roact.unmount(instance) end) -- FIXME: This test sometimes fails. I think it's because having a -- high spring frequency does not guarantee an opening in 1 frame. -- TODO: https://jira.rbx.com/browse/UIBLOX-181 itSKIP("should consistently close immediately after opening when provided a duration of 0", function() -- Run test 10 times to confirm it is not flaky for _ = 1, 10 do local appeared = false local disappeared = false local element = createSlideFromTopToast({ toastContent = { toastTitle = "Test Title", onAppeared = function() appeared = true end, onDismissed = function() disappeared = true end, }, springOptions = { frequency = 15000000, damping = 1, }, duration = 0, }) local instance = Roact.mount(element) -- Wait a heartbeat and a step to ensure the otter motor has a chance to complete its movement RunService.Heartbeat:Wait() RunService.Stepped:Wait() expect(appeared).to.equal(true) expect(disappeared).to.equal(false) RunService.Heartbeat:Wait() RunService.Stepped:Wait() expect(appeared).to.equal(true) expect(disappeared).to.equal(true) Roact.unmount(instance) end end) end
["cyrodiil/ava_ebonheart"] = { [1] = { [1] = 0.4610000000, [2] = 0.6850000000, [3] = -10, [4] = -10, [5] = 3662, }, [2] = { [1] = 0.5210000000, [2] = 0.2550000000, [3] = -10, [4] = -10, [5] = 3645, }, [3] = { [1] = 0.5900000000, [2] = 0.7800000000, [3] = -10, [4] = -10, [5] = 3865, }, [4] = { [1] = 0.5400000000, [2] = 0.5090000000, [3] = -10, [4] = -10, [5] = 3863, }, [5] = { [1] = 0.5190000000, [2] = 0.2530000000, [3] = -10, [4] = -10, [5] = 3645, }, [6] = { [1] = 0.5850000000, [2] = 0.8330000000, [3] = -10, [4] = -10, [5] = 3865, }, [7] = { [1] = 0.5240000000, [2] = 0.4140000000, [3] = -10, [4] = -10, [5] = 3645, }, [8] = { [1] = 0.5470000000, [2] = 0.1890000000, [3] = -10, [4] = -10, [5] = 3667, }, [9] = { [1] = 0.6060000000, [2] = 0.5920000000, [3] = -10, [4] = -10, [5] = 3858, }, [10] = { [1] = 0.4780000000, [2] = 0.7540000000, [3] = -10, [4] = -10, [5] = 3662, }, [11] = { [1] = 0.4810000000, [2] = 0.8550000000, [3] = -10, [4] = -10, [5] = 3667, }, [12] = { [1] = 0.5800000000, [2] = 0.8340000000, [3] = -10, [4] = -10, [5] = 3865, }, [13] = { [1] = 0.4790000000, [2] = 0.8530000000, [3] = -10, [4] = -10, [5] = 3667, }, [14] = { [1] = 0.6480000000, [2] = 0.7670000000, [3] = -10, [4] = -10, [5] = 3667, }, [15] = { [1] = 0.4570000000, [2] = 0.5830000000, [3] = -10, [4] = -10, [5] = 4435, }, [16] = { [1] = 0.4560000000, [2] = 0.5720000000, [3] = -10, [4] = -10, [5] = 3916, }, [17] = { [1] = 0.3560000000, [2] = 0.5900000000, [3] = -10, [4] = -10, [5] = 4474, }, [18] = { [1] = 0.6530000000, [2] = 0.7680000000, [3] = -10, [4] = -10, [5] = 3667, }, [19] = { [1] = 0.6530000000, [2] = 0.7690000000, [3] = -10, [4] = -10, [5] = 3639, }, [20] = { [1] = 0.4800000000, [2] = 0.8590000000, [3] = -10, [4] = -10, [5] = 3639, }, [21] = { [1] = 0.4760000000, [2] = 0.7540000000, [3] = -10, [4] = -10, [5] = 4474, }, [22] = { [1] = 0.5480000000, [2] = 0.1900000000, [3] = -10, [4] = -10, [5] = 3667, }, [23] = { [1] = 0.6620000000, [2] = 0.7470000000, [3] = -10, [4] = -10, [5] = 3639, }, [24] = { [1] = 0.6630000000, [2] = 0.7680000000, [3] = -10, [4] = -10, [5] = 3639, }, [25] = { [1] = 0.6510000000, [2] = 0.7720000000, [3] = -10, [4] = -10, [5] = 3667, }, [26] = { [1] = 0.6450000000, [2] = 0.2510000000, [3] = -10, [4] = -10, [5] = 3639, }, [27] = { [1] = 0.3550000000, [2] = 0.5910000000, [3] = -10, [4] = -10, [5] = 3667, }, [28] = { [1] = 0.4800000000, [2] = 0.8600000000, [3] = -10, [4] = -10, [5] = 3667, }, [29] = { [1] = 0.5760000000, [2] = 0.6020000000, [3] = -10, [4] = -10, [5] = 3858, }, [30] = { [1] = 0.6720000000, [2] = 0.7500000000, [3] = -10, [4] = -10, [5] = 3639, }, [31] = { [1] = 0.4690000000, [2] = 0.6100000000, [3] = -10, [4] = -10, [5] = 3639, }, [32] = { [1] = 0.5800000000, [2] = 0.5930000000, [3] = -10, [4] = -10, [5] = 3858, }, [33] = { [1] = 0.6070000000, [2] = 0.5880000000, [3] = -10, [4] = -10, [5] = 3858, }, [34] = { [1] = 0.5500000000, [2] = 0.1870000000, [3] = -10, [4] = -10, [5] = 3667, }, [35] = { [1] = 0.6900000000, [2] = 0.7860000000, [3] = -10, [4] = -10, [5] = 3639, }, [36] = { [1] = 0.3550000000, [2] = 0.5890000000, [3] = -10, [4] = -10, [5] = 3667, }, [37] = { [1] = 0.4790000000, [2] = 0.8530000000, [3] = -10, [4] = -10, [5] = 3639, }, [38] = { [1] = 0.5400000000, [2] = 0.6100000000, [3] = -10, [4] = -10, [5] = 3863, }, [39] = { [1] = 0.3560000000, [2] = 0.5880000000, [3] = -10, [4] = -10, [5] = 4474, }, [40] = { [1] = 0.6670000000, [2] = 0.7560000000, [3] = -10, [4] = -10, [5] = 3639, }, [41] = { [1] = 0.4910000000, [2] = 0.8660000000, [3] = -10, [4] = -10, [5] = 3639, }, [42] = { [1] = 0.4400000000, [2] = 0.6500000000, [3] = -10, [4] = -10, [5] = 4474, }, [43] = { [1] = 0.5980000000, [2] = 0.5810000000, [3] = -10, [4] = -10, [5] = 3858, }, [44] = { [1] = 0.4810000000, [2] = 0.8610000000, [3] = -10, [4] = -10, [5] = 3639, }, [45] = { [1] = 0.5830000000, [2] = 0.6060000000, [3] = -10, [4] = -10, [5] = 3858, }, [46] = { [1] = 0.6450000000, [2] = 0.7700000000, [3] = -10, [4] = -10, [5] = 3667, }, [47] = { [1] = 0.4550000000, [2] = 0.5780000000, [3] = -10, [4] = -10, [5] = 3639, }, [48] = { [1] = 0.5430000000, [2] = 0.6150000000, [3] = -10, [4] = -10, [5] = 3865, }, [49] = { [1] = 0.3810000000, [2] = 0.7920000000, [3] = -10, [4] = -10, [5] = 3639, }, [50] = { [1] = 0.4780000000, [2] = 0.8610000000, [3] = -10, [4] = -10, [5] = 3667, }, [51] = { [1] = 0.5400000000, [2] = 0.6090000000, [3] = -10, [4] = -10, [5] = 3863, }, [52] = { [1] = 0.3560000000, [2] = 0.5900000000, [3] = -10, [4] = -10, [5] = 3863, }, }, ["ruinsofabamath_base_0"] = { [1] = { [1] = 0.8729000000, [2] = 0.5362000000, [3] = -10, [4] = -10, [5] = 4156, }, },
--[[ _ ( ) _| | __ _ __ ___ ___ _ _ /'_` | /'__`\( '__)/' _ ` _ `\ /'_` ) ( (_| |( ___/| | | ( ) ( ) |( (_| | `\__,_)`\____)(_) (_) (_) (_)`\__,_) DImage --]] PANEL = {} AccessorFunc( PANEL, "m_Material", "Material" ) AccessorFunc( PANEL, "m_Color", "ImageColor" ) AccessorFunc( PANEL, "m_bKeepAspect", "KeepAspect" ) AccessorFunc( PANEL, "m_strMatName", "MatName" ) AccessorFunc( PANEL, "m_strMatNameFailsafe", "FailsafeMatName" ) --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:Init() self:SetImageColor( Color( 255, 255, 255, 255 ) ) self:SetMouseInputEnabled( false ) self:SetKeyboardInputEnabled( false ) self:SetKeepAspect( false ) self.ImageName = "" self.ActualWidth = 10 self.ActualHeight = 10 end --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:SetOnViewMaterial( MatName, MatNameBackup ) self:SetMatName( MatName ) self:SetFailsafeMatName( MatNameBackup ) self.ImageName = MatName end --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:Unloaded() return self.m_strMatName != nil end --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:LoadMaterial() if ( !self:Unloaded() ) then return end self:DoLoadMaterial() self:SetMatName( nil ) end function PANEL:DoLoadMaterial() local mat = Material( self:GetMatName() ) self:SetMaterial( mat ) if ( self.m_Material:IsError() && self:GetFailsafeMatName() ) then self:SetMaterial( Material( self:GetFailsafeMatName() ) ) end self:FixVertexLitMaterial() // // This isn't ideal, but it will probably help you out of a jam // in cases where you position the image according to the texture // size and you want to load on view - instead of on load. // self:InvalidateParent() end --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:SetMaterial( Mat ) -- Everybody makes mistakes, -- that's why they put erasers on pencils. if ( type( Mat ) == "string" ) then self:SetImage( Mat ) return end self.m_Material = Mat if (!self.m_Material) then return end local Texture = self.m_Material:GetTexture( "$basetexture" ) if ( Texture ) then self.ActualWidth = Texture:Width() self.ActualHeight = Texture:Height() else self.ActualWidth = self.m_Material:Width() self.ActualHeight = self.m_Material:Height() end end --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:SetImage( strImage, strBackup ) if ( strBackup && !file.Exists( "materials/"..strImage..".vmt", "GAME" ) ) then strImage = strBackup end self.ImageName = strImage local Mat = Material( strImage ) self:SetMaterial( Mat ) self:FixVertexLitMaterial() end --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:GetImage() return self.ImageName end function PANEL:FixVertexLitMaterial() -- -- If it's a vertexlitgeneric material we need to change it to be -- UnlitGeneric so it doesn't go dark when we enter a dark room -- and flicker all about -- local Mat = self:GetMaterial() local strImage = Mat:GetName() if ( string.find( Mat:GetShader(), "VertexLitGeneric" ) || string.find( Mat:GetShader(), "Cable" ) ) then local t = Mat:GetString( "$basetexture" ) if ( t ) then local params = {} params[ "$basetexture" ] = t params[ "$vertexcolor" ] = 1 params[ "$vertexalpha" ] = 1 Mat = CreateMaterial( strImage .. "_DImage", "UnlitGeneric", params ) end end self:SetMaterial( Mat ) end --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:GetImage() return self.ImageName end --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:SizeToContents( strImage ) self:SetSize( self.ActualWidth, self.ActualHeight ) end --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:Paint() self:PaintAt( 0, 0, self:GetWide(), self:GetTall() ) end function PANEL:PaintAt( x, y, dw, dh ) self:LoadMaterial() if ( !self.m_Material ) then return true end surface.SetMaterial( self.m_Material ) surface.SetDrawColor( self.m_Color.r, self.m_Color.g, self.m_Color.b, self.m_Color.a ) if ( self:GetKeepAspect() ) then local w = self.ActualWidth local h = self.ActualHeight -- Image is bigger than panel, shrink to suitable size if ( w > dw && h > dh ) then if ( w > dw ) then local diff = dw / w w = w * diff h = h * diff end if ( h > dh ) then local diff = dh / h w = w * diff h = h * diff end end if ( w < dw ) then local diff = dw / w w = w * diff h = h * diff end if ( h < dh ) then local diff = dh / h w = w * diff h = h * diff end local OffX = (dw - w) * 0.5 local OffY = (dh - h) * 0.5 surface.DrawTexturedRect( OffX+x, OffY+y, w, h ) return true end surface.DrawTexturedRect( x, y, dw, dh ) return true end --[[--------------------------------------------------------- Name: GenerateExample -----------------------------------------------------------]] function PANEL:GenerateExample( ClassName, PropertySheet, Width, Height ) local ctrl = vgui.Create( ClassName ) ctrl:SetImage( "brick/brick_model" ) ctrl:SetSize( 200, 200 ) PropertySheet:AddSheet( ClassName, ctrl, nil, true, true ) end derma.DefineControl( "DImage", "A simple image", PANEL, "DPanel" )
-- bisect.lua -- bisection method for solving non-linear equations function bisect(f,a,b,fa,fb) local delta=1e-10 -- tolerance local c=(a+b)/2 if c==a or c==b or math.abs(a-b)<delta then return c,b-a end n=n+1 local fc=f(c) if fa*fc<0 then return bisect(f,a,c,fa,fc) else return bisect(f,c,b,fc,fb) end end -- find root of f in the inverval [a,b]. needs f(a)*f(b)<0 function solve(f,a,b) n=0 local z,e=bisect(f,a,b,f(a),f(b)) io.write(string.format("after %d steps, root is %.17g with error %.1e, f=%.1e\n",n,z,e,f(z))) end -- our function function f(x) return x*x*x-x-1 end -- find zero in [1,2] solve(f,1,2)
local ScrollView = class("ScrollView", function(rect) if not rect then rect = CCRect(0, 0, 0, 0) end local node = display.newClippingRegionNode(rect) node:setNodeEventEnabled(true) require("framework.api.EventProtocol").extend(node) return node end) ScrollView.DIRECTION_VERTICAL = 1 ScrollView.DIRECTION_HORIZONTAL = 2 function ScrollView:ctor(rect, direction) assert(direction == ScrollView.DIRECTION_VERTICAL or direction == ScrollView.DIRECTION_HORIZONTAL, "ScrollView:ctor() - invalid direction") self.dragThreshold = 40 self.bouncThreshold = 140 self.defaultAnimateTime = 0.4 self.defaultAnimateEasing = "backOut" self.direction = direction self.touchRect = rect self.offsetX = 0 self.offsetY = 0 self.cells = {} self.currentIndex = 0 self:registerScriptHandler(function(event) if event == "enter" then self:onEnter() elseif event == "exit" then self:onExit() end end) -- create container layer self.view = display.newLayer() self:addChild(self.view) self.view:addTouchEventListener(function(event, x, y) return self:onTouch(event, x, y) end) end function ScrollView:getCurrentCell() if self.currentIndex > 0 then return self.cells[self.currentIndex] else return nil end end function ScrollView:getCurrentIndex() return self.currentIndex end function ScrollView:setCurrentIndex(index) self:scrollToCell(index) end function ScrollView:addCell(cell) self.view:addChild(cell) self.cells[#self.cells + 1] = cell self:reorderAllCells() self:dispatchEvent({name = "addCell", count = #self.cells}) end function ScrollView:insertCellAtIndex(cell, index) self.view:addChild(cell) table.insert(self.cells, index, cell) self:reorderAllCells() self:dispatchEvent({name = "insertCellAtIndex", index = index, count = #self.cells}) end function ScrollView:removeCellAtIndex(index) local cell = self.cells[index] cell:removeSelf() table.remove(self.cells, index) self:reorderAllCells() self:dispatchEvent({name = "removeCellAtIndex", index = index, count = #self.cells}) end function ScrollView:getView() return self.view end function ScrollView:getTouchRect() return self.touchRect end function ScrollView:setTouchRect(rect) self.touchRect = rect self:dispatchEvent({name = "setTouchRect", rect = rect}) end function ScrollView:getClippingRect() return self:getClippingRegion() end function ScrollView:setClippingRect(rect) self:setClippingRegion(rect) self:dispatchEvent({name = "setClippingRect", rect = rect}) end function ScrollView:scrollToCell(index, animated, time, easing) local count = #self.cells if count < 1 then self.currentIndex = 0 return end if index < 1 then index = 1 elseif index > count then index = count end self.currentIndex = index local offset = 0 for i = 2, index do local cell = self.cells[i - 1] local size = cell:getContentSize() if self.direction == ScrollView.DIRECTION_HORIZONTAL then offset = offset - size.width else offset = offset + size.height end end self:setContentOffset(offset, animated, time, easing) self:dispatchEvent({name = "scrollToCell", animated = animated, time = time, easing = easing}) end function ScrollView:isTouchEnabled() return self.view:isTouchEnabled() end function ScrollView:setTouchEnabled(enabled) self.view:setTouchEnabled(enabled) self:dispatchEvent({name = "setTouchEnabled", enabled = enabled}) end ---- events function ScrollView:onTouchBegan(x, y) self.drag = { currentOffsetX = self.offsetX, currentOffsetY = self.offsetY, startX = x, startY = y, isTap = true, } local cell = self:getCurrentCell() cell:onTouch(event, x, y) return true end function ScrollView:onTouchMoved(x, y) local cell = self:getCurrentCell() if self.direction == ScrollView.DIRECTION_HORIZONTAL then if self.drag.isTap and math.abs(x - self.drag.startX) >= self.dragThreshold then self.drag.isTap = false cell:onTouch("cancelled", x, y) end if not self.drag.isTap then self:setContentOffset(x - self.drag.startX + self.drag.currentOffsetX) else cell:onTouch(event, x, y) end else if self.drag.isTap and math.abs(y - self.drag.startY) >= self.dragThreshold then self.drag.isTap = false cell:onTouch("cancelled", x, y) end if not self.drag.isTap then self:setContentOffset(y - self.drag.startY + self.drag.currentOffsetY) else cell:onTouch(event, x, y) end end end function ScrollView:onTouchEnded(x, y) if self.drag.isTap then self:onTouchEndedWithTap(x, y) else self:onTouchEndedWithoutTap(x, y) end self.drag = nil end function ScrollView:onTouchEndedWithTap(x, y) local cell = self:getCurrentCell() cell:onTouch(event, x, y) cell:onTap(x, y) end function ScrollView:onTouchEndedWithoutTap(x, y) error("ScrollView:onTouchEndedWithoutTap() - inherited class must override this method") end function ScrollView:onTouchCancelled(x, y) self.drag = nil end function ScrollView:onTouch(event, x, y) if self.currentIndex < 1 then return end if event == "began" then if not self.touchRect:containsPoint(CCPoint(x, y)) then return false end return self:onTouchBegan(x, y) elseif event == "moved" then self:onTouchMoved(x, y) elseif event == "ended" then self:onTouchEnded(x, y) else -- cancelled self:onTouchCancelled(x, y) end end ---- private methods function ScrollView:reorderAllCells() local count = #self.cells local x, y = 0, 0 local maxWidth, maxHeight = 0, 0 for i = 1, count do local cell = self.cells[i] cell:setPosition(x, y) if self.direction == ScrollView.DIRECTION_HORIZONTAL then local width = cell:getContentSize().width if width > maxWidth then maxWidth = width end x = x + width else local height = cell:getContentSize().height if height > maxHeight then maxHeight = height end y = y - height end end if count > 0 then if self.currentIndex < 1 then self.currentIndex = 1 elseif self.currentIndex > count then self.currentIndex = count end else self.currentIndex = 0 end local size if self.direction == ScrollView.DIRECTION_HORIZONTAL then size = CCSize(x, maxHeight) else size = CCSize(maxWidth, math.abs(y)) end self.view:setContentSize(size) end function ScrollView:setContentOffset(offset, animated, time, easing) local ox, oy = self.offsetX, self.offsetY local x, y = ox, oy if self.direction == ScrollView.DIRECTION_HORIZONTAL then self.offsetX = offset x = offset local maxX = self.bouncThreshold local minX = -self.view:getContentSize().width - self.bouncThreshold + self.touchRect.size.width if x > maxX then x = maxX elseif x < minX then x = minX end else self.offsetY = offset y = offset local maxY = self.view:getContentSize().height + self.bouncThreshold - self.touchRect.size.height local minY = -self.bouncThreshold if y > maxY then y = maxY elseif y < minY then y = minY end end if animated then transition.stopTarget(self.view) transition.moveTo(self.view, { x = x, y = y, time = time or self.defaultAnimateTime, easing = easing or self.defaultAnimateEasing, }) else self.view:setPosition(x, y) end end function ScrollView:onExit() self:removeAllEventListeners() end return ScrollView
-- Physically simulated bullet -- SENT by Teta_Bonita AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self.Position = self.Entity:GetPos() self.Velocity = self.Entity:GetVar("Velocity",false) self.Acceleration = self.Entity:GetVar("Acceleration",false) self.Bullet = self.Entity:GetVar("Bullet",false) self.Trace = self.Entity:GetVar("Trace",false) if not (self.Position and self.Velocity and self.Acceleration and self.Bullet and self.Trace) then Msg("sent_bullt: Error! Insufficient data to spawn.\n") self:Remove() return end self.Owner = self.Owner or self.Entity self.LastThink = CurTime() self.Trace.endpos = self.Position self.Bullet.Spread = Vector(0,0,0) self.Bullet.Num = 1 self.Bullet.Tracer = 0 self.Entity:Fire("kill","",7) -- Kill this entity after awhile end function ENT:Think() -- Do prediction serverside local fTime = CurTime() local DeltaTime = fTime - self.LastThink self.LastThink = fTime self.Position = self.Position + self.Velocity*DeltaTime self.Velocity = self.Velocity + self.Acceleration*DeltaTime self.Trace.start = self.Trace.endpos self.Trace.endpos = self.Position local TraceRes = util.TraceLine(self.Trace) if TraceRes.Hit then self.Bullet.Src = self.Trace.start self.Bullet.Dir = (TraceRes.HitPos - self.Trace.start) self.Owner:FireBullets(self.Bullet) self:Remove() return false end end
-- title: ModelRenderer -- author: FlamingPandas -- desc: Shows 3D models -- script: lua point={x=0,y=0,z=300} fov=100 mesh={} -- Table that contains all the 3D points polygon={} -- Table that contains all conections of 3D points to create triangle polygons, with their texture specified too zorder={} -- Tabe used to know the rendering order of the triangles rspeed=.1 -- Rotation speed, you can change it tspeed=10 -- Translation speed, you can change it function addMesh(mx,my,mz) local m={x=mx,y=my,z=mz,u=0,v=0} table.insert(mesh,m) end function addPolygon(pp1,pp2,pp3,pu1,pv1,pu2,pv2,pu3,pv3) local p={p1=pp1,p2=pp2,p3=pp3,u1=pu1,v1=pv1,u2=pu2,v2=pv2,u3=pu3,v3=pv3,zOrd=0} table.insert(polygon,p) end function addZOrder(polygon,zor) local z={poly=polygon,zo=zor} table.insert(zorder,z) end function init() --"Loading" points and polygon data local m=addMesh m(-60,-60,5) m(60,-60,5) m(-60,-100,0) m(60,-100,0) m(-60,-105,-20) m(60,-105,-20) m(-60,-90,-30) m(60,-90,-30) m(-60,95,-30) m(60,95,-30) m(-60,100,-25) m(60,100,-25) m(-60,100,0) m(60,100,0) m(-60,50,5) m(60,50,5) m(-55,10,30) m(55,10,30) m(-55,-50,30) m(55,-50,30) local p=addPolygon --UnderNeath Surface p(7,8,10, 32,0,48,0,48,16) p(7,10,9, 32,0,48,16,32,16) --Back Protection p(5,6,8, 16,12,32,12,32,16) p(5,8,7, 16,12,32,16,16,16) --Back lights p(3,4,6, 16,8,32,8,32,12) p(3,6,5, 16,8,32,12,16,12) --Back Capo... maletera p(1,2,4, 0,0,16,0,16,8) p(1,4,3, 0,0,16,8,0,8) --Back WindShield p(19,20,2, 48,8,64,8,64,14) p(19,2,1, 48,8,64,14,48,14) --Roof p(20,19,17, 0,7,16,7,16,16) p(20,17,18, 0,7,16,16,0,16) --Front WindShield p(18,15,16, 48,0,64,8,48,8) p(18,17,15, 48,0,64,0,64,8) --Front Capo p(16,13,14, 0,0,16,8,0,8) p(16,15,13, 0,0,16,0,16,8) --Front Lights p(14,13,11, 16,0,32,0,32,4) p(14,11,12, 16,0,32,4,16,4) --Front Protection p(12,11,9, 16,5,32,5,32,8) p(12,9,10, 16,5,32,5,16,8) --Left WindShield p(16,20,18, 64,8,80,0,64,0) p(16,2,20, 64,8,80,8,80,0) --Right WindShield p(15,17,19, 64,8,64,0,80,0) p(15,19,1, 64,8,80,0,80,8) --Right side p(4,2,6, 32,24,24,24,32,28) p(6,2,8, 32,28,24,24,28,32) p(2,16,8, 24,24,10,24,28,32) p(8,16,10, 28,32,10,24,1,32) p(16,12,10, 10,24,0,31,1,32) p(16,14,12, 10,24,0,24,0,31) --Left side p(1,3,5, 24,16,32,16,32,20) p(1,5,7, 24,16,32,20,28,24) p(15,1,7, 10,16,24,16,28,24) p(15,7,9, 10,16,28,24,1,24) p(15,9,11, 10,16,1,24,0,23) p(15,11,13, 10,16,0,23,0,16) for i,p in pairs(polygon) do addZOrder(i,0) end end init() mode=1 function TIC() if btn(6) then if btn(0) then translate(0,-tspeed,0) end if btn(1) then translate(0,tspeed,0) end if btn(2) then translate(-tspeed,0,0) end if btn(3) then translate(tspeed,0,0) end else if btn(0) then rotatateX(-rspeed) end if btn(1) then rotatateX(rspeed) end if btn(2) then rotatateY(-rspeed) end if btn(3) then rotatateY(rspeed) end end if btn(4) then if fov<800 then fov=fov+10 end end if btn(5) then if fov>10 then fov=fov-10 end end if btnp(7) then if mode<3 then mode=mode+1 else mode=1 end end cls(13) --Shows info from the zorder table -- for i,z in pairs(zorder) do -- print(z.poly.." - "..z.zo,10,10*i) -- end calculateMeshUV() calculateZOrder() table.sort(zorder,function(a,b) return a.zo > b.zo end) if mode==1 then showMesh() end if mode==2 then showWireFrame() end if mode==3 then showMesh() showWireFrame() end end --Given this 3D points calculate how they would look in a 2D screen function calculateMeshUV() for i,m in pairs(mesh) do m.u=((m.x+point.x)*(fov/(m.z+point.z)))+120 m.v=((m.y+point.y)*(fov/(m.z+point.z)))+70 end end -- I made this up but ot works... it gives the avarage of the depth of the three points of each triangle, it works good enough to know witch triangles to draw first (the further ones) function calculateZOrder() m=mesh for i,p in pairs(polygon) do p.zord=(m[p.p1].z+m[p.p2].z+m[p.p3].z)/3 updateZOrder(i,p.zord) end end -- Once calcuated the zorder you need to update the zorder table with those values -- Why do we need this values in another table? well... lua can sort this table and now we have the order in witch to draw the triangles function updateZOrder(polygon,zor) for i,z in pairs(zorder) do if z.poly==polygon then z.zo=zor end end end -- Using the textri function you can show triangles with textures -- This function draws all triangles that are facimg the camera with the textures defined on the init function -- The function draws them in the zorder from further to closest so when a triangle is closer it shows "Above" othee triangles function showMesh() m=mesh for i,z in pairs(zorder) do p=polygon[z.poly] -- If the triangle points are clockwise they are facing the camera if isClockWise(p) then --Draw the textured triangle ttri(m[p.p1].u,m[p.p1].v, m[p.p2].u,m[p.p2].v, m[p.p3].u,m[p.p3].v, p.u1,p.v1, p.u2,p.v2, p.u3,p.v3, 0,{}, (m[p.p1].z+point.z), (m[p.p2].z+point.z), (m[p.p3].z+point.z)) end end end -- Given a triangle return true if it's points are clockwise false if they aren't function isClockWise(poly) p=poly m=mesh if ((m[p.p2].v-m[p.p1].v)* (m[p.p3].u-m[p.p2].u))- ((m[p.p3].v-m[p.p2].v)* (m[p.p2].u-m[p.p1].u))>0 then return false else return true end end --Function that draws all lines in the three points of a triangle (it just shpws the WireFrame and also the individual points) function showWireFrame() m=mesh for i,p in pairs(polygon) do line(m[p.p1].u,m[p.p1].v,m[p.p2].u,m[p.p2].v,15) line(m[p.p2].u,m[p.p2].v,m[p.p3].u,m[p.p3].v,15) line(m[p.p3].u,m[p.p3].v,m[p.p1].u,m[p.p1].v,15) end for i,m in pairs(mesh) do circ(m.u,m.v,1,0) print(i,m.u,m.v+5,3) end end -- Rotates all pf the points in the mesh by an angle in the x axes function rotatateX(angle) cos=math.cos(angle) sin=math.sin(angle) for i,p in pairs(mesh) do y=p.y*cos-p.z*sin z=p.z*cos+p.y*sin p.y=y p.z=z end end function rotatateY(angle) cos=math.cos(angle) sin=math.sin(angle) for i,p in pairs(mesh) do x=p.x*cos-p.z*sin z=p.z*cos+p.x*sin p.x=x p.z=z end end function rotatateZ(angle) cos=math.cos(angle) sin=math.sin(angle) for i,p in pairs(mesh) do x=p.x*cos-p.y*sin y=p.y*cos+p.x*sin p.x=x p.y=y end end -- Translate all of the points an x,y and z distance function translate(dx,dy,dz) point.x=point.x+dx point.y=point.y+dy point.z=point.z+dz end -- <TILES> -- 000:66666ff666666ff666666ff666666ff666666ff666666ff666666ff666666ff6 -- 001:6ff666666ff666666ff666666ff666666ff666666ff666666ff666666ff66666 -- 002:66666ff66ee373736ee737376666666663333333633333336333333363333333 -- 003:6ff6666673737ee637373ee66666666633333336333333363333333633333336 -- 004:63337733633377336333377363333773633aaaa3633aaaa3633aaaa3633aaaa3 -- 005:337733363377333637733336377333363aaaa3363aaaa3363aaaa3363aaaa336 -- 006:66666ff66888dd33688ddd8868ddd8886ddd888d6dd888dd6d00000d66666ff6 -- 007:6ff6666633ddd8868ddd8886ddd88886dd888886d8888886800000866ff66666 -- 008:6666666668888888688888886888888868888888688888886888888866666666 -- 009:6666666688888886888888868888888688888886888888868888888666666666 -- 010:6666666666666666666666666666666666666666666666666666666666666666 -- 011:6666666666666666666666666666666666666666666666666666666666666666 -- 016:66666f00666660ff66660ff066660fff66660fff666660ff66666f0066666ff6 -- 017:00f66666ff0666660ff066660ff066660ff06666ff06666600f666666ff66666 -- 018:66666ff669996faa69996faa666600f663337733633377336333773363337733 -- 019:6ff66666aaf69996aaf699966f00666633773336337733363377333633773336 -- 020:6333337363333373633337336333373363333733633337336333333363333333 -- 021:3733333637333336337333363373333633733336337333363333333633333336 -- 022:66666ff66888ddd8688ddd8868ddd8886dd0000066666ff60000000000000000 -- 023:6ff6666688ddd8868ddd8886ddd88886dd8888866ff666660000000000000000 -- 026:6666666666666666666666666666666666666666666666666666666666666666 -- 027:6666666666666666666666666666666666666666666666666666666666666666 -- 032:6666666666666666666666666666666666666666666666336666630066663000 -- 033:6666666666666666666006666666666666666666336666660036666600036666 -- 034:6666666666666666666666666666666666666666666666336666630066663000 -- 035:6666666666666666666666666666666666666666336666660036666600036666 -- 048:6666666666666666666666666666666666666666666666336666630066663000 -- 049:6666666666666666666006666666666666666666336666660036666600036666 -- 050:6666666666666666666666666666666666666666666666336666630066663000 -- 051:6666666666666666666666666666666666666666336666660036666600036666 -- </TILES> -- <PALETTE> -- 000:140c1c44243430346d4e4a4e854c30346524d04648757161597dceb23c408595a16daa2cd2aa996dc2cadad45edeeed6 -- </PALETTE>
local NXFS = require "nixio.fs" local SYS = require "luci.sys" local HTTP = require "luci.http" local DISP = require "luci.dispatcher" local UTIL = require "luci.util" local uci = require("luci.model.uci").cursor() m = Map("clash") s = m:section(TypedSection, "clash") --m.pageaction = false s.anonymous = true o = s:option(Value, "http_port") o.title = translate("Http Port") o.default = 7890 o.datatype = "port" o.rmempty = false o.description = translate("Http Port") o = s:option(Value, "socks_port") o.title = translate("Socks Port") o.default = 7891 o.datatype = "port" o.rmempty = false o.description = translate("Socks Port") o = s:option(Value, "redir_port") o.title = translate("Redir Port") o.default = 7892 o.datatype = "port" o.rmempty = false o.description = translate("Redir Port") o = s:option(ListValue, "allow_lan") o.title = translate("Allow Lan") o.default = true o.rmempty = false o:value("true", "true") o:value("false", "false") o.description = translate("Allow Lan") o = s:option(Value, "bind_addr") o.title = translate("Bind Address") o:value("*", translate("Bind All IP Addresses")) luci.ip.neighbors({ family = 4 }, function(entry) if entry.reachable then o:value(entry.dest:string()) end end) luci.ip.neighbors({ family = 6 }, function(entry) if entry.reachable then o:value(entry.dest:string()) end end) o.description = translate("Bind Address") o:depends("allow_lan", "true") o = s:option(Value, "dash_port") o.title = translate("Dashboard Port") o.default = 9191 o.datatype = "port" o.rmempty = false o.description = translate("Dashboard Port") o = s:option(Value, "dash_pass") o.title = translate("Dashboard Secret") o.default = 123456 o.rmempty = false o.description = translate("Dashboard Secret") o = s:option(ListValue, "level", translate("Log level")) o.description = translate("Choose Log Level") o:value("info", "info") o:value("silent", "silent") o:value("warning", "warning") o:value("error", "error") o:value("debug", "debug") local clash_conf = "/etc/clash/config.yaml" local apply = luci.http.formvalue("cbi.apply") if apply then if NXFS.access(clash_conf) then m.uci:commit("clash") SYS.call("sh /usr/share/clash/yum_change.sh 2>&1 &") if luci.sys.call("pidof clash >/dev/null") == 0 then SYS.call("/etc/init.d/clash restart >/dev/null 2>&1 &") luci.http.redirect(luci.dispatcher.build_url("admin", "services", "clash")) end end end return m
function onCreate() makeLuaSprite('thebackgroundbutlessfire','bg-fire',-600,-200) addLuaSprite('thebackgroundbutlessfire',false) makeLuaSprite('devteam','Characters',400,390) addLuaSprite('devteam',false) end
return {'slufter','sluier','sluierbewolking','sluierdoek','sluiereffect','sluieren','sluiering','sluierstaart','sluif','sluik','sluikblad','sluiken','sluikerij','sluikgoed','sluikhandel','sluikhandelaar','sluikharig','sluikpers','sluikreclame','sluiks','sluikstokerij','sluikstort','sluikstorten','sluikstorter','sluikweg','sluikwerk','sluimer','sluimeren','sluimering','sluimerrol','sluimertoestand','sluipen','sluipend','sluipenderwijs','sluiper','sluipers','sluipgang','sluiphoek','sluipmoord','sluipmoordenaar','sluiproute','sluipschutter','sluipschuttervuur','sluipverkeer','sluipweg','sluipwesp','sluis','sluisdeur','sluisgeld','sluiskolk','sluismeester','sluiswachter','sluiswerken','sluit','sluitappel','sluitbalk','sluitband','sluitboom','sluiten','sluiter','sluitergordijn','sluitertijd','sluitgat','sluiting','sluitingsbevel','sluitingsceremonie','sluitingsdag','sluitingsdatum','sluitingsplan','sluitingstermijn','sluitingstijd','sluitingsuur','sluitjas','sluitkool','sluitmand','sluitplaat','sluitpost','sluitrede','sluitspeld','sluitspier','sluitsteen','sluitstuk','sluitveer','sluitwerk','sluitzegel','sluizen','sluizencomplex','slum','slump','slungel','slungelachtig','slungelen','slungelig','slurf','slurfdier','slurp','slurpen','sluw','sluwe','sluwheid','sluitdop','sluikinvoer','sluimerig','sluipschutterkogel','sluipschuttersvuur','sluitketting','sluitklep','slurfachtig','sluikverkeer','sluimerstand','sluipverbruik','sluisbrug','sluiscomplex','sluishoofd','sluiterknop','sluitingsperiode','sluitlaken','sluitmechanisme','sluitsysteem','slurptaks','sluitingsmechanisme','sluipvlieg','sluipvliegen','sluishaak','sluitmunt','sluijter','sluijs','slump','sluijk','sluijsmans','slurink','slutter','slui','sluiman','sluierden','sluiers','sluierstaarten','sluiert','sluiertje','sluiertjes','sluike','sluiker','sluikerijen','sluikers','sluikhandelaars','sluikharige','sluikt','sluimerde','sluimerden','sluimerend','sluimerende','sluimeringen','sluimerrollen','sluimert','sluip','sluipende','sluipertje','sluipertjes','sluiphoeken','sluipmoorden','sluipmoordenaars','sluipt','sluipwegen','sluipwespen','sluisde','sluisden','sluisdeuren','sluisgelden','sluiskolken','sluismeesters','sluist','sluiswachters','sluitbalken','sluitbanden','sluitbomen','sluitend','sluitende','sluiters','sluitgaten','sluithaakje','sluitingen','sluitingsdagen','sluitingsplannen','sluitingstijden','sluitingsuren','sluitkolen','sluitmanden','sluitposten','sluitreden','sluitspelden','sluitspieren','sluitstenen','sluitstukken','sluitveren','sluitzegels','sluiven','slumps','slungelachtige','slungelde','slungelige','slungeliger','slungels','slungelt','slurfdieren','slurpt','slurpte','slurpten','slurven','sluwer','sluwere','sluwheden','sluwst','sluwste','slufters','sluierde','sluikbladen','sluikstokerijen','sluikstorters','sluikwegen','sluipgangen','sluiproutes','sluipschutters','sluitertijden','sluitplaten','sluitredes','slums','slurpend','slurpende','sluitingsdata','sluipweggetje','sluikse','sluimerige','sluikreclames','sluikstortte','sluiprouten','sluipschutterkogels','sluitdoppen','sluitingsdatums','sluitkettingen','sluitkleppen','slurfachtige','sluisje','sluisjes','sluishoofden','sluizencomplexen','sluitsystemen','sluiscomplexen','sluitplaatje','sluitingsperiodes','sluitingsmechanismen','slurfje'}
require "heka_mock" _G.cjson = require "cjson" set_default_config({ Type="my_type" }) -- describe("my_encoder", function() it("accepts table and sends out message", function () reset_all() -- run this before every test mock_read_config({foo="bar"}) -- define config parameters in -- addition to default_config as needed dofile "my_encoder.lua" -- don't use "require", use "dofile" send_message({foo="bar"}) result = injected()[1] assert.is.equal('{"foo":"bar"}', result.Payload) end) end)
local colors = { base00 = "#101317", base01 = "#1a1d21", base02 = "#23262a", base03 = "#2b2e32", base04 = "#323539", base05 = "#c5c5c6", base06 = "#cbcbcc", base07 = "#d4d4d5", base08 = "#37d99e", base09 = "#f0a988", base0A = "#e5d487", base0B = "#e87979", base0C = "#37d99e", base0D = "#5fb0fc", base0E = "#c397d8", base0F = "#e87979", } return colors
local wibox = require("wibox") -- Create a textclock widget local mytextclock = wibox.widget.textclock() table.insert(globalwidgets.right, mytextclock)
--- module The SuperToast module ---@class SuperToast ---@field public ArgParser ArgParser re-export ---@field public Array Array re-export ---@field public Client SuperToastClient re-export ---@field public Command Command re-export ---@field public Embed Embed re-export ---@field public TypedArray TypedArray re-export ---@field public Option Option re-export ---@field public Subcommand Subcommand re-export ---@field public dotenv dotenv re-export ---@field public ms ms re-export ---@field public stringx stringx re-export ---@field public typed typed re-export local SuperToast = { ---@type ArgParser ArgParser = require('classes/ArgParser'), ---@type Array Array = require('classes/Array'), ---@type SuperToastClient Client = require('classes/Client'), ---@type Command Command = require('classes/Command'), ---@type CommandUtil CommandUtil = require('classes/CommandUtil'), ---@type Embed Embed = require('classes/Embed'), ---@type TypedArray TypedArray = require('classes/TypedArray'), ---@type Subcommand Subcommand = require('classes/Subcommand'), commandHandler = require('utils/commandHandler'), ---@type dotenv dotenv = require('utils/dotenv'), errorResolver = require('utils/errorResolver'), help = require('utils/help'), ---@type ms ms = require('utils/ms'), ---@type stringx stringx = require('utils/stringx'), ---@type typed typed = require('typed') } return SuperToast
require 'shaders/utils' tileMap = Geometry2DPass { depthStencilState = { depthTestEnable = false, depthWriteEnable = false }, shaderFile = 'DrawTileMap.glsl' }
local lpeg = require 'lpeg' local P, C, R, S, Cs, Cc, Ct, Cf, Cg, V, Cmt = lpeg.P, lpeg.C, lpeg.R, lpeg.S, lpeg.Cs, lpeg.Cc, lpeg.Ct, lpeg.Cf, lpeg.Cg, lpeg.V, lpeg.Cmt local lpegmatch, lpegpatterns, replacer = lpeg.match, lpeg.patterns, lpeg.replacer local inspect = require 'inspect' local function parse_link_header(str) -- This is our placeholder for matches local links = links or {} -- As we get a table match, we add a new entry to the links table in the format of: -- { reltype = "target" } local function build_pagination(t1) links[t1.rel] = t1.url return t1 end -- link headers look like so: -- <someurl>; rel="sometype" -- multiple links can be joined together with commas: -- <someurl1>; rel="foo",<someurl2>; rel="bar" -- local openbracket = P("<") local closebracket = P(">") local semicolon = P(";") local equal = P("=") local comma = P(",") local quote = P('"') local endofstring = P(-1) local nothing = Cc("") local whitespace = P(" ")^1 -- target is the url in in between <> local target = Cg(((P(1) - closebracket)^-0), "url") -- reltype is the value for rel local reltype = Cg(((P(1) - quote)^-0), "rel") -- Make a capture table of one match -- { rel = "next", url = "https://....." } local match_one = Ct((whitespace)^0 * openbracket * target * closebracket * semicolon * (whitespace)^0 * "rel=" * quote * reltype * quote * (whitespace)^0 * (comma)^0) -- apply function to one match local linkwfunc = (match_one / build_pagination) -- make a capture table of one or more matches local match_any = Ct((linkwfunc)^1) -- do the match match_links = lpegmatch(match_any, str) return links end local parsers = { parse_link_header = parse_link_header } return parsers
require('lualine').setup({ options = { icons_enabled = true, -- theme = 'rose-pine', disabled_filetypes = {}, always_divide_middle = true, }, sections = { lualine_a = { 'mode' }, lualine_b = { 'branch', { 'diagnostics', sources = { 'nvim_diagnostic' }, colored = true } }, lualine_c = { 'filename' }, lualine_x = { 'encoding', 'fileformat', 'filetype' }, lualine_y = { 'progress' }, lualine_z = { 'location' }, }, inactive_sections = { lualine_a = {}, lualine_b = {}, lualine_c = { 'filename' }, lualine_x = { 'location' }, lualine_y = {}, lualine_z = {}, }, tabline = {}, extensions = {}, })
local K, C, L = unpack(select(2, ...)) if C.ActionBar.Enable ~= true then return end -- Lua API local _G = _G -- MultiBarBottomLeft(by Tukz) local ActionBar2 = CreateFrame("Frame", "Bar2Holder", ActionBarAnchor) ActionBar2:SetAllPoints(ActionBarAnchor) MultiBarBottomLeft:SetParent(ActionBar2) for i = 1, 12 do local b = _G["MultiBarBottomLeftButton"..i] local b2 = _G["MultiBarBottomLeftButton"..i-1] b:ClearAllPoints() if i == 1 then b:SetPoint("BOTTOM", ActionButton1, "TOP", 0, C.ActionBar.ButtonSpace) else b:SetPoint("LEFT", b2, "RIGHT", C.ActionBar.ButtonSpace, 0) end end -- Hide bar if C.ActionBar.BottomBars == 1 then ActionBar2:Hide() end
-- -- Anti-Cheat Control Panel -- -- s_main.lua -- local wasAllowedList = {} addEventHandler ( "onResourceStart", resourceRoot, function () doesResourceHasPermissions() for _,plr in ipairs(getElementsByType("player")) do updatePlayer(plr) end end ) addEventHandler ( "onPlayerJoin", root, function () updatePlayer(source) end ) addEventHandler ( "onPlayerQuit", root, function () wasAllowedList[source] = nil end ) addEventHandler ( "onPlayerLogin", root, function () updatePlayer(source) end ) addEventHandler ( "onPlayerLogout", root, function () updatePlayer(source) end ) function updatePlayer(player) local oldAllowed = wasAllowedList[player] local newAllowed = isPlayerAllowedHere(player) wasAllowedList[player] = newAllowed if newAllowed and not oldAllowed then bindKey( player, "o", "down", "Show_AC_Panel" ) outputChatBox ( "Press 'o' to open your AC panel", player ) if not bAllowGui then return end sendAllSettingsToClient() triggerClientEvent(player, 'onAcpClientInitialSettings', resourceRoot, getServerConfigSettingsToTransfer() ) elseif not newAllowed and oldAllowed then triggerClientEvent(player, 'aClientAcMenu', resourceRoot, "close" ) unbindKey( player, "o", "down", "Show_AC_Panel" ) end end function showACPanel(player) if not isPlayerAllowedHere(player) then return false end if not doesResourceHasPermissions() then return end triggerClientEvent(player, 'aClientAcMenu', resourceRoot, "toggle" ) end addCommandHandler('acp',showACPanel) addCommandHandler('Show_AC_Panel',showACPanel) function getServerConfigSettingsToTransfer() local result = {} local settingNameList = { "disableac", "enablesd", "verifyclientsettings" } for _,name in ipairs(settingNameList) do local value = getServerConfigSetting(name) result[name] = value end local verifyFlags = getServerConfigSetting( "verifyclientsettings" ) verifyFlags = -1-verifyFlags local stringresult = "" for i=1,32 do local isset = math.hasbit(verifyFlags, math.bit(i)) stringresult = stringresult .. ( isset and "1" or "0" ) end result["verifyclientsettingsstring"] = stringresult return result end -------------------------------------------------------------------- -- Check this resource can do stuff -------------------------------------------------------------------- function doesResourceHasPermissions() if hasObjectPermissionTo( getThisResource(), "function.kickPlayer" ) and hasObjectPermissionTo( getThisResource(), "function.setServerConfigSetting" ) and hasObjectPermissionTo( getThisResource(), "function.fetchRemote" ) then bResourceHasPermissions = true end if not bDoneFirstCheck then bDoneFirstCheck = true if bResourceHasPermissions then bAllowGui = true return true end end if bAllowGui then return true end if not bResourceHasPermissions then outputChatBox( "AC Panel can not start until this command is run:" ) outputChatBox( "aclrequest allow acpanel all" ) else outputChatBox( "Please restart AC Panel" ) end return false end -------------------------------------------------------------------- -- Check player can do stuff -------------------------------------------------------------------- function isPlayerAllowedHere(player) local admingroup = get("admingroup") or "Admin" if not isPlayerInACLGroup(player, tostring(admingroup) ) then return false end return true end function isPlayerInACLGroup(player, groupName) local account = getPlayerAccount(player) if not account then return false end local accountName = getAccountName(account) for _,name in ipairs(split(groupName,',')) do local group = aclGetGroup(name) if group then for i,obj in ipairs(aclGroupListObjects(group)) do if obj == 'user.' .. accountName or obj == 'user.*' then return true end end end end return false end
-- Copyright 2008 Steven Barth <[email protected]> -- Copyright 2008 Jo-Philipp Wich <[email protected]> -- Copyright 2013 Manuel Munz <freifunk at somakoma dot de> -- Copyright 2014-2015 Christian Schoenebeck <christian dot schoenebeck at gmail dot com> -- Licensed to the public under the Apache License 2.0. local NX = require "nixio" local NXFS = require "nixio.fs" local SYS = require "luci.sys" local UTIL = require "luci.util" local DISP = require "luci.dispatcher" local WADM = require "luci.tools.webadmin" local DTYP = require "luci.cbi.datatypes" local DDNS = require "luci.tools.ddns" -- ddns multiused functions -- takeover arguments -- ####################################################### local section = arg[1] -- check supported options -- ################################################## -- saved to local vars here because doing multiple os calls slow down the system local has_ipv6 = DDNS.check_ipv6() -- IPv6 support local has_ssl = DDNS.check_ssl() -- HTTPS support local has_proxy = DDNS.check_proxy() -- Proxy support local has_dnstcp = DDNS.check_bind_host() -- DNS TCP support local has_force = has_ssl and has_dnstcp -- Force IP Protocoll -- html constants -- ########################################################### local font_red = "<font color='red'>" local font_off = "</font>" local bold_on = "<strong>" local bold_off = "</strong>" -- error text constants -- ##################################################### err_ipv6_plain = translate("IPv6 not supported") .. " - " .. translate("please select 'IPv4' address version") err_ipv6_basic = bold_on .. font_red .. translate("IPv6 not supported") .. font_off .. "<br />" .. translate("please select 'IPv4' address version") .. bold_off err_ipv6_other = bold_on .. font_red .. translate("IPv6 not supported") .. font_off .. "<br />" .. translate("please select 'IPv4' address version in") .. " " .. [[<a href="]] .. DISP.build_url("admin", "services", "ddns", "detail", section) .. "?tab.dns." .. section .. "=basic" .. [[">]] .. translate("Basic Settings") .. [[</a>]] .. bold_off function err_tab_basic(self) return translate("Basic Settings") .. " - " .. self.title .. ": " end function err_tab_adv(self) return translate("Advanced Settings") .. " - " .. self.title .. ": " end function err_tab_timer(self) return translate("Timer Settings") .. " - " .. self.title .. ": " end -- function to verify settings around ip_source -- will use dynamic_dns_lucihelper to check if -- local IP can be read local function _verify_ip_source() -- section is globally defined here be calling agrument (see above) local _network = "-" local _url = "-" local _interface = "-" local _script = "-" local _proxy = "" local _ipv6 = usev6:formvalue(section) local _source = (_ipv6 == "1") and src6:formvalue(section) or src4:formvalue(section) if _source == "network" then _network = (_ipv6 == "1") and ipn6:formvalue(section) or ipn4:formvalue(section) elseif _source == "web" then _url = (_ipv6 == "1") and iurl6:formvalue(section) or iurl4:formvalue(section) -- proxy only needed for checking url _proxy = (pxy) and pxy:formvalue(section) or "" elseif _source == "interface" then _interface = ipi:formvalue(section) elseif _source == "script" then _script = ips:formvalue(section) end local command = [[/usr/lib/ddns/dynamic_dns_lucihelper.sh get_local_ip ]] .. _ipv6 .. [[ ]] .. _source .. [[ ]] .. _network .. [[ ]] .. _url .. [[ ]] .. _interface .. [[ ']] .. _script.. [[' ]] .. _proxy local ret = SYS.call(command) if ret == 0 then return true -- valid else return nil -- invalid end end -- cbi-map definition -- ####################################################### m = Map("ddns") m.title = [[<a href="]] .. DISP.build_url("admin", "services", "ddns") .. [[">]] .. translate("Dynamic DNS") .. [[</a>]] m.description = translate("Dynamic DNS allows that your router can be reached with " .. "a fixed hostname while having a dynamically changing " .. "IP address.") m.redirect = DISP.build_url("admin", "services", "ddns") m.on_after_commit = function(self) if self.changed then -- changes ? local pid = DDNS.get_pid(section) if pid > 0 then -- running ? local tmp = NX.kill(pid, 1) -- send SIGHUP end end end -- read application settings -- ################################################ -- date format; if not set use ISO format date_format = m.uci:get(m.config, "global", "date_format") or "%F %R" -- log directory log_dir = m.uci:get(m.config, "global", "log_dir") or "/var/log/ddns" -- cbi-section definition -- ################################################### ns = m:section( NamedSection, section, "service", translate("Details for") .. ([[: <strong>%s</strong>]] % section), translate("Configure here the details for selected Dynamic DNS service.") .. [[<br /><a href="http://wiki.openwrt.org/doc/uci/ddns#version_1x" target="_blank">]] .. translate("For detailed information about parameter settings look here.") .. [[</a>]] ) ns.instance = section -- arg [1] ns:tab("basic", translate("Basic Settings"), nil ) ns:tab("advanced", translate("Advanced Settings"), nil ) ns:tab("timer", translate("Timer Settings"), nil ) ns:tab("logview", translate("Log File Viewer"), nil ) -- TAB: Basic ##################################################################################### -- enabled -- ################################################################# en = ns:taboption("basic", Flag, "enabled", translate("Enabled"), translate("If this service section is disabled it could not be started." .. "<br />" .. "Neither from LuCI interface nor from console") ) en.orientation = "horizontal" function en.parse(self, section) DDNS.flag_parse(self, section) end -- use_ipv6 (NEW) -- ########################################################## usev6 = ns:taboption("basic", ListValue, "use_ipv6", translate("IP address version"), translate("Defines which IP address 'IPv4/IPv6' is send to the DDNS provider") ) usev6.widget = "radio" usev6.default = "0" usev6:value("0", translate("IPv4-Address") ) function usev6.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if has_ipv6 or (value == "1" and not has_ipv6) then self:value("1", translate("IPv6-Address") ) end if value == "1" and not has_ipv6 then self.description = err_ipv6_basic end return value end function usev6.validate(self, value) if (value == "1" and has_ipv6) or value == "0" then return value end return nil, err_tab_basic(self) .. err_ipv6_plain end function usev6.write(self, section, value) if value == "0" then -- force rmempty return self.map:del(section, self.option) else return self.map:set(section, self.option, value) end end -- IPv4 - service_name -- ###################################################### svc4 = ns:taboption("basic", ListValue, "ipv4_service_name", translate("DDNS Service provider") .. " [IPv4]" ) svc4.default = "-" svc4:depends("use_ipv6", "0") -- only show on IPv4 local services4 = { } local fd4 = io.open("/usr/lib/ddns/services", "r") if fd4 then local ln repeat ln = fd4:read("*l") local s = ln and ln:match('^%s*"([^"]+)"') if s then services4[#services4+1] = s end until not ln fd4:close() end for _, v in UTIL.vspairs(services4) do svc4:value(v) end svc4:value("-", translate("-- custom --") ) function svc4.cfgvalue(self, section) local v = DDNS.read_value(self, section, "service_name") if not v or #v == 0 then return "-" else return v end end function svc4.validate(self, value) if usev6:formvalue(section) == "0" then -- do only on IPv4 return value else return "" -- supress validate error end end function svc4.write(self, section, value) if usev6:formvalue(section) == "0" then -- do only IPv4 here self.map:del(section, self.option) -- to be shure if value ~= "-" then -- and write "service_name self.map:del(section, "update_url") -- delete update_url return self.map:set(section, "service_name", value) else return self.map:del(section, "service_name") end end end -- IPv6 - service_name -- ###################################################### svc6 = ns:taboption("basic", ListValue, "ipv6_service_name", translate("DDNS Service provider") .. " [IPv6]" ) svc6.default = "-" svc6:depends("use_ipv6", "1") -- only show on IPv6 if not has_ipv6 then svc6.description = err_ipv6_basic end local services6 = { } local fd6 = io.open("/usr/lib/ddns/services_ipv6", "r") if fd6 then local ln repeat ln = fd6:read("*l") local s = ln and ln:match('^%s*"([^"]+)"') if s then services6[#services6+1] = s end until not ln fd6:close() end for _, v in UTIL.vspairs(services6) do svc6:value(v) end svc6:value("-", translate("-- custom --") ) function svc6.cfgvalue(self, section) local v = DDNS.read_value(self, section, "service_name") if not v or #v == 0 then return "-" else return v end end function svc6.validate(self, value) if usev6:formvalue(section) == "1" then -- do only on IPv6 if has_ipv6 then return value end return nil, err_tab_basic(self) .. err_ipv6_plain else return "" -- supress validate error end end function svc6.write(self, section, value) if usev6:formvalue(section) == "1" then -- do only when IPv6 self.map:del(section, self.option) -- delete "ipv6_service_name" helper if value ~= "-" then -- and write "service_name self.map:del(section, "update_url") -- delete update_url return self.map:set(section, "service_name", value) else return self.map:del(section, "service_name") end end end -- IPv4/IPv6 - update_url -- ################################################### uurl = ns:taboption("basic", Value, "update_url", translate("Custom update-URL"), translate("Update URL to be used for updating your DDNS Provider." .. "<br />" .. "Follow instructions you will find on their WEB page.") ) uurl:depends("ipv4_service_name", "-") uurl:depends("ipv6_service_name", "-") function uurl.validate(self, value) local script = ush:formvalue(section) if (usev6:formvalue(section) == "0" and svc4:formvalue(section) ~= "-") or (usev6:formvalue(section) == "1" and svc6:formvalue(section) ~= "-") then return "" -- suppress validate error elseif not value then if not script or not (#script > 0) then return nil, err_tab_basic(self) .. translate("missing / required") else return "" -- suppress validate error / update_script is given end elseif (#script > 0) then return nil, err_tab_basic(self) .. translate("either url or script could be set") end local url = DDNS.parse_url(value) if not url.scheme == "http" then return nil, err_tab_basic(self) .. translate("must start with 'http://'") elseif not url.query then return nil, err_tab_basic(self) .. "<QUERY> " .. translate("missing / required") elseif not url.host then return nil, err_tab_basic(self) .. "<HOST> " .. translate("missing / required") elseif SYS.call([[nslookup ]] .. url.host .. [[ >/dev/null 2>&1]]) ~= 0 then return nil, err_tab_basic(self) .. translate("can not resolve host: ") .. url.host end return value end -- IPv4/IPv6 - update_script -- ################################################ ush = ns:taboption("basic", Value, "update_script", translate("Custom update-script"), translate("Custom update script to be used for updating your DDNS Provider.") ) ush:depends("ipv4_service_name", "-") ush:depends("ipv6_service_name", "-") function ush.validate(self, value) local url = uurl:formvalue(section) if (usev6:formvalue(section) == "0" and svc4:formvalue(section) ~= "-") or (usev6:formvalue(section) == "1" and svc6:formvalue(section) ~= "-") then return "" -- suppress validate error elseif not value then if not url or not (#url > 0) then return nil, err_tab_basic(self) .. translate("missing / required") else return "" -- suppress validate error / update_url is given end elseif (#url > 0) then return nil, err_tab_basic(self) .. translate("either url or script could be set") elseif not NXFS.access(value) then return nil, err_tab_basic(self) .. translate("File not found") end return value end -- IPv4/IPv6 - domain -- ####################################################### dom = ns:taboption("basic", Value, "domain", translate("Hostname/Domain"), translate("Replaces [DOMAIN] in Update-URL") ) dom.rmempty = false dom.placeholder = "mypersonaldomain.dyndns.org" function dom.validate(self, value) if not value or not (#value > 0) or not DTYP.hostname(value) then return nil, err_tab_basic(self) .. translate("invalid - Sample") .. ": 'mypersonaldomain.dyndns.org'" else return value end end -- IPv4/IPv6 - username -- ##################################################### user = ns:taboption("basic", Value, "username", translate("Username"), translate("Replaces [USERNAME] in Update-URL") ) user.rmempty = false function user.validate(self, value) if not value then return nil, err_tab_basic(self) .. translate("missing / required") end return value end -- IPv4/IPv6 - password -- ##################################################### pw = ns:taboption("basic", Value, "password", translate("Password"), translate("Replaces [PASSWORD] in Update-URL") ) pw.rmempty = false pw.password = true function pw.validate(self, value) if not value then return nil, err_tab_basic(self) .. translate("missing / required") end return value end -- IPv4/IPv6 - use_https (NEW) -- ############################################## if has_ssl or ( ( m:get(section, "use_https") or "0" ) == "1" ) then https = ns:taboption("basic", Flag, "use_https", translate("Use HTTP Secure") ) https.orientation = "horizontal" https.rmempty = false -- force validate function function https.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if not has_ssl and value == "1" then self.description = bold_on .. font_red .. translate("HTTPS not supported") .. font_off .. "<br />" .. translate("please disable") .. " !" .. bold_off else self.description = translate("Enable secure communication with DDNS provider") end return value end function https.parse(self, section) DDNS.flag_parse(self, section) end function https.validate(self, value) if (value == "1" and has_ssl ) or value == "0" then return value end return nil, err_tab_basic(self) .. translate("HTTPS not supported") .. " !" end function https.write(self, section, value) if value == "1" then return self.map:set(section, self.option, value) else self.map:del(section, "cacert") return self.map:del(section, self.option) end end end -- IPv4/IPv6 - cacert (NEW) -- ################################################# if has_ssl then cert = ns:taboption("basic", Value, "cacert", translate("Path to CA-Certificate"), translate("directory or path/file") .. "<br />" .. translate("or") .. bold_on .. " IGNORE " .. bold_off .. translate("to run HTTPS without verification of server certificates (insecure)") ) cert:depends("use_https", "1") cert.rmempty = false -- force validate function cert.default = "/etc/ssl/certs" function cert.validate(self, value) if https:formvalue(section) == "0" then return "" -- supress validate error if NOT https end if value then -- otherwise errors in datatype check if DTYP.directory(value) or DTYP.file(value) or value == "IGNORE" then return value end end return nil, err_tab_basic(self) .. translate("file or directory not found or not 'IGNORE'") .. " !" end end -- TAB: Advanced ################################################################################## -- IPv4 - ip_source -- ######################################################### src4 = ns:taboption("advanced", ListValue, "ipv4_source", translate("IP address source") .. " [IPv4]", translate("Defines the source to read systems IPv4-Address from, that will be send to the DDNS provider") ) src4:depends("use_ipv6", "0") -- IPv4 selected src4.default = "network" src4:value("network", translate("Network")) src4:value("web", translate("URL")) src4:value("interface", translate("Interface")) src4:value("script", translate("Script")) function src4.cfgvalue(self, section) return DDNS.read_value(self, section, "ip_source") end function src4.validate(self, value) if usev6:formvalue(section) == "1" then return "" -- ignore on IPv6 selected elseif not _verify_ip_source() then return nil, err_tab_adv(self) .. translate("can not detect local IP. Please select a different Source combination") else return value end end function src4.write(self, section, value) if usev6:formvalue(section) == "1" then return true -- ignore on IPv6 selected elseif value == "network" then self.map:del(section, "ip_url") -- delete not need parameters self.map:del(section, "ip_interface") self.map:del(section, "ip_script") elseif value == "web" then self.map:del(section, "ip_network") -- delete not need parameters self.map:del(section, "ip_interface") self.map:del(section, "ip_script") elseif value == "interface" then self.map:del(section, "ip_network") -- delete not need parameters self.map:del(section, "ip_url") self.map:del(section, "ip_script") elseif value == "script" then self.map:del(section, "ip_network") self.map:del(section, "ip_url") -- delete not need parameters self.map:del(section, "ip_interface") end self.map:del(section, self.option) -- delete "ipv4_source" helper return self.map:set(section, "ip_source", value) -- and write "ip_source end -- IPv6 - ip_source -- ######################################################### src6 = ns:taboption("advanced", ListValue, "ipv6_source", translate("IP address source") .. " [IPv6]", translate("Defines the source to read systems IPv6-Address from, that will be send to the DDNS provider") ) src6:depends("use_ipv6", 1) -- IPv6 selected src6.default = "network" src6:value("network", translate("Network")) src6:value("web", translate("URL")) src6:value("interface", translate("Interface")) src6:value("script", translate("Script")) if not has_ipv6 then src6.description = err_ipv6_other end function src6.cfgvalue(self, section) return DDNS.read_value(self, section, "ip_source") end function src6.validate(self, value) if usev6:formvalue(section) == "0" then return "" -- ignore on IPv4 selected elseif not has_ipv6 then return nil, err_tab_adv(self) .. err_ipv6_plain elseif not _verify_ip_source() then return nil, err_tab_adv(self) .. translate("can not detect local IP. Please select a different Source combination") else return value end end function src6.write(self, section, value) if usev6:formvalue(section) == "0" then return true -- ignore on IPv4 selected elseif value == "network" then self.map:del(section, "ip_url") -- delete not need parameters self.map:del(section, "ip_interface") self.map:del(section, "ip_script") elseif value == "web" then self.map:del(section, "ip_network") -- delete not need parameters self.map:del(section, "ip_interface") self.map:del(section, "ip_script") elseif value == "interface" then self.map:del(section, "ip_network") -- delete not need parameters self.map:del(section, "ip_url") self.map:del(section, "ip_script") elseif value == "script" then self.map:del(section, "ip_network") self.map:del(section, "ip_url") -- delete not need parameters self.map:del(section, "ip_interface") end self.map:del(section, self.option) -- delete "ipv4_source" helper return self.map:set(section, "ip_source", value) -- and write "ip_source end -- IPv4 - ip_network (default "wan") -- ######################################## ipn4 = ns:taboption("advanced", ListValue, "ipv4_network", translate("Network") .. " [IPv4]", translate("Defines the network to read systems IPv4-Address from") ) ipn4:depends("ipv4_source", "network") ipn4.default = "wan" WADM.cbi_add_networks(ipn4) function ipn4.cfgvalue(self, section) return DDNS.read_value(self, section, "ip_network") end function ipn4.validate(self, value) if usev6:formvalue(section) == "1" or src4:formvalue(section) ~= "network" then -- ignore if IPv6 selected OR -- ignore everything except "network" return "" else return value end end function ipn4.write(self, section, value) if usev6:formvalue(section) == "1" or src4:formvalue(section) ~= "network" then -- ignore if IPv6 selected OR -- ignore everything except "network" return true else -- set also as "interface" for monitoring events changes/hot-plug self.map:set(section, "interface", value) self.map:del(section, self.option) -- delete "ipv4_network" helper return self.map:set(section, "ip_network", value) -- and write "ip_network" end end -- IPv6 - ip_network (default "wan6") -- ####################################### ipn6 = ns:taboption("advanced", ListValue, "ipv6_network", translate("Network") .. " [IPv6]" ) ipn6:depends("ipv6_source", "network") ipn6.default = "wan6" WADM.cbi_add_networks(ipn6) if has_ipv6 then ipn6.description = translate("Defines the network to read systems IPv6-Address from") else ipn6.description = err_ipv6_other end function ipn6.cfgvalue(self, section) return DDNS.read_value(self, section, "ip_network") end function ipn6.validate(self, value) if usev6:formvalue(section) == "0" or src6:formvalue(section) ~= "network" then -- ignore if IPv4 selected OR -- ignore everything except "network" return "" elseif has_ipv6 then return value else return nil, err_tab_adv(self) .. err_ipv6_plain end end function ipn6.write(self, section, value) if usev6:formvalue(section) == "0" or src6:formvalue(section) ~= "network" then -- ignore if IPv4 selected OR -- ignore everything except "network" return true else -- set also as "interface" for monitoring events changes/hotplug self.map:set(section, "interface", value) self.map:del(section, self.option) -- delete "ipv6_network" helper return self.map:set(section, "ip_network", value) -- and write "ip_network" end end -- IPv4 - ip_url (default "checkip.dyndns.com") -- ############################# iurl4 = ns:taboption("advanced", Value, "ipv4_url", translate("URL to detect") .. " [IPv4]", translate("Defines the Web page to read systems IPv4-Address from") ) iurl4:depends("ipv4_source", "web") iurl4.default = "http://checkip.dyndns.com" function iurl4.cfgvalue(self, section) return DDNS.read_value(self, section, "ip_url") end function iurl4.validate(self, value) if usev6:formvalue(section) == "1" or src4:formvalue(section) ~= "web" then -- ignore if IPv6 selected OR -- ignore everything except "web" return "" elseif not value or #value == 0 then return nil, err_tab_adv(self) .. translate("missing / required") end local url = DDNS.parse_url(value) if not (url.scheme == "http" or url.scheme == "https") then return nil, err_tab_adv(self) .. translate("must start with 'http://'") elseif not url.host then return nil, err_tab_adv(self) .. "<HOST> " .. translate("missing / required") elseif SYS.call([[nslookup ]] .. url.host .. [[>/dev/null 2>&1]]) ~= 0 then return nil, err_tab_adv(self) .. translate("can not resolve host: ") .. url.host else return value end end function iurl4.write(self, section, value) if usev6:formvalue(section) == "1" or src4:formvalue(section) ~= "web" then -- ignore if IPv6 selected OR -- ignore everything except "web" return true else self.map:del(section, self.option) -- delete "ipv4_url" helper return self.map:set(section, "ip_url", value) -- and write "ip_url" end end -- IPv6 - ip_url (default "checkipv6.dyndns.com") -- ########################### iurl6 = ns:taboption("advanced", Value, "ipv6_url", translate("URL to detect") .. " [IPv6]" ) iurl6:depends("ipv6_source", "web") iurl6.default = "http://checkipv6.dyndns.com" if has_ipv6 then iurl6.description = translate("Defines the Web page to read systems IPv6-Address from") else iurl6.description = err_ipv6_other end function iurl6.cfgvalue(self, section) return DDNS.read_value(self, section, "ip_url") end function iurl6.validate(self, value) if usev6:formvalue(section) == "0" or src6:formvalue(section) ~= "web" then -- ignore if IPv4 selected OR -- ignore everything except "web" return "" elseif not has_ipv6 then return nil, err_tab_adv(self) .. err_ipv6_plain elseif not value or #value == 0 then return nil, err_tab_adv(self) .. translate("missing / required") end local url = DDNS.parse_url(value) if not (url.scheme == "http" or url.scheme == "https") then return nil, err_tab_adv(self) .. translate("must start with 'http://'") elseif not url.host then return nil, err_tab_adv(self) .. "<HOST> " .. translate("missing / required") elseif SYS.call([[nslookup ]] .. url.host .. [[>/dev/null 2>&1]]) ~= 0 then return nil, err_tab_adv(self) .. translate("can not resolve host: ") .. url.host else return value end end function iurl6.write(self, section, value) if usev6:formvalue(section) == "0" or src6:formvalue(section) ~= "web" then -- ignore if IPv4 selected OR -- ignore everything except "web" return true else self.map:del(section, self.option) -- delete "ipv6_url" helper return self.map:set(section, "ip_url", value) -- and write "ip_url" end end -- IPv4 + IPv6 - ip_interface -- ############################################### ipi = ns:taboption("advanced", ListValue, "ip_interface", translate("Interface"), translate("Defines the interface to read systems IP-Address from") ) ipi:depends("ipv4_source", "interface") -- IPv4 ipi:depends("ipv6_source", "interface") -- or IPv6 for _, v in pairs(SYS.net.devices()) do -- show only interface set to a network -- and ignore loopback net = WADM.iface_get_network(v) if net and net ~= "loopback" then ipi:value(v) end end function ipi.validate(self, value) if (usev6:formvalue(section) == "0" and src4:formvalue(section) ~= "interface") or (usev6:formvalue(section) == "1" and src6:formvalue(section) ~= "interface") then return "" else return value end end function ipi.write(self, section, value) if (usev6:formvalue(section) == "0" and src4:formvalue(section) ~= "interface") or (usev6:formvalue(section) == "1" and src6:formvalue(section) ~= "interface") then return true else -- get network from device to -- set also as "interface" for monitoring events changes/hotplug local net = WADM.iface_get_network(value) self.map:set(section, "interface", net) return self.map:set(section, self.option, value) end end -- IPv4 + IPv6 - ip_script (NEW) -- ############################################ ips = ns:taboption("advanced", Value, "ip_script", translate("Script"), translate("User defined script to read systems IP-Address") ) ips:depends("ipv4_source", "script") -- IPv4 ips:depends("ipv6_source", "script") -- or IPv6 ips.rmempty = false ips.placeholder = "/path/to/script.sh" function ips.validate(self, value) local split if value then split = UTIL.split(value, " ") end if (usev6:formvalue(section) == "0" and src4:formvalue(section) ~= "script") or (usev6:formvalue(section) == "1" and src6:formvalue(section) ~= "script") then return "" elseif not value or not (#value > 0) or not NXFS.access(split[1], "x") then return nil, err_tab_adv(self) .. translate("not found or not executable - Sample: '/path/to/script.sh'") else return value end end function ips.write(self, section, value) if (usev6:formvalue(section) == "0" and src4:formvalue(section) ~= "script") or (usev6:formvalue(section) == "1" and src6:formvalue(section) ~= "script") then return true else return self.map:set(section, self.option, value) end end -- IPv4 - interface - default "wan" -- ######################################### -- event network to monitor changes/hotplug/dynamic_dns_updater.sh -- only needs to be set if "ip_source"="web" or "script" -- if "ip_source"="network" or "interface" we use their network eif4 = ns:taboption("advanced", ListValue, "ipv4_interface", translate("Event Network") .. " [IPv4]", translate("Network on which the ddns-updater scripts will be started") ) eif4:depends("ipv4_source", "web") eif4:depends("ipv4_source", "script") eif4.default = "wan" WADM.cbi_add_networks(eif4) function eif4.cfgvalue(self, section) return DDNS.read_value(self, section, "interface") end function eif4.validate(self, value) if usev6:formvalue(section) == "1" or src4:formvalue(section) == "network" or src4:formvalue(section) == "interface" then return "" -- ignore IPv6, network, interface else return value end end function eif4.write(self, section, value) if usev6:formvalue(section) == "1" or src4:formvalue(section) == "network" or src4:formvalue(section) == "interface" then return true -- ignore IPv6, network, interface else self.map:del(section, self.option) -- delete "ipv4_interface" helper return self.map:set(section, "interface", value) -- and write "interface" end end -- IPv6 - interface (NEW) - default "wan6" -- ################################## -- event network to monitor changes/hotplug (NEW) -- only needs to be set if "ip_source"="web" or "script" -- if "ip_source"="network" or "interface" we use their network eif6 = ns:taboption("advanced", ListValue, "ipv6_interface", translate("Event Network") .. " [IPv6]" ) eif6:depends("ipv6_source", "web") eif6:depends("ipv6_source", "script") eif6.default = "wan6" WADM.cbi_add_networks(eif6) if not has_ipv6 then eif6.description = err_ipv6_other else eif6.description = translate("Network on which the ddns-updater scripts will be started") end function eif6.cfgvalue(self, section) return DDNS.read_value(self, section, "interface") end function eif6.validate(self, value) if usev6:formvalue(section) == "0" or src4:formvalue(section) == "network" or src4:formvalue(section) == "interface" then return "" -- ignore IPv4, network, interface elseif not has_ipv6 then return nil, err_tab_adv(self) .. err_ipv6_plain else return value end end function eif6.write(self, section, value) if usev6:formvalue(section) == "0" or src4:formvalue(section) == "network" or src4:formvalue(section) == "interface" then return true -- ignore IPv4, network, interface else self.map:del(section, self.option) -- delete "ipv6_interface" helper return self.map:set(section, "interface", value) -- and write "interface" end end -- IPv4/IPv6 - bind_network -- ################################################# if has_ssl or ( ( m:get(section, "bind_network") or "" ) ~= "" ) then bnet = ns:taboption("advanced", ListValue, "bind_network", translate("Bind Network") ) bnet:depends("ipv4_source", "web") bnet:depends("ipv6_source", "web") bnet.rmempty = true bnet.default = "" bnet:value("", translate("-- default --")) WADM.cbi_add_networks(bnet) function bnet.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if not has_ssl and value ~= "" then self.description = bold_on .. font_red .. translate("Binding to a specific network not supported") .. font_off .. "<br />" .. translate("please set to 'default'") .. " !" .. bold_off else self.description = translate("OPTIONAL: Network to use for communication") .. "<br />" .. translate("Casual users should not change this setting") end return value end function bnet.validate(self, value) if (value ~= "" and has_ssl ) or value == "" then return value end return nil, err_tab_adv(self) .. translate("Binding to a specific network not supported") .. " !" end end -- IPv4 + IPv6 - force_ipversion (NEW) -- ###################################### -- optional to force wget/curl and host to use only selected IP version -- command parameter "-4" or "-6" if has_force or ( ( m:get(section, "force_ipversion") or "0" ) ~= "0" ) then fipv = ns:taboption("advanced", Flag, "force_ipversion", translate("Force IP Version") ) fipv.orientation = "horizontal" function fipv.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if not has_force and value ~= "0" then self.description = bold_on .. font_red .. translate("Force IP Version not supported") .. font_off .. "<br />" .. translate("please disable") .. " !" .. bold_off else self.description = translate("OPTIONAL: Force the usage of pure IPv4/IPv6 only communication.") end return value end function fipv.validate(self, value) if (value == "1" and has_force) or value == "0" then return value end return nil, err_tab_adv(self) .. translate("Force IP Version not supported") end function fipv.parse(self, section) DDNS.flag_parse(self, section) end function fipv.write(self, section, value) if value == "1" then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end end -- IPv4 + IPv6 - dns_server (NEW) -- ########################################### -- optional DNS Server to use resolving my IP if "ip_source"="web" dns = ns:taboption("advanced", Value, "dns_server", translate("DNS-Server"), translate("OPTIONAL: Use non-default DNS-Server to detect 'Registered IP'.") .. "<br />" .. translate("Format: IP or FQDN")) dns.placeholder = "mydns.lan" function dns.validate(self, value) -- if .datatype is set, then it is checked before calling this function if not value then return "" -- ignore on empty elseif not DTYP.host(value) then return nil, err_tab_adv(self) .. translate("use hostname, FQDN, IPv4- or IPv6-Address") else local ipv6 = usev6:formvalue(section) local force = (fipv) and fipv:formvalue(section) or "0" local command = [[/usr/lib/ddns/dynamic_dns_lucihelper.sh verify_dns ]] .. value .. [[ ]] .. ipv6 .. [[ ]] .. force local ret = SYS.call(command) if ret == 0 then return value -- everything OK elseif ret == 2 then return nil, err_tab_adv(self) .. translate("nslookup can not resolve host") elseif ret == 3 then return nil, err_tab_adv(self) .. translate("nc (netcat) can not connect") elseif ret == 4 then return nil, err_tab_adv(self) .. translate("Forced IP Version don't matched") else return nil, err_tab_adv(self) .. translate("unspecific error") end end end -- IPv4 + IPv6 - force_dnstcp (NEW) -- ######################################### if has_dnstcp or ( ( m:get(section, "force_dnstcp") or "0" ) ~= "0" ) then tcp = ns:taboption("advanced", Flag, "force_dnstcp", translate("Force TCP on DNS") ) tcp.orientation = "horizontal" function tcp.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if not has_dnstcp and value ~= "0" then self.description = bold_on .. font_red .. translate("DNS requests via TCP not supported") .. font_off .. "<br />" .. translate("please disable") .. " !" .. bold_off else self.description = translate("OPTIONAL: Force the use of TCP instead of default UDP on DNS requests.") end return value end function tcp.validate(self, value) if (value == "1" and has_dnstcp ) or value == "0" then return value end return nil, err_tab_adv(self) .. translate("DNS requests via TCP not supported") end function tcp.parse(self, section) DDNS.flag_parse(self, section) end end -- IPv4 + IPv6 - proxy (NEW) -- ################################################ -- optional Proxy to use for http/https requests [user:password@]proxyhost[:port] if has_proxy or ( ( m:get(section, "proxy") or "" ) ~= "" ) then pxy = ns:taboption("advanced", Value, "proxy", translate("PROXY-Server") ) pxy.placeholder="user:[email protected]:8080" function pxy.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if not has_proxy and value ~= "" then self.description = bold_on .. font_red .. translate("PROXY-Server not supported") .. font_off .. "<br />" .. translate("please remove entry") .. "!" .. bold_off else self.description = translate("OPTIONAL: Proxy-Server for detection and updates.") .. "<br />" .. translate("Format") .. ": " .. bold_on .. "[user:password@]proxyhost:port" .. bold_off .. "<br />" .. translate("IPv6 address must be given in square brackets") .. ": " .. bold_on .. " [2001:db8::1]:8080" .. bold_off end return value end function pxy.validate(self, value) -- if .datatype is set, then it is checked before calling this function if not value then return "" -- ignore on empty elseif has_proxy then local ipv6 = usev6:formvalue(section) or "0" local force = (fipv) and fipv:formvalue(section) or "0" local command = [[/usr/lib/ddns/dynamic_dns_lucihelper.sh verify_proxy ]] .. value .. [[ ]] .. ipv6 .. [[ ]] .. force local ret = SYS.call(command) if ret == 0 then return value elseif ret == 2 then return nil, err_tab_adv(self) .. translate("nslookup can not resolve host") elseif ret == 3 then return nil, err_tab_adv(self) .. translate("nc (netcat) can not connect") elseif ret == 4 then return nil, err_tab_adv(self) .. translate("Forced IP Version don't matched") elseif ret == 5 then return nil, err_tab_adv(self) .. translate("proxy port missing") else return nil, err_tab_adv(self) .. translate("unspecific error") end else return nil, err_tab_adv(self) .. translate("PROXY-Server not supported") end end end -- use_syslog -- ############################################################### slog = ns:taboption("advanced", ListValue, "use_syslog", translate("Log to syslog"), translate("Writes log messages to syslog. Critical Errors will always be written to syslog.") ) slog.default = "2" slog:value("0", translate("No logging")) slog:value("1", translate("Info")) slog:value("2", translate("Notice")) slog:value("3", translate("Warning")) slog:value("4", translate("Error")) -- use_logfile (NEW) -- ######################################################## logf = ns:taboption("advanced", Flag, "use_logfile", translate("Log to file"), translate("Writes detailed messages to log file. File will be truncated automatically.") .. "<br />" .. translate("File") .. [[: "]] .. log_dir .. [[/]] .. section .. [[.log"]] ) logf.orientation = "horizontal" logf.rmempty = false -- we want to save in /etc/config/ddns file on "0" because logf.default = "1" -- if not defined write to log by default function logf.parse(self, section) DDNS.flag_parse(self, section) end -- TAB: Timer ##################################################################################### -- check_interval -- ########################################################### ci = ns:taboption("timer", Value, "check_interval", translate("Check Interval") ) ci.template = "ddns/detail_value" ci.default = 10 ci.rmempty = false -- validate ourselves for translatable error messages function ci.validate(self, value) if not DTYP.uinteger(value) or tonumber(value) < 1 then return nil, err_tab_timer(self) .. translate("minimum value 5 minutes == 300 seconds") end local secs = DDNS.calc_seconds(value, cu:formvalue(section)) if secs >= 300 then return value else return nil, err_tab_timer(self) .. translate("minimum value 5 minutes == 300 seconds") end end function ci.write(self, section, value) -- simulate rmempty=true remove default local secs = DDNS.calc_seconds(value, cu:formvalue(section)) if secs ~= 600 then --default 10 minutes return self.map:set(section, self.option, value) else self.map:del(section, "check_unit") return self.map:del(section, self.option) end end -- check_unit -- ############################################################### cu = ns:taboption("timer", ListValue, "check_unit", "not displayed, but needed otherwise error", translate("Interval to check for changed IP" .. "<br />" .. "Values below 5 minutes == 300 seconds are not supported") ) cu.template = "ddns/detail_lvalue" cu.default = "minutes" cu.rmempty = false -- want to control write process cu:value("seconds", translate("seconds")) cu:value("minutes", translate("minutes")) cu:value("hours", translate("hours")) --cu:value("days", translate("days")) function cu.write(self, section, value) -- simulate rmempty=true remove default local secs = DDNS.calc_seconds(ci:formvalue(section), value) if secs ~= 600 then --default 10 minutes return self.map:set(section, self.option, value) else return true end end -- force_interval (modified) -- ################################################ fi = ns:taboption("timer", Value, "force_interval", translate("Force Interval") ) fi.template = "ddns/detail_value" fi.default = 72 -- see dynamic_dns_updater.sh script fi.rmempty = false -- validate ourselves for translatable error messages function fi.validate(self, value) if not DTYP.uinteger(value) or tonumber(value) < 0 then return nil, err_tab_timer(self) .. translate("minimum value '0'") end local force_s = DDNS.calc_seconds(value, fu:formvalue(section)) if force_s == 0 then return value end local ci_value = ci:formvalue(section) if not DTYP.uinteger(ci_value) then return "" -- ignore because error in check_interval above end local check_s = DDNS.calc_seconds(ci_value, cu:formvalue(section)) if force_s >= check_s then return value end return nil, err_tab_timer(self) .. translate("must be greater or equal 'Check Interval'") end function fi.write(self, section, value) -- simulate rmempty=true remove default local secs = DDNS.calc_seconds(value, fu:formvalue(section)) if secs ~= 259200 then --default 72 hours == 3 days return self.map:set(section, self.option, value) else self.map:del(section, "force_unit") return self.map:del(section, self.option) end end -- force_unit -- ############################################################### fu = ns:taboption("timer", ListValue, "force_unit", "not displayed, but needed otherwise error", translate("Interval to force updates send to DDNS Provider" .. "<br />" .. "Setting this parameter to 0 will force the script to only run once" .. "<br />" .. "Values lower 'Check Interval' except '0' are not supported") ) fu.template = "ddns/detail_lvalue" fu.default = "hours" fu.rmempty = false -- want to control write process --fu:value("seconds", translate("seconds")) fu:value("minutes", translate("minutes")) fu:value("hours", translate("hours")) fu:value("days", translate("days")) function fu.write(self, section, value) -- simulate rmempty=true remove default local secs = DDNS.calc_seconds(fi:formvalue(section), value) if secs ~= 259200 and secs ~= 0 then --default 72 hours == 3 days return self.map:set(section, self.option, value) else return true end end -- retry_count (NEW) -- ######################################################## rc = ns:taboption("timer", Value, "retry_count") rc.title = translate("Error Retry Counter") rc.description = translate("On Error the script will stop execution after given number of retrys") .. "<br />" .. translate("The default setting of '0' will retry infinite.") rc.default = 0 rc.rmempty = false -- validate ourselves for translatable error messages function rc.validate(self, value) if not DTYP.uinteger(value) then return nil, err_tab_timer(self) .. translate("minimum value '0'") else return value end end function rc.write(self, section, value) -- simulate rmempty=true remove default if tonumber(value) ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end -- retry_interval -- ########################################################### ri = ns:taboption("timer", Value, "retry_interval", translate("Error Retry Interval") ) ri.template = "ddns/detail_value" ri.default = 60 ri.rmempty = false -- validate ourselves for translatable error messages function ri.validate(self, value) if not DTYP.uinteger(value) or tonumber(value) < 1 then return nil, err_tab_timer(self) .. translate("minimum value '1'") else return value end end function ri.write(self, section, value) -- simulate rmempty=true remove default local secs = DDNS.calc_seconds(value, ru:formvalue(section)) if secs ~= 60 then --default 60seconds return self.map:set(section, self.option, value) else self.map:del(section, "retry_unit") return self.map:del(section, self.option) end end -- retry_unit -- ############################################################### ru = ns:taboption("timer", ListValue, "retry_unit", "not displayed, but needed otherwise error", translate("On Error the script will retry the failed action after given time") ) ru.template = "ddns/detail_lvalue" ru.default = "seconds" ru.rmempty = false -- want to control write process ru:value("seconds", translate("seconds")) ru:value("minutes", translate("minutes")) --ru:value("hours", translate("hours")) --ru:value("days", translate("days")) function ru.write(self, section, value) -- simulate rmempty=true remove default local secs = DDNS.calc_seconds(ri:formvalue(section), value) if secs ~= 60 then --default 60seconds return self.map:set(section, self.option, value) else return true -- will be deleted by retry_interval end end -- TAB: LogView (NEW) ############################################################################# lv = ns:taboption("logview", DummyValue, "_logview") lv.template = "ddns/detail_logview" lv.inputtitle = translate("Read / Reread log file") lv.rows = 50 function lv.cfgvalue(self, section) local lfile=log_dir .. "/" .. section .. ".log" if NXFS.access(lfile) then return lfile .. "\n" .. translate("Please press [Read] button") end return lfile .. "\n" .. translate("File not found or empty") end return m
local API = require(script.Parent.Parent:WaitForChild("MinimalAPI")) local SN = script.Parent.Parent:WaitForChild("Events"):WaitForChild("SendNotification") local command = {} command.Configuration = { Information = { Command = "serverban", Aliases = {"sb"}, Description = "Bans the target player from the server", Usage = "serverban [player] [reason]" }, PermissionLevel = 2 } command.Server_Bans = {} function command:Execute(player,args) if args[2] then local target = API:GetPlayer(args[2]) if target then if args[3] == nil then args[3] = "No reason specified" end local targetId = target.UserId table.insert(command.Server_Bans,#command.Server_Bans+1,{UserId=targetId,Reason=args[3]}) target:Kick("You have been server banned: "..args[3]) SN:FireClient(player,{Text = "Player has been server banned", Duration = 3, Color = Color3.fromRGB(100,250,100), ClickFunction = "Close"}) else SN:FireClient(player,{Text = "Could not find player", Duration = 3, Color = Color3.fromRGB(250,50,50), ClickFunction = "Close"}) end else SN:FireClient(player,{Text = "You must specify a player", Duration = 3, Color = Color3.fromRGB(250,50,50), ClickFunction = "Close"}) end end game.Players.PlayerAdded:Connect(function(plr) for _,v in pairs(command.Server_Bans) do if plr.UserId == v.UserId then plr:Kick("You have been server banned: "..v.Reason) end end end) return command
players = {} function tablefind(tab, el) for index, value in pairs(tab) do if value == el then return index end end return nil end function countBots() local count = 0 for index, value in pairs(players) do local isBot = game:isbot(value) if isBot == 1 then count = count + 1 end end return count end function removePlayer(player) local index = tablefind(players, player) if index ~= nil then table.remove(players, index) end end function kickPlayer(player) local clientNum = player:getentitynumber() game:kickplayer(clientNum) end function kickLeftoverBot(player) local timer = game:ontimeout( function() kickPlayer(player) end, 10000 ) timer:endon(player, "spawned_player") end function player_connected(player) player:onnotifyonce( "disconnect", function() removePlayer(player) end ) table.insert(players, player) local isBot = game:isbot(player) if isBot == 1 then player:botsetdifficulty("default") kickLeftoverBot(player) end end function kickBot() for index, player in pairs(players) do local isBot = game:isbot(player) if isBot == 1 then kickPlayer(player) break end end end function spawnBot() game:executecommand("spawnbot 1") end function monitor() local count = #players local botCount = countBots() if count < 10 and botCount < 6 then spawnBot() elseif count > 14 and botCount > 0 then kickBot() end end function startLogic() game:oninterval(monitor, 3000) end if game:getdvar("gamemode") == "mp" then game:executecommand("spawnbot 6") level:onnotifyonce("matchStartTimer", startLogic) level:onnotify("connected", player_connected) end
local php = {} php.psysh = { command = {"psysh"}, } php.php = { command = {"php", "-a"}, } return php
DRONES_REWRITE.Overlay["Sci Fi"] = function(drone) local eff_tab = { ["$pp_colour_addr"] = 0, ["$pp_colour_addg"] = 0.1, ["$pp_colour_addb"] = 0.1, ["$pp_colour_brightness"] = -0.25, ["$pp_colour_contrast"] = 1.2, ["$pp_colour_colour"] = 0.25, ["$pp_colour_mulr"] = 0, ["$pp_colour_mulg"] = 0, ["$pp_colour_mulb"] = 0 } DrawColorModify(eff_tab) DrawBloom(0.5, 1, 1, 1, 1, 1, 1, 1, 1) DrawSharpen(2, 0.5) end
function lovr.conf(t) -- Set the project identity t.identity = 'Core' -- Hotkeys t.hotkeys = true -- Headset settings t.headset.drivers = {}--{ 'leap', 'openxr', 'oculus', 'oculusmobile', 'openvr', 'webvr', 'desktop' } t.headset.msaa = 0 t.headset.offset = 0 -- Math settings --t.math.globals = true -- Enable or disable different modules t.modules.audio = false t.modules.data = true t.modules.event = true t.modules.graphics = true t.modules.headset = false t.modules.math = true t.modules.physics = true t.modules.thread = true t.modules.timer = true -- Configure the desktop window t.window.width = 1900 t.window.height = 900 t.window.fullscreen = false t.window.msaa = 0 t.window.vsync = 0 t.window.title = 'Core' t.window.icon = nil end
-------------------------------------------------------------------------------- -- Module Declaration -- local mod, CL = BigWigs:NewBoss("Tik'ali", 1594, 2114) if not mod then return end mod:RegisterEnableMob(129227) mod.engageId = 2106 mod.respawnTime = 30 -------------------------------------------------------------------------------- -- Initialization -- function mod:GetOptions() return { 271698, -- Azerite Infusion 258622, -- Resonant Pulse 257593, -- Call Earthrager {257582, "SAY"}, -- Raging Gaze 275907, -- Tectonic Smash }, { [271698] = "general", [275907] = "heroic", } end function mod:OnBossEnable() self:Log("SPELL_CAST_START", "CallEarthrager", 257593) self:Log("SPELL_AURA_APPLIED", "RagingGaze", 257582) self:Log("SPELL_CAST_SUCCESS", "AzeriteInfusion", 271698) self:Log("SPELL_CAST_START", "ResonantPulse", 258622) self:Log("SPELL_CAST_START", "TectonicSmash", 275907) end function mod:OnEngage() self:Bar(258622, 9.5) -- Resonant Pulse self:Bar(271698, 20) -- Azerite Infusion self:Bar(257593, 64) -- Call Earthrager if not self:Normal() then self:Bar(275907, 5) -- Tectonic Smash end end -------------------------------------------------------------------------------- -- Event Handlers -- function mod:CallEarthrager(args) self:Message2(args.spellId, "cyan") self:PlaySound(args.spellId, "info", "mobsoon") --self:Bar(args.spellId, 64) -- XXX Only seen it once end do local playerList = mod:NewTargetList() local prev = 0 function mod:RagingGaze(args) playerList[#playerList+1] = args.destName local t = args.time if self:Me(args.destGUID) and t-prev > 0.3 then -- Only run once per targetsmessage prev = t self:PlaySound(args.spellId, "warning", "fixate") self:Say(args.spellId) end self:TargetsMessage(args.spellId, "red", playerList) end end function mod:AzeriteInfusion(args) self:Message2(args.spellId, "yellow") self:PlaySound(args.spellId, "alert", "killmob") self:Bar(args.spellId, 17) end function mod:ResonantPulse(args) self:Message2(args.spellId, "orange") self:PlaySound(args.spellId, "long", "aesoon") self:Bar(args.spellId, 34) end function mod:TectonicSmash(args) self:Message2(args.spellId, "red") self:PlaySound(args.spellId, "alarm") self:CDBar(args.spellId, 21) end
local class = require('src.Utils.MiddleClass'); local Logger = require('src.Utils.Logger'); local Node = require('src.Node'); --- Adds a reference to a subtree in the behavior tree, to execute a same behavior --- in many different parts of the tree. ---@class SubTree: Node ---@field ref string The id of the referenced subtree. local SubTree = class('SubTree', Node); function SubTree:start() if self._referencedNode == nil then self:_findReferencedNode(); end self._referencedNode:start(); end function SubTree:tick() if self._referencedNode == nil then self:_findReferencedNode(); end self._referencedNode:tick(); end function SubTree:finish() if self._referencedNode == nil then self:_findReferencedNode(); end self._referencedNode:finish(); end function SubTree:failure() if self._referencedNode == nil then self:_findReferencedNode(); end self._referencedNode:failure() end function SubTree:running() if self._referencedNode == nil then self:_findReferencedNode(); end self._referencedNode:running(); end function SubTree:success() if self._referencedNode == nil then self:_findReferencedNode(); end self._referencedNode:success(); end function SubTree:setSubject(subject) if self._referencedNode == nil then self:_findReferencedNode(); end self._referencedNode:setSubject(subject); end function SubTree:_setParent(parent) Node._setParent(self, parent); if self._referencedNode == nil then self:_findReferencedNode(); end self._referencedNode:_setParent(parent); end function SubTree:_parseXmlNode(node, context) if node._name ~= self.class.name then Logger.error('Tried to parse an invalid node as a ' .. self.class.name .. ' node.'); end if node._children.n ~= 0 then Logger.error('The ' .. self.class.name .. ' node cannot have children.'); end if not node._attr or not node._attr.ref then Logger.error('The ' .. self.class.name .. ' node must have a name attribute.'); end self.ref = node._attr.ref; end function SubTree:_findReferencedNode() local tree = self:getNearestBehaviorTreeNode(); for key, value in pairs(tree.subtrees) do if key == self.ref then self._referencedNode = value; break; end end return self._referencedNode; end return SubTree;
function love.conf(t) t.console = true -- enable the console end function love.run() if love.math then love.math.setRandomSeed(os.time()) end if love.load then love.load(arg) end if love.timer then love.timer.step() end local dt = 0 local accumulator = 0 local TICK_RATE = 1 / 30 while true do -- process events if love.event then love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then if not love.quit or not love.quit() then return a end end love.handlers[name](a,b,c,d,e,f) end end -- update dt if love.timer then love.timer.step() dt = love.timer.getDelta() end -- limit dt if dt > TICK_RATE * 2 then dt = TICK_RATE * 2 end -- update game accumulator = accumulator + dt while accumulator >= TICK_RATE do accumulator = accumulator - TICK_RATE if love.update then love.update() end end -- render game if love.graphics and love.graphics.isActive() then love.graphics.clear(love.graphics.getBackgroundColor()) love.graphics.origin() if love.draw then local alpha = accumulator / TICK_RATE love.draw(alpha) end love.graphics.present() end -- sleep if love.timer then love.timer.sleep(0.001) end end end
require "debugLog" require "wagons.wagon" function on_init() debugLog( 1, "on_init()" ) global.logisticWagons = global.logisticWagons or {} end function on_tick( event ) local syncTicks = settings.global[ "lw-sync-ticks" ].value if( ( event.tick % syncTicks ) ~= 0 )then return end debugLog( 4, "on_tick()" ) for i, wagon in pairs( global.logisticWagons ) do wagon_on_tick( wagon ) end end function on_built_entity( event ) local entity = event.created_entity local proxy_name = get_proxy_name( entity.name ) if( proxy_name ~= nil )then debugLog( 1, "on_built_entity() :: entity = " .. event.name .. " :: proxy = " .. proxy_name ) local wagon = wagon_create( entity, proxy_name ) if( wagon ~= nil )then table.insert( global.logisticWagons, wagon ) end end end function on_entity_removed( event ) local entity = event.entity local i = find_wagon_index( entity ) if( i ~= nil )then debugLog( 1, "on_entity_removed() :: wagon_index = " .. i ) wagon_remove_proxy( global.logisticWagons[ i ] ) table.remove( global.logisticWagons, i ) end end function on_gui_opened( event ) local entity = event.entity debugLog( 1, "on_gui_opened() :: event = " .. serpent.dump( event ), nil, true ) dumpWagons() local i = find_wagon_index( entity ) if( i ~= nil )then local wagon = global.logisticWagons[ i ] debugLog( 1, "on_gui_opened() :: index = " .. i .. " :: wagon = " .. serpent.dump( wagon ), nil, true ) wagon_on_gui_opened( wagon, event ) end end function get_proxy_name( name ) if( name == "lw-cargo-wagon-passive" )then return "lw-logistic-chest-passive-provider-trans" elseif( name == "lw-cargo-wagon-active" )then return "lw-logistic-chest-active-provider-trans" elseif( name == "lw-cargo-wagon-requester" )then return "lw-logistic-chest-requester-trans" elseif( name == "lw-cargo-wagon-storage" )then return "lw-logistic-chest-storage-provider-trans" end return nil end function find_wagon_index( entity ) if( entity == nil )then return nil end global.logisticWagons = global.logisticWagons or {} for i = 1, #global.logisticWagons do local wagon = global.logisticWagons[ i ] if( entity.unit_number ~= nil )then if( wagon.entity.unit_number == entity.unit_number )then return i end end end return nil end function find_wagon( entity ) local i = find_wagon_index( entity ) if( i ~= nil )then return global.logisticWagons[ i ] end return nil end function dumpWagons() global.logisticWagons = global.logisticWagons or {} for i = 1, #global.logisticWagons do local wagon = global.logisticWagons[ i ] debugLog( 0, "index = " .. i .. " :: wagon.entity.unit_number = " .. wagon.entity.unit_number, serpent.dump( wagon ) ) end end -- Initialization script.on_init( on_init ) script.on_load( on_load ) -- Entity was placed on map script.on_event( { defines.events.on_built_entity, defines.events.on_robot_built_entity, defines.events.script_raised_built }, function( event ) on_built_entity( event ) end ) -- Entity item was removed from the map script.on_event( { defines.events.on_entity_died, defines.events.on_pre_player_mined_item, defines.events.on_robot_pre_mined, defines.events.script_raised_destroy }, function( event ) on_entity_removed( event ) end ) -- GUI was opened script.on_event( { defines.events.on_gui_opened }, function( event ) on_gui_opened( event ) end ) -- Main loop script.on_event( defines.events.on_tick, function( event ) on_tick( event ) end )
--[[ Copyright 2008-2018 João Cardoso Sushi is distributed under the terms of the GNU General Public License (or the Lesser GPL). This file is part of Sushi. Sushi 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. Sushi 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 Sushi. If not, see <http://www.gnu.org/licenses/>. --]] local Check = SushiCheck local Expand = MakeSushi(1, 'CheckButton', 'ExpandCheck', nil, nil, Check) if not Expand then return end Expand.left = Check.left + 14 --[[ Events ]]-- function Expand:OnCreate() local toggle = CreateFrame('Button', nil, self) toggle:SetNormalTexture('Interface\\Buttons\\UI-PlusButton-UP') toggle:SetPushedTexture('Interface\\Buttons\\UI-PlusButton-DOWN') toggle:SetHighlightTexture('Interface\\Buttons\\UI-PlusButton-Hilight') toggle:SetScript('OnClick', function() self:OnExpandClick() end) toggle:SetPoint('LEFT', self, -14, 0) toggle:SetSize(14, 14) self.toggle = toggle Check.OnCreate(self) end function Expand:OnRelease() Check.OnRelease(self) self:SetExpanded(nil) end function Expand:OnExpandClick() local expanded = not self.expanded self:SetExpanded(expanded) self:FireCall('OnToggle', expanded) self:FireCall('OnExpand', expanded) self:FireCall('OnUpdate') end --[[ Expansion ]]-- function Expand:SetExpanded(expanded) local texture = expanded and 'MINUS' or 'PLUS' self.toggle:SetNormalTexture('Interface\\Buttons\\UI-' .. texture .. 'Button-UP') self.toggle:SetPushedTexture('Interface\\Buttons\\UI-' .. texture .. 'Button-DOWN') self.expanded = expanded end function Expand:IsExpanded() return self.expanded end
--- Stand alone text formatter object. Remembers the options you set and can be adjusted as needed -- @classmod TextFormatter --@author Damian Monogue <[email protected]> --@copyright 2020 Damian Monogue --@license MIT, see LICENSE.lua local TextFormatter = {} TextFormatter.validFormatTypes = { 'd', 'dec', 'decimal', 'h', 'hex', 'hexidecimal', 'c', 'color', 'colour', 'col', 'name'} local pathOfThisFile = (...):match("(.-)[^%.]+$") local ftext = require(pathOfThisFile .. "ftext") local fText = ftext.fText --- Set's the formatting type whether it's for cecho, decho, or hecho --@tparam string typeToSet What type of formatter is this? Valid options are { 'd', 'dec', 'decimal', 'h', 'hex', 'hexidecimal', 'c', 'color', 'colour', 'col', 'name'} function TextFormatter:setType(typeToSet) local isNotValid = not table.contains(self.validFormatTypes, typeToSet) if isNotValid then error("TextFormatter:setType: Invalid argument, valid types are:" .. table.concat(self.validFormatTypes, ", ")) end self.options.formatType = typeToSet end function TextFormatter:toBoolean(thing) if type(thing) ~= "boolean" then if thing == "true" then thing = true elseif thing == "false" then thing = false else return nil end end return thing end function TextFormatter:checkString(str) if type(str) ~= "string" then if tostring(str) then str = tostring(str) else return nil end end return str end --- Sets whether or not we should do word wrapping. --@tparam boolean shouldWrap should we do wordwrapping? function TextFormatter:setWrap(shouldWrap) local argumentType = type(shouldWrap) shouldWrap = self:toBoolean(shouldWrap) if shouldWrap == nil then error("TextFormatter:setWrap(shouldWrap) Argument error, boolean expected, got " .. argumentType .. ", if you want to set the number of characters wide to format for, use setWidth()") end self.options.wrap = shouldWrap end --- Sets the width we should format for --@tparam number width the width we should format for function TextFormatter:setWidth(width) if type(width) ~= "number" then if tonumber(width) then width = tonumber(width) else error("TextFormatter:setWidth(width): Argument error, number expected, got " .. type(width)) end end self.options.width = width end --- Sets the cap for the formatter --@tparam string cap the string to use for capping the formatted string. function TextFormatter:setCap(cap) local argumentType = type(cap) local cap = self:checkString(cap) if cap == nil then error("TextFormatter:setCap(cap): Argument error, string expect, got " .. argumentType) end self.options.cap = cap end --- Sets the color for the format cap --@tparam string capColor Color which can be formatted via Geyser.Color.parse() function TextFormatter:setCapColor(capColor) local argumentType = type(capColor) local capColor = self:checkString(capColor) if capColor == nil then error("TextFormatter:setCapColor(capColor): Argument error, string expected, got " .. argumentType) end self.options.capColor = capColor end --- Sets the color for spacing character --@tparam string spacerColor Color which can be formatted via Geyser.Color.parse() function TextFormatter:setSpacerColor(spacerColor) local argumentType = type(spacerColor) local spacerColor = self:checkString(spacerColor) if spacerColor == nil then error("TextFormatter:setSpacerColor(spacerColor): Argument error, string expected, got " .. argumentType) end self.options.spacerColor = spacerColor end --- Sets the color for formatted text --@tparam string textColor Color which can be formatted via Geyser.Color.parse() function TextFormatter:setTextColor(textColor) local argumentType = type(textColor) local textColor = self:checkString(textColor) if textColor == nil then error("TextFormatter:setTextColor(textColor): Argument error, string expected, got " .. argumentType) end self.options.textColor = textColor end --- Sets the spacing character to use. Should be a single character --@tparam string spacer the character to use for spacing function TextFormatter:setSpacer(spacer) local argumentType = type(spacer) local spacer = self:checkString(spacer) if spacer == nil then error("TextFormatter:setSpacer(spacer): Argument error, string expect, got " .. argumentType) end self.options.spacer = spacer end --- Set the alignment to format for --@tparam string alignment How to align the formatted string. Valid options are 'left', 'right', or 'center' function TextFormatter:setAlignment(alignment) local validAlignments = { "left", "right", "center" } if not table.contains(validAlignments, alignment) then error("TextFormatter:setAlignment(alignment): Argument error: Only valid arguments for setAlignment are 'left', 'right', or 'center'. You sent" .. alignment) end self.options.alignment = alignment end --- Set whether the the spacer should go inside the the cap or outside of it --@tparam boolean spacerInside function TextFormatter:setInside(spacerInside) local argumentType = type(spacerInside) spacerInside = self:toBoolean(spacerInside) if spacerInside == nil then error("TextFormatter:setInside(spacerInside) Argument error, boolean expected, got " .. argumentType) end self.options.inside = spacerInside end --- Set whether we should mirror/reverse the caps. IE << becomes >> if set to true --@tparam boolean shouldMirror function TextFormatter:setMirror(shouldMirror) local argumentType = type(shouldMirror) shouldMirror = self:toBoolean(shouldMirror) if shouldMirror == nil then error("TextFormatter:setMirror(shouldMirror): Argument error, boolean expected, got " .. argumentType) end self.options.mirror = shouldMirror end --- Format a string based on the stored options --@tparam string str The string to format function TextFormatter:format(str) return fText(str, self.options) end --- Creates and returns a new TextFormatter. For valid options, please see https://github.com/demonnic/fText/wiki/fText --@tparam table options the options for the text formatter to use when running format() --<br><br>Table of options -- <table class="tg"> -- <thead> -- <tr> -- <th>option name</th> -- <th>description</th> -- <th>default</th> -- </tr> -- </thead> -- <tbody> -- <tr> -- <td class="tg-odd">wrap</td> -- <td class="tg-odd">Should it wordwrap to multiple lines?</td> -- <td class="tg-odd">true</td> -- </tr> -- <tr> -- <td class="tg-even">formatType</td> -- <td class="tg-even">Determines how it formats for color. 'c' for cecho, 'd' for decho, 'h' for hecho, and anything else for no colors</td> -- <td class="tg-even">"c"</td> -- </tr> -- <tr> -- <td class="tg-odd">width</td> -- <td class="tg-odd">How wide should we format the text?</td> -- <td class="tg-odd">80</td> -- </tr> -- <tr> -- <td class="tg-even">cap</td> -- <td class="tg-even">what characters to use for the endcap.</td> -- <td class="tg-even">""</td> -- </tr> -- <tr> -- <td class="tg-odd">capColor</td> -- <td class="tg-odd">what color to make the endcap?</td> -- <td class="tg-odd">the correct 'white' for your formatType</td> -- </tr> -- <tr> -- <td class="tg-even">spacer</td> -- <td class="tg-even">What character to use for empty space. Must be a single character</td> -- <td class="tg-even">" "</td> -- </tr> -- <tr> -- <td class="tg-odd">spacerColor</td> -- <td class="tg-odd">what color should the spacer be?</td> -- <td class="tg-odd">the correct 'white' for your formatType</td> -- </tr> -- <tr> -- <td class="tg-even">textColor</td> -- <td class="tg-even">what color should the text itself be?</td> -- <td class="tg-even">the correct 'white' for your formatType</td> -- </tr> -- <tr> -- <td class="tg-odd">alignment</td> -- <td class="tg-odd">How should the text be aligned within the width. "center", "left", or "right"</td> -- <td class="tg-odd">"center"</td> -- </tr> -- <tr> -- <td class="tg-even">nogap</td> -- <td class="tg-even">Should we put a literal space between the spacer character and the text?</td> -- <td class="tg-even">false</td> -- </tr> -- <tr> -- <td class="tg-odd">inside</td> -- <td class="tg-odd">Put the spacers inside the caps?</td> -- <td class="tg-odd">false</td> -- </tr> -- <tr> -- <td class="tg-even">mirror</td> -- <td class="tg-even">Should the endcap be reversed on the right? IE [[ becomes ]]</td> -- <td class="tg-even">true</td> -- </tr> -- </tbody> -- </table> function TextFormatter:new(options) if options == nil then options = {} end if options and type(options) ~= "table" then error("TextFormatter:new(options): Argument error, table expected, got " .. type(options)) end local me = {} me.options = { formatType = "c", wrap = true, width = 80, cap = "", spacer = " ", alignment = "center", inside = true, mirror = false, } for option, value in pairs(options) do me.options[option] = value end setmetatable(me, self) self.__index = self return me end return TextFormatter
ITEM.name = "FN P90" ITEM.description = "A sub machine gun chambered in 5.7x28mm." ITEM.model = "models/weapons/ethereal/w_p90.mdl" ITEM.class = "cw_kk_ins2_p90" ITEM.weaponCategory = "primary" ITEM.width = 3 ITEM.height = 2 ITEM.price = 46000 ITEM.weight = 6
--[=====[ ## XP MultiBar ver. @@release-version@@ ## XPMultiBar_Bars.lua - module Bar displaying logic for XPMultiBar addon --]=====] local addonName = ... local Utils = LibStub("rmUtils-1.0") local XPMultiBar = LibStub("AceAddon-3.0"):GetAddon(addonName) local Bars = XPMultiBar:NewModule("Bars") local B = Bars -- Remove all known globals after this point -- luacheck: std none -- Bar consts B.None = 0 B.XP = 1 B.AZ = 2 B.REP = 3 local currentSettings = { priority = {}, isMaxLevelXP = false, hasAzerite = false, isMaxLevelAzerite = false, } local currentState = { isOver = false, isAlt = false, isShift = false, } local currentBars = nil local visibleBar = nil local mouseOverWithShift = nil local function GetCurrentBars(state) --[[ 1. 0 0 ? 2. 0 1 ? 2C. 1 0 ? 3. 1 1 0 4. 1 1 1 5. 1 0 0 -- For 9.0.1 Prepatch ]] local prio, maxLevelXP, hasAzerite, maxLevelAzer = state.priority, state.isMaxLevelXP, state.hasAzerite, state.isMaxLevelAzerite local index if not maxLevelXP and not hasAzerite then index = 1 elseif not maxLevelXP then index = 2 elseif not hasAzerite then index = 5 elseif not maxLevelAzer then index = 3 else index = 4 end return Utils.SliceLength(prio, (index - 1) * 3 + 1, 3) end function B:OnInitialize() end function B.UpdateBarSettings(barSettings) Utils.Override(currentSettings, barSettings) currentBars = GetCurrentBars(currentSettings) end function B.UpdateBarState(isOver, isAlt, isShift) if isOver == nil then isOver, isAlt, isShift = currentState.isOver, currentState.isAlt, currentState.isShift end mouseOverWithShift = isOver and isShift Utils.Override(currentState, { isOver = false, isAlt = false, isShift = false, }) if not isOver or mouseOverWithShift then visibleBar = currentBars[1] elseif isAlt then visibleBar = currentBars[3] else visibleBar = currentBars[2] end end function B.GetVisibleBar() return visibleBar end
local nmatch = ngx.re.match local ins = table.insert ---dump ---@param obj table @object to dump ---@param name string function dump(obj, name) name = name or '' ngx.print(dump_lua(obj, name)) end ---dump_log dump into the log ---@param obj table ---@param name string function dump_log(obj, name) name = name or '' local info = nmatch(debug.traceback('debug', 2), [[traceback:\s+([\s\S]+>)]], 'jo')[1] obj = { traceback = info, [name] = obj } ngx.log(ngx.NOTICE, dump_lua(obj, '')) end ---log easy way to log multiple object, string, function --- default with WARN level function log(...) local arr = { ... } local sb = string.buffer() local info = '\n' .. nmatch(debug.traceback('debug', 2), [[traceback:\s+([\s\S]+>)]], 'jo')[1]..'\n' for i = 1, #arr do local val = arr[i] local tp = type(val) if tp == 'table' then sb:add(dump_lua(val, i)) elseif tp == 'function' then local fi = parse_func(val, '', false) sb:add('function(' .. fi.param .. [[) end'\t\t-- ]] .. fi.source .. '\n') else sb:add(val) end end ngx.log(ngx.WARN, info, sb:tos('\n')..'\n') end ---dump_lua ---@param obj ebitop @object to dump out ---@param name string @name for the description ---@param sb sbuffer @buffer writer ---@param indent_depth number @indention level ---@return string @ dumpped text function dump_lua(obj, name, sb, indent_depth) local is_root, indent = false, '' if not sb then sb = string.buffer('\n') is_root = true indent_depth = 0 end name = name or '' if indent_depth > 0 then indent = string.rep( '\t', indent_depth) end -- name = name or debug.getinfo(2).namewhat if (name ~= '') then if type(name) == 'number' then --sb:add(indent,'[', name, '] = {\n') sb:add(indent, '{\n') else sb:add(indent, name, ' = {\n') end else sb:add(indent, '{\n') end if type(obj) ~= 'table' then return '\n\t' .. name .. ' = ' .. tostring(obj) .. '\n' end for key, var in pairs(obj) do if key then local tps = type(var) if tps == 'function' then local fi = parse_func(var, key) sb:add('\t', indent, key, ' = function(', fi.param, ') end,', indent, '\t\t\t-- ', fi.source, '\n') elseif tps == 'table' then if #var ~= 0 then if type(var[1]) == 'string' then sb:add('\t', indent, key, ' = {"', table.concat(var, '", "'), '"') sb:add('},\n') elseif type(var[1]) == 'number' then sb:add('\t', indent, key, ' = {', table.concat(var, ', '), '},\n') else sb:add('\t', indent, key, ' = {\n') for i = 1, #var do sb:add('', dump_lua(var[i], '', sb, indent_depth + 1)) sb:add(',\n') end sb:add('\t', indent, '},\n') end else dump_lua(var, key, sb, indent_depth + 1) sb:add(',\n') end elseif tps == 'string' then sb:add('\t', indent, key, ' = "', var, '",\n') elseif tps == 'userdata' then sb:add('\t', indent, key, ' = "', var, '",\n') else sb:add('\t', indent, key, ' = ', tostring(var), ',\n') end end end sb:add(indent, '}') if is_root then local str = sb:tos(); str = ngx.re.gsub(str, [[\},(\s+\},)]], '}$1') --remove it code still work str = ngx.re.gsub(str, [[,(\s+})]], '$1') --remove it code still work return str end end ---dump_class dump LUA class with more readable way,and suits for IDE code intellisense ---@param obj ebitop @object to dump out ---@param name string @name for the description ---@param sb sbuffer @buffer writer ---@param indent_depth number @indention level ---@return string @ dumpped text function dump_class(obj, name, sb, indent_depth) local is_root, indent = false, '' if not sb then sb = string.buffer('\n') is_root = true indent_depth = 0 end name = name or 'LUAOBJ' if indent_depth > 0 then indent = string.rep( '\t', indent_depth) end if (name ~= '') then sb:add('\n---@class ', name, '\n', name, ' = {}\n') else --sb:add(indent, '{\n') end for key, var in pairs(obj) do if key then local tps = type(var) if tps == 'function' then local fi = parse_func(var, key) sb:add('\n---@param arg string\n---@return string @type\n') sb:add('function ', name, ':', key, '(', fi.param, ') end', '\t\t\t-- ', fi.source, '\n') elseif tps == 'table' then if #var ~= 0 then if type(var[1]) == 'string' then sb:add(name, '.', key, ' = {"', table.concat(var, '", "'), '"', '}\n') elseif type(var[1]) == 'number' then sb:add(name, '.', key, ' = {', table.concat(var, ', '), '},\n') else sb:add(name, '.', key, ' = {\n') for i = 1, #var do sb:add('', dump_lua(var[i], '', sb, indent_depth)) sb:add(',\n') end sb:add('\t', indent, '}\n') end else sb:add(name, '.') dump_lua(var, key, sb, indent_depth) sb:add('\n') end elseif tps == 'number' then sb:add(name, '.', key, ' = ', tostring(var), '\n') else sb:add(name, '.', key, ' = "', tostring(var), '"\n') end end end sb:add('\n') if is_root then local str = sb:tos(); str = ngx.re.gsub(str, [[\},(\s+\},)]], '}$1') --remove it code still work str = ngx.re.gsub(str, [[,(\s+})]], '$1') --remove it code still work return str end end --[[ local sb = string.buffer('fds','1',232,4343) sb:add('11', 'ss', 123,4343, 4343):add('324324'):add('2',4356,6565,1111):add():add(nil):add(2223232):add(false):pop(1) print(sb:tos(',')) ]] ---@class sbuffer local sbuffer = {} ---new @create new stringbuffer ---@return sbuffer function sbuffer:new(...) local sbs = { buffer = { ... } } setmetatable(sbs, { __index = self }) return sbs end ---add @add multiple string args. :add(1,2,nil,'4',5) =1,2 ---@return sbuffer function sbuffer:add(...) local args = { ... } for i = 1, #args do local arg = args[i] ins(self.buffer, tostring(arg)) end return self end ---pop @remove buffer elements at tail poistion ---@param count number @element count to remove at tail position ---@return sbuffer function sbuffer:pop(count) count = count or 2 local len = #self.buffer for i = 1, count do table.remove(self.buffer, len) len = len - 1 end return self end ---tos @convert stringbuffer to string ---@param splitor string @ string to join buffer together ---@return string function sbuffer:tos(splitor) return table.concat(self.buffer, splitor) end ---buffer attach to string class function string.buffer(...) return sbuffer:new(...) end utils = {} -- fi info as below: ---@class debug.function_info local fi = { linedefined = 1, currentline = -1, func = 'function: 0x4086f228', isvararg = false, namewhat = 'func_name', lastlinedefined = 3, source = '@/root/lua/info.lua', nups = 0, what = 'Lua', nparams = 2, short_src = '/root/lua/info.lua', is_lua = true, name = 'name' } ---parse_func parse function and return function details ---@param func function @func to parse ---@param fname string @function name ---@param with_self boolean @ default :(arg1, arg2), with_self .(self, arg1, arg2) ---@return table function parse_func(func, fname, with_self) ---@type debug.function_info local fi = debug.getinfo(func) fi.name = fname local sb = string.buffer() if fi.nparams > 1 then fi.nparams = with_self and fi.nparams or fi.nparams - 1 for i = 1, fi.nparams do sb:add('arg', i, ', ') end else sb:add('arg', '') end fi.param = sb:pop(1):tos() fi.source = string.gsub(fi.source .. ' @line: ' .. fi.linedefined, [[%\]], '/') fi.is_lua = (fi.what ~= 'C') return fi end ---parse_code ---usage: --- call this function in any code. It will search for local object within current lua file context from to to bottom --- When encounter the 'local end_list' variable, the parse process will stop. --- it will return well formatted function stub with parameters arrays( the param name will be lost due to the lua vm) --- ALSO THE CODE SOURCE FILE AND LINE NUMBER, IT'S VERY USEFUL TO DETECT THE CLASS INHERTS RELATIONS. function parse_code() local a = 1 local sb = string.buffer() while true do local name, value = debug.getlocal(2, a) if not name then break end if name == 'end_list' then break end -- var_tb[name]= value if type(value) == 'table' then sb:add(dump_class(value, name)) end end return sb:tos() end
--[=[ @interface LinearOptions @within Linear @field velocity number -- How fast the goal should move towards the target. Default: 1 ]=] --[=[ @class Linear Represents a linear Goal. Moves towards the target at a specified velocity. ]=] local Linear = {} Linear.__index = Linear --[=[ Creates a new Linear. @param targetValue number @param options LinearOptions @return Linear ]=] function Linear.new(targetValue, options) assert(targetValue, "Missing argument #1: targetValue") options = options or {} return setmetatable({ _targetValue = targetValue, _velocity = options.velocity or 1, }, Linear) end --[=[ Advances the specified MotorState by `deltaTime * velocity` and returns a new MotorState. ]=] function Linear:step(state, dt) local position = state.value local velocity = self._velocity -- Linear motion ignores the state's velocity local goal = self._targetValue local dPos = dt * velocity local complete = dPos >= math.abs(goal - position) position = position + dPos * (goal > position and 1 or -1) if complete then position = self._targetValue velocity = 0 end return { complete = complete, value = position, velocity = velocity, } end return Linear
-- Knuth-Morris-Pratt string searching algorithm implementation -- See: http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm local function kmp_table(pattern) local result = {} for i = 1, #pattern+1,1 do local j = i while true do if j == 1 then result[#result + 1] = 1 break end j = j-1 if pattern:sub(result[j], result[j]) == pattern:sub(i, i) then result[#result + 1] = result[j] + 1 break end j = result[j] end end return result end -- Knuth-Morris-Pratt string searching function -- needle : the pattern to search -- haystack : the string in which the pattern will be searched -- returns : the position of the match, otherwise nil return function(needle, haystack) local fail = kmp_table(needle) local index, match = 0,1 while index + match < #haystack do if haystack:sub(index + match, index + match) == needle:sub(match, match) then match = match + 1 if match-1 == #needle then return index end else if match == 1 then index = index + 1 else index = index + match - (fail[match-1]) match = fail[match-1] end end end end
const Application typeof System.Windows.Forms.Application; const Form typeof System.Windows.Forms.Form; const Button typeof System.Windows.Forms.Button; const MessageBox typeof System.Windows.Forms.MessageBox; const MessageBoxButtons typeof System.Windows.Forms.MessageBoxButtons; const MessageBoxIcon typeof System.Windows.Forms.MessageBoxIcon; const String typeof System.String; const Brushes typeof System.Drawing.Brushes; local iClicked : int = 0; Application:EnableVisualStyles(); do (frm : Form, cmd : Button = Form(), Button()) frm.Text = 'Hallo Welt!'; cmd.Text = 'Click'; cmd.Left = 16; cmd.Top = 16; cmd.Click:add( function (sender, e) : void iClicked = iClicked + 1; MessageBox:Show(frm, String:Format('Clicked {0:N0} times!', iClicked), 'Lua', MessageBoxButtons.OK, MessageBoxIcon.Information); end); frm.Paint:add( function (sender, e) : void e.Graphics:FillRectangle(Brushes.Lime, 10, 10, 100, 100); end); frm.Controls:Add(cmd); Application:Run(frm); end;
-- Minetest 0.4 mod: bones -- See README.txt for licensing and other information. bones = {} local function is_owner(pos, name) local owner = minetest.get_meta(pos):get_string("owner") if owner == "" or owner == name then return true end return false end bones.bones_formspec = "size[8,9]".. default.gui_bg.. default.gui_bg_img.. default.gui_slots.. "list[current_name;main;0,0.3;8,4;]".. "list[current_player;main;0,4.85;8,1;]".. "list[current_player;main;0,6.08;8,3;8]".. default.get_hotbar_bg(0,4.85) local share_bones_time = tonumber(minetest.setting_get("share_bones_time") or 1200) local share_bones_time_early = tonumber(minetest.setting_get("share_bones_time_early") or (share_bones_time/4)) minetest.register_node("bones:bones", { description = "Bones", tiles = { "bones_top.png", "bones_bottom.png", "bones_side.png", "bones_side.png", "bones_rear.png", "bones_front.png" }, paramtype2 = "facedir", groups = {dig_immediate=2}, sounds = default.node_sound_dirt_defaults({ footstep = {name="default_gravel_footstep", gain=0.5}, dug = {name="default_gravel_footstep", gain=1.0}, }), can_dig = function(pos, player) local inv = minetest.get_meta(pos):get_inventory() return is_owner(pos, player:get_player_name()) and inv:is_empty("main") end, allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) if is_owner(pos, player:get_player_name()) then return count end return 0 end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) return 0 end, allow_metadata_inventory_take = function(pos, listname, index, stack, player) if is_owner(pos, player:get_player_name()) then return stack:get_count() end return 0 end, on_metadata_inventory_take = function(pos, listname, index, stack, player) local meta = minetest.get_meta(pos) if meta:get_inventory():is_empty("main") then minetest.remove_node(pos) end end, on_punch = function(pos, node, player) if(not is_owner(pos, player:get_player_name())) then return end if(minetest.get_meta(pos):get_string("infotext") == "") then return end local inv = minetest.get_meta(pos):get_inventory() local player_inv = player:get_inventory() local has_space = true for i=1,inv:get_size("main") do local stk = inv:get_stack("main", i) if player_inv:room_for_item("main", stk) then inv:set_stack("main", i, nil) player_inv:add_item("main", stk) else has_space = false break end end -- remove bones if player emptied them if has_space then if player_inv:room_for_item("main", {name = "bones:bones"}) then player_inv:add_item("main", {name = "bones:bones"}) else minetest.add_item(pos,"bones:bones") end minetest.remove_node(pos) end end, on_timer = function(pos, elapsed) local meta = minetest.get_meta(pos) local time = meta:get_int("time") + elapsed if time >= share_bones_time then meta:set_string("infotext", meta:get_string("owner").."'s old bones") meta:set_string("owner", "") else meta:set_int("time", time) return true end end, }) local function may_replace(pos, player) local node_name = minetest.get_node(pos).name local node_definition = minetest.registered_nodes[node_name] -- if the node is unknown, we let the protection mod decide -- this is consistent with when a player could dig or not dig it -- unknown decoration would often be removed -- while unknown building materials in use would usually be left if not node_definition then -- only replace nodes that are not protected return not minetest.is_protected(pos, player:get_player_name()) end -- allow replacing air and liquids if node_name == "air" or node_definition.liquidtype ~= "none" then return true end -- don't replace filled chests and other nodes that don't allow it local can_dig_func = node_definition.can_dig if can_dig_func and not can_dig_func(pos, player) then return false end -- default to each nodes buildable_to; if a placed block would replace it, why shouldn't bones? -- flowers being squished by bones are more realistical than a squished stone, too -- exception are of course any protected buildable_to return node_definition.buildable_to and not minetest.is_protected(pos, player:get_player_name()) end minetest.register_on_dieplayer(function(player) if minetest.setting_getbool("creative_mode") then return end local player_inv = player:get_inventory() if player_inv:is_empty("main") and player_inv:is_empty("craft") then return end local pos = player:getpos() pos.x = math.floor(pos.x+0.5) pos.y = math.floor(pos.y+0.5) pos.z = math.floor(pos.z+0.5) local param2 = minetest.dir_to_facedir(player:get_look_dir()) local player_name = player:get_player_name() local player_inv = player:get_inventory() if (not may_replace(pos, player)) then if (may_replace({x=pos.x, y=pos.y+1, z=pos.z}, player)) then -- drop one node above if there's space -- this should solve most cases of protection related deaths in which players dig straight down -- yet keeps the bones reachable pos.y = pos.y+1 else -- drop items instead of delete for i=1,player_inv:get_size("main") do minetest.add_item(pos, player_inv:get_stack("main", i)) end for i=1,player_inv:get_size("craft") do minetest.add_item(pos, player_inv:get_stack("craft", i)) end -- empty lists main and craft player_inv:set_list("main", {}) player_inv:set_list("craft", {}) return end end minetest.set_node(pos, {name="bones:bones", param2=param2}) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() inv:set_size("main", 8*4) inv:set_list("main", player_inv:get_list("main")) for i=1,player_inv:get_size("craft") do local stack = player_inv:get_stack("craft", i) if inv:room_for_item("main", stack) then inv:add_item("main", stack) else --drop if no space left minetest.add_item(pos, stack) end end player_inv:set_list("main", {}) player_inv:set_list("craft", {}) meta:set_string("formspec", bones.bones_formspec) meta:set_string("owner", player_name) if share_bones_time ~= 0 then meta:set_string("infotext", player_name.."'s fresh bones") if share_bones_time_early == 0 or not minetest.is_protected(pos, player_name) then meta:set_int("time", 0) else meta:set_int("time", (share_bones_time - share_bones_time_early)) end minetest.get_node_timer(pos):start(10) else meta:set_string("infotext", player_name.."'s bones") end end)
module("luci.controller.exfiletransfer", package.seeall) function index() entry({"admin", "NAS", "exfiletransfer"}, form("exupdownload"), _("EXFileTransfer"), 89) end
local menu = require 'create_menu_background' local bg = 1 local buttons = 2 function draw_background_menu() for i = 1, 7 do love.graphics.draw(menu[bg].background[i], menu[bg].x, menu[bg].y, math.rad(0), menu[bg].scalex, menu[bg].scaley) end love.graphics.draw(menu[bg].rock, menu[bg].rock_x, menu[bg].rock_y, math.rad(0), menu[bg].rock_scalex, menu[bg].rock_scaley, menu[bg].rock_sizex/2, menu[bg].rock_sizey/2) local red = {1, 0, 0, 1} love.graphics.print({red, "HUNGRY}SHARK"}, 385, 150) end function draw_button_menu() if menu[buttons].collision == 2 then love.graphics.draw(menu[buttons].play, menu[buttons].playx - 5, menu[buttons].playy - 5, math.rad(0), menu[buttons].playscalex, menu[buttons].playscaley, button.playsizex/2, button.playsizey/2) else love.graphics.draw(menu[buttons].playwshadow, menu[buttons].playx, menu[buttons].playy, math.rad(0), menu[buttons].playscalex, menu[buttons].playscaley, button.playsizex/2, button.playsizey/2) end if menu[buttons].collision == 1 then love.graphics.draw(menu[buttons].settings, menu[buttons].settingsx - 4, menu[buttons].settingsy - 3, math.rad(0), menu[buttons].settingsscalex, menu[buttons].settingsscaley, menu[buttons].settingssizex/2, menu[buttons].settingssizey/2) else love.graphics.draw(menu[buttons].settingswshadow, menu[buttons].settingsx, menu[buttons].settingsy, math.rad(0), menu[buttons].settingsscalex, menu[buttons].settingsscaley, menu[buttons].settingssizex/2, menu[buttons].settingssizey/2) end if menu[buttons].collision == 4 then love.graphics.draw(menu[buttons].info, menu[buttons].infox - 3, menu[buttons].infoy - 2, math.rad(0), menu[buttons].infoscalex, menu[buttons].infoscaley, menu[buttons].infosizex/2, menu[buttons].infosizey/2) else love.graphics.draw(menu[buttons].infowshadow, menu[buttons].infox, menu[buttons].infoy, math.rad(0), menu[buttons].infoscalex, menu[buttons].infoscaley, menu[buttons].infosizex/2, menu[buttons].infosizey/2) end if menu[buttons].collision == 3 then love.graphics.draw(menu[buttons].leader, menu[buttons].leaderx - 4, menu[buttons].leadery - 3, math.rad(0), menu[buttons].leaderscalex, menu[buttons].leaderscaley, menu[buttons].leadersizex/2, menu[buttons].leadersizey/2) else love.graphics.draw(menu[buttons].leaderwshadow, menu[buttons].leaderx, menu[buttons].leadery, math.rad(0), menu[buttons].leaderscalex, menu[buttons].leaderscaley, menu[buttons].leadersizex/2, menu[buttons].leadersizey/2) end end function display_mmenu() if menu == 2 then return 2 end draw_background_menu() draw_button_menu() end
class 'Passive' function Passive:__init() self.interval = 3600 * 6 -- DB write interval in seconds (Default: 6h) self.passives = {} self.diff = {} self.nextSave = self.interval SQL:Execute("CREATE TABLE IF NOT EXISTS passive (steamid VARCHAR PRIMARY KEY)") -- Load all DB entries into the cache local i = 0 local timer = Timer() for _, row in ipairs(SQL:Query("SELECT * FROM passive"):Execute()) do self.passives[row.steamid] = true i = i + 1 end print(string.format("Loaded %d passives in %dms.", i, timer:GetMilliseconds())) Network:Subscribe( "TogglePVPMode", self, self.TogglePVPMode ) Network:Subscribe( "Toggle", self, self.Toggle ) Network:Subscribe( "Disable", self, self.Disable ) --Network:Subscribe("CheckPassive", self, self.CheckPassive) --Events:Subscribe( "PlayerExitVehicle", self, self.PlayerExitVehicle ) Events:Subscribe( "ClientModuleLoad", self, self.ClientModuleLoad ) Events:Subscribe( "PlayerEnterVehicle", self, self.PlayerEnterVehicle ) Events:Subscribe( "PostTick", self, self.PostTick ) Events:Subscribe( "ModuleUnload", self, self.ModuleUnload ) end function Passive:TogglePVPMode( args, sender ) if args.enabled then sender:SetNetworkValue( "PVPMode", 1 ) else sender:SetNetworkValue( "PVPMode", nil ) end end function Passive:Toggle( state, sender ) sender:SetNetworkValue("Passive", state or nil) local vehicle = sender:GetVehicle() if IsValid(vehicle) and vehicle:GetDriver() == sender then vehicle:SetInvulnerable(state == true) end if sender:GetValue( "Lang" ) and sender:GetValue( "Lang" ) == "ENG" then Network:Send( sender, "Text", "Passive mode " .. (state and "enabled" or "disabled") ) else Network:Send( sender, "Text", "Мирный режим " .. (state and "включён" or "отключён") ) end local steamid = sender:GetSteamId().string self.diff[steamid] = not self.diff[steamid] or nil self.passives[steamid] = state or nil end function Passive:Disable( state, sender ) sender:SetNetworkValue("Passive", state or nil) local vehicle = sender:GetVehicle() if IsValid(vehicle) and vehicle:GetDriver() == sender then vehicle:SetInvulnerable(state == true) end local steamid = sender:GetSteamId().string self.diff[steamid] = not self.diff[steamid] or nil self.passives[steamid] = state or nil end function Passive:ClientModuleLoad( args ) local state = self.passives[args.player:GetSteamId().string] args.player:SetNetworkValue("Passive", state) local vehicle = args.player:GetVehicle() if IsValid(vehicle) and vehicle:GetDriver() == args.player then vehicle:SetInvulnerable(state ~= nil) end end function Passive:PlayerEnterVehicle( args ) if args.is_driver then args.vehicle:SetInvulnerable(args.player:GetValue("Passive") == true) end end function Passive:PlayerExitVehicle( args ) if args.player:GetValue( "Passive" ) then args.player:EnableCollision( CollisionGroup.Vehicle, CollisionGroup.Player ) end end function Passive:PostTick() if Server:GetElapsedSeconds() > self.nextSave then self:ModuleUnload() self.nextSave = Server:GetElapsedSeconds() + self.interval end end function Passive:CheckPassive( args, sender ) for p in Server:GetPlayers() do jDist = sender:GetPosition():Distance( p:GetPosition() ) if sender:GetVehicle() then if jDist < 5 then p:DisableCollision( CollisionGroup.Vehicle, CollisionGroup.Player ) else p:EnableCollision( CollisionGroup.Vehicle, CollisionGroup.Player ) end end end end function Passive:ModuleUnload() local i = 0 local timer = Timer() local trans = SQL:Transaction() for steamid, _ in pairs(self.diff) do local state = self.passives[steamid] local command if state then command = SQL:Command("INSERT OR REPLACE INTO passive VALUES (?)") else command = SQL:Command("DELETE FROM passive WHERE steamid = ?") end command:Bind(1, steamid) command:Execute() i = i + 1 end trans:Commit() self.diff = {} print(string.format("Saved %d passives in %dms.", i, timer:GetMilliseconds())) end passive = Passive()
-- KEYS[1]: this consumer's inflight set -- KEYS[2]: the active jobs list -- KEYS[3]: the signal list -- ARGV[]: the list of job IDs -- Returns: nil for _,job_id in ipairs(ARGV) do -- Remove the jobs from this consumer's inflight set local removed = redis.call("srem", KEYS[1], job_id) if removed == 1 then -- Push the job back into the active jobs list redis.call("rpush", KEYS[2], job_id) end end -- Signal that there are jobs in the queue redis.call("del", KEYS[3]) redis.call("lpush", KEYS[3], 1) return true
Config = {} -- Should be a multiple of 5 + 1 Config.PlayerSlots = 51 -- 30kg is a lot to carry Config.PlayerWeight = 30000 -- Blur the screen while in an inventory Config.EnableBlur = true -- Requires esx_licenses Config.WeaponsLicense = true Config.WeaponsLicensePrice = 5000 -- Requires setup; I'll release something in the future Config.Logs = false -- Default keymapping for the inventory; players can assign their own Config.InventoryKey = 'F2' Config.VehicleInventoryKey = 'K' -- Reload empty weapons automatically Config.AutoReload = false -- Randomise the price of items in each shop at resource start Config.RandomPrices = false
--[[ Craft Guide for Minetest Copyright (c) 2012 cornernote, Brett O'Donnell <[email protected]> Source Code: https://github.com/cornernote/minetest-craft_guide License: BSD-3-Clause https://raw.github.com/cornernote/minetest-craft_guide/master/LICENSE CRAFT GUIDE API ]]-- -- expose object to other modules craft_guide = {} -- vvv INTERNAL SETTINGS vvv -- enable or disable you need feature craft_guide.you_need=true -- enable or disable copy craft recipe to crafting grid feature craft_guide.copy_button=true -- show items which only have have craft recipes of type "fuel". This are for example: tree trunks, saplings, .. etc. --Don't matter when craft_guide.show_fuel=false craft_guide.show_all_fuel_crafts=false -- don't show any recipes of type fuel in craft guide craft_guide.show_fuel=true --shows crafts other then normal crafts in crafting grid or of type "cooking" or "fuel". --at the moment this are crafts for machines from technic mod craft_guide.other_crafting_types=true --don't show crafts which are registered in moreblocks mod to get the original item back from its slabs, panels, microblocks, etc... --and don't show all ingots, dusts and blocks of uranium with different percentages craft_guide.remove_cluttering_crafts=true -- here you can define base items for "you need" feature --all items with this prefix are base items: craft_guide.basic_item_prefixes = { "dye:", } --all items which belong to this groups are base items craft_guide.basic_item_groups = { "wood", "stone", "stick", "tree", "sand", "glass", } --all items which end with these strings are base items craft_guide.basic_item_endings = { "ingot", "lump", "glass", "dust", } -- here you can define single items as base items. -- items without crafting recipe or items which match criterias from the tables above are base items too. craft_guide.basic_items = { "default:dirt", "default:sand", "default:cobble", "default:snowblock", "default:ice", "default:wood", "default:stone", "default:stick", "default:clay_brick", "default:gravel", "default:mossycobble", "default:desert_stone", "default:desert_cobble", "default:desert_sand", "default:diamond", "default:mese_crystal", "default:glass", "default:obsidian", "default:wheat", "bucket:bucket_water", "bucket:bucket_lava", "technic:uranium", "technic:raw_latex", "homedecor:roof_tile_terracotta", "homedecor:terracotta_base", "mesecons_materials:glue", "wool:white" } -- END OF SETTINGS SECTION -- define api variables craft_guide.crafts = {} craft_guide.alias = {} craft_guide.fuel = {} craft_guide.saved_you_need_lists = {} craft_guide.you_need_list = {} craft_guide.add_things=true craft_guide.fuel_to_add=false -- log craft_guide.log = function(message) --if not craft_guide.DEBUG then return end minetest.log("action", "[CraftGuide] "..message) end -- register_craft craft_guide.register_craft = function(options) if options.type == "fuel" and craft_guide.show_fuel and options.recipe~=nil then local itemstack = ItemStack(options.recipe) if itemstack:is_empty() then return end if craft_guide.fuel[itemstack:get_name()]==nil then craft_guide.fuel[itemstack:get_name()] = {} end table.insert(craft_guide.fuel[itemstack:get_name()],options) craft_guide.fuel_to_add=true return end if options.output == nil then return end local itemstack = ItemStack(options.output) if itemstack:is_empty() then return end --this should remove crafts which craft original item back from stairs, slabs, panels or micros, if craft_guide.remove_cluttering_crafts then local mod,_=string.find(itemstack:get_name(),":") if mod~=nil then mod=string.sub(itemstack:get_name(),1,mod) local recipestr="" if options.recipe[1]~=nil and type(options.recipe[1])=="string" then recipestr=" "..options.recipe[1] elseif options.recipe[1]~=nil and type(options.recipe[1][1])=="string" then recipestr=" "..options.recipe[1][1] elseif options.recipe[2]~=nil and type(options.recipe[2][1])=="string" then recipestr=" "..options.recipe[2][1] end if --dont show recipes for ingots, dusts and blocks of uranium with different percentages string.find(itemstack:get_name(),"technic:uranium._")==nil and string.find(itemstack:get_name(),"technic:uranium.._")==nil and (recipestr==""or (options.recipe~=nil and string.find(recipestr," "..mod.."panel_")==nil and string.find(recipestr," "..mod.."stair_")==nil and string.find(recipestr," "..mod.."micro_")==nil and string.find(recipestr," "..mod.."slab_")==nil and string.find(recipestr," moreblocks:panel_")==nil and string.find(recipestr," moreblocks:stair_")==nil and string.find(recipestr," moreblocks:micro_")==nil and string.find(recipestr," moreblocks:slab_")==nil)) then --craft_guide.log("registered craft for - "..itemstack:get_name()) if craft_guide.crafts[itemstack:get_name()]==nil then craft_guide.crafts[itemstack:get_name()] = {} end table.insert(craft_guide.crafts[itemstack:get_name()],options) end end end end -- register_alias craft_guide.register_alias = function(alias,convert_to) local count=#craft_guide.alias craft_guide.alias[count+1]=alias craft_guide.alias[count+2]=convert_to end -- get_craft_guide_formspec craft_guide.get_craft_guide_formspec = function(meta, search, page, alternate) if craft_guide.add_things then craft_guide.add_additional_crafts() end if search == nil then search = meta:get_string("search") end if meta:get_string("formspec")=="" then meta:set_string("owner","") meta:set_string("saved_search","|") meta:set_string("saved_page","1") meta:set_string("saved_pages","1") meta:set_string("switch","bookmarks") meta:set_string("poslist","down") meta:set_string("globalcount","1") meta:set_string("time","0") meta:set_string("method","Cook") meta:set_string("locked","0") meta:set_string("isowner","0") end if page == nil then page = craft_guide.get_current_page(meta) end if alternate == nil then alternate = craft_guide.get_current_alternate(meta) end local inv = meta:get_inventory() local size = inv:get_size("main") local start = (page-1) * (5*14) --was 1 too much before local pages = math.floor((size-1) / (5*14) + 1) local alternates = 0 local stack = inv:get_stack("output",1) local crafts = craft_guide.crafts[stack:get_name()] if crafts ~= nil then alternates = #crafts end local backbutton="" if meta:get_string("saved_search")~="|" then backbutton="button[6.3,5.8;2.7,1;back_button;<--- Back]" end local changeable_part="" if meta:get_string("switch")=="youneed" and craft_guide.you_need then changeable_part="button[9.7,6.35;0.8,0.7;switch_to_bookmarks;>>]" .."tooltip[switch_to_bookmarks;Show your saved bookmarks]" if meta:get_string("poslist")=="down" then changeable_part= changeable_part.."label[8,6.5;You need:]" .."button[10.42,6.35;0.5,0.7;move_up;^]" .."tooltip[move_up;Move the list of needed items upwards]" .."label[11.4,6.0;Add to]" .."label[11.2,6.35;bookmarks]" .."label[12.6,6.05;->]" .."list[current_name;add;13,6;1,1;]" ..craft_guide.build_button_list(meta,inv,"youneed",12,29,8,7,6) else changeable_part= changeable_part.."button[10.42,6.35;0.5,0.7;move_down;v]" .."tooltip[move_down;Move the list of needed items downwards]" ..craft_guide.build_button_list(meta,inv,"youneed",12,29,0,1,14,0) end changeable_part= changeable_part..craft_guide.get_amounts(meta,inv,"youneed") end if meta:get_string("switch")=="bookmarks" or (not craft_guide.you_need) or meta:get_string("poslist")=="up" then changeable_part= changeable_part.."label[8,6.5;Bookmarks]" if craft_guide.you_need and meta:get_string("switch")=="bookmarks" then changeable_part= changeable_part.."button[9.7,6.35;0.8,0.7;switch_to_youneed;>>]" .."tooltip[switch_to_youneed;Show amount of basic items needed]" end changeable_part= changeable_part.."list[current_name;bookmark;8,7;6,3;]" .."label[12,6.1;Bin ->]" .."list[current_name;bin;13,6;1,1;]" end local formspec = "size[14,10;]" if meta:get_string("switch")=="youneed" and meta:get_string("poslist")=="up" then formspec=formspec.."label[0.1,0.3;You need:]" else formspec=formspec.."list[current_name;main;0,0;14,5;"..tostring(start).."]" end formspec=formspec.."label[0,5;--== Learn to Craft ==--]" .."label[0,5.4;Drag any item to the Output box to see the]" .."label[0,5.8;craft. Save your favorite items in Bookmarks.]" .."field[6,5.4;2.3,1;craft_guide_search_box;;"..tostring(search).."]" .."button[7.8,5.1;1.2,1;craft_guide_search_button;Search]" ..backbutton .."label[9.1,5.2;page "..tostring(page).." of "..tostring(pages).."]" .."button[11,5;1.5,1;craft_guide_prev;<<]" .."button[12.5,5;1.5,1;craft_guide_next;>>]" if inv:get_stack("fuel",1)==nil or inv:get_stack("fuel",1):get_name()==nil or inv:get_stack("fuel",1):get_name()=="" then formspec=formspec.."label[0,6.5;Output]" end formspec=formspec.."list[current_name;output;0,7;1,1;]" .."label[2,6.5;Inventory Craft]" if not (inv:get_stack("additional",1)==nil or inv:get_stack("additional",1):get_name()==nil or inv:get_stack("additional",1):get_name()=="") then formspec=formspec.."list[current_name;additional;0.96,7;1,1;]" end formspec=formspec..craft_guide.build_button_list(meta,inv,"build",3,11,2,7,3) if not (inv:get_stack("cook",1)==nil or inv:get_stack("cook",1):get_name()==nil or inv:get_stack("cook",1):get_name()=="") or (inv:get_stack("fuel",1)==nil or inv:get_stack("fuel",1):get_name()==nil or inv:get_stack("fuel",1):get_name()=="") then formspec=formspec.."label["..tostring(6.22-string.len(meta:get_string("method"))*0.05)..",6.5;"..meta:get_string("method").."]" if not (inv:get_stack("cook",2)==nil or inv:get_stack("cook",2):get_name()==nil or inv:get_stack("cook",2):get_name()=="") then formspec=formspec..craft_guide.build_button_list(meta,inv,"cook",1,2,5.5,7,2) else formspec=formspec..craft_guide.build_button_list(meta,inv,"cook",1,1,6,7,1) end end --add flames from default mod for craft fuel if not (inv:get_stack("fuel",1)==nil or inv:get_stack("fuel",1):get_name()==nil or inv:get_stack("fuel",1):get_name()=="") then formspec=formspec.."label[6,6.5;Fuel]" ..craft_guide.build_button_list(meta,inv,"fuel",1,1,6,7,1) .."image[6.13,9.1;0.7,0.7;default_furnace_fire_fg.png]" if meta:get_string("time")~=nil and meta:get_string("time")~="nil" then formspec=formspec.."label[6.02,8.17;"..meta:get_string("time").." sec]" end end if not (inv:get_stack("cook",1)==nil or inv:get_stack("cook",1):get_name()==nil or inv:get_stack("cook",1):get_name()=="") then formspec=formspec.."list[current_name;machine;6,9;1,1;]" if meta:get_string("time")~=nil and meta:get_string("time")~="nil" then formspec=formspec.."label[6.02,8.17;"..meta:get_string("time").." sec]" end end if alternates > 1 then if alternate>alternates then alternate=1 end formspec = formspec .."label[0,8;recipe "..tostring(alternate).." of "..tostring(alternates).."]" .."button[0,8.4;2,1;alternate;Alternate]" end if craft_guide.copy_button and inv:get_stack("output",1)~=nil and inv:get_stack("output",1):get_name()~=nil and inv:get_stack("output",1):get_name()~=nil then if craft_guide.crafts[inv:get_stack("output",1):get_name()]~=nil then if craft_guide.crafts[inv:get_stack("output",1):get_name()][alternate]~=nil then if (craft_guide.crafts[inv:get_stack("output",1):get_name()][alternate]).type==nil or (craft_guide.crafts[inv:get_stack("output",1):get_name()][alternate]).type=="shapeless" then formspec=formspec.."label[5.45,8.6;Prepare to craft:]" .."button[5.6,9.2;0.7,0.8;copy1;1]" .."button[6.2,9.2;0.7,0.8;copy10;10]" .."button[6.8,9.2;0.7,0.8;copy99;99]" end end end end formspec=formspec..changeable_part .."button_exit[0,9.2;1,0.8;close_mm;ESC]" meta:set_string("saved_formspec",formspec) --this needs to be added last, so it can be changed when restoring a locked formspec if meta:get_string("isowner")=="1" then if meta:get_string("locked")=="0" then formspec=formspec.."button[0.88,9.2;1.22,0.8;lock;Lock]" .."tooltip[lock;Lock Craft Guide in current state]" else formspec=formspec.."button[0.88,9.2;1.22,0.8;lock;Locked]" .."tooltip[lock;Craft Guide is locked - Press again to unlock]" end else if meta:get_string("locked")~="0" and meta:get_string("owner")~=nil and meta:get_string("owner")~="" then formspec=formspec.."label[0.88,9.2;Locked]" .."tooltip[close_mm; Owner: "..meta:get_string("owner").."]" end end return formspec end -- on_construct craft_guide.on_construct = function(pos) local meta = minetest.env:get_meta(pos) local inv = meta:get_inventory() inv:set_size("output", 1) inv:set_size("additional", 1) --here goes the second output of centrifuge recipe, just shown when needed inv:set_size("build", 3*3) inv:set_size("cook", 2*1) inv:set_size("fuel", 1) inv:set_size("machine", 1) inv:set_size("bookmark", 6*3) inv:set_size("youneed", 6*15) inv:set_size("bin", 1) inv:set_size("add", 1) inv:set_size("copylist", 9) inv:set_size("tempinv", 42) inv:set_size("tempmain", 32) inv:set_size("tempresult", 1) if meta:get_string("locked")~="1" then craft_guide.create_inventory(inv) end meta:set_string("formspec",craft_guide.get_craft_guide_formspec(meta)) meta:set_string("out","") meta:set_string("addindex","1") end -- on_receive_fields craft_guide.on_receive_fields = function(pos, formname, fields, player) local meta = minetest.env:get_meta(pos); if meta:get_string("locked")=="1" then craft_guide.save_meta(meta) end if minetest.get_node(pos).name=="craft_guide:sign_wall_locked" or minetest.get_node(pos).name=="craft_guide:lcd_pc_locked" then if meta:get_string("owner")=="" then meta:set_string("owner",player:get_player_name()) meta:set_string("isowner","1") elseif meta:get_string("owner")==player:get_player_name() then meta:set_string("isowner","1") end end local inv = meta:get_inventory() if inv:get_size("additional")==nil or inv:get_size("additional")~=1 then --old version, construct again local node=minetest.get_node(pos) minetest.set_node(pos, node) meta = minetest.env:get_meta(pos) inv = meta:get_inventory() end if inv:get_size("copylist")==nil or inv:get_size("copylist")~=9 then inv:set_size("copylist", 9) inv:set_size("tempinv", 42) inv:set_size("tempmain", 32) inv:set_size("tempresult", 1) end local size = inv:get_size("main",1) local stack = inv:get_stack("output",1) local crafts = craft_guide.crafts[stack:get_name()] local alternate = craft_guide.get_current_alternate(meta) local alternates = 0 if crafts ~= nil then alternates = #crafts end local page = craft_guide.get_current_page(meta) local pages = math.floor((size-1) / (5*14) + 1) -- search local update_search=false local search search = fields.craft_guide_search_box if search~=nil then if string.lower(search)==string.upper(search) and tonumber(search)==nil and search~="*" then search="" end update_search=true else search=meta:get_string("search") end meta:set_string("search", search) if fields.craft_guide_search_button then if search==nil then meta:set_string("search", "") end if meta:get_string("switch")=="youneed" and meta:get_string("poslist")=="up" then meta:set_string("switch","bookmarks") end meta:set_string("saved_search", "|") page = 1 update_search=true end -- copy buttons: local copy=0 if fields.copy99 then copy=99 elseif fields.copy10 then copy=10 elseif fields.copy1 then copy=1 end if copy~=0 and player~=nil then local inv2=player:get_inventory() if inv2~=nil then for i=0,inv:get_size("copylist"),1 do inv:set_stack("copylist",i,ItemStack(nil)) end for i=0,inv:get_size("build"),1 do local stk=inv:get_stack("build", i) if stk:get_count()>0 then if string.sub(stk:get_name(),1,6)=="group:" then inv:set_stack("copylist",i,ItemStack(stk:get_name().."~|@q 1")) else inv:add_item("copylist",ItemStack(stk:get_name().."~|@q 1")) --trick, because stacksize of unknown items is 99 end end end inv:set_list("tempinv",inv2:get_list("main")) for i=0,inv2:get_size("craft"),1 do local st=inv2:get_stack("craft",i) if st:get_count()>0 then inv:add_item("tempinv",st) end end local st=inv2:get_stack("craftresult",1) if st:get_count()>0 then inv:add_item("tempinv",st) end for i=0,inv:get_size("copylist"),1 do local stk=inv:get_stack("copylist", i) local stkcount=stk:get_count() if stkcount>0 then local stkname=stk:get_name() if string.sub(stkname,1,6)~="group:" then stk=ItemStack(string.sub(stkname,1,string.len(stkname)-4).." "..tostring(stkcount*copy)) inv:set_stack("copylist",i,ItemStack(nil)) local lastcheck=0 local removed=0 for x=1,9,1 do if stk:get_count()>stk:get_stack_max()+removed then stk=ItemStack(stk:get_name().." "..tostring(stk:get_stack_max())) else lastcheck=1 end removed=removed+(inv:remove_item("tempinv",stk)):get_count() if lastcheck==1 or not (inv:contains_item("tempinv",ItemStack(stk:get_name().." 1"))) then break end end if copy>math.floor(removed/stkcount) then inv:add_item("tempinv",ItemStack(stk:get_name().." "..tostring(removed-(math.floor(removed/stkcount)*stkcount)))) for jj=0,i-1,1 do local oldstack=inv:get_stack("copylist", jj) if oldstack:get_count()>0 and string.sub(oldstack:get_name(),1,6)~="group:"then local newstack=ItemStack(oldstack:get_name().." "..tostring((copy-math.floor(removed/stkcount))*oldstack:get_count())) inv:add_item("tempinv", newstack) end end copy=math.floor(removed/stkcount) end lastcheck=0 if copy<1 then break end end end end if copy>0 then for i=0,inv:get_size("copylist"),1 do local stk=inv:get_stack("copylist", i) local stkcount=stk:get_count() if stkcount>0 then local stkname=stk:get_name() if string.sub(stkname,1,6)=="group:" then local success=false local groups=string.sub(stkname,7,string.len(stkname)-4) for count=copy,0,-1 do for i2=0,inv:get_size("tempinv"),1 do local check=inv:get_stack("tempinv",i2) if check:get_count()>0 then local name=check:get_name() local hasgroup=1 for group in string.gmatch(groups,"([^,]+)") do if minetest.get_item_group(name, group)==0 then hasgroup=0 break end end if hasgroup==1 then if inv:contains_item("tempinv",ItemStack(name.." "..tostring(count))) then inv:remove_item("tempinv",ItemStack(name.." "..tostring(count))) inv:set_stack("copylist",i,ItemStack(name.." 1")) success=true break end end end end if copy>count then for jj=0,i-1,1 do local oldstack=inv:get_stack("copylist", jj) if oldstack:get_count()>0 and string.sub(oldstack:get_name(),1,6)~="group:" then local newstack=ItemStack(oldstack:get_name().." "..tostring((copy-count)*oldstack:get_count())) inv:add_item("tempinv", newstack) end end copy=count end if success or count<1 then break end end end end if copy<1 then break end end end if copy>0 then for i=0,inv:get_size("build"),1 do local stk=inv:get_stack("build", i) local stkcount=stk:get_count() if stkcount>0 then local stkname=stk:get_name() if string.sub(stkname,1,6)=="group:" then stk=inv:get_stack("copylist", i) stkname=stk:get_name() end stk=ItemStack(stkname.." "..tostring(copy)) inv:set_stack("copylist",i,stk) end end local clean=1 if copy>0 then for i=0,inv:get_size("tempmain"),1 do inv:set_stack("tempmain",i,ItemStack(nil)) end local stk=inv2:get_stack("craftresult", 1) if stk:get_count()>0 then if inv:contains_item("tempinv",stk) then inv:remove_item("tempinv",stk) inv:add_item("tempresult",1,stk) else inv:add_item("tempresult",1,ItemStack(nil)) end end for i=0,inv2:get_size("main"),1 do --restore players main inventory local stk=inv2:get_stack("main", i) if stk:get_count()>0 then local removed=(inv:remove_item("tempinv",stk)):get_count() if removed>0 then inv:set_stack("tempmain",i,ItemStack(stk:get_name().." "..tostring(removed))) end end end for i=0,inv:get_size("tempinv"),1 do --check if items left in crafting grid can be moved to players inventory local stk=inv:get_stack("tempinv", i) if stk:get_count()>0 then if inv:room_for_item("tempmain",stk) then inv:add_item("tempmain",stk) inv:set_stack("tempinv",i,ItemStack(nil)) else clean=0 end end end if clean==0 then local free=0 for i=0,inv:get_size("tempmain"),1 do --check if two small stacks of same item can be joined to one big stack local stk=inv:get_stack("tempmain", i) if stk:get_count()>0 then if inv:room_for_item("tempmain",ItemStack(stk:get_name().." "..tostring(stk:get_stack_max()*(1+free)))) then inv:set_stack("tempmain",i,ItemStack(nil)) inv:add_item("tempmain",stk) free=free+1 end end end for i=0,inv:get_size("build"),1 do --try to move more items to crafting grid local stk=inv:get_stack("build", i) local stkcount=stk:get_count() if stkcount>0 then local stkname=stk:get_name() stk=ItemStack(stkname.." 1") local stkmax=ItemStack(stkname.." "..tostring(stk:get_stack_max()-copy)) if inv:contains_item("tempinv",stk) then local removed=inv:remove_item("tempinv",stkmax) inv:set_stack("copylist",i,ItemStack(stkname.." "..tostring(removed:get_count()+copy))) elseif inv:contains_item("tempmain",stk) then local removed=inv:remove_item("tempmain",stkmax) inv:set_stack("copylist",i,ItemStack(stkname.." "..tostring(removed:get_count()+copy))) end end end for i=0,inv:get_size("tempinv"),1 do --last try to place all left items in main inventory local stk=inv:get_stack("tempinv", i) if stk:get_count()>0 then if inv:room_for_item("tempmain",stk) then inv:add_item("tempmain",stk) inv:set_stack("tempinv",i,ItemStack(nil)) else minetest.chat_send_player(player:get_player_name(), "Can't copy this recipe to crafting grid because your inventory is too full to move items around!") copy=0 break end end end end if copy>0 then --we can successfully craft some of this item for i=0,inv:get_size("copylist"),1 do local stk=inv:get_stack("copylist", i) local stkcount=stk:get_count() if stkcount>copy then --if possible remove additional items back to inventory stk=ItemStack(stk:get_name().." 1") if inv:room_for_item("tempmain",stk) then local left=inv:add_item("tempmain",ItemStack(stk:get_name().." "..tostring(stkcount-copy))) if left~=nil and left~=0 then inv:set_stack("copylist", i,ItemStack(stk:get_name().." "..tostring(copy+left:get_count()))) end end end end --add wear and metadata to items again for t=0,42,1 do local tx=-10 local invlist="tempmain" if t<=9 then invlist="copylist" tx=0 end local itemStack=inv:get_stack(invlist, tx+t) if itemStack:get_count()==1 then if itemStack:get_stack_max()==1 then local itempos=t local found=false local itemStack2=ItemStack(nil) for slot=0,42,1 do if slot<=9 then itemStack2=inv2:get_stack("craft", slot) if itemStack2:get_name()==itemStack:get_name() then found=true end else itemStack2=inv2:get_stack("main", slot-10) if itemStack2:get_name()==itemStack:get_name() then found=true end end if found then found=false inv:set_stack(invlist, t+tx,itemStack2) for tt=itempos+1,42,1 do if tt<=9 then itemStack2=inv:get_stack("copylist", tt) if itemStack2:get_name()==itemStack:get_name() then itemStack=inv2:get_stack("copylist", tt) itempos=tt break end else itemStack2=inv:get_stack("tempmain",tt-10) if itemStack2:get_name()==itemStack:get_name() then itemStack=inv:get_stack("tempmain", tt-10) itempos=tt break end end end end end end end end --copy tempinventory to real inventory inv2:set_list("craft",inv:get_list("copylist")) inv2:set_list("main",inv:get_list("tempmain")) inv2:set_list("craftresult",inv:get_list("tempresult")) end end end end end -- change page if fields.craft_guide_prev then page = page - 1 if page < 1 then page = pages end if meta:get_string("switch")=="youneed" and meta:get_string("poslist")=="up" then meta:set_string("switch","bookmarks") end end if fields.craft_guide_next then page = page + 1 if page > pages then page = 1 end if meta:get_string("switch")=="youneed" and meta:get_string("poslist")=="up" then meta:set_string("switch","bookmarks") end end if page > pages then page = pages end if page < 1 then page = 1 end -- go back to search result if fields.back_button then if meta:get_string("switch")=="youneed" and meta:get_string("poslist")=="up" then meta:set_string("switch","bookmarks") end local saved_search = meta:get_string("saved_search") if saved_search~="|" then search=saved_search meta:set_string("search", saved_search) page=tonumber(meta:get_string("saved_page")) pages=tonumber(meta:get_string("saved_pages")) meta:set_string("saved_search", "|") end update_search=true end --lock current state if fields.lock and meta:get_string("owner")==player:get_player_name() then if meta:get_string("locked")=="2" then meta:set_string("locked","0") else meta:set_string("locked","1") end end --toogle between bookmarks/you need if fields.switch_to_bookmarks then meta:set_string("switch","bookmarks") end if fields.switch_to_youneed then meta:set_string("switch","youneed") craft_guide.update_recipe(meta, player, stack, alternate) end --replacing bookmarks or main item list? if fields.move_up then if meta:get_string("switch")=="youneed" then meta:set_string("poslist","up") if meta:get_string("locked")~="0" then craft_guide.update_recipe(meta, player, stack, alternate) end end end if fields.move_down then if meta:get_string("switch")=="youneed" then meta:set_string("poslist","down") if meta:get_string("locked")~="0" then craft_guide.update_recipe(meta, player, stack, alternate) end end end -- get an alternate recipe if fields.alternate then alternate = alternate+1 craft_guide.update_recipe(meta, player, stack, alternate) end if alternate > alternates then alternate = 1 end --group buttons, finally a solution with a for loop local starts="" local ends="" local xx="" local formspec = meta:get_string("formspec") for button_number=1,29,1 do if fields[("t_758s"..tostring(button_number))] then --search the group name of pressed group button directly in formspec string xx,starts=string.find(formspec,"tooltip%[t_758s"..tostring(button_number)..";") if starts~=nil then ends,xx=string.find(formspec,"%]",starts+1) local group=string.lower(string.sub(formspec,starts+1,ends-2)) --displaying of items in a group is implemented in search function, just need to set search string meta:set_string("search", "group:"..group) --save old search string for restoring when "<-- back" is pressed if meta:get_string("saved_search")=="|" then meta:set_string("saved_search", search) meta:set_string("saved_page", tostring(page)) meta:set_string("saved_pages", tostring(pages)) end page = 1 search="group:"..group update_search=true end break end end if starts~="" and meta:get_string("switch")=="youneed" and meta:get_string("poslist")=="up" then --button pressed, need to move back to bookmarks meta:set_string("switch","bookmarks") end -- update the formspec if meta:get_string("locked")=="2" and (fields["quit"] or fields.close_mm) then craft_guide.restore_meta(meta) else if update_search then craft_guide.create_inventory(inv, search) end meta:set_string("formspec",craft_guide.get_craft_guide_formspec(meta, search, page, alternate)) if meta:get_string("locked")=="1" then craft_guide.save_meta(meta) end end end -- returns formspec string of a inventory list with buttons for group items craft_guide.build_button_list = function(meta,inv,list,start_index,end_index,x,y,w,show_empty) --button numbers go from start_index to end_index --button numbers 1,(2)= cook or fuel --button numbers 3-11= inventory craft field --button numbers 12-29= you need items if show_empty~=0 then show_empty=1 end local string="" for i=1,end_index-start_index+1,1 do local string_old=string local stack = inv:get_stack(list,i) if stack~=nil then local name=stack:get_name() if string.sub(name,1,6)=="group:" then local groups=string.sub(name,7) local saved="" for name,def in pairs(minetest.registered_items) do local hasgroup=1 for group in string.gmatch(groups,"([^,]+)") do if minetest.get_item_group(name, group)==0 then hasgroup=0 end end if hasgroup==1 then --prefer items from default mod if string.sub(name,1,8)=="default:" then --prefer items with simple short names, because cnc machines adds items under default prefix too if string.len(name)<20 then string=string.."item_image_button["..tostring(x+((i-1)%w)).."," ..tostring(y+math.floor((i-1)/w))..";1,1;" ..name..";t_758s"..tostring(i+start_index-1)..";group]" .."tooltip[t_758s"..tostring(i+start_index-1)..";" ..string.upper(string.sub(groups,1,1))..string.sub(groups.." ",2).."]" saved="" break end elseif saved=="" then saved=name end end end if saved~="" then string=string.."item_image_button["..tostring(x+((i-1)%w)).."," ..tostring(y+math.floor((i-1)/w))..";1,1;"..saved..";t_758s"..tostring(i+start_index-1)..";group]" .."tooltip[t_758s"..tostring(i+start_index-1)..";" ..string.upper(string.sub(groups,1,1))..string.sub(groups.." ",2).."]" end end end if string_old==string and ((stack~=nil and stack:get_name()~="") or show_empty==1) then string=string.."list[current_name;"..list..";"..tostring(x+((i-1)%w))..","..tostring(y+math.floor((i-1)/w)) ..";1,1;"..tostring(i-1).."]" end end return string end -- returns a formspec string with item amounts craft_guide.get_amounts = function(meta,inv,list) local amounts="" local xx=8.1 local yy=7.45 local w=6 local size=18 if meta:get_string("poslist")=="up" then xx=0.1 yy=1.45 w=14 size=70 end for jj=1,size,1 do local item=string.lower(inv:get_stack(list,jj):get_name()) local cnt=meta:get_string("globalcount") if item==nil or item=="" then break end local count=craft_guide.you_need_list[item] if count~=nil then cnt=math.floor(((count)/tonumber(meta:get_string("globalcount")))*1000+0.49)/1000 if cnt>1000 then cnt=math.floor(cnt+0.49) elseif cnt>100 then cnt=math.floor(cnt*10+0.49)/10 elseif cnt>10 then cnt=math.floor(cnt*100+0.49)/100 end amounts=amounts.."label["..tostring(xx+((jj-1)%w))..","..tostring(yy+math.floor((jj-1)/w))..";"..tostring(cnt).."]" end jj=jj+1 if jj > size then break end end return amounts end -- get_current_page craft_guide.get_current_page = function(meta) local formspec = meta:get_string("formspec") local page = string.match(formspec, "label%[[%d.]+,[%d.]+;page (%d+) of [%d.]+%]") page = tonumber(page) or 1 return page end -- get_current_alternate craft_guide.get_current_alternate = function(meta) local formspec = meta:get_string("formspec") local alternate = string.match(formspec, "label%[[%d.]+,[%d.]+;recipe (%d+) of [%d.]+%]") alternate = tonumber(alternate) or 1 return alternate end -- update_recipe craft_guide.update_recipe = function(meta, player, stack, alternate) local globalcount=1 local list={} local list2={} local test={} local forlist={} local inv = meta:get_inventory() for i=0,inv:get_size("build"),1 do inv:set_stack("build", i, nil) end for i=0,inv:get_size("youneed"),1 do inv:set_stack("youneed", i, nil) end inv:set_stack("cook", 1, nil) inv:set_stack("cook", 2, nil) inv:set_stack("fuel", 1, nil) inv:set_stack("machine", 1, nil) inv:set_stack("additional", 1, nil) meta:set_string("method","Cook") if stack==nil then return end inv:set_stack("output", 1, stack:get_name()) if alternate==nil then alternate=craft_guide.get_current_alternate(meta) end alternate = tonumber(alternate) or 1 local crafts = craft_guide.crafts[stack:get_name()] if crafts == nil then if stack:get_name()~=nil and stack:get_name()~="" then minetest.chat_send_player(player:get_player_name(), "no recipe available for "..stack:get_name()) end meta:set_string("formspec",craft_guide.get_craft_guide_formspec(meta)) return end if alternate < 1 or alternate > #crafts then alternate = 1 end if stack:get_name()~=nil and stack:get_name()~="" then if meta:get_string("switch")=="youneed" then craft_guide.log(player:get_player_name().." shows needed items for recipe "..alternate.." for "..stack:get_name()) else craft_guide.log(player:get_player_name().." requests recipe "..alternate.." for "..stack:get_name()) end end local craft = crafts[alternate] -- show me the unknown items --craft_guide.log(dump(craft)) --minetest.chat_send_player(player:get_player_name(), "recipe for "..stack:get_name()..": "..dump(craft)) local itemstack = ItemStack(craft.output) inv:set_stack("output", 1, itemstack) if craft.type~=nil and craft.type~="shapeless" and craft.type~="fuel" then -- cook if craft.type=="cooking" then if craft.cooktime==nil then meta:set_string("time","3") else meta:set_string("time",tostring(craft.cooktime)) end inv:set_stack("cook", 1, craft.recipe) if minetest.get_modpath("default") then inv:set_stack("machine", 1, ItemStack("default:furnace")) end else -- custom types added by technic mod local input={} if type(craft.input)~="table" or craft.input[1]==nil or craft.input[1]=="" then table.insert(input,craft.input) else input=craft.input end if type(input)~="table" or input[1]==nil or input[1]=="" then input={} table.insert(input,craft.input) end if craft.type=="Grinder" then inv:set_stack("machine", 1, ItemStack("technic:lv_grinder")) inv:set_stack("cook", 1, input[1]) elseif craft.type=="Extractor" then inv:set_stack("machine", 1, ItemStack("technic:extractor")) inv:set_stack("cook", 1, input[1]) elseif craft.type=="Compressor" then inv:set_stack("machine", 1, ItemStack("technic:compressor")) inv:set_stack("cook", 1, input[1]) elseif craft.type=="Alloy Furnace" then inv:set_stack("machine", 1, ItemStack("technic:lv_alloy_furnace")) inv:set_stack("cook", 1, craft.input[2]) inv:set_stack("cook", 2, craft.input[1]) elseif craft.type=="Centrifuge" then inv:set_stack("machine", 1, ItemStack("technic:mv_centrifuge")) inv:set_stack("cook", 1, input[1]) inv:set_stack("additional", 1, craft.output2) end meta:set_string("method",craft.type) meta:set_string("time",tostring(craft.time)) meta:set_string("globalcount",tostring(ItemStack(craft.output):get_count())) end else -- fuel if craft.type == "fuel" then meta:set_string("time",tostring(craft.burntime)) itemstack=ItemStack(craft.recipe) inv:set_stack("output", 1, meta:get_string("out")) inv:set_stack("fuel", 1, craft.recipe) else -- build (shaped or shapeless) if craft.recipe[1] then if (type(craft.recipe[1]) == "string") then inv:set_stack("build", 1, craft.recipe[1]) else if craft.recipe[1][1] then inv:set_stack("build", 1, craft.recipe[1][1]) end if craft.recipe[1][2] then inv:set_stack("build", 2, craft.recipe[1][2]) end if craft.recipe[1][3] then inv:set_stack("build", 3, craft.recipe[1][3]) end end end if craft.recipe[2] then if (type(craft.recipe[2]) == "string") then inv:set_stack("build", 2, craft.recipe[2]) else if craft.recipe[2][1] then inv:set_stack("build", 4, craft.recipe[2][1]) end if craft.recipe[2][2] then inv:set_stack("build", 5, craft.recipe[2][2]) end if craft.recipe[2][3] then inv:set_stack("build", 6, craft.recipe[2][3]) end end end if craft.recipe[3] then if (type(craft.recipe[3]) == "string") then inv:set_stack("build", 3, craft.recipe[3]) else if craft.recipe[3][1] then inv:set_stack("build", 7, craft.recipe[3][1]) end if craft.recipe[3][2] then inv:set_stack("build", 8, craft.recipe[3][2]) end if craft.recipe[3][3] then inv:set_stack("build", 9, craft.recipe[3][3]) end end end if craft.recipe[4] then if (type(craft.recipe[4]) == "string") then inv:set_stack("build", 4, craft.recipe[4]) end end if craft.recipe[5] then if (type(craft.recipe[5]) == "string") then inv:set_stack("build", 5, craft.recipe[5]) end end if craft.recipe[6] then if (type(craft.recipe[6]) == "string") then inv:set_stack("build", 6, craft.recipe[6]) end end if craft.recipe[7] then if (type(craft.recipe[7]) == "string") then inv:set_stack("build", 7, craft.recipe[7]) end end if craft.recipe[8] then if (type(craft.recipe[8]) == "string") then inv:set_stack("build", 8, craft.recipe[8]) end end if craft.recipe[9] then if (type(craft.recipe[9]) == "string") then inv:set_stack("build", 9, craft.recipe[9]) end end end end if meta:get_string("switch")=="youneed" and craft_guide.you_need then craft_guide.you_need_list=nil craft_guide.you_need_list={} local stack_name=stack:get_name() -- get the saved list if we have it already, no need to calcalute all again if craft_guide.saved_you_need_lists[stack_name.."@|²"..tostring(alternate)]~=nil then craft_guide.you_need_list=craft_guide.saved_you_need_lists[stack_name.."@|²"..tostring(alternate)] globalcount=tonumber(craft_guide.saved_you_need_lists[stack_name.."@|³"..tostring(alternate)]) if globalcount==nil or globalcount<1 then globalcount=1 end local v=1 for _item,_ in pairs(craft_guide.you_need_list) do inv:set_stack("youneed", v, _item) v=v+1 end else list[stack_name] = {} list[stack_name] = 1 for j=1,6,1 do --main iteration loop for resolving recipes into base items local finished=1 local limit=inv:get_size("youneed") local k=0 for name,count in pairs(list) do if k>limit then break end k=k+1 local isbase=0 if name==nil or name=="" or count==0 or string.sub(name,1,6)=="group:" then isbase=1 elseif j>1 or k>1 then for ii=1,999,1 do if craft_guide.basic_item_prefixes[ii]==nil or craft_guide.basic_item_prefixes[ii]=="" then break elseif string.sub(name,1,string.len(craft_guide.basic_item_prefixes[ii]))== string.lower(craft_guide.basic_item_prefixes[ii]) then isbase=1 break end end if isbase==0 then for aa=1,999,1 do if craft_guide.basic_item_groups[aa]==nil or craft_guide.basic_item_groups[aa]=="" then break elseif minetest.get_item_group(name, string.lower(craft_guide.basic_item_groups[aa]))>0 then isbase=1 break end end if isbase==0 then for bb=1,999,1 do if craft_guide.basic_item_endings[bb]==nil or craft_guide.basic_item_endings[bb]=="" then break elseif string.sub(name,string.len(name)- (string.len(craft_guide.basic_item_endings[bb])-1) )== string.lower(craft_guide.basic_item_endings[bb]) then isbase=1 break end end if isbase==0 then for cc=1,999,1 do if craft_guide.basic_items[cc]==nil or craft_guide.basic_items[cc]=="" then break elseif name==string.lower(craft_guide.basic_items[cc]) then isbase=1 break end end end end end end crafts = craft_guide.crafts[name] if crafts==nil or ((j>1 or k>1) and crafts[1].type~=nil and crafts[1].type~="cooking" and crafts[1].type~="shapeless") then isbase=1 end if isbase==0 then finished=0 if crafts ~= nil then local istest=1 local bestcraft=1 local bestvalue=10 --lower is better --too much tabs needed, starting here left again till this section is over for craftnumber=1,#crafts+1,1 do if craftnumber>49 then craftnumber=#crafts+1 end local index=craftnumber if j>1 then if #crafts==1 and index<=#crafts then bestvalue=0 istest=0 elseif index>#crafts or bestvalue==0 then index=bestcraft bestvalue=0 istest=0 end else bestvalue=0 index=alternate istest=0 end local craft = crafts[index] if craft~=nil and craft.type~="fuel" then local amount=count if istest==0 then list[name]=0 local output_count=ItemStack(craft.output):get_count() if output_count~=1 and (j>1 or k>1) then if amount/output_count==math.floor(amount/output_count) then amount=amount/output_count else globalcount=globalcount*output_count for _name,_amount in pairs(list) do if tonumber(amount)>0 then list[_name]=tonumber(_amount)*output_count end end end end end if istest==1 then list2=list list=nil list={} list=test end if craft.type == "cooking" then if list[craft.recipe]==nil then list[(craft.recipe)]={} list[(craft.recipe)]=amount else local add=amount+tonumber(list[(craft.recipe)]) list[(craft.recipe)]=add end elseif craft.type ~=nil and craft.type ~= "fuel" and craft.type ~= "shapeless" then local input=ItemStack(craft.input):get_name() local _count=ItemStack(craft.input):get_count() if input~=nil and input~="" then if list[input]==nil then list[input]={} list[input]=amount*_count else local add=amount*_count+tonumber(list[input]) list[input]=add end else input=ItemStack(craft.input[1]):get_name() _count=ItemStack(craft.input[1]):get_count() if input~=nil and input~="" then if list[input]==nil then list[input]={} list[input]=amount*_count else local add=amount*_count+tonumber(list[input]) list[input]=add end input=ItemStack(craft.input[2]):get_name() _count=ItemStack(craft.input[2]):get_count() if input~=nil and input~="" then if list[input]==nil then list[input]={} list[input]=amount*_count else local add=amount*_count+tonumber(list[input]) list[input]=add end end end end elseif craft.type==nil or craft.type=="shapeless" then if craft.recipe[1] then if (type(craft.recipe[1]) == "string") then if list[craft.recipe[1]]==nil then list[(craft.recipe[1])]={} list[(craft.recipe[1])]=amount else local add =amount+tonumber(list[(craft.recipe[1])]) list[(craft.recipe[1])]=add end else if craft.recipe[1][1] then if list[(craft.recipe[1][1])]==nil then list[(craft.recipe[1][1])]={} list[(craft.recipe[1][1])]=amount else local add =amount+tonumber(list[(craft.recipe[1][1])]) list[(craft.recipe[1][1])]=add end end if craft.recipe[1][2] then if list[(craft.recipe[1][2])]==nil then list[(craft.recipe[1][2])]={} list[(craft.recipe[1][2])]=amount else local add =amount+tonumber(list[(craft.recipe[1][2])]) list[(craft.recipe[1][2])]=add end end if craft.recipe[1][3] then if list[(craft.recipe[1][3])]==nil then list[(craft.recipe[1][3])]={} list[(craft.recipe[1][3])]=amount else local add =amount+tonumber(list[(craft.recipe[1][3])]) list[(craft.recipe[1][3])]=add end end end end if craft.recipe[2] then if (type(craft.recipe[2]) == "string") then if list[(craft.recipe[2])]==nil then list[(craft.recipe[2])]={} list[(craft.recipe[2])]=amount else local add =amount+tonumber(list[(craft.recipe[2])]) list[(craft.recipe[2])]=add end else if craft.recipe[2][1] then if list[(craft.recipe[2][1])]==nil then list[(craft.recipe[2][1])]={} list[(craft.recipe[2][1])]=amount else local add =amount+tonumber(list[(craft.recipe[2][1])]) list[(craft.recipe[2][1])]=add end end if craft.recipe[2][2] then if list[(craft.recipe[2][2])]==nil then list[(craft.recipe[2][2])]={} list[(craft.recipe[2][2])]=amount else local add =amount+tonumber(list[(craft.recipe[2][2])]) list[(craft.recipe[2][2])]=add end end if craft.recipe[2][3] then if list[(craft.recipe[2][3])]==nil then list[(craft.recipe[2][3])]={} list[(craft.recipe[2][3])]=amount else local add =amount+tonumber(list[(craft.recipe[2][3])]) list[(craft.recipe[2][3])]=add end end end end if craft.recipe[3] then if (type(craft.recipe[3]) == "string") then if list[(craft.recipe[3])]==nil then list[(craft.recipe[3])]={} list[(craft.recipe[3])]=amount else local add =amount+tonumber(list[(craft.recipe[3])]) list[(craft.recipe[3])]=add end else if craft.recipe[3][1] then if list[(craft.recipe[3][1])]==nil then list[(craft.recipe[3][1])]={} list[(craft.recipe[3][1])]=amount else local add =amount+tonumber(list[(craft.recipe[3][1])]) list[(craft.recipe[3][1])]=add end end if craft.recipe[3][2] then if list[(craft.recipe[3][2])]==nil then list[(craft.recipe[3][2])]={} list[(craft.recipe[3][2])]=amount else local add =amount+tonumber(list[(craft.recipe[3][2])]) list[(craft.recipe[3][2])]=add end end if craft.recipe[3][3] then if list[(craft.recipe[3][3])]==nil then list[(craft.recipe[3][3])]={} list[(craft.recipe[3][3])]=amount else local add =amount+tonumber(list[(craft.recipe[3][3])]) list[(craft.recipe[3][3])]=add end end end end if craft.recipe[4] then if (type(craft.recipe[4]) == "string") then if list[(craft.recipe[4])]==nil then list[(craft.recipe[4])]={} list[(craft.recipe[4])]=amount else local add =amount+tonumber(list[(craft.recipe[4])]) list[(craft.recipe[4])]=add end end end if craft.recipe[5] then if (type(craft.recipe[5]) == "string") then if list[(craft.recipe[5])]==nil then list[(craft.recipe[5])]={} list[(craft.recipe[5])]=amount else local add =amount+tonumber(list[(craft.recipe[5])]) list[(craft.recipe[5])]=add end end end if craft.recipe[6] then if (type(craft.recipe[6]) == "string") then if list[(craft.recipe[6])]==nil then list[(craft.recipe[6])]={} list[(craft.recipe[6])]=amount else local add =amount+tonumber(list[(craft.recipe[6])]) list[(craft.recipe[6])]=add end end end if craft.recipe[7] then if (type(craft.recipe[7]) == "string") then if list[(craft.recipe[7])]==nil then list[(craft.recipe[7])]={} list[(craft.recipe[7])]=amount else local add =amount+tonumber(list[(craft.recipe[7])]) list[(craft.recipe[7])]=add end end end if craft.recipe[8] then if (type(craft.recipe[8]) == "string") then if list[(craft.recipe[8])]==nil then list[(craft.recipe[8])]={} list[(craft.recipe[8])]=amount else local add =amount+tonumber(list[(craft.recipe[8])]) list[(craft.recipe[8])]=add end end end if craft.recipe[9] then if (type(craft.recipe[9]) == "string") then if list[(craft.recipe[9])]==nil then list[(craft.recipe[9])]={} list[(craft.recipe[9])]=amount else local add =amount+tonumber(list[(craft.recipe[9])]) list[(craft.recipe[9])]=add end end end end if istest==1 then test=list list=nil list={} list=list2 end end if istest==1 then local value=0 local h=0 for name,testcount in pairs(test) do h=h+1 if h>888 then break end if testcount>0 then if name.def==nil or (craft_guide.crafts[name]==nil and string.sub(name,1,8)=="technic:") then bestvalue=10 h=999 else local testcrafts = craft_guide.crafts[name] local testcraft="" if testcrafts~=nil then testcraft=testcrafts[1] end local isbase=0 if name==nil or name=="" or string.sub(name,1,6)=="group:" or testcrafts==nil or testcraft==nil or (testcraft.type~=nil and testcraft.type~="shapeless") then isbase=1 else for ii=1,999,1 do if craft_guide.basic_item_prefixes[ii]==nil or craft_guide.basic_item_prefixes[ii]=="" then break elseif string.sub(name,1,string.len(craft_guide.basic_item_prefixes[ii]))== string.lower(craft_guide.basic_item_prefixes[ii]) then isbase=1 break end end if isbase==0 then for aa=1,999,1 do if craft_guide.basic_item_groups[aa]==nil or craft_guide.basic_item_groups[aa]=="" then break elseif minetest.get_item_group(name, string.lower(craft_guide.basic_item_groups[aa]))>0 then isbase=1 break end end if isbase==0 then for bb=1,999,1 do if craft_guide.basic_item_endings[bb]==nil or craft_guide.basic_item_endings[bb]=="" then break elseif string.sub(name,string.len(name)-(string.len(craft_guide.basic_item_endings[bb])-1))== string.lower(craft_guide.basic_item_endings[bb]) then isbase=1 break end end if isbase==0 then for cc=1,999,1 do if craft_guide.basic_items[cc]==nil or craft_guide.basic_items[cc]=="" then break elseif name==string.lower(craft_guide.basic_items[cc]) then isbase=1 break end end end end end end if isbase==0 then value=value+1 -- if string.find(name,"slab")~=nil -- or string.find(name,"panel")~=nil -- or string.find(name,"microblock")~=nil -- or string.find(name,"stair")~=nil -- then -- value=value+5 -- end end end end end --starting with correct tabs here again: if value<bestvalue then bestcraft=index bestvalue=value end else craftnumber=999 break end end end end end if finished==1 then break end end end local jj=1 local duplicate=0 for name,amount in pairs(list) do local count=tonumber(amount) if name~=nil and count>0 and string.lower(name)~=string.upper(name) then local lower=string.lower(name) if craft_guide.you_need_list[lower]~=nil and craft_guide.you_need_list[lower]>0 then craft_guide.you_need_list[lower]=count+craft_guide.you_need_list[lower] else inv:add_item("youneed", lower) if inv:get_stack("youneed",jj)==nil or inv:get_stack("youneed",jj):get_name()=="" then for jjj=1,jj,1 do if inv:get_stack("youneed",jjj):get_count()>1 then local alias=string.lower(inv:get_stack("youneed",jjj):get_name()) if craft_guide.you_need_list[alias]==nil then craft_guide.you_need_list[alias]={} craft_guide.you_need_list[alias]=count inv:set_stack("youneed",jjj,alias) else craft_guide.you_need_list[alias]=craft_guide.you_need_list[alias]+count inv:set_stack("youneed",jjj,alias) end end end inv:set_stack("youneed",jj,ItemStack(nil)) duplicate=1 list[lower]=0 elseif string.lower(inv:get_stack("youneed",jj):get_name())~=lower then local alias=string.lower(inv:get_stack("youneed",jj):get_name()) if craft_guide.you_need_list[alias]~=nil then craft_guide.you_need_list[alias]=craft_guide.you_need_list[alias]+count else if list[alias]==nil then craft_guide.you_need_list[alias]={} craft_guide.you_need_list[alias]=count inv:set_stack("youneed",jj,alias) else list[alias]=list[alias]+count end end list[lower]=0 else craft_guide.you_need_list[lower]={} craft_guide.you_need_list[lower]=count end if duplicate==0 then jj=jj+1 else duplicate=0 end if jj>inv:get_size("youneed") then break end end end craft_guide.saved_you_need_lists[stack_name.."@|²"..tostring(alternate)]={} craft_guide.saved_you_need_lists[stack_name.."@|²"..tostring(alternate)]=craft_guide.you_need_list craft_guide.saved_you_need_lists[stack_name.."@|³"..tostring(alternate)]={} craft_guide.saved_you_need_lists[stack_name.."@|³"..tostring(alternate)]=tostring(globalcount) end end meta:set_string("globalcount",tostring(globalcount)) meta:set_string("formspec",craft_guide.get_craft_guide_formspec(meta)) end -- create_inventory craft_guide.create_inventory = function(inv, search) local craft_guide_list = {} for name,def in pairs(minetest.registered_items) do -- local craft_recipe = minetest.get_craft_recipe(name); -- if craft_recipe.items ~= nil then local craft = craft_guide.crafts[name]; if (not def.groups.not_in_craft_guide or def.groups.not_in_craft_guide == 0) and (craft ~= nil or (not def.groups.not_in_creative_inventory or def.groups.not_in_creative_inventory == 0)) --and (not def.groups.not_in_creative_inventory or def.groups.not_in_creative_inventory == 0) and def.description and def.description ~= "" then if search and search~="" then --search used to display groups of items --if you enter something in search field it displays items without crafting recipes too search=string.lower(search) if string.sub(search,1,6)=="group:" then local groups=string.sub(search,7) local hasgroup=0 for group in string.gmatch(groups,"([^,]+)") do if minetest.get_item_group(name, group)>0 then hasgroup=1 else hasgroup=0 break end end if hasgroup==1 then table.insert(craft_guide_list, name) end else search=string.lower(search) local test1=0 local test2=0 local test3=0 test1,test2=string.find(string.lower(def.name.." "), search) test2,test3=string.find(string.lower(def.description.." "), search) if (test1~=nil and test1>0) or (test2~=nil and test2>0) or search=="*" then table.insert(craft_guide_list, name) end end else if craft~=nil and craft[1]~=nil and ((craft[1]).type~="fuel" or craft_guide.show_all_fuel_crafts) then table.insert(craft_guide_list, name) end end end end table.sort(craft_guide_list) for i=0,inv:get_size("main"),1 do inv:set_stack("main", i, nil) end inv:set_size("main", #craft_guide_list) for _,itemstring in ipairs(craft_guide_list) do inv:add_item("main", ItemStack(itemstring)) end end -- add fuel recipes and recipes from technic machines to craft list craft_guide.add_additional_crafts = function() if craft_guide.other_crafting_types then if minetest.get_modpath("technic") then local oldversion=false local recipelist={} if technic.recipes==nil or technic.recipes["grinding"]==nil and technic.grinder_recipes~=nil then oldversion=true recipelist=technic.grinder_recipes for t,recipe in pairs(recipelist) do recipe.type="Grinder" local name=ItemStack(recipe.output):get_name() if name~=nil and name~="" then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end recipe.time=recipe.time or 3 table.insert(craft_guide.crafts[name],recipe) end end else recipelist=technic.recipes["grinding"].recipes for t,recipe in pairs(recipelist) do recipe.type="Grinder" local name=ItemStack(recipe.output):get_name() if name~=nil and name~="" and (not craft_guide.remove_cluttering_crafts or (string.find(name,"technic:uranium._")==nil and string.find(name,"technic:uranium.._")==nil)) then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end local idx=1 for _name, _count in pairs(recipe.input) do recipe.input[idx]=_name.." ".._count break end recipe.time=recipe.time or 3 table.insert(craft_guide.crafts[name],recipe) end end end if oldversion then for t,recipe in pairs(technic.compressor_recipes) do recipe.type="Compressor" local name=ItemStack(recipe.dst_name):get_name() if name~=nil and name~="" then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end recipe.input=t.." "..tostring(recipe.src_count) recipe.output=recipe.dst_name.." "..tostring(recipe.dst_count) recipe.time=recipe.time or 4 table.insert(craft_guide.crafts[name],recipe) end end else for t,recipe in pairs(technic.recipes["compressing"].recipes) do recipe.type="Compressor" local name=ItemStack(recipe.output):get_name() if name~=nil and name~="" then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end local idx=1 for _name, _count in pairs(recipe.input) do recipe.input[idx]=_name.." ".._count break end recipe.time=recipe.time or 4 table.insert(craft_guide.crafts[name],recipe) end end end if oldversion then for t,recipe in pairs(technic.extractor_recipes) do recipe.type="Extractor" local name=ItemStack(recipe.dst_name):get_name() if name~=nil and name~="" then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end recipe.input=t.." "..tostring(recipe.src_count) recipe.output=recipe.dst_name.." "..tostring(recipe.dst_count) recipe.time=recipe.time or 4 table.insert(craft_guide.crafts[name],recipe) end end else for t,recipe in pairs(technic.recipes["extracting"].recipes) do recipe.type="Extractor" local name=ItemStack(recipe.output):get_name() if name~=nil and name~="" then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end local idx=1 for _name, _count in pairs(recipe.input) do recipe.input[idx]=_name.." ".._count break end recipe.time=recipe.time or 4 table.insert(craft_guide.crafts[name],recipe) end end end if oldversion then recipelist=technic.alloy_recipes for t,recipe in pairs(recipelist) do recipe.type="Alloy Furnace" local name=ItemStack(recipe.output):get_name() if name~=nil and name~="" then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end recipe.time=recipe.time or 6 table.insert(craft_guide.crafts[name],recipe) end end else recipelist=technic.recipes["alloy"].recipes for t,recipe in pairs(recipelist) do local rec={} rec.type="Alloy Furnace" local name=ItemStack(recipe.output):get_name() if name~=nil and name~="" then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end local idx=1 rec.output=recipe.output rec.time=recipe.time or 6 rec.input={} for _name, _count in pairs(recipe.input) do rec.input[idx]=_name.." ".._count idx=idx+1 if idx>2 then break end end table.insert(craft_guide.crafts[name],rec) end end end if not oldversion then for t,recipe in pairs(technic.recipes["separating"].recipes) do local rec={} local rec2={} rec.type="Centrifuge" rec2.type="Centrifuge" local name=ItemStack(recipe.output[1]):get_name() local name2=ItemStack(recipe.output[2]):get_name() local count=ItemStack(recipe.output[1]):get_count() local count2=ItemStack(recipe.output[2]):get_count() if name~=nil and name~="" and (not craft_guide.remove_cluttering_crafts or (string.find(name,"technic:uranium._")==nil and string.find(name,"technic:uranium.._")==nil)) then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end local idx=1 rec.input={} rec2.input={} for _name, _count in pairs(recipe.input) do rec.input[idx]=_name.." ".._count rec2.input[idx]=_name.." ".._count break end rec.time=recipe.time or 10 rec2.time=recipe.time or 10 rec.output2=name2.." "..tostring(count2) rec.output=name.." "..tostring(count) table.insert(craft_guide.crafts[name],rec) if name2~=nil and name2~="" and (not craft_guide.remove_cluttering_crafts or (string.find(name2,"technic:uranium._")==nil and string.find(name2,"technic:uranium.._")==nil)) then if craft_guide.crafts[name2]==nil then craft_guide.crafts[name2] = {} end rec2.output=name2.." "..tostring(count2) rec2.output2=name.." "..tostring(count) table.insert(craft_guide.crafts[name2],rec2) end end end end end end craft_guide.other_crafting_types = false if craft_guide.fuel_to_add then --add crafts with type "fuel" for name,def in pairs(minetest.registered_items) do if (not def.groups.not_in_craft_guide or def.groups.not_in_craft_guide == 0) then if craft_guide.fuel[name]~=nil then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end local fuels=craft_guide.fuel[name] local fuel=fuels[1] table.insert(craft_guide.crafts[name],fuel) else local best=0 local bestgroup="" for group,_ in pairs(def.groups) do if craft_guide.fuel["group:"..group]~=nil then local fuels=craft_guide.fuel["group:"..group] local fuel=fuels[1] if fuel.burntime>best then best=fuel.burntime bestgroup=group end end end if bestgroup~="" then if craft_guide.crafts[name]==nil then craft_guide.crafts[name] = {} end local fuels=craft_guide.fuel["group:"..bestgroup] local fuel=fuels[1] table.insert(craft_guide.crafts[name],fuel) end end end end end craft_guide.fuel_to_add=false craft_guide.fuel=nil craft_guide.fuel={} -- all aliases should share the same crafting recipes if craft_guide.add_things then for i=1,9999,2 do local alias=craft_guide.alias[i] local convert_to=craft_guide.alias[i+1] if alias~=nil and convert_to~=nil and (craft_guide.crafts[convert_to]~=nil or craft_guide.crafts[alias]~=nil) then if craft_guide.crafts[convert_to]==nil and craft_guide.crafts[alias]~=nil then craft_guide.crafts[convert_to]={} elseif craft_guide.crafts[alias]==nil and craft_guide.crafts[convert_to]~=nil then craft_guide.crafts[alias]={} end for ii=1,9999,1 do local craft=(craft_guide.crafts[alias])[ii] if craft==nil then break else table.insert(craft_guide.crafts[convert_to],craft) end end craft_guide.crafts[alias]={} for ii=1,9999,1 do local craft=(craft_guide.crafts[convert_to])[ii] if craft==nil then break else table.insert(craft_guide.crafts[alias],craft) end end end end end craft_guide.add_things=false end -- allow_metadata_inventory_move craft_guide.allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) local meta = minetest.env:get_meta(pos) if meta:get_string("locked")=="1" then craft_guide.save_meta(meta) end local inv = meta:get_inventory() if to_list == "bin" and from_list == "output" then inv:set_stack(from_list,from_index,nil) craft_guide.update_recipe(meta, player, inv:get_stack(from_list, from_index)) end if to_list == "bin" and from_list == "bookmark" then inv:set_stack(from_list,from_index,nil) inv:set_stack("add",1,nil)--clear this because bookmarks aren't full anymore end if to_list == "bookmark" and not inv:contains_item("bookmark",inv:get_stack(from_list, from_index):get_name()) then inv:set_stack(to_list, to_index, inv:get_stack(from_list, from_index):get_name()) if not inv:contains_item("bookmark",ItemStack(nil)) then inv:set_stack("add", 1, inv:get_stack("bookmark", tonumber(meta:get_string("addindex"))):get_name()) end end if to_list == "add" and not inv:contains_item("bookmark",inv:get_stack(from_list, from_index):get_name()) then local index=tonumber(meta:get_string("addindex")) local stack=inv:get_stack("bookmark",index) local status=0 if stack~=nil and stack:get_name()~=nil and stack:get_name()~="" then for i=1,inv:get_size("bookmark"),1 do stack=inv:get_stack("bookmark",i) if stack~=nil and stack:get_name()~=nil and stack:get_name()~="" then else if status==0 then inv:set_stack("bookmark", i, inv:get_stack(from_list, from_index):get_name()) meta:set_string("addindex",tostring(i)) status=1 elseif status==1 then status=2 end end end if status==1 then --bookmarks are full now inv:set_stack("add", to_index, inv:get_stack(from_list, from_index):get_name()) elseif status==2 then --bookmarks has still empty slots after adding this stack inv:set_stack("add", to_index, nil) elseif status==0 then --bookmarks were already full, replace last added item inv:set_stack("bookmark", index, inv:get_stack(from_list, from_index):get_name()) inv:set_stack("add", to_index, inv:get_stack(from_list, from_index):get_name()) end else inv:set_stack("bookmark", index, inv:get_stack(from_list, from_index):get_name()) inv:set_stack("add", to_index, nil) end end if to_list == "output" or from_list == "output" then if from_list ~= "output" and to_list == "output" then local name=inv:get_stack(from_list, from_index) if name~=nil then name=name:get_name() end if name~=nil then meta:set_string("out",name) inv:set_stack(to_list, to_index, nil) end end if from_list == "output" and (to_list == "bin" or to_list=="add" ) then meta:set_string("out","") end craft_guide.update_recipe(meta, player, inv:get_stack(from_list, from_index)) end if from_list == "bookmark" and to_list == "bookmark" then return count end return 0 end -- allow_metadata_inventory_put craft_guide.allow_metadata_inventory_put = function(pos, listname, index, stack, player) return 0 end -- allow_metadata_inventory_take craft_guide.allow_metadata_inventory_take = function(pos, listname, index, stack, player) return 0 end craft_guide.save_meta = function (meta) meta:set_string("saved_search2",meta:get_string("saved_search")) meta:set_string("saved_page2",meta:get_string("saved_page")) meta:set_string("saved_pages2",meta:get_string("saved_pages")) meta:set_string("switch2",meta:get_string("switch")) meta:set_string("poslist2",meta:get_string("poslist")) meta:set_string("globalcount2",meta:get_string("globalcount")) meta:set_string("time2",meta:get_string("time")) meta:set_string("method2",meta:get_string("method")) meta:set_string("out2",meta:get_string("out")) meta:set_string("addindex2",meta:get_string("addindex")) meta:set_string("search2",meta:get_string("search")) local inv=meta:get_inventory() inv:set_size("main2", inv:get_size("main")) inv:set_size("output2", 1) inv:set_size("additional2", 1) inv:set_size("build2", 3*3) inv:set_size("cook2", 2*1) inv:set_size("fuel2", 1) inv:set_size("machine2", 1) inv:set_size("bookmark2", 6*3) inv:set_size("youneed2", 6*15) inv:set_size("bin2", 1) inv:set_size("add2", 1) for i=0,inv:get_size("main2"),1 do inv:set_stack("main2", i, inv:get_stack("main",i)) end for i=0,inv:get_size("build2"),1 do inv:set_stack("build2", i, inv:get_stack("build",i)) end for i=0,inv:get_size("bookmark2"),1 do inv:set_stack("bookmark2", i, inv:get_stack("bookmark",i)) end for i=0,inv:get_size("youneed2"),1 do inv:set_stack("youneed2", i, inv:get_stack("youneed",i)) end inv:set_stack("cook2", 1, inv:get_stack("cook",1)) inv:set_stack("cook2", 2, inv:get_stack("cook",2)) inv:set_stack("output2", 1, inv:get_stack("output",1)) inv:set_stack("additional2", 1, inv:get_stack("additional",1)) inv:set_stack("fuel2", 1, inv:get_stack("fuel",1)) inv:set_stack("bin2", 1, inv:get_stack("bin",1)) inv:set_stack("machine2", 1, inv:get_stack("machine",1)) inv:set_stack("add2", 1, inv:get_stack("add",1)) meta:set_string("locked","2") meta:set_string("formspec2",meta:get_string("saved_formspec")) end craft_guide.restore_meta = function (meta) meta:set_string("saved_search",meta:get_string("saved_search2")) meta:set_string("saved_page",meta:get_string("saved_page2")) meta:set_string("saved_pages",meta:get_string("saved_pages2")) meta:set_string("switch",meta:get_string("switch2")) meta:set_string("poslist",meta:get_string("poslist2")) meta:set_string("globalcount",meta:get_string("globalcount2")) meta:set_string("time",meta:get_string("time2")) meta:set_string("method",meta:get_string("method2")) meta:set_string("out",meta:get_string("out2")) meta:set_string("addindex",meta:get_string("addindex2")) meta:set_string("search",meta:get_string("search2")) local inv=meta:get_inventory() inv:set_size("main",inv:get_size("main2")) for i=0,inv:get_size("main"),1 do inv:set_stack("main", i, inv:get_stack("main2",i)) end for i=0,inv:get_size("build"),1 do inv:set_stack("build", i, inv:get_stack("build2",i)) end for i=0,inv:get_size("bookmark"),1 do inv:set_stack("bookmark", i, inv:get_stack("bookmark2",i)) end for i=0,inv:get_size("youneed"),1 do inv:set_stack("youneed", i, inv:get_stack("youneed2",i)) end inv:set_stack("cook", 1, inv:get_stack("cook2",1)) inv:set_stack("cook", 2, inv:get_stack("cook2",2)) inv:set_stack("output", 1, inv:get_stack("output2",1)) inv:set_stack("additional", 1, inv:get_stack("additional2",1)) inv:set_stack("fuel", 1, inv:get_stack("fuel2",1)) inv:set_stack("bin", 1, inv:get_stack("bin2",1)) inv:set_stack("machine", 1, inv:get_stack("machine2",1)) inv:set_stack("add", 1, inv:get_stack("add2",1)) meta:set_string("isowner","0") meta:set_string("locked","1") local formspec= meta:get_string("formspec2") meta:set_string("saved_formspec",formspec) formspec=formspec.."label[0.88,9.2;Locked]" .."tooltip[close_mm; Owner: "..meta:get_string("owner").."]" meta:set_string("formspec",formspec) end
--[[ Copyright (C) 2013-2018 Draios Inc dba Sysdig. This file is part of sysdig. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ scallslower.lua - trace the syscalls slower than a given threshold. USAGE: sysdig -c scallslower min_ms eg, sysdig -c scallslower 1000 # show syscalls slower than 1000 ms. sysdig -c scallslower "1 disable_colors" # show syscalls slower than 1 ms. w/ no colors sysdig -pc -c scallslower 1000 # show syscalls slower than 1000 ms and container output --]] -- Chisel description description = "Trace syscalls slower than a threshold milliseconds. This chisel is compatible with containers using the sysdig -pc or -pcontainer argument, otherwise no container information will be shown. (Blue represents a process running within a container, and Green represents a host process)"; short_description = "Trace slow syscalls"; category = "Performance"; -- Chisel argument list args = { { name = "min_ms", description = "Minimum milliseconds before which a syscall should complete", argtype = "int", optional = false }, { name = "disable_color", description = "Set to 'disable_colors' if you want to disable color output", argtype = "string", optional = true }, } require "common" terminal = require "ansiterminal" terminal.enable_color(true) -- Argument notification callback function on_set_arg(name, val) if name == "disable_color" and val == "disable_color" then terminal.enable_color(false) elseif name == "min_ms" then min_ms = parse_numeric_input(val, name) end return true end -- Initialization callback function on_init() -- set the following fields on_event() evtnum = chisel.request_field("evt.num") etype = chisel.request_field("evt.type") dir = chisel.request_field("evt.dir") datetime = chisel.request_field("evt.datetime") pname = chisel.request_field("proc.name") pid = chisel.request_field("proc.pid") tid = chisel.request_field("thread.tid") latency = chisel.request_field("evt.latency") fcontainername = chisel.request_field("container.name") fcontainerid = chisel.request_field("container.id") -- The -pc or -pcontainer options was supplied on the cmd line print_container = sysdig.is_print_container_data() -- The -pc or -pcontainer options was supplied on the cmd line if print_container then print(string.format("%-23.23s %-23.23s %-20.20s %-20.20s %-10s %-10s %-23.23s %-20s %s", "evt.num", "evt.datetime", "container.id", "container.name", "proc.pid", "proc.tid", "proc.name", "LATENCY(ms)", "evt.type")) print(string.format("%-23.23s %-23.23s %-20.20s %-20.20s %-10s %-10s %-23.23s %-20s %s", "-----------------------", "-----------------------", "--------------------", "--------------------", "----------", "----------", "-----------------------", "--------------------", "--------------------")) else print(string.format("%-23.23s %-23.23s %-10s %-10s %-23.23s %-20s %s", "evt.num", "evt.datetime", "proc.pid", "proc.tid", "proc.name", "LATENCY(ms)", "evt.type")) print(string.format("%-23.23s %-23.23s %-10s %-10s %-23.23s %-20s %s", "-----------------------", "-----------------------", "----------", "----------", "-----------------------", "--------------------", "--------------------")) end return true end -- Event callback function on_event() local color = terminal.green lat = evt.field(latency) if lat == nil then return end lat = lat / 1000000 if lat > min_ms then if evt.field(fcontainername) ~= "host" then color = terminal.blue end -- The -pc or -pcontainer options was supplied on the cmd line if print_container then print(color .. string.format("%-23.23s %-23.23s %-20.20s %-20.20s %-10s %-10s %-23.23s %-20s %s", evt.field(evtnum), evt.field(datetime), evt.field(fcontainerid), evt.field(fcontainername), evt.field(pid), evt.field(tid), evt.field(pname), lat, evt.field(etype))) else print(color .. string.format("%-23.23s %-23.23s %-10s %-10s %-23.23s %-20s %s", evt.field(evtnum), evt.field(datetime), evt.field(pid), evt.field(tid), evt.field(pname), lat, evt.field(etype))) end end end
require("lists") require("tables") texts = require('texts') images = require('images') local selectable_list = {} local BORDER_PADDING = 10 local COLUMN_WIDTH = 170 local ROW_HEIGHT = 50 function selectable_list:setup(theme_options, base_x, base_y, max_width, max_height) self.theme_options = theme_options self.frame_image_path = windower.addon_path..'/themes/' .. (theme_options.frame_theme:lower()) .. '/frame.png' self.base_x = base_x or 150 self.base_y = base_y or 150 local temp_width = max_width or (windower.get_windower_settings().ui_x_res - 300) local temp_height = max_height or (windower.get_windower_settings().ui_y_res - 300) self.max_row = math.floor((temp_height - 2 * BORDER_PADDING) / ROW_HEIGHT) self.max_col = math.floor((temp_width - 2 * BORDER_PADDING) / COLUMN_WIDTH) self.width = 2 * BORDER_PADDING + self.max_col * COLUMN_WIDTH self.height = 2 * BORDER_PADDING + self.max_row * ROW_HEIGHT self.fields = L{} self.field_coords = {} self.selected_row = 1 self.selected_col = 1 self.images = L{} self.current_page = 1 self.is_prev_button_showing = false self.is_next_button_showing = false windower.prim.create('selectablelist_selection_highlight') windower.prim.set_color('selectablelist_selection_highlight', 255, 171, 252, 252) windower.prim.set_position('selectablelist_selection_highlight', 0, 0) windower.prim.set_size('selectablelist_selection_highlight', COLUMN_WIDTH, ROW_HEIGHT) windower.prim.set_visibility('selectablelist_selection_highlight', false) windower.prim.create('prev_page_button') windower.prim.set_color('prev_page_button', 200, 0, 0, 0) windower.prim.set_position('prev_page_button', 0, 0) windower.prim.set_size('prev_page_button', COLUMN_WIDTH, ROW_HEIGHT) windower.prim.set_visibility('prev_page_button', false) windower.prim.create('next_page_button') windower.prim.set_color('next_page_button', 200, 0, 0, 0) windower.prim.set_position('next_page_button', 0, 0) windower.prim.set_size('next_page_button', COLUMN_WIDTH, ROW_HEIGHT) windower.prim.set_visibility('next_page_button', false) end function selectable_list:reset_state() self.is_showing = false self.current_page = 1 self.current_options = L{} windower.prim.set_visibility('prev_page_button', false) windower.prim.set_visibility('next_page_button', false) for index, field in ipairs(self.fields) do field:hide() end for index, image in ipairs(self.images) do image:hide() end self.fields = L{} self.field_coords = {} self.selected_row = 1 self.selected_col = 1 end function selectable_list:export_selection_state() return {page = self.current_page, row = self.selected_row, col = self.selected_col} end function selectable_list:import_selection_state(selection_state) self.current_page = selection_state.page self.selected_row = selection_state.row self.selected_col = selection_state.col self:highlight_selection() end function selectable_list:set_page(page) self.current_page = page end function selectable_list:increment_page() self.current_page = self.current_page + 1 self:display_options(self.current_options) if (self.is_next_button_showing) then self.selected_row = self.max_row + 1 self.selected_col = self.max_col self:highlight_selection() else self.selected_row = self.max_row + 1 self.selected_col = 1 self:highlight_selection() end end function selectable_list:decrement_page() self.current_page = self.current_page - 1 self:display_options(self.current_options) if (self.is_prev_button_showing) then self.selected_row = self.max_row + 1 self.selected_col = 1 self:highlight_selection() else self.selected_row = self.max_row + 1 self.selected_col = self.max_col self:highlight_selection() end end function selectable_list:increment_row() local new_row = self.selected_row + 1 if (self.field_coords[self.selected_col][new_row] ~= nil) then self.selected_row = new_row self:highlight_selection() elseif (self.field_coords[self.selected_col][self.max_row + 1] ~= nil) then -- handling the "Previous Page" button self.selected_row = self.max_row + 1 self:highlight_selection() end end function selectable_list:decrement_row() local new_row = self.selected_row - 1 if (self.field_coords[self.selected_col][new_row] ~= nil) then self.selected_row = new_row self:highlight_selection() elseif (self.field_coords[self.selected_col][self.selected_row].id == 'PREV') then -- handling jumping from the "Previous Page" button to the last row with entries while (self.field_coords[self.selected_col][new_row] == nil) do new_row = new_row - 1 end self.selected_row = new_row self:highlight_selection() end end function selectable_list:increment_col() local new_col = self.selected_col + 1 if (self.field_coords[new_col] ~= nil and self.field_coords[new_col][self.selected_row] ~= nil) then self.selected_col = new_col self:highlight_selection() elseif (self.field_coords[self.selected_col][self.selected_row].id == 'PREV' and self.is_next_button_showing) then -- handle "jumping" from the Previous Page button to the Next Page button self.selected_col = self.max_col self:highlight_selection() end end function selectable_list:decrement_col() local new_col = self.selected_col - 1 if (self.field_coords[new_col] ~= nil and self.field_coords[new_col][self.selected_row] ~= nil) then self.selected_col = new_col self:highlight_selection() elseif (self.field_coords[self.selected_col][self.selected_row].id == 'NEXT' and self.is_prev_button_showing) then -- handle "jumping" from the Next Page button to the Previous Page button self.selected_col = 1 self:highlight_selection() end end function selectable_list:hide() self.is_showing = false windower.prim.set_visibility('selectablelist_selection_highlight', false) windower.prim.set_visibility('prev_page_button', false) windower.prim.set_visibility('next_page_button', false) for index, field in ipairs(self.fields) do field:hide() end for index, image in ipairs(self.images) do image:hide() end end function selectable_list:show() end function selectable_list:create_text(text_string, row, col) local text = texts.new({flags = {draggable = false}}) text:bg_alpha(0) text:bg_visible(false) text:font(self.theme_options.font) text:size(self.theme_options.font_size + 2) text:color(self.theme_options.font_color_red, self.theme_options.font_color_green, self.theme_options.font_color_blue) text:stroke_transparency(self.theme_options.font_stroke_alpha) text:stroke_color(self.theme_options.font_stroke_color_red, self.theme_options.font_stroke_color_green, self.theme_options.font_stroke_color_blue) text:stroke_width(self.theme_options.font_stroke_width) local x, y = self:get_pos(row, col) text:pos(x + 50, y + 18) text:text(text_string) text:show() return text end function selectable_list:highlight_selection() local x, y = self:get_pos(self.selected_row, self.selected_col) windower.prim.set_position('selectablelist_selection_highlight', x, y) windower.prim.set_visibility('selectablelist_selection_highlight', true) end function selectable_list:draw_prev_page_button(row, col) local x, y = self:get_pos(row, col) windower.prim.set_position('prev_page_button', x, y) windower.prim.set_visibility('prev_page_button', true) end function selectable_list:draw_next_page_button(row, col) local x, y = self:get_pos(row, col) windower.prim.set_position('next_page_button', x, y) windower.prim.set_visibility('next_page_button', true) end function selectable_list:get_pos(row, col) local x = self.base_x + BORDER_PADDING + (col - 1) * COLUMN_WIDTH local y = self.base_y + BORDER_PADDING + (row - 1) * ROW_HEIGHT return x, y end function selectable_list:get_row_col_from_pos(x, y) local row = math.floor((y - (self.base_y + BORDER_PADDING)) / ROW_HEIGHT) + 1 local col = math.floor((x - (self.base_x + BORDER_PADDING)) / COLUMN_WIDTH) + 1 return row, col end function selectable_list:get_row_col(index) local row = math.ceil((index + 1) / self.max_col) local col = (index % self.max_col) + 1 return row, col end function selectable_list:display_options(options) local current_page = self.current_page self:reset_state() self.is_showing = true self.current_options = options self.current_page = current_page local first_row = (self.current_page - 1) * self.max_row + 1 local last_row = self.current_page * self.max_row local entries_to_skip = (self.current_page - 1) * self.max_row * self.max_col + 1 local newlines = 0 local col_offset = 0 local count = 0 for i, value in ipairs(options) do count = count + 1 local option_id = value.id local option_caption = value.name local data = value.data local abs_row, abs_col = self:get_row_col(i - 1) if (first_row <= abs_row and abs_row <= last_row) then local row, col = self:get_row_col(i - entries_to_skip) row = row + newlines if (option_caption == 'newline') then newlines = newlines + 1 col_offset = col % self.max_col else col = col - col_offset if (row == self.selected_row and col == self.selected_col) then self:highlight_selection() end self.fields:append(self:create_text(option_caption, row, col)) local icon = images.new({draggable = false}) local icon_path = windower.addon_path .. '/images/' .. value.icon local x, y = self:get_pos(row, col) x = x + 5 y = y + 5 setup_image(icon, icon_path) local icon_offset = value.icon_offset or 0 icon:pos(x + icon_offset, y + icon_offset) self.images:append(icon) local frame = images.new({draggable = false}) setup_image(frame, self.frame_image_path) frame:pos(x, y) self.images:append(frame) -- populate the "collision" map for dpad navigation local field_col = self.field_coords[col] or {} field_col[row] = {['id'] = option_id, ['text'] = option_caption, ['data'] = data} self.field_coords[col] = field_col end end end if (count > self.current_page * self.max_row * self.max_col) then self.is_next_button_showing = true local row = self.max_row + 1 local col = self.max_col -- display "next" button self.fields:append(self:create_text('Next Page', row, col)) if (row == self.selected_row and col == self.selected_col) then windower.prim.set_visibility('next_page_button', false) self:highlight_selection() else self:draw_next_page_button(row, col) end -- populate the "collision" map for dpad navigation local field_col = self.field_coords[self.max_col] or {} field_col[row] = {['id'] = 'NEXT', ['text'] = 'Next Page'} self.field_coords[col] = field_col else self.is_next_button_showing = false end if (self.current_page > 1) then self.is_prev_button_showing = true local row = self.max_row + 1 local col = 1 -- display "prev" button self.fields:append(self:create_text('Previous Page', row, col)) if (row == self.selected_row and col == self.selected_col) then windower.prim.set_visibility('prev_page_button', false) self:highlight_selection() else self:draw_prev_page_button(row, col) end -- populate the "collision" map for dpad navigation local field_col = self.field_coords[col] or {} field_col[row] = {['id'] = 'PREV', ['text'] = 'Previous Page'} self.field_coords[col] = field_col else self.is_prev_button_showing = false end end function selectable_list:submit_selected_option() local option = self.field_coords[self.selected_col][self.selected_row] if (option.id ~= 'PREV' and option.id ~= 'NEXT') then self:hide() self:reset_state() end return option end function selectable_list:is_valid_row_col(row, col) return selectable_list.field_coords and selectable_list.field_coords[col] ~= nil and selectable_list.field_coords[col][row] ~= nil end function setup_image(image, path) image:path(path) image:repeat_xy(1, 1) image:draggable(false) image:fit(true) image:alpha(255) image:show() end windower.register_event('mouse', function(type, x, y, delta, blocked) if blocked then return end if (selectable_list.is_showing) then -- Mouse drag (0) or left click (1) if (type == 0 or type == 1) then local row, col = selectable_list:get_row_col_from_pos(x, y) if (selectable_list:is_valid_row_col(row, col)) then selectable_list.selected_row = row selectable_list.selected_col = col selectable_list:highlight_selection() return true end -- Mouse left release elseif type == 2 then end end end) return selectable_list
local wibox = require('wibox') local beautiful = require('beautiful') local dpi = require('beautiful').xresources.apply_dpi -- Notification Center ------------------------- -- header local notif_header = wibox.widget { text = 'Notification Center', font = beautiful.font_name .. 'Bold 14', align = 'left', valign = 'center', widget = wibox.widget.textbox } -- build notif-center local notif_center = function(s) s.dont_disturb = require('ui.notifs.notif-center.dont-disturb') s.clear_all = require('ui.notifs.notif-center.clear-all') s.notifbox_layout = require('ui.notifs.notif-center.build-notifbox').notifbox_layout return wibox.widget { expand = 'none', layout = wibox.layout.fixed.vertical, spacing = dpi(10), { expand = 'none', layout = wibox.layout.align.horizontal, notif_header, nil, { layout = wibox.layout.fixed.horizontal, spacing = dpi(5), s.dont_disturb, s.clear_all }, }, s.notifbox_layout } end return notif_center
return {'wie','wiebelen','wiebelig','wiebeltaks','wieberen','wied','wieden','wieder','wiedijzer','wiedster','wiedvorkje','wieg','wiegelen','wiegelied','wiegeling','wiegen','wiegendood','wiegendruk','wiegenkind','wiegetouw','wiek','wieken','wiekslag','wiel','wielas','wielband','wielbasis','wielbeslag','wieldop','wieldruk','wielen','wielerarts','wielerbaan','wielerbond','wielercarriere','wielerclub','wielerevenement','wielerfederatie','wielerformatie','wielergek','wielergeschiedenis','wielerheld','wielerjournalist','wielerkalender','wielerkampioen','wielerkaravaan','wielerklassieker','wielerkoers','wielerland','wielerleven','wielerliefhebber','wielerloopbaan','wielermilieu','wielerpeloton','wielerpers','wielerploeg','wielerprof','wielerronde','wielerseizoen','wielerspektakel','wielersponsor','wielersponsoring','wielersport','wielerteam','wielertoerisme','wielertoerist','wielertoernooi','wielerverslaggever','wielerwedstrijd','wielerwereld','wielewaal','wieling','wielkast','wielklem','wielophanging','wielrennen','wielrenner','wielrennerij','wielrenster','wielrenunie','wielrenwedstrijd','wielrijden','wielrijder','wielrijdersbond','wielrijdster','wielstel','wieltje','wieme','wiemelen','wiemen','wienerschnitzel','wiens','wiep','wier','wierde','wierf','wierhuis','wierig','wieroken','wierook','wierookboom','wierookbrander','wierookdamp','wierookdrager','wierookgeur','wierookstokje','wierookvat','wierookwolk','wierp','wierven','wies','wiet','wietplantage','wietteelt','wiettelers','wiekgeklap','wielrenbroek','wielvlucht','wiebeltand','wieleffect','wielercircus','wielerfan','wielerfanaat','wielerfeest','wielergebeuren','wielerjaar','wielerkleding','wielerpiste','wielershirt','wielertalent','wielertoeristenclub','wielertraditie','wielerunie','wielervereniging','wiellader','wiellager','wielmaat','wielspin','wierpot','wietboulevard','wietgebruik','wietkwekerij','wietlucht','wielnaaf','wielspoor','wietboter','wietroker','wietteler','wielerfestijn','wielergala','wiebe','wiek','wiekevorst','wieldrecht','wielsbeke','wierden','wierdenaar','wierdens','wierder','wieringen','wieringer','wieringermeer','wieringermeerder','wieringermeers','wierings','wies','wietske','wieze','wieken','wielder','wiersma','wieringa','wiebren','wieger','wieke','wieneke','wiep','wierd','wiert','wiesje','wieske','wieteke','wietse','wietze','wiegel','wiegersma','wientjes','wiegerinck','wierenga','wieggers','wiegmans','wieland','wielenga','wielens','wielinga','wieman','wiersema','wierda','wiertz','wielink','wietsma','wielemaker','wienen','wieberdink','wiechers','wiebenga','wiecherink','wiegeraad','wiegerink','wieling','wiendels','wienholts','wienk','wiercx','wierdsma','wierema','wiersum','wieleman','wiedijk','wiese','wiers','wierckx','wiermans','wieten','wiefferink','wientjens','wiemer','wierstra','wieskamp','wiersinga','wiebing','wiedeman','wiegant','wielandt','wiertsema','wieffering','wiegmink','wieser','wiebel','wiebelde','wiebelden','wiebelend','wiebelende','wiebelt','wiedde','wiedden','wieders','wiedsters','wiedt','wiegde','wiegden','wiegel','wiegelde','wiegelden','wiegelend','wiegeliederen','wiegelt','wiegendrukken','wiegje','wiegt','wiekt','wielbanden','wielde','wielden','wieldoppen','wielerbanen','wielerkoersen','wielerlanden','wielerliefhebbers','wielerprofs','wielerwedstrijden','wielewalen','wielingen','wielophangingen','wielren','wielrenners','wielrensters','wielrent','wielrijders','wielrijdsters','wielstellen','wielt','wieltjes','wiemel','wiemelde','wiemelt','wiepen','wierden','wieren','wierige','wieriger','wierookbomen','wierookdampen','wierookgeuren','wierookscheepje','wierookt','wierookte','wierookten','wierookvaten','wierookwolken','wierpen','wiesen','wietplantages','wietplanten','wietplantjes','wiewauw','wiebelige','wiebeltaksen','wieberde','wiegelingen','wiegend','wiegende','wiegetouwen','wiekte','wielassen','wielerclubs','wielerevenementen','wielerkampioenen','wielerklassiekers','wielerploegen','wielertoeristen','wielkasten','wielklemmen','wielrijdersbonden','wierookbranders','wierookdragers','wierookstokjes','wiedvorkjes','wiegenkinderen','wiekslagen','wienerschnitzels','wiebes','wiebrens','wiegers','wieks','wiekes','wienekes','wieps','wierds','wierts','wies','wiesjes','wieskes','wietekes','wietses','wietskes','wietzes','wiegjes','wielerfanaten','wielerfans','wielerhelden','wielerrondes','wielladers','wietkwekerijen','wietrokers','wielerwereldje','wielsporen','wielerteams','wielmaten','wielerverenigingen','wielerronden','wielerbonden','wielerfederaties','wielerjaren','wielertalenten','wieldrechtse','wienese','wierdense'}
-------------------------------- -- @module Sprite3DCache -- @parent_module cc -------------------------------- -- remove the SpriteData from Sprite3D by given the specified key -- @function [parent=#Sprite3DCache] removeSprite3DData -- @param self -- @param #string key -- @return Sprite3DCache#Sprite3DCache self (return value: cc.Sprite3DCache) -------------------------------- -- remove all the SpriteData from Sprite3D -- @function [parent=#Sprite3DCache] removeAllSprite3DData -- @param self -- @return Sprite3DCache#Sprite3DCache self (return value: cc.Sprite3DCache) -------------------------------- -- -- @function [parent=#Sprite3DCache] destroyInstance -- @param self -- @return Sprite3DCache#Sprite3DCache self (return value: cc.Sprite3DCache) -------------------------------- -- get & destroy -- @function [parent=#Sprite3DCache] getInstance -- @param self -- @return Sprite3DCache#Sprite3DCache ret (return value: cc.Sprite3DCache) -------------------------------- -- -- @function [parent=#Sprite3DCache] Sprite3DCache -- @param self -- @return Sprite3DCache#Sprite3DCache self (return value: cc.Sprite3DCache) return nil
local PluginRoot = script.Parent.Parent.Parent local Core = PluginRoot.Core local Modules = Core.Modules local InputState = require(Modules.InputState) local CameraState = require(Modules.CameraState) local Constants = require(Modules.Constants) local CircleSelector = require(Modules.CircleSelector) local RectangleSelector = require(Modules.RectangleSelector) local Libs = PluginRoot.Libs local Maid = require(Libs.Maid) local Oyrc = require(Libs.Oyrc) local UserInputService = game:GetService("UserInputService") local RunService = game:GetService("RunService") local Selection = game:GetService("Selection") local MainManager = {} MainManager.__index = MainManager function MainManager.new(plugin) local self = {} setmetatable(self, MainManager) self.maid = Maid.new() self.mode = "none" local mouse = plugin:GetMouse() self.mouse = mouse self.plugin = plugin local toolbar = plugin:CreateToolbar("Power Selectors") self.maid:GiveTask(toolbar) local function createButtonAndAction(options) local name = options.name local actionId = options.actionId local buttonId = options.buttonId local actionDescription = options.actionDescription local buttonDescription = options.buttonDescription local callback = options.callback local image = options.image local action = plugin:CreatePluginAction(actionId, name, actionDescription, image) action.Triggered:Connect(callback) local button = toolbar:CreateButton(buttonId, buttonDescription, image, name) button.Click:Connect(callback) return action, button end local function toggleCircleSelect() if self.mode ~= "circle" then self:deactivate() task.wait() -- weird workaround that works self:activate("circle") else self:deactivate() end end local circleSelectAction, circleSelectButton = createButtonAndAction({ name = "Circle Select", actionId = "PowerSelectors:CircleSelectAction", buttonId = "PowerSelectors:CircleSelectButton", actionDescription = "Toggle Circle Select (Recommended: C)", buttonDescription = "Toggle Circle Select (Do not set a hotkey to this, it will not save! Set it on the other one instead.)", callback = toggleCircleSelect, image = "rbxassetid://7707725859", }) self.circleSelectAction = circleSelectAction self.circleSelectButton = circleSelectButton local function toggleRectangleSelect() if self.mode ~= "rectangle" then self:deactivate() task.wait() -- weird workaround that works self:activate("rectangle") else self:deactivate() end end local rectangleSelectAction, rectangleSelectButton = createButtonAndAction({ name = "Rectangle Select", actionId = "PowerSelectors:RectangleSelectAction", buttonId = "PowerSelectors:RectangleSelectButton", actionDescription = "Toggle Rectangle Select (Recommended: B)", buttonDescription = "Toggle Rectangle Select (Do not set a hotkey to this, it will not save! Set it on the other one instead.)", callback = toggleRectangleSelect, image = "rbxassetid://7707726258", }) self.rectangleSelectAction = rectangleSelectAction self.rectangleSelectButton = rectangleSelectButton self.mainEvent = Instance.new("BindableEvent") self.maid:GiveTask(self.mainEvent) self.settings = { circleRadius = 24, operation = "add" } self.cameraState = self:_calculateCurrentCameraState() self.inputState = self:_calculateCurrentInputState() self.selector = nil self.maid:GiveTask(RunService.Heartbeat:Connect(function(dt) debug.profilebegin("PowerSelector, MainManager::step") self:_step(dt) debug.profileend() end)) self.maid:GiveTask(Selection.SelectionChanged:Connect(function() self.cachedSelection = nil end)) self.maid:GiveTask(UserInputService.InputChanged:Connect(function(inputObject, gameProcessedEvent) if gameProcessedEvent then return end if self.mode == "circle" and inputObject.UserInputType == Enum.UserInputType.MouseWheel and inputObject:IsModifierKeyDown(Enum.ModifierKey.Ctrl) then local newRadius if inputObject.Position.Z > 0 then newRadius = math.clamp(self.settings.circleRadius * 0.9, Constants.CIRCLE_MIN_RADIUS, Constants.CIRCLE_MAX_RADIUS) else newRadius = math.clamp(self.settings.circleRadius * 1.11, Constants.CIRCLE_MIN_RADIUS, Constants.CIRCLE_MAX_RADIUS) end if newRadius ~= self.settings.circleRadius then self.settings.circleRadius = newRadius self.selector:setRadius(self.settings.circleRadius) self.mainEvent:Fire() end end end)) self.maid:GiveTask(RunService.RenderStepped:Connect(function() if self.mode == "none" then return end if UserInputService:IsKeyDown(Enum.KeyCode.LeftShift) then if self.settings.operation == "add" then self.settings.operation = "subtract" self.mainEvent:Fire() end else if self.settings.operation == "subtract" then self.settings.operation = "add" self.mainEvent:Fire() end end end)) plugin.Deactivation:Connect(function() self.selector = nil self.mode = "none" self.rectangleSelectButton:SetActive(false) self.circleSelectButton:SetActive(false) self.mainEvent:Fire() end) return self end function MainManager:_step(dt) local updated = false local currentCameraState = self:_calculateCurrentCameraState() if CameraState.isDifferent(self.cameraState, currentCameraState) then self.cameraState = currentCameraState updated = true end local currentInputState = self:_calculateCurrentInputState() if InputState.isDifferent(self.inputState, currentInputState) then self.inputState = currentInputState updated = true end if self.selector then updated = self.selector:step(self.cameraState, self.inputState) or updated if self.selector:isCommitted() then local pending = self.selector:getPending() if self.settings.operation == "add" then self:addToSelection(pending) else self:removeFromSelection(pending) end self:_resetSelector() updated = true end end if updated then self.mainEvent:Fire() end end function MainManager:addToSelection(parts) if #parts == 0 then return end local addSet = Oyrc.List.toSet(parts) for _, part in pairs(self:getCurrentSelection()) do addSet[part] = nil end if next(addSet) == nil then return end local newSelection = Oyrc.List.join(self:getCurrentSelection(), Oyrc.Dictionary.keys(addSet)) Selection:Set(newSelection) end function MainManager:removeFromSelection(parts) if #parts == 0 then return end local currentParts = Oyrc.List.toSet(self:getCurrentSelection()) local changed = false for _, part in pairs(parts) do if currentParts[part] then changed = true currentParts[part] = nil end end if not changed then return end local newSelection = Oyrc.Dictionary.keys(currentParts) Selection:Set(newSelection) end function MainManager:_calculateCurrentInputState() return InputState.create( self.mouse, UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) ) end function MainManager:_calculateCurrentCameraState() return CameraState.create(workspace.CurrentCamera) end function MainManager:activate(mode) self.mode = mode self.plugin:Activate(true) if mode == "circle" then self.circleSelectButton:SetActive(true) self.rectangleSelectButton:SetActive(false) self.selector = self:_createSelector("circle") elseif mode == "rectangle" then self.rectangleSelectButton:SetActive(true) self.circleSelectButton:SetActive(false) self.selector = self:_createSelector("rectangle") end self.mainEvent:Fire() end function MainManager:_createSelector(selectorType) if selectorType == "circle" then return CircleSelector.new(self.settings.circleRadius, self.cameraState, self.inputState) elseif selectorType == "rectangle" then return RectangleSelector.new(self.cameraState, self.inputState) end end function MainManager:_resetSelector() local mode = self.mode -- selene: allow(incorrect_standard_library_use) assert(self.mode ~= "none") if mode == "circle" then self.selector = self:_createSelector("circle") elseif mode == "rectangle" then self.selector = self:_createSelector("rectangle") end end function MainManager:deactivate() self.circleSelectButton:SetActive(false) self.rectangleSelectButton:SetActive(false) self.plugin:Deactivate() end function MainManager:getInputState() return self.inputState end function MainManager:getCameraState() return self.cameraState end function MainManager:subscribe(callback) local connection = self.mainEvent.Event:Connect(callback) return function() connection:Disconnect() end end function MainManager:_onCameraStateChanged(newCameraState) self.cameraState = newCameraState self.mainEvent:Fire() end function MainManager:_onInputStateChanged(newInputState) self.inputState = newInputState self.mainEvent:Fire() end function MainManager:Destroy() self.maid:Destroy() end function MainManager:getCurrentSelection() if self.cachedSelection == nil then self.cachedSelection = Selection:Get() end return self.cachedSelection end function MainManager:getMode() return self.mode end function MainManager:getSettings() return self.settings end function MainManager:getSelector() return self.selector end function MainManager:getPlugin() return self.plugin end return MainManager
--[[ CLILUACORE-311: We need to find a proper way to encapsulate this; conditionally depending on PlatformService is bad! ]] local PlatformService = nil pcall(function() PlatformService = game:GetService("PlatformService") end) local Promise = require(script.Parent.Parent.Promise) local function parseRobuxValue(productInfo) local rawText = productInfo and productInfo.Name local noJunk = string.gsub(rawText, ",", "") noJunk = noJunk and string.match(noJunk, "[0-9]+") or nil return noJunk and tonumber(noJunk) or 1000 end local XboxCatalogData = {} function XboxCatalogData.GetCatalogInfoAsync() if PlatformService == nil then error("PlatformService unavailable; are you on XboxOne?") end local promisified = Promise.promisify(function() return PlatformService:BeginGetCatalogInfo() end) return promisified() :andThen(function(catalogInfo) local availableProducts = {} for _, productInfo in pairs(catalogInfo) do local product = { robuxValue = parseRobuxValue(productInfo), productId = productInfo.ProductId } table.insert(availableProducts, product) end return availableProducts end) end return XboxCatalogData
-- OPTIONS RESET_FOR_TIME = true -- Set to true if you're trying to break the record, not just finish a run BEAST_MODE = false -- WARNING: Do not engage. Will yolo everything, and reset at every opportunity in the quest for 1:47. STREAMING_MODE = true LIVESPLIT = true INITIAL_SPEED = 1500 AFTER_BROCK_SPEED = 1500 AFTER_MOON_SPEED = 500 E4_SPEED = 500 local NIDORAN_NAME = "A" -- Set this to the single character to name Nidoran (note, to replay a seed, it MUST match!) PAINT_ON = false -- Display contextual information while the bot runs local CUSTOM_SEED = true -- Set to true to use seeds from SEEDARRAY, or leave nil for random runs SEEDARRAY = {1511530723} -- Insert custom seeds here LOOP_SEEDS = false ERR = true -- Show error messages on console WRN = false -- Show warning messages on console INF = false -- Show info messages on console TWT = false -- Show tweets on console DGB = false -- Show debug split status msg every 10 secs DBT = false -- Show extra times on split msgs -- START CODE (hard hats on) VERSION = "2.4.9" CURRENT_SPEED = nil local Data = require "data.data" Data.init() EARLY_RESET_LOG = "./logs/"..Data.gameName.."/earlyresets.txt" EARLY_RESET_SPLIT_LIMIT = 4 --MtMoon RESET_LOG = "./logs/"..Data.gameName.."/resets.txt" VICTORY_LOG = "./logs/"..Data.gameName.."/victories.txt" SPLIT_LOG = "./logs/"..Data.gameName.."/splits/" local Battle = require "action.battle" local Textbox = require "action.textbox" local Walk = require "action.walk" local Combat = require "ai.combat" local Control = require "ai.control" local Strategies = require("ai."..Data.gameName..".strategies") local Pokemon = require "storage.pokemon" local Bridge = require "util.bridge" local Input = require "util.input" local Memory = require "util.memory" local Paint = require "util.paint" local Utils = require "util.utils" local Settings = require "util.settings" local hasAlreadyStartedPlaying = false local oldSeconds local running = true local previousMap -- HELPERS function resetAll() Strategies.softReset() Combat.reset() Control.reset() Walk.reset() Paint.reset() Bridge.reset() Utils.reset() oldSeconds = 0 running = false CURRENT_SPEED = INITIAL_SPEED client.speedmode(INITIAL_SPEED) if CUSTOM_SEED and #SEEDARRAY > 0 then Data.run.seed = Utils.getNextSeed() Strategies.replay = true else Data.run.seed = os.time() end Utils.printFilter(nil, "PokeBot "..Utils.capitalize(Data.gameName).." v"..VERSION.."\n| "..NIDORAN_NAME.." | "..(CUSTOM_SEED and "Custom Seed "..(SEEDINDEX - 1).."/"..#SEEDARRAY..": " or BEAST_MODE and "BEAST MODE seed: " or "New Seed: ")..Data.run.seed) math.randomseed(Data.run.seed) end -- EXECUTE p("Welcome to PokeBot "..Utils.capitalize(Data.gameName).." v"..VERSION, true) Control.init() Utils.init() if CUSTOM_SEED then Strategies.reboot() else hasAlreadyStartedPlaying = Utils.ingame() end Strategies.init(hasAlreadyStartedPlaying) if hasAlreadyStartedPlaying and RESET_FOR_TIME then RESET_FOR_TIME = false p("Disabling time-limit resets as the game is already running. Please reset the emulator and restart the script.", true) end if LIVESPLIT then Bridge.init(Data.gameName) end if PAINT_ON then Input.setDebug(true) end -- LOOP local function generateNextInput(currentMap) if not Utils.ingame() then Bridge.pausegametime() if currentMap == 0 then if running then if not hasAlreadyStartedPlaying then if emu.framecount() ~= 1 then Strategies.reboot() end hasAlreadyStartedPlaying = true else resetAll() end else Settings.startNewAdventure() end else if not running then Bridge.liveSplit() running = true end Settings.choosePlayerNames() end else Bridge.time() Utils.splitCheck() local battleState = Memory.value("game", "battle") Control.encounter(battleState) local curr_hp = Combat.hp() Combat.updateHP(curr_hp) if curr_hp == 0 and not Control.canDie() and Pokemon.index(0) > 0 then Strategies.death(currentMap) elseif Walk.strategy then if Strategies.execute(Walk.strategy) then if Walk.traverse(currentMap) == false then return generateNextInput(currentMap) end end elseif battleState > 0 then if not Control.shouldCatch() then Battle.automate() end elseif Textbox.handle() then if Walk.traverse(currentMap) == false then return generateNextInput(currentMap) end end end end while true do local currentMap = Memory.value("game", "map") if currentMap ~= previousMap then Input.clear() previousMap = currentMap end if Strategies.frames then if Memory.value("game", "battle") == 0 then Strategies.frames = Strategies.frames + 1 end Utils.drawText(0, 80, Strategies.frames) end if Bridge.polling then Settings.pollForResponse(NIDORAN_NAME) end if not Input.update() then generateNextInput(currentMap) end if STREAMING_MODE then local newSeconds = Memory.value("time", "seconds") if newSeconds ~= oldSeconds and (newSeconds > 0 or Memory.value("time", "frames") > 0) then Bridge.time(Utils.elapsedTime()) oldSeconds = newSeconds end end if PAINT_ON then Paint.draw(currentMap) end Input.advance() emu.frameadvance() end Bridge.close()
local local0 = 0.5 local local1 = 0 - local0 local local2 = 3.8 - local0 local local3 = 0 - local0 local local4 = 3 - local0 local local5 = 0 - local0 local local6 = 3.8 - local0 local local7 = 0 - local0 local local8 = 3.3 - local0 local local9 = 0 - local0 local local10 = 7.6 - local0 local local11 = 0 - local0 local local12 = 3.6 - local0 local local13 = 0 - local0 local local14 = 3.5 - local0 local local15 = 0 - local0 local local16 = 4 - local0 local local17 = 0 - local0 local local18 = 2.3 - local0 local local19 = 0 - local0 local local20 = 0 - local0 local local21 = 0 - local0 function OnIf_230030(arg0, arg1, arg2) if arg2 == 0 then KingGhost_LowClass_Sword230030_ActAfter_RealTime(arg0, arg1) end return end function KingGhost_LowClass_Sword230030Battle_Activate(arg0, arg1) local local0 = {} local local1 = {} local local2 = {} Common_Clear_Param(local0, local1, local2) local local3 = arg0:GetDist(TARGET_ENE_0) local local4 = arg0:GetRandam_Int(1, 100) if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 90) then local0[20] = 100 elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 90) then if local4 <= 50 then local0[20] = 100 else arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 2, TARGET_ENE_0, 0, arg0:GetRandam_Int(30, 45), true, true, -1) end elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 90) then if local4 <= 50 then local0[20] = 100 else arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 2, TARGET_ENE_0, 1, arg0:GetRandam_Int(30, 45), true, true, -1) end elseif 8 <= local3 then local0[1] = 25 local0[2] = 0 local0[3] = 0 local0[4] = 0 local0[5] = 50 local0[6] = 25 local0[7] = 0 local0[8] = 0 local0[9] = 0 elseif 5 <= local3 then local0[1] = 25 local0[2] = 0 local0[3] = 0 local0[4] = 25 local0[5] = 25 local0[6] = 25 local0[7] = 0 local0[8] = 0 local0[9] = 0 elseif 2.5 <= local3 then local0[1] = 35 local0[2] = 0 local0[3] = 0 local0[4] = 25 local0[5] = 0 local0[6] = 30 local0[7] = 0 local0[8] = 0 local0[9] = 10 else local0[1] = 25 local0[2] = 0 local0[3] = 0 local0[4] = 30 local0[5] = 0 local0[6] = 25 local0[7] = 0 local0[8] = 0 local0[9] = 20 end local1[1] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act01) local1[2] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act02) local1[3] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act03) local1[4] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act04) local1[5] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act05) local1[6] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act06) local1[7] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act07) local1[8] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act08) local1[9] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act09) local1[10] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act10) local1[11] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act11) local1[12] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act12) local1[20] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act20) local1[30] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act30) local1[31] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act31) local1[32] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act32) local1[33] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act33) local1[34] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act34) local1[35] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act35) local1[36] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act36) local1[37] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act37) local1[38] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act38) local1[39] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act39) local1[40] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act40) local1[41] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act41) local1[42] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act42) local1[43] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act43) local1[44] = REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_Act44) Common_Battle_Activate(arg0, arg1, local0, local1, REGIST_FUNC(arg0, arg1, KingGhost_LowClass_Sword230030_ActAfter_AdjustSpace), local2) return end local0 = local2 function KingGhost_LowClass_Sword230030_Act01(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 local local2 = UPVAL0 if local2 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local2, UPVAL0 + 10, 0, 3) end if local0 <= 10 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 120) elseif local0 <= 20 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 120) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3001, TARGET_ENE_0, local1, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 120) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, local1, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, local1, 0) end GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local4 function KingGhost_LowClass_Sword230030_Act02(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, UPVAL0 + 10, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3001, TARGET_ENE_0, UPVAL0, 0, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local6 function KingGhost_LowClass_Sword230030_Act03(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, UPVAL0 + 10, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3002, TARGET_ENE_0, UPVAL0, 0, 180) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local8 function KingGhost_LowClass_Sword230030_Act04(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 local local2 = UPVAL0 if local2 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local2, UPVAL0 + 10, 0, 3) end if local0 <= 25 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3003, TARGET_ENE_0, local1, 0, 180) elseif local0 <= 50 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, local1, 0, 120) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3011, TARGET_ENE_0, local1, 0) elseif local0 <= 75 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, local1, 0, 120) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3012, TARGET_ENE_0, local1, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, local1, 0, 120) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3013, TARGET_ENE_0, local1, 0) end GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local10 function KingGhost_LowClass_Sword230030_Act05(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, UPVAL0 + 10, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3004, TARGET_ENE_0, UPVAL0, 0, 180) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local12 function KingGhost_LowClass_Sword230030_Act06(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 local local2 = UPVAL0 if local2 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local2, UPVAL0 + 10, 0, 3) end if local0 <= 10 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, local1, 0, 180) elseif local0 <= 20 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, local1, 0, 120) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3006, TARGET_ENE_0, local1, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, local1, 0, 120) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3006, TARGET_ENE_0, local1, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3007, TARGET_ENE_0, local1, 0) end GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local14 function KingGhost_LowClass_Sword230030_Act07(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, UPVAL0 + 10, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3006, TARGET_ENE_0, UPVAL0, 0, 180) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local16 function KingGhost_LowClass_Sword230030_Act08(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, UPVAL0 + 10, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, UPVAL0, 0, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local18 function KingGhost_LowClass_Sword230030_Act09(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL0 local local3 = UPVAL0 if local3 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local3, UPVAL0 + 10, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_GuardBreakTunable, 10, 3010, TARGET_ENE_0, local2, -1, 40) if local0 <= 40 then if local1 <= 25 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3003, TARGET_ENE_0, local2, 0, 180) elseif local1 <= 50 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, local2, 0, 180) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3011, TARGET_ENE_0, local2, 0) elseif local1 <= 75 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, local2, 0, 180) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3012, TARGET_ENE_0, local2, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, local2, 0, 180) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3013, TARGET_ENE_0, local2, 0) end elseif local0 <= 70 then if local1 <= 10 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, local2, 0, 180) elseif local1 <= 20 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local2, 0, 180) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3001, TARGET_ENE_0, local2, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local2, 0, 180) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, local2, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, local2, 0) end elseif local0 <= 10 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, local2, 0, 180) elseif local0 <= 20 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, local2, 0, 180) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3006, TARGET_ENE_0, local2, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, local2, 0, 180) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3006, TARGET_ENE_0, local2, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3007, TARGET_ENE_0, local2, 0) end GetWellSpace_Odds = 100 return GetWellSpace_Odds end function KingGhost_LowClass_Sword230030_Act15(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 10, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 0) elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 180) then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 10, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 0) end GetWellSpace_Odds = 100 return GetWellSpace_Odds end function KingGhost_LowClass_Sword230030_Act20(arg0, arg1, arg2) if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 90) then arg1:AddSubGoal(GOAL_COMMON_Turn, 3, TARGET_ENE_0, 15, 0, 0) elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 140) then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 3, TARGET_ENE_0, 0, arg0:GetRandam_Int(30, 45), true, true, -1) elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 140) then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 3, TARGET_ENE_0, 1, arg0:GetRandam_Int(30, 45), true, true, -1) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local2 function KingGhost_LowClass_Sword230030_Act30(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local4 function KingGhost_LowClass_Sword230030_Act31(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3001, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local6 function KingGhost_LowClass_Sword230030_Act32(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3002, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local8 function KingGhost_LowClass_Sword230030_Act33(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3003, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local10 function KingGhost_LowClass_Sword230030_Act34(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3004, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local12 function KingGhost_LowClass_Sword230030_Act35(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local14 function KingGhost_LowClass_Sword230030_Act36(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3006, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local16 function KingGhost_LowClass_Sword230030_Act37(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local18 function KingGhost_LowClass_Sword230030_Act38(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3008, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function KingGhost_LowClass_Sword230030_Act39(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, Att3009_Dist_max, Att3009_Dist_max + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3009, TARGET_ENE_0, Att3009_Dist_max, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function KingGhost_LowClass_Sword230030_Act40(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, Att3010_Dist_max, Att3010_Dist_max + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3010, TARGET_ENE_0, Att3010_Dist_max, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 4.5 - local0 function KingGhost_LowClass_Sword230030_Act41(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3011, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 3.8 - local0 function KingGhost_LowClass_Sword230030_Act42(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3012, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 4 - local0 function KingGhost_LowClass_Sword230030_Act43(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0) arg1:AddSubGoal(GOAL_COMMON_Wait, 1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3013, TARGET_ENE_0, UPVAL0, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function KingGhost_LowClass_Sword230030_ActAfter_RealTime(arg0, arg1) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) if local0 <= 3 then if local1 <= 30 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 2.2, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(30, 45), true, true, -1) elseif local1 <= 60 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 2.7, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(30, 45), true, true, -1) elseif local1 <= 80 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, -1, AI_DIR_TYPE_B, 4) elseif local1 <= 100 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, -1, AI_DIR_TYPE_B, 4) end elseif local0 <= 6 then if local1 <= 15 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 2.2, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(30, 45), true, true, -1) elseif local1 <= 30 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 2.7, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(30, 45), true, true, -1) elseif local1 <= 50 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, -1, AI_DIR_TYPE_B, 4) elseif local1 <= 70 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, -1, AI_DIR_TYPE_B, 4) elseif local1 <= 90 then arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 2.5, TARGET_ENE_0, 3.5, TARGET_SELF, true, -1) else arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 700, TARGET_ENE_0, -1, AI_DIR_TYPE_B, 4) end elseif local1 <= 20 then arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 3, TARGET_ENE_0, 2.5, TARGET_SELF, false, -1) elseif local1 <= 50 then arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 5, TARGET_ENE_0, 2.5, TARGET_SELF, true, -1) elseif local1 <= 70 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 2.7, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(30, 45), true, true, -1) elseif local1 <= 90 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 700, TARGET_ENE_0, -1, AI_DIR_TYPE_B, 4) end return end function KingGhost_LowClass_Sword230030_ActAfter_AdjustSpace(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_If, 10, 0) return end function KingGhost_LowClass_Sword230030Battle_Update(arg0, arg1) return GOAL_RESULT_Continue end function KingGhost_LowClass_Sword230030Battle_Terminate(arg0, arg1) return end function KingGhost_LowClass_Sword230030Battle_Interupt(arg0, arg1) if arg0:IsLadderAct(TARGET_SELF) then return false else local local0 = arg0:GetRandam_Int(1, 100) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Int(1, 100) local local3 = arg0:GetDist(TARGET_ENE_0) if RebByOpGuard_Step(arg0, arg1, 20, 20, 40, 40, 4) then return true else return false end end end return
--[[ love.run Standard run with fixed update step. Edited specifically for this project. ]] return function() love.load(love.arg.parseGameArguments(arg), arg) -- We don't want the first frame's dt to include time taken by love.load. love.timer.step() local dt = 0 local targetFrameLength = 1/60 local frameTime =targetFrameLength --ensure that we always start with an update -- Main loop time. return function() -- Update frame timer frameTime = frameTime + love.timer.step() -- Call update if necessary if frameTime >= targetFrameLength then --process events love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then if not love.quit or not love.quit() then return a or 0 end end love.handlers[name](a,b,c,d,e,f) end love.update() frameTime = 0 --frameTime - targetFrameLength end --Call draw if love.graphics.isActive() then love.graphics.origin() love.graphics.clear(love.graphics.getBackgroundColor()) if love.draw then love.draw() end love.graphics.present() end if love.timer then love.timer.sleep(0.001) end end end
--================================== Get String Pixel Width --Obtains the pixel width of a string of characters. function chinGetStringPixelWidth(str) pixelWidth=0; for k=1,(string.len(str)) do charCode=string.byte(string.sub(str,k,k)); pixelWidth=pixelWidth+chiGetCharacterWidth(charCode); end return pixelWidth; end
grim_ogre = { on_healed = function(mob, healer) mob_ai_basic.on_healed(mob, healer) end, on_attacked = function(mob, attacker) mob_ai_basic.on_attacked(mob, attacker) end, move = function(mob, target) local chance = math.random(1, 100) if chance == 1 then --mob:talk(0,mob.name..": Grroar!") mob:talk(2, "~Grroar!~") elseif chance == 2 then --mob:talk(0,mob.name..": Smash!") mob:talk(2, "~Smash!~") elseif chance == 3 then --mob:talk(0,mob.name..": Crunch!") mob:talk(2, "~Crunch!~") elseif chance == 4 then --mob:talk(0,mob.name..": Grunt!") mob:talk(2, "~Grunt!~") end mob_ai_basic.move(mob, target) end, attack = function(mob, target) mob_ai_basic.attack(mob, target) end, after_death = function(mob) mob_ai_basic.after_death(mob) end } southern_ogre = { on_healed = function(mob, healer) mob_ai_basic.on_healed(mob, healer) end, on_attacked = function(mob, attacker) mob_ai_basic.on_attacked(mob, attacker) end, move = function(mob, target) local chance = math.random(1, 100) if chance == 1 then --mob:talk(0,mob.name..": Grroar!") mob:talk(2, "~Grroar!~") elseif chance == 2 then --mob:talk(0,mob.name..": Smash!") mob:talk(2, "~Smash!~") elseif chance == 3 then --mob:talk(0,mob.name..": Crunch!") mob:talk(2, "~Crunch!~") elseif chance == 4 then --mob:talk(0,mob.name..": Grunt!") mob:talk(2, "~Grunt!~") end mob_ai_basic.move(mob, target) end, attack = function(mob, target) mob_ai_basic.attack(mob, target) end, after_death = function(mob) mob_ai_basic.after_death(mob) end } muck_ogre = { on_healed = function(mob, healer) mob_ai_basic.on_healed(mob, healer) end, on_attacked = function(mob, attacker) mob_ai_basic.on_attacked(mob, attacker) end, move = function(mob, target) local chance = math.random(1, 100) if chance == 1 then --mob:talk(0,mob.name..": Grroar!") mob:talk(2, "~Grroar!~") elseif chance == 2 then --mob:talk(0,mob.name..": Smash!") mob:talk(2, "~Smash!~") elseif chance == 3 then --mob:talk(0,mob.name..": Crunch!") mob:talk(2, "~Crunch!~") elseif chance == 4 then --mob:talk(0,mob.name..": Grunt!") mob:talk(2, "~Grunt!~") end mob_ai_basic.move(mob, target) end, attack = function(mob, target) mob_ai_basic.attack(mob, target) end, after_death = function(mob) mob_ai_basic.after_death(mob) end } slime_ogre = { on_healed = function(mob, healer) mob_ai_basic.on_healed(mob, healer) end, on_attacked = function(mob, attacker) mob_ai_basic.on_attacked(mob, attacker) end, move = function(mob, target) local chance = math.random(1, 100) if chance == 1 then --mob:talk(0,mob.name..": Grroar!") mob:talk(2, "~Grroar!~") elseif chance == 2 then --mob:talk(0,mob.name..": Smash!") mob:talk(2, "~Smash!~") elseif chance == 3 then --mob:talk(0,mob.name..": Crunch!") mob:talk(2, "~Crunch!~") elseif chance == 4 then --mob:talk(0,mob.name..": Grunt!") mob:talk(2, "~Grunt!~") end mob_ai_basic.move(mob, target) end, attack = function(mob, target) mob_ai_basic.attack(mob, target) end, after_death = function(mob) mob_ai_basic.after_death(mob) end } log_ogre = { on_healed = function(mob, healer) mob_ai_basic.on_healed(mob, healer) end, on_attacked = function(mob, attacker) mob_ai_basic.on_attacked(mob, attacker) end, move = function(mob, target) local chance = math.random(1, 100) if chance == 1 then --mob:talk(0,mob.name..": Grroar!") mob:talk(2, "~Grroar!~") elseif chance == 2 then --mob:talk(0,mob.name..": Smash!") mob:talk(2, "~Smash!~") elseif chance == 3 then --mob:talk(0,mob.name..": Crunch!") mob:talk(2, "~Crunch!~") elseif chance == 4 then --mob:talk(0,mob.name..": Grunt!") mob:talk(2, "~Grunt!~") end mob_ai_basic.move(mob, target) end, attack = function(mob, target) mob_ai_basic.attack(mob, target) end, after_death = function(mob) mob_ai_basic.after_death(mob) end } hill_ogre = { on_healed = function(mob, healer) mob_ai_basic.on_healed(mob, healer) end, on_attacked = function(mob, attacker) mob_ai_basic.on_attacked(mob, attacker) end, move = function(mob, target) local chance = math.random(1, 100) if chance == 1 then --mob:talk(0,mob.name..": Grroar!") mob:talk(2, "~Grroar!~") elseif chance == 2 then --mob:talk(0,mob.name..": Smash!") mob:talk(2, "~Smash!~") elseif chance == 3 then --mob:talk(0,mob.name..": Crunch!") mob:talk(2, "~Crunch!~") elseif chance == 4 then --mob:talk(0,mob.name..": Grunt!") mob:talk(2, "~Grunt!~") end mob_ai_basic.move(mob, target) end, attack = function(mob, target) mob_ai_basic.attack(mob, target) end, after_death = function(mob) mob_ai_basic.after_death(mob) end } marsh_ogre = { on_healed = function(mob, healer) mob_ai_basic.on_healed(mob, healer) end, on_attacked = function(mob, attacker) mob_ai_basic.on_attacked(mob, attacker) end, move = function(mob, target) local chance = math.random(1, 100) if chance == 1 then --mob:talk(0,mob.name..": Grroar!") mob:talk(2, "~Grroar!~") elseif chance == 2 then --mob:talk(0,mob.name..": Smash!") mob:talk(2, "~Smash!~") elseif chance == 3 then --mob:talk(0,mob.name..": Crunch!") mob:talk(2, "~Crunch!~") elseif chance == 4 then --mob:talk(0,mob.name..": Grunt!") mob:talk(2, "~Grunt!~") end mob_ai_basic.move(mob, target) end, attack = function(mob, target) mob_ai_basic.attack(mob, target) end, after_death = function(mob) mob_ai_basic.after_death(mob) end } zangze_ogre = { on_healed = function(mob, healer) mob_ai_basic.on_healed(mob, healer) end, on_attacked = function(mob, attacker) mob_ai_basic.on_attacked(mob, attacker) end, move = function(mob, target) local chance = math.random(1, 100) if chance == 1 then --mob:talk(0,mob.name..": Grroar!") mob:talk(2, "~Grroar!~") elseif chance == 2 then --mob:talk(0,mob.name..": Smash!") mob:talk(2, "~Smash!~") elseif chance == 3 then --mob:talk(0,mob.name..": Crunch!") mob:talk(2, "~Crunch!~") elseif chance == 4 then --mob:talk(0,mob.name..": Grunt!") mob:talk(2, "~Grunt!~") end mob_ai_basic.move(mob, target) end, attack = function(mob, target) mob_ai_basic.attack(mob, target) end, after_death = function(mob) mob_ai_basic.after_death(mob) end } zinte_ogre = { on_healed = function(mob, healer) mob_ai_basic.on_healed(mob, healer) end, on_attacked = function(mob, attacker) mob_ai_basic.on_attacked(mob, attacker) end, move = function(mob, target) local chance = math.random(1, 100) if chance == 1 then --mob:talk(0,mob.name..": Grroar!") mob:talk(2, "~Grroar!~") elseif chance == 2 then --mob:talk(0,mob.name..": Smash!") mob:talk(2, "~Smash!~") elseif chance == 3 then --mob:talk(0,mob.name..": Crunch!") mob:talk(2, "~Crunch!~") elseif chance == 4 then --mob:talk(0,mob.name..": Grunt!") mob:talk(2, "~Grunt!~") end mob_ai_basic.move(mob, target) end, attack = function(mob, target) mob_ai_basic.attack(mob, target) end, after_death = function(mob) mob_ai_basic.after_death(mob) end }