content
stringlengths
5
1.05M
VBLANG.Language.French = { ["grocery_stop_being_cook"] = "Stop Being A Cook", ["grocery_become_cook"] = "Become a Cook", ["grocery_hello"] = "Hello!", ["grocery_buy_ingredients"] = "Buy ingredients", ["grocery_quit"] = "Leave", ["pol_wep_arm_title"] = "Police armory", ["pol_wep_arm_get_snip"] = "Take an AWP", ["pol_wep_arm_get_rif"] = "Take an M4A1", ["pol_wep_arm_get_shot"] = "Take an SPAS-12", ["pol_wep_arm_get_rif2"] = "Take an G36C", ["pol_wep_arm_noaccess"] = "You do not have access to the police armory", ["pol_cen_title"] = "Police", ["pol_cen_lst_name"] = "Name", ["pol_cen_lst_pl_name"] = "Name", ["pol_cen_lst_job"] = "Job", ["pol_cen_lst_veh_mdl"] = "Model", ["pol_cen_lst_veh_license"] = "Registration", ["pol_cen_lst_veh_clr"] = "Color", ["pol_cen_srch_veh"] = "Search a person's vehicles", ["pol_cen_lst_arby"] = "Arrested by", ["pol_cen_lst_hrst"] = "Stopped at", ["pol_cen_lst_hren"] = "End of sentence", ["pol_cen_menu_unarrest"] = "Release", ["op_perms"] = "Permissions", ["op_change_perms"] = "Change permissions", ["op_received_invitation"] = "Invitation to an organization", ["op_invite_message"] = "You have been invited to the organization:% s, do you want to join it?", ["op_accept_invite"] = "Accept the invitation", ["op_deny_invite"] = "Decline invitation", ["op_window_title"] = "Players and organizations", ["op_player_name"] = "Full Name", ["op_same_org"] = "same organization", ["op_are_friends"] = "Friends", ["op_add_friend"] = "Add as friend", ["op_rem_friend"] = "Remove from my friends", ["op_invite_org"] = "Invite in the organization", ["op_player_list"] = "List of players", ["op_is_online"] = "Online", ["op_no"] = "No", ["op_yes"] = "Yes", ["op_org"] = "Organisation", ["op_quit_org"] = "Leave the organization", ["cd_cust_window_title"] = "Vehicle customization", ["cd_cust_price"] = "Price", ["cd_cust_name"] = "Name", ["cd_cust_reset"] = "Discard changes", ["cd_cust_confirm"] = "Confirm purchase", ["cd_cust_colors"] = "Color", ["cd_cust_wing"] = "Spoiler", ["cd_cust_skirt"] = "Side skirts", ["cd_cust_hood"] = "Hood", ["cd_cust_bumperr"] = "Rear bumper", ["cd_cust_bumperf"] = "Front bumper", ["cd_cust_wheels"] = "Wheels", ["cd_cust_recap"] = "Summary", ["cd_cust_recap_colors"] = "Change of paint [% d,% d,% d]", ["cd_cust_recap_wing"] = "Spoiler: %s", ["cd_cust_recap_skirt"] = "Side skirts: %s", ["cd_cust_recap_hood"] = "Hood: %s", ["cd_cust_recap_bumperr"] = "Rear Bumper: %s", ["cd_cust_recap_bumperf"] = "Front Bumper: %s", ["cd_cust_recap_wheels"] = "Wheels: %s", ["cd_spawn_car"] = "Spawn vehicle", ["cd_window_title"] = "Garage owner", ["cd_my_cars"] = "My cars", ["cd_veh_available"] = "Vehicles available", ["cd_veh_want_custom"] = "Do you want to modify your vehicle?", ["cd_want_buy_veh"] = "Hello ! The Evocity dealer offers a multitude of vehicles", ["cd_viewoffer_yes"] = "I would like to buy a vehicle ...", ["cd_viewoffer_no"] = "I'm just taking a ride", ["cd_car_request"] = "Do you want to collect your vehicle?", ["cd_answer_yes"] = "Yes", ["cd_answer_no"] = "No", ["cd_window_title2"] = "Dealer", ["cd_select_veh_to_buy"] = "Select a vehicle to buy.", ["cd_buy"] = "Buy (%s)", ["cd_cardealer_confirm_buy"] = "Do you really want to buy this vehicle:% s, for:% s?", ["cd_buy_window_title"] = "Vehicle purchase confirmation", ["dd_selling_request"] = "what are you looking for?", ["dd_selling_yes"] = "* Sell your cannabis *", ["dd_selling_no"] = "Uh, nothing, I'm just walking around.", ["cc_sex_male"] = "Male", ["cc_sex_female"] = "Female", ["cc_input_firstname"] = "First name", ["cc_input_lastname"] = "Last Name", ["cc_name_too_long"] = "This name is too long.", ["cc_no_name_provided"] = "No name was given.", ["cc_clothes_request"] = "Do you want to change your look?", ["cc_answer_yes"] = "Yep! ($ 20,000)", ["cc_answer_no"] = "No !", ["cc_name_already_exist"] = "This name already exists.", ["cc_confirm"] = "To confirm", ["dialog_title"] = "Dialogue with% s", ["fl_market_title"] = "Flea", ["fl_quantity_required"] = "Quantity required.", ["fl_buy"] = "Buy (% s)", ["fl_cannot_afford"] = "You do not have enough money to buy this item", ["fl_quantity"] = "Amount: ", ["fl_description"] = "Description: ", ["fl_npc_dialog"] = "Hello do you want to discover our wide choice of objects?", ["fl_npc_answer_yes"] = "Yes (open menu)", ["fl_npc_answer_no"] = "No, I'm just going around here", ["inv_window_title"] = "Protocol Servers Inventory", ["inv_store"] = "Store in inventory", ["inv_storing_weapon"] = "You are putting away your gun", ["inv_storing_weapon_status"] = "Putting away this gun", ["inv_equip_weapon"] = "You are pulling out your gun", ["inv_equip_weapon_status"] = "Pulling out this gun", ["inv_heavy_weapon"] = "Heavy weapon", ["inv_light_weapon"] = "Light weapon", ["inv_quantity_short"] = "Qty: %s", ["inv_equip"] = "Equip", ["inv_furniture"] = "Furniture", ["inv_weapons"] = "Weapons", ["inv_ammunition"] = "Ammunition", ["inv_equipments"] = "Equipment", ["inv_market"] = "Black market", ["inv_misc"] = "Misc", ["re_no_properties_available"] = "No property is available", ["re_window_title"] = "Real estate agency", ["re_sell"] = "Sell", ["re_buy"] = "Buy", ["re_selling_confirmation"] = "Confirmation of sale", ["re_buying_confirmation"] = "Purchase confirmation", ["re_selling_message"] = "We confirm that your property has been sold.", ["re_buying_message"] = "We confirm that your property has been purchased.", ["re_cannot_afford"] = "Can't buy this property because you don't have enough money", ["re_dialog1"] = "Hello would you like to buy one of our properties?", ["re_answer1_yes"] = "Yes, that's why I'm here", ["re_answer1_no"] = "No, I'm just going around here", ["re_dialog2"] = "Hello would you like to rent one of our rooms", ["re_answer2_yes"] = "Yes, I will take room number .. ", ["re_answer2_no"] = "No, I'm only passing through", ["re_dialog3"] = "Are you looking for a warehouse, a factory? You are in the right place !", ["re_answer3_yes"] = "I'm looking for some information ..", ["re_answer3_no"] = "No it's good thank you!", ["re_dialog4"] = "The city offers infrastructure for your shops or restaurants!", ["re_answer4_yes"] = "I'm interested !", ["re_answer4_no"] = "No thank you, I'm not interested", ["re_property_info"] = "Price:% s", ["ecfd_job_offer"] = "Evocity firefighters are looking for volunteers to fight the fires! Are you interested ?", ["ecfd_answer_yes"] = "Yes", ["ecfd_answer_no"] = "No", ["jo_police_dialog"] = "Evocity police are recruiting! Do you want to join us?", ["jo_police_answer_yes"] = "I am interested", ["jo_police_answer_no"] = "Sorry, but I'm not interested (leave) ", ["jo_police_dialog_alt"] = "Hello.", ["jo_police_answer_yes_alt"] = "I would like to quit my service (leave)", ["jo_police_answer_no_alt"] = "No nothing * do nothing *", ["jo_medic_dialog"] = "Evocity emergency services are recruiting! Do you want to join us?", ["jo_medic_answer_yes"] = "I am interested", ["jo_medic_answer_no"] = "Sorry, but I'm not interested (leave)", ["jo_medic_dialog_alt"] = "Hello.", ["jo_medic_answer_yes_alt"] = "I would like to quit my service (leave)", ["jo_medic_answer_no_alt"] = "No nothing * do nothing *", ["job_citizen_pname"] = "Citizen", ["job_cop_pname"] = "Policeman", ["job_pchief_pname"] = "Police chief", ["job_swat_pname"] = "SWAT Unit", ["job_medic_pname"] = "Doctor", ["job_cook_pname"] = "Cook", ["notify_already_have_hv_wep"] = "You already have a heavy weapon on you.", ["notify_already_have_lw_wep"] = "You already have a light weapon on you.", ["notify_cannot_store_wep"] = "You can only store your weapons if you are out of work.", ["progress_loading"] = "Loading...", ["global_error"] = "Error", }
-- Autogenerated from KST: please remove this line if doing any edits by hand! local luaunit = require("luaunit") require("expr_io_pos") TestExprIoPos = {} function TestExprIoPos:test_expr_io_pos() local r = ExprIoPos:from_file("src/expr_io_pos.bin") luaunit.assertEquals(r.substream1.my_str, "CURIOSITY") luaunit.assertEquals(r.substream1.body, "\017\034\051\068") luaunit.assertEquals(r.substream1.number, 66) luaunit.assertEquals(r.substream2.my_str, "KILLED") luaunit.assertEquals(r.substream2.body, "\097\032\099\097\116") luaunit.assertEquals(r.substream2.number, 103) end
local m = string.match local gsub = string.gsub local f = string.find --[[ MOVE LISTS ORDER 1. Level Up 2. TM/HM 3. Egg 4. Tutor 5.Mega/Forme/Nonsense (NOT MOVE LIVES BUT NEED FILTERING) ]] local movesLog = logger('movesLog.txt') local total, numTutor = 0, 0 local noTutor = {} -- 3-byte sequence used to denote favourite moves, should be § but pdf2txt kludged it, or some UTF-8 stuff is going on local shittyBytes = "efbfbd" --string.format("%s%s%s", string.char(0xEF), string.char(0xBF), string.char(0xBD)) function parseLvlMoveList(s) local list = {} -- movesLog:print("LVL LIST STRING:", s) -- for line in s:gmatch("(%d.-)%s+%-*%s") do for line in s:gmatch("(.-)%s+%-*%s.-\r\n") do -- detect and strip favourite move signifiers local isFavourite = ""--m(line, "^shittyBytes") -- string.match seems to not work for this, so do it manually for n=1, 3 do isFavourite = isFavourite .. string.format("%x", string.byte(line, n, n)) end isFavourite = isFavourite == shittyBytes or nil if isFavourite then movesLog:print "FAVE" line = line:sub(4) line = m(line, "%s*(.+)") end -- alola/galar dex use the actual § character, so check for that too if not isFavourite and m(line, "^" .. string.char(0xa7)) then isFavourite = true line = string.sub(line, 3) end -- get level local lvl = m(line, "(%d*)%s*") if lvl == "" then movesLog:print("NO LVL FOUND") end -- get name, check for 'Evo' as the lvl local name = m(line, "%d*%s*(.+)") if m(name, "^Evo%s*.+") then name = gsub(name, "^Evo%s*(.+)", "%1") lvl = 0 end -- insert and finish table.insert(list, {lvl = tonumber(lvl), name = name, favourite = isFavourite}) movesLog:print(lvl, name) end return list end function flattenMoveStr(s) s = gsub(s, "-[%c]+", "") s = gsub(s, "[%c]+", " ") return s end function parseMoveList(s) local list = {} s = s .. "," movesLog:print "NEW MOVE LIST-------------------" for line in s:gmatch("%s*(.-)%s*,") do line = flattenMoveStr(line) -- ignore empty lists if line == "None" or not m(line, "%w") then return end local naturalFlag -- get natural flag if m(line, "%(N%)%s*$") then naturalFlag = true line = m(line, "(.-)%s*%(N%)") end movesLog:print(line) table.insert(list, {name = line, natural = naturalFlag}) end return list end function parseTMMoveList(s) local list = {} s = s .. "," for line in s:gmatch("%s*(.-)%s*,") do line = flattenMoveStr(line) -- ignore empty lists if line == "None" or not m(line, "%w") then return end -- typo hax if line == "Thief" then line = "46 Thief" end -- movesLog:print(line) local tm = m(line, "(A?%d+)%s*.+") local multiplier = 1 -- p2(tm) if m(tm, "A") then tm = m(tm, "A(.+)") multiplier = -1 end local tmNum = tonumber(tm) * multiplier local name = m(line, "A?%d*%s*(.+)") -- movesLog:print(line) movesLog:print(tmNum, name) table.insert(list, {name = name, tm = tmNum}) end return list end local moveListIndicators = { lvl = "Level%s*Up%s*Move%s*List[%s%c]*", tm = "TM[/HM]*%s*Move%s*List[%s%c]*", tutor = "Tutor%s*Move%s*List[%s%c]*", egg = "Egg%s*Move%s*List[%s%c]*" } function getMovesStr(p, name) total = total + 1 local s = m(p, "Level%s*Up%s*Move%s*List[%s%c]*.*") movesLog:print "========================================" movesLog:print(name) -- Detect pages that break the algo if not s then s = p movesLog:print "NO LEVEL MOVE LIST FOUND" -- return end -- movesLog:print(s) local hasLvl = m(s, moveListIndicators.lvl) local hasTM = m(s, moveListIndicators.tm) local hasEgg = m(s, moveListIndicators.egg) local hasTutor = m(s, moveListIndicators.tutor) local endingPhrase = findSpecialPhrase(p) -- Ordering of the indicators table has to match pokedex PDF layout! local indicators = {} if hasLvl then table.insert(indicators, {str = moveListIndicators.lvl, name = "lvl"}) end if hasTM then table.insert(indicators, {str = moveListIndicators.tm, name = "tm"}) end if hasEgg then table.insert(indicators, {str = moveListIndicators.egg, name = "egg"}) end if hasTutor then table.insert(indicators, {str = moveListIndicators.tutor, name = "tutor"}) end table.insert(indicators, {str = findSpecialPhrase(s) or "$"}) local moveLists = {} if #indicators < 2 then return {} end for n = 1, #indicators - 1 do local start, fin = indicators[n], indicators[n+1] moveLists[start.name] = getMoveSection(s, start.str, fin.str) end movesLog:print(#indicators) -- for k, v in pairs(moveLists) do -- movesLog:print(k, v) -- end -- if hasLvl then movesLog:print("Has lvl") end -- if hasTM then movesLog:print("Has TM") end -- if hasTutor then -- movesLog:print("Has Tutor") -- numTutor = numTutor + 1 -- else -- table.insert(noTutor, name) -- end -- if hasEgg then movesLog:print("Has Egg") end -- if endingPhrase ~= "" then -- movesLog:print("Has special phrase", endingPhrase) -- end return moveLists end function getMoveSection(str, start, endStr) return m(str, start .. "(.-)" .. endStr) end local specialPhrases = { "Mega%s*Evolution", "DARMANITAN%s*Zen%s*Mode", "%*Therian%s*Forme:", "%*Sky%s*Forme:", "Multiform%c*Deoxys", "Dragon%s*Fusion:", "%*Origin%s*Forme", "Forme%s*Change:", "Ultra%s*Burst", "Zygarde%s*Cube%s*Move%s*List", "Confined:" } function findSpecialPhrase(p) for _, phrase in ipairs(specialPhrases) do if m(p, phrase) then return phrase end end -- return "" end function printTotalTutor() movesLog:printf("%d/%d", numTutor, total) movesLog:print "PKMN WITH NO TUTOR LIST" for k, v in ipairs(noTutor) do movesLog:print("", v) end end
help( [[ This module loads Udunits 2.2.17 The UDUNITS package supports units of physical quantities. Its C library provides for arithmetic manipulation of units and for conversion of numeric values between compatible units. ]]) whatis("Loads Udunits binaries and libraries") local version = "2.2.17" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/udunits/"..version prepend_path("PATH", pathJoin(base, "bin")) prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib")) prepend_path("CPATH", pathJoin(base, "include")) prepend_path("LIBRARY_PATH", pathJoin(base, "lib")) family('udunits') load('expat/2.1.0')
local KeyConfigScene = Scene:extend() KeyConfigScene.title = "Key Config" require 'load.save' local configurable_inputs = { "menu_decide", "menu_back", "left", "right", "up", "down", "rotate_left", "rotate_left2", "rotate_right", "rotate_right2", "rotate_180", "hold", "retry", "pause", } local function newSetInputs() local set_inputs = {} for i, input in ipairs(configurable_inputs) do set_inputs[input] = false end return set_inputs end function KeyConfigScene:new() self.input_state = 1 self.set_inputs = newSetInputs() self.new_input = {} DiscordRPC:update({ details = "In menus", state = "Changing key config", }) end function KeyConfigScene:update() end function KeyConfigScene:render() love.graphics.setColor(1, 1, 1, 1) love.graphics.draw( backgrounds["input_config"], 0, 0, 0, 0.5, 0.5 ) love.graphics.setFont(font_3x5_2) for i, input in ipairs(configurable_inputs) do love.graphics.printf(input, 40, 50 + i * 20, 200, "left") if self.set_inputs[input] then love.graphics.printf(self.set_inputs[input], 240, 50 + i * 20, 300, "left") end end if self.input_state > table.getn(configurable_inputs) then love.graphics.print("press enter to confirm, delete/backspace to retry" .. (config.input and ", escape to cancel" or "")) else love.graphics.print("press key input for " .. configurable_inputs[self.input_state] .. ", tab to skip" .. (config.input and ", escape to cancel" or ""), 0, 0) love.graphics.print("function keys (F1, F2, etc.), escape, and tab can't be changed", 0, 20) end end function KeyConfigScene:onInputPress(e) if e.type == "key" then -- function keys, escape, and tab are reserved and can't be remapped if e.scancode == "escape" and config.input then -- cancel only if there was an input config already scene = InputConfigScene() elseif self.input_state > table.getn(configurable_inputs) then if e.scancode == "return" then -- save new input, then load next scene local had_config = config.input ~= nil if not config.input then config.input = {} end config.input.keys = self.new_input saveConfig() scene = had_config and InputConfigScene() or TitleScene() elseif e.scancode == "delete" or e.scancode == "backspace" then -- retry self.input_state = 1 self.set_inputs = newSetInputs() self.new_input = {} end elseif e.scancode == "tab" then self.set_inputs[configurable_inputs[self.input_state]] = "skipped" self.input_state = self.input_state + 1 elseif e.scancode ~= "escape" then -- all other keys can be configured self.set_inputs[configurable_inputs[self.input_state]] = "key " .. love.keyboard.getKeyFromScancode(e.scancode) .. " (" .. e.scancode .. ")" self.new_input[e.scancode] = configurable_inputs[self.input_state] self.input_state = self.input_state + 1 end end end return KeyConfigScene
local M = {} M.__index = M --- Build components dynamically. --- @param create_component function: |stlparts.nvim-types-component| --- @return table: |stlparts.nvim-types-component| function M.new(create_component) local tbl = { _create_component = create_component, } return setmetatable(tbl, M) end local get = require("stlparts.core.component").get function M.build(self, ctx) local component = self._create_component(ctx) return get(component):build(ctx) end return M
class("AboutSidebar").extends(Sidebar) function AboutSidebar:init() AboutSidebar.super.init(self) end function AboutSidebar:enter(context, selected) local config = { menuItems = { { text = "Show info", exec = function() closeSidebar() end } } } AboutSidebar.super.enter(self, context, config) end
data:extend({ { type = "item", name = "long-range-radar", icon = "__Long_Range_Radar__/graphics/item_icon_advanced_radar.png", icon_size = 64, icon_mipmaps = 4, subgroup = "defensive-structure", order = "z[radar]-a[radar]", place_result = "long-range-radar", stack_size = 10 } })
resource_manifest_version '05cfa83c-a124-4cfa-a768-c24a5811d8f9' client_scripts { "@es_extended/locale.lua", "clienten.lua", '@mysql-async/lib/MySQL.lua' } server_scripts { "server.lua", '@es_extended/locale.lua', '@mysql-async/lib/MySQL.lua' }
-- If you're not sure your plugin is executing, uncomment the line below and restart Kong -- then it will throw an error which indicates the plugin is being loaded at least. --assert(ngx.get_phase() == "timer", "The world is coming to an end!") -- Grab pluginname from module name local plugin_name = ({...})[1]:match("^kong%.plugins%.([^%.]+)") -- load the base plugin object and create a subclass local plugin = require("kong.plugins.base_plugin"):extend() -- constructor function plugin:new() plugin.super.new(self, plugin_name) -- do initialization here, runs in the 'init_by_lua_block', before worker processes are forked end ---[[ runs in the 'access_by_lua_block' function plugin:access(conf) plugin.super.access(self) -- your custom code here local ordered_selectors = plugin_conf.meta and plugin_conf.meta.selectors if not plugin_conf.enable or plugin_conf.enable ~= true or not plugin_conf.meta or not plugin_conf.ordered_selectors or not plugin_conf.selectors then return end local ngx_var = ngx.var local ngx_var_uri = ngx_var.uri local ngx_var_host = ngx_var.host for i, sid in plugin_conf.ipairs(ordered_selectors) do ngx.log(ngx.INFO, "==[Divide][PASS THROUGH SELECTOR:", sid, "]") local selector = selectors[sid] if selector and selector.enable == true then local selector_pass if selector.type == 0 then -- 全流量选择器 selector_pass = true else -- 待实现 selector_pass = judge_util.judge_selector(selector, "divide")-- selector judge end if selector_pass then if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[Divide][PASS-SELECTOR:", sid, "] ", ngx_var_uri) end local stop = filter_rules(sid, "divide", ngx_var, ngx_var_uri, ngx_var_host) local selector_continue = selector.handle and selector.handle.continue if stop or not selector_continue then -- 不再执行此插件其他逻辑 return end else if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[Divide][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri) end end end end --local pattern = plugin_conf.pattern --local token = kong.request.get_header("authorization") --if token == nil then -- return --end -- 忽略大小写 --local matched = ngx.re.match(token, pattern, "joi") --if matched then -- -- 设置upstream -- local ok, err = kong.service.set_upstream(plugin_conf.upstream) -- if not ok then -- kong.log.err(err) -- return -- end -- -- 匹配成功添加特定头部方便监控 -- ngx.req.set_header("X-Kong-" .. plugin_name .. "-upstream", plugin_conf.upstream) -- ngx.req.set_header("X-Kong-" .. plugin_name .. "-pattern", plugin_conf.pattern) --end end --]] -- set the plugin priority, which determines plugin execution order plugin.PRIORITY = 1000 -- return our plugin object return plugin
require("gameBase/gameSocket"); require("hall/onlineSocket/globalSocketCmd"); require("hall/php/phpSocketCmd"); require("hall/php/phpManager"); require("hall/onlineSocket/socketReconnectLogic"); require("common/socketHandlersStack"); OnlineSocketManager = class(GameSocket); SocketStatus = { None = 0; Connecting = 1; Connected = 2; ConnectFailed = 3; HeartBeatTimeout = 4; Closing = 5; Closed = 6; Reconnecting = 7; Reconnected = 8; ReconnectFailed = 9; }; local SOCKET_CLOSE_TYPE = { SERVER_CLOSE = 0; --server主动断开链接(eg停服)or由于网络变化导致断开链接 USER_CLOSE = 1; --业务主动调用closeSocket断开链接 } OnlineSocketManager.getInstance = function() --地方棋牌使用QE协议,网络字节序 if not OnlineSocketManager.s_instance then OnlineSocketManager.s_instance = new(OnlineSocketManager,kSocketRoom,PROTOCOL_TYPE_QE, 1, 1,nil,kProtocalVersion); OnlineSocketManager.s_instance:setHeartBeatCmd(SERVER_SEND_HEART); OnlineSocketManager.s_instance:setKeepAliveCmd(PHP_KEEPALIVE); end return OnlineSocketManager.s_instance; end OnlineSocketManager.releaseInstance = function() delete(OnlineSocketManager.s_instance); OnlineSocketManager.s_instance = nil; end ------------------------------------------------------------------------------------------------------------ OnlineSocketManager.ctor = function(self,socketType,sockHeader,netEndian, gameId, deviceType, ver, subVer) EventDispatcher.getInstance():register(Event.Resume,self,self.onResume); self.m_fileName = "OnlineSocketManager"; self.m_socketReconnectLogFileName = "SocketReconnect "; self.m_logicMap = {}; System.setSocketHeaderSize(14); System.setSocketHeaderExtSize(0); self:setReconnectParam(100,3000); self.m_keepAliveInterval = 5 * 60 * 1000; --保持会话 定时器时长 self.m_isKeepAlive = false; --开启保持会话定时器开关 self.m_maxRequestReplyInterval = 1200 --单次收发包最大间隔 self.m_maxAverageInterval = 500 --最近一次收发包间隔与平均收发包间隔的最大差值 self.m_requestReplyIntervalTable = {} --请求回复间隔时间表 self.m_nowRequestTimestamp = nil --当前请求时间戳 self:_setSocketStatus(SocketStatus.None); self.m_reconnectLogic = new(SocketReconnectLogic,self); end OnlineSocketManager.dtor = function(self) EventDispatcher.getInstance():unregister(Event.Resume,self,self.onResume); self:_setSocketStatus(); self:__stopKeepAliveTimeoutTimer(); self:stopKeepAlive(); self:_stopOnResumeCheckTimer(); self:_clearReopenSocketDelayTimer(); self:_clearDelayReceiverTimer(); delete(self.m_reconnectLogic); self.m_reconnectLogic = nil; self.m_logicMap = {}; self.m_requestReplyIntervalTable = nil self.m_nowRequestTimestamp = nil end OnlineSocketManager.log = function(self,funcName,...) Log.s(self.m_fileName," ",funcName," ",...); end ------------------------------------------------------------------------------------------------------------ --@override OnlineSocketManager.sendMsg = function(self, cmd, info,timeout) self:openSocket(); if self:isSocketOpen() then self:log("sendMsg","socket opened ==> GameSocket.sendMsg, cmd = ",number.formatToHex(cmd)); if cmd < PHP_CMD_CONSTANT then GameSocket.sendMsg(self, cmd, info); else self:log("sendMsg","sendPhpMsg phpCmd = ",number.formatToHex(cmd - PHP_CMD_CONSTANT)); local phpCmd,packetInfo = PhpManager.getInstance():generatePhpPacket(cmd, info,timeout); if phpCmd then GameSocket.sendMsg(self, phpCmd, packetInfo); end end return true; end end --@override OnlineSocketManager.createSocket = function(self,socketType,sockHeader,netEndian, gameId, deviceType, ver, subVer) return new(Socket,socketType,sockHeader,netEndian,gameId,deviceType,ver,subVer); end --@override OnlineSocketManager.openSocket = function(self) if self.m_serverStoped then --停服后不再重新打开socket return; end if self:isSocketOpen() or self:isSocketOpening() then -- self:log("openSocket","isSocketOpen or isSocketOpening"); if not self:isNetWorkAvailable() then self:log("openSocket","network disabled ==> onSocketConnectFailed"); self:onSocketConnectFailed(); end return; end self:log("openSocket"); self:_setSocketStatus(SocketStatus.Connecting); local ip,port = ServerConfig.getInstance():getIpPort(); if ip and port then self:log("openSocket-->","ip = ",ip,"port = ",port); GameSocket.openSocket(self,ip,port); else self:log("openSocket-->","ip = 1, port = 1"); GameSocket.openSocket(self,1,1); end end --@override OnlineSocketManager.closeSocketSync = function(self) self:log("closeSocketSync"); Log.sWF(self.m_socketReconnectLogFileName,"OnlineSocketManager.closeSocketSync"); self.m_isKeepAlive = false; self:_setSocketStatus(SocketStatus.Closing); GameSocket.closeSocketSync(self); end --@override OnlineSocketManager.onSocketClosed = function(self, param) self:log("onSocketClosed", "param = ", param); Log.sWF(self.m_socketReconnectLogFileName,"OnlineSocketManager.onSocketClosed"); GameSocket.onSocketClosed(self); self.m_isKeepAlive = false; self:_setSocketStatus(SocketStatus.Closed); self:onReceivePacket(SOCKET_USER_CLOSED,{socket_close_type = param}); self:resetRequestTimestamp() end --@override --socket连接成功 OnlineSocketManager.onSocketConnected = function(self) self:log("onSocketConnected"); Log.sWF(self.m_socketReconnectLogFileName,"OnlineSocketManager.onSocketConnected"); GameSocket.onSocketConnected(self); self:_setSocketStatus(SocketStatus.Connected); ServerConfig.getInstance():onSocketConnected(); self:startKeepAlive();--保持会话 self.m_connectedCount = number.valueOf(self.m_connectedCount); if self.m_connectedCount == 0 then self:onReceivePacket(SOCKET_FIRST_CONNECTED,{}); else self:onReceivePacket(SOCKET_CONNECT_SUCCESS,{}); end self.m_connectedCount = self.m_connectedCount + 1; self:resetRequestTimestamp() end --@override --socket连接失败 OnlineSocketManager.onSocketConnectFailed = function(self,info) self:log("onSocketConnectFailed"); Log.sWF(self.m_socketReconnectLogFileName,"OnlineSocketManager.onSocketConnectFailed"); GameSocket.onSocketConnectFailed(self); self.m_isKeepAlive = false; self:_setSocketStatus(SocketStatus.ConnectFailed); ServerConfig.getInstance():clearBestIpPortIndex(); self:onReceivePacket(SOCKET_CONNECT_FAILED,{}); self:resetRequestTimestamp() end --@override --心跳包超时 OnlineSocketManager.onTimeout = function(self) self:log("onTimeout"); Log.sWF(self.m_socketReconnectLogFileName,"OnlineSocketManager.onTimeout"); GameSocket.onTimeout(self); self:closeSocketSync(); self:_setSocketStatus(SocketStatus.HeartBeatTimeout); self:onReceivePacket(SOCKET_HEARTBEAT_TIMEOUT,{}); self:resetRequestTimestamp() end OnlineSocketManager.onSocketReconnecting = function(self, data) self:log("onSocketReconnecting"); Log.sWF(self.m_socketReconnectLogFileName,"OnlineSocketManager.onSocketReconnecting"); self:_setSocketStatus(SocketStatus.Reconnecting); self:onReceivePacket(SOCKET_RECONNECT_ING,data); end OnlineSocketManager.onSocketReconnected = function(self) self:log("onSocketReconnected"); Log.sWF(self.m_socketReconnectLogFileName,"OnlineSocketManager.onSocketReconnected"); self:startKeepAlive();--保持会话 self:_setSocketStatus(SocketStatus.Reconnected); self:onReceivePacket(SOCKET_RECONNECT_SUCCESS,{}); self:resetRequestTimestamp() end OnlineSocketManager.onSocketReconnectFailed = function(self) self:log("onSocketReconnectFailed"); Log.sWF(self.m_socketReconnectLogFileName,"OnlineSocketManager.onSocketReconnectFailed"); self.m_isKeepAlive = false; self:_setSocketStatus(SocketStatus.ReconnectFailed); self:onReceivePacket(SOCKET_RECONNECT_FAILED,{}); self:resetRequestTimestamp() end --@override OnlineSocketManager.writeBegin = function(self, socket, cmd) local packetId = socket:writeBegin3(cmd); return packetId; end --override OnlineSocketManager.onSocketServerPacket = function(self, packetId) GameSocket.stopTimer(self); self:updateNetIconState() local cmd,info,isValidPacket = self:parseMsg(packetId); if isValidPacket then self:onReceivePacket(cmd,info); else self:log("onSocketServerPacket", "WARNING filter cmd = ", number.formatToHex(cmd)); end end OnlineSocketManager.updateNetIconState = function(self) if self.m_nowRequestTimestamp then local state = false local val = Clock.now() - self.m_nowRequestTimestamp local num = #self.m_requestReplyIntervalTable if val > self.m_maxRequestReplyInterval then state = true self:log("OnlineSocketManager.updateNetIconState:",ClientInfo.getInstance():getNetworkName(),val) else local average = 0 if num > 3 then local count = 0 for i = 1, num do count = count + tonumber(self.m_requestReplyIntervalTable[i]) end average = count / num if val - average > self.m_maxAverageInterval then state = true self:log("OnlineSocketManager.updateNetIconState:",ClientInfo.getInstance():getNetworkName(),val,average) end end end if num >= 10 then table.remove(self.m_requestReplyIntervalTable, 1) end table.insert(self.m_requestReplyIntervalTable, val) self.m_nowRequestTimestamp = nil self:onReceivePacket(SOCKET_UPDATE_NET_ICON, state) end end OnlineSocketManager.resetRequestTimestamp = function(self) self.m_nowRequestTimestamp = nil self.m_requestReplyIntervalTable = {} self:onReceivePacket(SOCKET_UPDATE_NET_ICON, false) end --override OnlineSocketManager.parseMsg = function(self, packetId) local cmd = self:readBegin(packetId); local info, isValidPacket = self:readPacket(self.m_socket,packetId,cmd); self:readEnd(packetId); return cmd,info,isValidPacket; end --override OnlineSocketManager.readPacket = function(self, socket, packetId, cmd) local packetInfo = nil; local isValidPacket = false; for k,v in pairs(self.m_socketReaders) do local packetInfo, isValid = v:readPacket(socket,packetId,cmd); isValidPacket = isValid and true or isValidPacket; if packetInfo then return packetInfo, true; end end for k,v in pairs(self.m_commonSocketReaders) do local packetInfo, isValid = v:readPacket(socket,packetId,cmd); isValidPacket = isValid and true or isValidPacket; if packetInfo then return packetInfo, true; end end return packetInfo, isValidPacket; end OnlineSocketManager.onReceivePacket = function(self, cmd, info) self:log("onReceivePacket","cmd =" ,number.formatToHex(cmd)); if self.m_isStartDelayReceiver then self:log("onReceivePacket","StartDelayReceiver ==> _addPacketToDelayReceiver cmd = " ,number.formatToHex(cmd)); self:_addPacketToDelayReceiver(cmd,info); else self:log("onReceivePacket","==> _handleReceivePacket"); self:_handleReceivePacket(cmd,info); end end OnlineSocketManager._handleReceivePacket = function(self,cmd,info) if cmd == RESPONSE_PHP_REQUEST or cmd == RESPONSE_PHP_REQUEST_NEW then PhpManager.getInstance():pushCmdToRecQueue(cmd,info); else self:log("_handleReceivePacket", "receive server cmd = ", number.formatToHex(cmd), " info = ", info); self:_handlePacket(cmd,info); end end OnlineSocketManager.onReceivePhpPacket = function(self, phpCmd, phpInfo) if not phpCmd then return; end if phpCmd == PHP_KEEPALIVE then self:__stopKeepAliveTimeoutTimer(); end self:log("_handleReceivePacket","receive php subCmd =" ,number.formatToHex(phpCmd - PHP_CMD_CONSTANT)); self:_handlePacket(phpCmd,unpack(phpInfo)); end OnlineSocketManager._handlePacket = function(self,cmd,...) local isHandle = SocketHandlersStack.getInstance():handlePacket(cmd,...); if not isHandle then self:log("_handlePacket"," Not handler cmd =", number.formatToHex(cmd)); end end OnlineSocketManager.isNetWorkAvailable = function(self) local res = NativeEvent.getInstance():getNetWorkAvalible(); self:log("OnlineSocketManager.isNetWorkAvailable", "res = ", res); return res; end OnlineSocketManager.isSocketOpening = function(self) local status = self:_getSocketStatus(); local isOpening = status == SocketStatus.Connecting or status == SocketStatus.Reconnecting; self:log("OnlineSocketManager.isSocketOpening", "isOpening = ", isOpening); return isOpening; end OnlineSocketManager.isSocketAvailable = function(self) local isOpen = self:isSocketOpen(); local status = self:_getSocketStatus(); local isAvailable = status == SocketStatus.Connected or status == SocketStatus.Reconnected; return isOpen and isAvailable; end OnlineSocketManager.isSocketOffline = function(self) local status = self:_getSocketStatus(); self:log("OnlineSocketManager.isSocketOffline", "status = ", status); return status == SocketStatus.Offline; end OnlineSocketManager._setSocketStatus = function(self,status) self:log("OnlineSocketManager._setSocketStatus", "status = ", status); self.m_socketStatus = status or SocketStatus.None; end OnlineSocketManager._getSocketStatus = function(self) return self.m_socketStatus or SocketStatus.None; end OnlineSocketManager.setServerStoped = function(self) self.m_serverStoped = true; end ---------------------------------------------------------------------------------------------- OnlineSocketManager.reopenSocket = function(self,time) self:log("OnlineSocketManager.reopenSocket"); if self:isSocketOpen() or self:isSocketOpening() then self:log("OnlineSocketManager.reopenSocket", "begin close last socket "); --原来的连接未断开 self:closeSocketSync();--关闭连接 --留一定的时间来关闭连接 if not self.m_reopenSocketDelayTimer then self.m_reopenSocketDelayTimer = AnimFactory.createAnimInt(kAnimNormal,0,1,(time or 1000),0); self.m_reopenSocketDelayTimer:setDebugName("AnimInt|OnlineSocketManager|reopenSocketDelayTimer"); self.m_reopenSocketDelayTimer:setEvent(self, self._onReopenSocketTimer); end else self:log("OnlineSocketManager.reopenSocket", "openSocket"); --原来的连接已断开 self:openSocket(); end end OnlineSocketManager._onReopenSocketTimer = function(self) self:log("OnlineSocketManager._onReopenSocketTimer"); self:_clearReopenSocketDelayTimer(); self:openSocket(); end OnlineSocketManager._clearReopenSocketDelayTimer = function(self) self:log("OnlineSocketManager._clearReopenSocketDelayTimer"); delete(self.m_reopenSocketDelayTimer); self.m_reopenSocketDelayTimer = nil; end ---------------------------------------------------------------------------------------------- --延时接收数据包 OnlineSocketManager.startDelayReceiver = function(self,time) self:log("startDelayReceiver","time = ",time); self.m_isStartDelayReceiver = true; self:_clearDelayReceiverTimer(); self.m_delayReceiverTimer = AnimFactory.createAnimInt(kAnimNormal,0,1,(time or 1000),0); self.m_delayReceiverTimer:setDebugName("AnimInt|OnlineSocketManager|delayReceiverTimer"); self.m_delayReceiverTimer:setEvent(self, self._onDelayReceiverTimeout); end OnlineSocketManager._onDelayReceiverTimeout = function(self) self:log("OnlineSocketManager._onDelayReceiverTimeout"); self:_clearDelayReceiverTimer(); self:log("_onDelayReceiverTimeout","handle start"); self:_handleMsgInDelayReceiver(); self:log("_onDelayReceiverTimeout","handle end"); end OnlineSocketManager._handleMsgInDelayReceiver = function(self) self.m_delayReceiverMap = table.verify(self.m_delayReceiverMap); self:log("_handleMsgInDelayReceiver","#self.m_delayReceiverMap = ",#self.m_delayReceiverMap); if #self.m_delayReceiverMap > 0 then local v = table.remove(self.m_delayReceiverMap, 1); self:log("_handleMsgInDelayReceiver"," ==> _handleReceivePacket cmd = ",number.formatToHex(v.cmd)); self:_handleReceivePacket(v.cmd,v.info); self:_handleMsgInDelayReceiver(); else self.m_isStartDelayReceiver = false; end end OnlineSocketManager._clearDelayReceiverTimer = function(self) self:log("OnlineSocketManager._clearDelayReceiverTimer"); delete(self.m_delayReceiverTimer); self.m_delayReceiverTimer = nil; end OnlineSocketManager._addPacketToDelayReceiver = function(self,cmd,info) self:log("_addPacketToDelayReceiver","cmd =" ,number.formatToHex(cmd)); local receiver = table.verify(self.m_delayReceiverMap); local data = {}; data.cmd = cmd; data.info = info; table.insert(receiver,data); self.m_delayReceiverMap = receiver; end --------------------------------------------------------------------------------------------------------- ---------------------------------- 请求会话开始 ----------------------------------------------- --保持会话 设置发送指令 OnlineSocketManager.setKeepAliveCmd = function(self,cmd) self.m_keepAliveCmd = cmd; end --保持会话 设置发送指令间隔时长 OnlineSocketManager.setKeepAliveInterval = function(self,keepAliveInterval) self.m_keepAliveInterval = keepAliveInterval or self.m_keepAliveInterval; end --保持会话 开启发送指令定时器 OnlineSocketManager.startKeepAlive = function(self) self:log("startKeepAlive =========> ","self.m_isKeepAlive = ",self.m_isKeepAlive); if self.m_isKeepAlive then return; end self:stopKeepAlive(); self.m_isKeepAlive = true; self:log("startKeepAlive =========> "); self.m_keepAliveAnim = AnimFactory.createAnimDouble(kAnimRepeat,0,1,self.m_keepAliveInterval,-1); self.m_keepAliveAnim:setDebugName("OnlineSocketManager.m_keepAliveAnim"); self.m_keepAliveAnim:setEvent(self,self.onStartKeepAlive); end --保持会话 设置发送指令定时器到时间 发送指令 OnlineSocketManager.onStartKeepAlive = function(self) if not self.m_keepAliveCmd then self:log("onStartKeepAlive =========> ","not self.m_keepAliveCmd ==> return "); return; end self:log("onStartKeepAlive ========> sendMsg self.m_keepAliveCmd"); self:__startKeepAliveTimeoutTimer(); self:sendMsg(self.m_keepAliveCmd,{}); end --保持会话 删除发送指令定时器 OnlineSocketManager.stopKeepAlive = function(self) self:log("stopKeepAlive"); self:__stopKeepAliveTimeoutTimer(); delete(self.m_keepAliveAnim); self.m_keepAliveAnim = nil; end OnlineSocketManager.__stopKeepAliveTimeoutTimer = function(self) self:log("OnlineSocketManager.__stopKeepAliveTimeoutTimer"); delete(self.m_keepAliveTimeoutTimer); self.m_keepAliveTimeoutTimer = nil; end OnlineSocketManager.__startKeepAliveTimeoutTimer = function(self) self:log("OnlineSocketManager.__startKeepAliveTimeoutTimer"); self:__stopKeepAliveTimeoutTimer(); self.m_keepAliveTimeoutTimer = AnimFactory.createAnimDouble(kAnimRepeat, 0, 1, 6000, -1); self.m_keepAliveTimeoutTimer:setDebugName("OnlineSocketManager.m_keepAliveTimeoutTimer"); self.m_keepAliveTimeoutTimer:setEvent(self, self.__onKeepAliveTimeout); end OnlineSocketManager.__onKeepAliveTimeout = function(self) self:log("OnlineSocketManager.__onKeepAliveTimeout"); self:__stopKeepAliveTimeoutTimer(); self.m_isKeepAlive = false; self:onStartKeepAlive();--保持会话消息发送超时后,先重新发送条 self:startKeepAlive(); end ---------------------------------- 请求会话结束 ----------------------------------------------- --游戏从后台切回来后,延迟1s尝试打开socket与发送心跳包,减少在后台时网络发生后重连花费的时间 OnlineSocketManager.onResume = function(self) self:log("OnlineSocketManager.onResume"); self:_stopOnResumeCheckTimer(); self.m_onResumeCheckTimer = AnimFactory.createAnimInt(kAnimNormal, 0, 1, 1000, 0); self.m_onResumeCheckTimer:setDebugName("OnlineSocketManager.m_onResumeCheckTimer"); self.m_onResumeCheckTimer:setEvent(self, self._onResumeCheckTimeout); end OnlineSocketManager._stopOnResumeCheckTimer = function(self) self:log("OnlineSocketManager._stopOnResumeCheckTimer"); delete(self.m_onResumeCheckTimer); self.m_onResumeCheckTimer = nil; end OnlineSocketManager._onResumeCheckTimeout = function(self) self:log("OnlineSocketManager._onResumeCheckTimeout"); self:_stopOnResumeCheckTimer(); self:openSocket(); GameSocket.onHeartBeat(self); end OnlineSocketManager.onHeartBeat = function(self) GameSocket.onHeartBeat(self) self.m_nowRequestTimestamp = Clock.now() end --获取server断开链接type值 OnlineSocketManager.getServerCloseSocketTypeValue = function(self) return SOCKET_CLOSE_TYPE.SERVER_CLOSE; end --获取业务主动断开链接type值 OnlineSocketManager.getUserCloseSocketTypeValue = function(self) return SOCKET_CLOSE_TYPE.USER_CLOSE; end
local console_monitor = core.monitor(core.LOG, core.INFO, core.FMT_TEXT) console_monitor:name("console.monitor") console_monitor:tail(1024) local console_dispatcher = core.dispatcher(core.EVENTQ) console_dispatcher:name("console.dispatcher") console_dispatcher:attach(console_monitor, "eventrec") console_dispatcher:run() local package = { q = console_queue, dispatcher = console_dispatcher, monitor = console_monitor, } return package
--# Monster converted using Devm monster converter #-- local mType = Game.createMonsterType("Behemoth") local monster = {} monster.description = "a behemoth" monster.experience = 2500 monster.outfit = { lookType = 55, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.raceId = 55 monster.Bestiary = { class = "Giant", race = BESTY_RACE_GIANT, toKill = 1000, FirstUnlock = 50, SecondUnlock = 500, CharmsPoints = 25, Stars = 3, Occurrence = 0, Locations = "Cyclopolis, deepest part of Tarpit Tomb after the flame, Forbidden Lands, Vandura Mountain, \z Deeper Banuta, Serpentine Tower (unreachable), deep into the Formorgar Mines, Arena and Zoo Quarter, \z The Dark Path, Lower Spike, Chyllfroest, Medusa Tower and Underground Glooth Factory (west side)." } monster.health = 4000 monster.maxHealth = 4000 monster.race = "blood" monster.corpse = 5999 monster.speed = 340 monster.manaCost = 0 monster.maxSummons = 0 monster.changeTarget = { interval = 4000, chance = 10 } monster.strategiesTarget = { nearest = 70, damage = 30, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = false, illusionable = false, canPushItems = true, canPushCreatures = true, staticAttackChance = 70, targetDistance = 1, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = true, canWalkOnPoison = true, pet = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "You're so little!", yell = false}, {text = "Human flesh - delicious!", yell = false}, {text = "Crush the intruders!", yell = false} } monster.loot = { {id = 2893, chance = 100}, -- amphora {id = 3008, chance = 2530}, -- crystal necklace {id = 3031, chance = 595300, maxCount = 100}, -- gold coin {id = 3031, chance = 40000, maxCount = 99}, -- gold coin {id = 3033, chance = 6380, maxCount = 5}, -- small amethyst {id = 3035, chance = 59800, maxCount = 5}, -- platinum coin {id = 3058, chance = 750}, -- strange symbol {id = 3116, chance = 670}, -- big bone {id = 3265, chance = 5980}, -- two handed sword {id = 3275, chance = 10510}, -- double axe {id = 3281, chance = 1006}, -- giant sword {id = 3304, chance = 100}, -- crowbar {id = 3342, chance = 50}, -- war axe {id = 3357, chance = 3930}, -- plate armor {id = 3383, chance = 4370}, -- dark armor {id = 3456, chance = 650}, -- pick {id = 3554, chance = 380}, -- steel boots {id = 3577, chance = 30000, maxCount = 6}, -- meat {id = 5893, chance = 1090}, -- perfect behemoth fang {id = 5930, chance = 430}, -- behemoth claw {id = 7368, chance = 9750, maxCount = 5}, -- assassin star {id = 7396, chance = 170}, -- behemoth trophy {id = 7413, chance = 90}, -- titan axe {id = 239, chance = 5120}, -- great health potion {id = 11447, chance = 14000} -- battle stone } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -450}, {name ="combat", interval = 2000, chance = 15, type = COMBAT_PHYSICALDAMAGE, minDamage = 0, maxDamage = -200, range = 7, shootEffect = CONST_ANI_LARGEROCK, target = false} } monster.defenses = { defense = 45, armor = 45, {name ="speed", interval = 2000, chance = 15, speedChange = 300, effect = CONST_ME_MAGIC_RED, target = false, duration = 5000} } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 10}, {type = COMBAT_ENERGYDAMAGE, percent = 10}, {type = COMBAT_EARTHDAMAGE, percent = 80}, {type = COMBAT_FIREDAMAGE, percent = 30}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = -10}, {type = COMBAT_HOLYDAMAGE , percent = 30}, {type = COMBAT_DEATHDAMAGE , percent = -5} } monster.immunities = { {type = "paralyze", condition = true}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
--[[ desc: Drawable, a Renderer's practice. Be used for drawing some resource. author: Musoucrow since: 2018-4-26 alter: 2019-9-17 ]]-- local _Renderer = require("graphics.renderer.init") ---@class Graphics.Drawable ---@field protected _upperEvent event ---@field protected _event event ---@field protected _renderer Graphics.Renderer ---@field protected _drawableObj Drawable local _Base = require("core.class")() ---@param upperEvent event function _Base:Ctor(upperEvent) self._upperEvent = upperEvent self._event = { AddListener = function(...) self._renderer:AddListener(...) end, Impart = function(...) self._renderer:Impart(...) end } if (self._upperEvent and self._upperEvent.AddListener and self._upperEvent.Impart) then self._event.AddListenerToUpper = self._upperEvent.AddListener self._event.ImpartFromUpper = self._upperEvent.Impart self._renderer = _Renderer.New(self._event, "ImpartFromUpper", "AddListenerToUpper") else self._renderer = _Renderer.New(self._event) end end ---@param type string function _Base:SetAttri(type, ...) self._renderer:SetAttri(type, ...) end ---@param type string ---@param isSelf boolean ---@param name string function _Base:GetAttri(type, isSelf, name) return self._renderer:GetAttri(type, isSelf, name) end ---@param quad Quad function _Base:SetQuad(quad) self._renderer.quad = quad end ---@return number function _Base:GetQuadValues() local quad = self._renderer.quad if (not quad) then return end local x, y, w, h = quad:getViewport() local sw, sh = quad:getTextureDimensions() return x, y, w, h, sw, sh end ---@param type string @color, blendmode, shader ---@param isBan boolean function _Base:SetBan(type, isBan) self._renderer:SetBan(type, isBan) end ---@param type string ---@param unlock boolean function _Base:SwitchAttriLock(type, unlock) self._renderer:SwitchAttriLock(type, unlock) end ---@return Graphics.Drawable function _Base:GetUpper() return self._upperEvent.GetUpper() end function _Base:GetData() return self._data end function _Base:Draw() self._renderer:Apply() self:_OnDraw() self._renderer:Reset() end function _Base:Update() end function _Base:_OnDraw() end return _Base
function onCreate() makeLuaSprite("beatbox bg","beatbox bg",-500,-100) addLuaSprite("beatbox bg",false) setLuaSpriteScrollFactor("beatbox bg",0.6,0.6) setProperty('gfGroup.visible', false) end
local servers = { "angularls", "bashls", "clangd", "clojure_lsp", "cmake", "cssls", "dockerls", "elixirls", "elmls", "emmet_ls", "fsautocomplete", "hls", "html", "jsonls", "kotlin_language_server", "omnisharp", "purescriptls", "pyright", "rust_analyzer", "solang", "sumneko_lua", "svelte", "tailwindcss", "terraformls", "texlab", "tsserver", "vimls", "volar", "vuels", } return { get = function(server_name) if server_name then return require("lspmanager.servers." .. server_name) end return servers end, set = function(user_configs) vim.validate({ user_configs = { user_configs, "table" } }) local new_servers = {} for name, configuration in pairs(user_configs) do local server = require("lspmanager.servers." .. name) server = vim.tbl_deep_extend("force", server, { config = configuration, }) new_servers[name] = server end return new_servers end, }
local random = require 'lqc.random' local char = require 'lqc.generators.char' local r = require 'lqc.report' local property = require 'lqc.property' local lqc = require 'lqc.quickcheck' local lowest_ascii_value = 32 local highest_ascii_value = 126 local lowest_ascii_char = string.char(lowest_ascii_value) local function is_readable_char(value) local char_value = string.byte(value) return type(value) == 'string' and string.len(value) == 1 and char_value >= lowest_ascii_value and char_value <= highest_ascii_value end local function do_setup() random.seed() lqc.init(100, 100) lqc.properties = {} r.report = function() end end describe('char generator module', function() describe('pick function', function() before_each(do_setup) it('should pick a char', function() local spy_check = spy.new(function(x) return is_readable_char(x) end) property 'char() should pick a char' { generators = { char() }, check = spy_check } lqc.check() assert.spy(spy_check).was.called(lqc.numtests) end) end) describe('shrink function', function() before_each(do_setup) it('should converge to " "', function() local shrunk_values r.report_failed_property = function(_, _, shrunk_vals) shrunk_values = shrunk_vals[1] end property 'char() should converge to 32 (lowest allowed ASCII value)' { generators = { char() }, check = function(x) return not is_readable_char(x) -- always fails! end } for _ = 1, 100 do shrunk_values = nil lqc.check() assert.equal(lowest_ascii_char, shrunk_values) end end) end) end)
print("I'm inside a module!")
/*--------------------------------------------------------------------------- Expression Advanced: Editor. Purpose: Make the fancy EA editor. Author: Oskar ---------------------------------------------------------------------------*/ local EA = LEMON EA.Editor = {} local Editor = EA.Editor require( "vector2" ) /*--------------------------------------------------------------------------- Custom fonts ---------------------------------------------------------------------------*/ timer.Simple( 0.5, function() surface.CreateFont( "Fixedsys", { font = "Fixedsys", size = 13, weight = 400, blursize = 0, scanlines = 0, antialias = true, underline = false, italic = false, strikeout = false, symbol = false, rotary = false, shadow = false, additive = false, outline = false, } ) surface.CreateFont( "Trebuchet22", { font = "Trebuchet MS", size = 22, weight = 900, blursize = 0, scanlines = 0, antialias = true, underline = false, italic = false, strikeout = false, symbol = false, rotary = false, shadow = false, additive = false, outline = false } ) surface.CreateFont( "Trebuchet20", { font = "Trebuchet MS", size = 20, weight = 900, blursize = 0, scanlines = 0, antialias = false, underline = false, italic = false, strikeout = false, symbol = false, rotary = false, shadow = false, additive = false, outline = false } ) end ) /*--------------------------------------------------------------------------- Home Screen ---------------------------------------------------------------------------*/ local HomeScreen = [[/*=================================================== Expression Advanced: * Check out our new repo browser! Docs: https://github.com/SpaceTown-Developers/Lemon-Gate/wiki Bug Reports: https://github.com/SpaceTown-Developers/Lemon-Gate/issues Credits: Rusketh, Oskar94, Divran, Syranide. ===================================================*/ ]] /*--------------------------------------------------------------------------- Syntax Highlighting ---------------------------------------------------------------------------*/ local function SyntaxColorLine( self, Row ) local Tokens, Ok Ok, Tokens = pcall( Syntax.Parse, self, Row ) if !Ok then ErrorNoHalt( Tokens .. "\n" ) Tokens = {{self.Rows[Row], Color(255,255,255)}} end return Tokens end /*--------------------------------------------------------------------------- Editor Functions ---------------------------------------------------------------------------*/ function Editor.Create( ) if Editor.Instance then return end file.CreateDir("lemongate") local Instance = vgui.Create( "EA_EditorPanel" ) function Instance:OnTabCreated( Tab, Code, Path ) if Code or Path then return false end local Editor = Tab:GetPanel( ) Editor:SetCode( HomeScreen ) Editor.Caret = Vector2( #Editor.Rows, #Editor.Rows[#Editor.Rows] + 1 ) Editor.Start = Vector2( 1, 1 ) return true end Instance:SetSyntaxColorLine( SyntaxColorLine ) Instance:SetKeyBoardInputEnabled( true ) Instance:SetVisible( false ) Editor.Instance = Instance end function Editor.Open( Code, NewTab ) Editor.Create( ) Editor.Instance:Open( Code, NewTab ) end function Editor.NewTab( Script, FilePath ) Editor.Create( ) Editor.Instance:NewTab( Script, FilePath ) end function Editor.GetCode( ) if Editor.Instance then return Editor.Instance:GetCode( ) end end function Editor.GetInstance( ) Editor.Create( ) return Editor.Instance end function Editor.ReciveDownload( Download ) Editor.Create( ) Editor.Instance:ReciveDownload( Download ) end function Editor.Validate( Script ) if Editor.Instance then return Editor.Instance:DoValidate( nil, nil, Script ) end end
-- The engine Visual Studio project project "Foundation" kind "StaticLib" language "C++" cppdialect "C++17" staticruntime "on" -- Binaries and Intermediate folders targetdir ("%{wks.location}/Binaries/" .. outputdir .. "/%{prj.name}") objdir ("%{wks.location}/Intermediate/" .. outputdir .. "/%{prj.name}") -- Precompiled header files pchheader "fdpch.h" pchsource "Source/fdpch.cpp" -- Which files to include in our Visual Studio project files { "Source/**.h", "Source/**.cpp", "ThirdParty/stb_image/**.h", "ThirdParty/stb_image/**.cpp", "ThirdParty/glm/glm/**.hpp", "ThirdParty/glm/glm/**.inl", "ThirdParty/ImGuizmo/ImGuizmo.h", "ThirdParty/ImGuizmo/ImGuizmo.cpp", "ThirdParty/Reflection/ReflectCommon.cpp", "ThirdParty/Reflection/Reflect.cpp", "%{wks.location}/Intermediate/GeneratedCode/**.cpp" } defines { "_CRT_SECURE_NO_WARNINGS", "GLFW_INCLUDE_NONE" } -- Additional include directories includedirs { "Source", "%{IncludeDir.spdlog}", "%{IncludeDir.GLFW}", "%{IncludeDir.Glad}", "%{IncludeDir.ImGui}", "%{IncludeDir.glm}", "%{IncludeDir.stb_image}", "%{IncludeDir.yaml_cpp}", "%{IncludeDir.Reflection}", "%{IncludeDir.asio}", "%{IncludeDir.NetworkFramework}", "%{IncludeDir.ImGuizmo}" } -- Linking other projects links { "GLFW", "Glad", "ImGui", "yaml-cpp", "NetworkFramework", "opengl32.lib", "FoundationCodeGenerator" } prebuildmessage "Generating code files to intermediate folder!" prebuildcommands { "%{wks.location}/Binaries/" .. outputdir .. "/FoundationCodeGenerator/FoundationCodeGenerator.exe %{prj.location}/Source/" } postbuildmessage "Copying assets over to the FoundationEditor" postbuildcommands { "{COPY} %{prj.location}/Assets %{wks.location}/FoundationEditor/Assets" } filter "files:ThirdParty/ImGuizmo/**.cpp" flags { "NoPCH" } filter "files:ThirdParty/Reflection/ReflectCommon.cpp" flags { "NoPCH" } -- Configuration setup for Windows filter "system:windows" systemversion "latest" -- Debug configuration, turn debug symbols on filter "configurations:Debug" targetname "Foundation_Debug" defines "FD_DEBUG" runtime "Debug" symbols "on" -- Release configuration, optimizations turned on filter "configurations:Release" targetname "Foundation_Release" defines "FD_RELEASE" runtime "Release" optimize "on" -- Distribution configuration, optimizations turned on filter "configurations:Distribution" targetname "Foundation_Distribution" defines "FD_DISTRIBUTION" runtime "Release" optimize "on"
local meta = FindMetaTable("Player") if not meta then return end function meta:EndState(nocallended) if self == MySelf then self:SetState(STATE_NONE, nil, nil, nocallended) end end
local mod = DBM:NewMod(1433, "DBM-HellfireCitadel", nil, 669) local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 14938 $"):sub(12, -3)) mod:SetCreatureID(90316) mod:SetEncounterID(1788) mod:DisableESCombatDetection()--Remove if blizz fixes trash firing ENCOUNTER_START mod:SetMinSyncRevision(13887) mod:SetZone() mod:SetUsedIcons(8, 7, 6, 5, 4, 3, 2, 1)--Unknown full spectrum of icons yet. Don't know how many debuffs go out. mod:SetHotfixNoticeRev(14463) mod.respawnTime = 15 mod:DisableRegenDetection()--Boss returns true on UnitAffectingCombat when fighting his trash, making boss pre mature pull by REGEN method mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_CAST_START 181912 181827 187998 181873 185345", "SPELL_CAST_SUCCESS 182178 181956 185510 181912", "SPELL_AURA_APPLIED 179202 181957 182325 187990 181824 179219 185510 181753 182178 182200", "SPELL_AURA_REMOVED 179202 181957 182325 187990 181824 179219 185510 181753 182178 182200", "SPELL_PERIODIC_DAMAGE 182600", "SPELL_PERIODIC_MISSED 182600", "RAID_BOSS_WHISPER", "CHAT_MSG_ADDON", "INSTANCE_ENCOUNTER_ENGAGE_UNIT", "UNIT_DIED", "UNIT_SPELLCAST_SUCCEEDED boss1" ) --(ability.id = 181912 or ability.id = 181827 or ability.id = 187998 or ability.id = 181873 or ability.id = 185345) and type = "begincast" or (ability.id = 182178 or ability.id = 181956 or ability.id = 181912 or ability.id = 185510) and type = "cast" or (ability.id = 181824 or ability.id = 187990 or ability.id = 181753) and type = "applydebuff" --Boss local warnEyeofAnzu = mod:NewTargetAnnounce(179202, 1, nil, false)--Important, but spammy, Will do something fancy with infoframe to show target instead of spamming screen with warnings local warnPhantasmalWinds = mod:NewTargetAnnounce(181957, 4)--Announce to all, for things like life grips, body and soul, etc to keep them on platform while anzu person helps clear them. local warnPhantasmalWounds = mod:NewTargetAnnounce(182325, 2, nil, "Healer") local warnFelChakram = mod:NewTargetAnnounce(182178, 4) local warnLaser = mod:NewTargetAnnounce(182582, 3) local warnShadowRiposte = mod:NewSpellAnnounce(185345, 4) --Adds local warnPhantasmalCorruption = mod:NewTargetAnnounce(181824, 3) local warnPhantasmalFelBomb = mod:NewTargetAnnounce(179219, 3, nil, false)--Fake fel bombs, they'll show up on radar but don't need to know targets if person with anzu isn't terrlbe at game. they have 5 seconds to find and throw to ONE target. local warnFelBomb = mod:NewTargetAnnounce(181753, 3) local warnDarkBindings = mod:NewTargetAnnounce(185510, 4)--Mythic (Chains of Despair Debuff) local warnFelConduit = mod:NewCastAnnounce(181827, 3, nil, nil, "-Healer") --Boss local specWarnEyeofAnzu = mod:NewSpecialWarningYou(179202) local specWarnThrowAnzu = mod:NewSpecialWarning("specWarnThrowAnzu", nil, nil, nil, 1, 5) local specWarnFocusedBlast = mod:NewSpecialWarningCount(181912, nil, nil, nil, 2) local specWarnPhantasmalWinds = mod:NewSpecialWarningYou(181957, nil, nil, nil, 3) local specWarnFelChakram = mod:NewSpecialWarningMoveAway(182178, nil, nil, nil, 1, 2) local yellFelChakram = mod:NewYell(182178) local specWarnFelChakramTank = mod:NewSpecialWarningTaunt(182178, nil, nil, nil, 1, 2) local yellPhantasmalWinds = mod:NewYell(181957)--So person with eye can see where the targets are faster local specWarnPhantasmalWounds = mod:NewSpecialWarningYou(182325, false) local yellPhantasmalWounds = mod:NewYell(182325, nil, false)--Can't see much reason to have THIS one on by default, but offered as an option. local specWarnFelLaser = mod:NewSpecialWarningMoveAway(182582, nil, nil, nil, 1, 2) local specWarnFelLaserGTFO = mod:NewSpecialWarningMove(182600, nil, nil, nil, 1, 2) local yellFelLaser = mod:NewYell(182582) local specWarnShadowRiposte = mod:NewSpecialWarningSpell(185345, nil, nil, nil, 3)--Has eye of anzu, they need to know this badly. --Adds local specWarnPhantasmalCorruption = mod:NewSpecialWarningYou(181824)--Not move away on purpose, correct way to handle is get eye of anzu, you do NOT move local yellPhantasmalCorruption = mod:NewYell(181824)--For eye of anzu holder. Explosion shouldn't happen. local specWarnPhantasmalFelBomb = mod:NewSpecialWarningYou(179219)--Not move away on purpose, correct way to handle is get eye of anzu to real fel bomb local yellPhantasmalFelBomb = mod:NewYell(179219, nil, false)--Fake bombs off by default, they will never explode and eye of anzu holder will get distracted local specWarnFelBomb = mod:NewSpecialWarningYou(181753)--Not move away on purpose, correct way to handle is get eye of anzu, you do NOT move local yellFelBomb = mod:NewYell(181753)--Yell for real fel bomb on by default only local specWarnFelBombDispel = mod:NewSpecialWarningDispel(181753, nil, nil, nil, 1, 2)--Doesn't need option default, it's filtered by anzu check local specWarnDarkBindings = mod:NewSpecialWarningYou(185510)--Mythic local specWarnFelConduit = mod:NewSpecialWarningInterrupt(181827, nil, nil, nil, 1, 2)--On for everyone, filtered by eye of anzu, if this person can't interrupt, then they better pass it to someone who can local timerFelLaserCD = mod:NewCDTimer(16, 182582, nil, nil, nil, 3)--16-22. Never pauses, used all phases local timerChakramCD = mod:NewCDTimer(33, 182178, nil, nil, nil, 3) local timerPhantasmalWindsCD = mod:NewCDTimer(35, 181957, nil, nil, nil, 3, nil, DBM_CORE_DEADLY_ICON) local timerPhantasmalWoundsCD = mod:NewCDTimer(30.5, 182325, nil, "Healer", 2, 5)--30.5-32 local timerFocusedBlast = mod:NewCastTimer(11, 181912, nil, nil, nil, 2)--Doesn't realy need a cd timer. he casts it twice back to back, then lands local timerShadowRiposteCD = mod:NewCDTimer(23.5, 185345, nil, nil, nil, 3, nil, DBM_CORE_HEROIC_ICON) --Adds local timerFelBombCD = mod:NewCDTimer(18.5, 181753, nil, nil, nil, 3, nil, DBM_CORE_MAGIC_ICON) local timerFelConduitCD = mod:NewCDTimer(15, 181827, nil, nil, nil, 4, nil, DBM_CORE_INTERRUPT_ICON) local timerPhantasmalCorruptionCD = mod:NewCDTimer(14, 181824, 156842, "Tank", nil, 3)--14-18 local timerDarkBindingsCD = mod:NewCDTimer(34, 185456, nil, nil, nil, 3, nil, DBM_CORE_HEROIC_ICON) local countdownPhantasmalWinds = mod:NewCountdown(35, 181957) local countdownFelBomb = mod:NewCountdown("Alt18", 181753) local countdownCorruption = mod:NewCountdown("AltTwo14", 181824, "Tank") local berserkTimer = mod:NewBerserkTimer(540) local voiceFocusedBlast = mod:NewVoice(181912)--gather local voiceFelConduit = mod:NewVoice(181827)--kickcast local voiceFelChakram = mod:NewVoice(182178)--runout local voiceFelLaser = mod:NewVoice(182582)--runout local voiceFelBombDispel = mod:NewVoice(181753) --dispel now local voiceThrowAnzu = mod:NewVoice(179202) --New, 179202,"throw eye to someone with debuff"; 179202h,"throw eye to healer"; 179202m,"throw eye to melee" mod:AddRangeFrameOption(15)--Both aoes are 15 yards, ref 187991 and 181748 mod:AddSetIconOption("SetIconOnAnzu", 179202, false) mod:AddSetIconOption("SetIconOnWinds", 181957, true) mod:AddSetIconOption("SetIconOnFelBomb", 181753, true) mod:AddSetIconOption("SetIconOnAdds", 181873, false, true) mod:AddHudMapOption("HudMapOnChakram", 182178) mod.vb.escapeCount = 0 mod.vb.focusedBlast = 0 mod.vb.savedChakram = nil mod.vb.savedWinds = nil mod.vb.savedWounds = nil mod.vb.savedRiposte = nil mod.vb.windsTargets = 0 mod.vb.bombActive = nil local chakramTargets = {} local playerHasAnzu = false local corruption = GetSpellInfo(181824) local phantasmalFelBomb = GetSpellInfo(179219) local realFelBomb = GetSpellInfo(181753) local darkBindings = GetSpellInfo(185510) local playerName = UnitName("player") local AddsSeen = {} local debuffFilter do debuffFilter = function(uId) if UnitDebuff(uId, corruption) or UnitDebuff(uId, phantasmalFelBomb) or UnitDebuff(uId, realFelBomb) then return true end end end local function updateRangeFrame(self) if not self.Options.RangeFrame then return end --Both spells have same 15 yard range so this makes it easy --Player has either debuff, show everyone if UnitDebuff("player", corruption) or UnitDebuff("player", phantasmalFelBomb) or UnitDebuff("player", realFelBomb) then DBM.RangeCheck:Show(15) else--Show players with either debuff near you. DBM.RangeCheck:Show(15, debuffFilter) end end local function showChakram(self) warnFelChakram:Show(table.concat(chakramTargets, "<, >")) --Chakram is always thrown ranged-->melee-->Tank --Need to determine roles for the hud if not self.Options.HudMapOnChakram then return end local ranged, melee, tank = nil, nil, nil for i = 1, #chakramTargets do local name = chakramTargets[i] local uId = DBM:GetRaidUnitId(name) if not uId then return end--Prevent errors if person leaves group if self:IsMeleeDps(uId) then--Melee melee = chakramTargets[i] DBM:Debug("Melee Chakram found: "..melee, 2) elseif self:IsTanking(uId, "boss1") then--Tank tank = chakramTargets[i] DBM:Debug("Tank Chakram found: "..tank, 2) else--Ranged ranged = chakramTargets[i] DBM:Debug("Ranged Chakram found: "..ranged, 2) end end if ranged and melee and tank then DBM:Debug("All Chakram found!", 2) DBMHudMap:RegisterRangeMarkerOnPartyMember(182178, "party", ranged, 0.65, 6, nil, nil, nil, 0.8, nil, false):Appear():SetLabel(ranged, nil, nil, nil, nil, nil, 0.8, nil, -15, 8, nil) DBMHudMap:RegisterRangeMarkerOnPartyMember(182178, "party", melee, 0.65, 6, nil, nil, nil, 0.8, nil, false):Appear():SetLabel(melee, nil, nil, nil, nil, nil, 0.8, nil, -15, 8, nil) DBMHudMap:RegisterRangeMarkerOnPartyMember(182178, "party", tank, 0.65, 6, nil, nil, nil, 0.8, nil, false):Appear():SetLabel(tank, nil, nil, nil, nil, nil, 0.8, nil, -15, 8, nil) if playerName == melee or playerName == ranged or playerName == tank then--Player in it, Yellow lines DBMHudMap:AddEdge(1, 1, 0, 0.5, 6, ranged, melee, nil, nil, nil, nil) DBMHudMap:AddEdge(1, 1, 0, 0.5, 6, melee, tank, nil, nil, nil, nil) else--Red lines DBMHudMap:AddEdge(1, 0, 0, 0.5, 6, ranged, melee, nil, nil, nil, nil) DBMHudMap:AddEdge(1, 0, 0, 0.5, 6, melee, tank, nil, nil, nil, nil) end end end function mod:OnCombatStart(delay) self.vb.escapeCount = 0 self.vb.focusedBlast = 0 self.vb.savedChakram = nil self.vb.savedWinds = nil self.vb.savedWounds = nil self.vb.savedRiposte = nil self.vb.windsTargets = 0 self.vb.bombActive = nil playerHasAnzu = false table.wipe(AddsSeen) table.wipe(chakramTargets) updateRangeFrame(self) timerChakramCD:Start(5-delay)--Seems still 5 in all modes if self:IsNormal() then--Normal timers are about 40% slower on pull, 20% slower rest of fight timerFelLaserCD:Start(25) timerPhantasmalWindsCD:Start(30-delay) countdownPhantasmalWinds:Start(30-delay) timerPhantasmalWoundsCD:Start(44-delay) else timerPhantasmalWindsCD:Start(16.5-delay) countdownPhantasmalWinds:Start(16.5-delay) timerFelLaserCD:Start(18.5)--Verify it can still be this low, every pull on mythic was 20-22 timerPhantasmalWoundsCD:Start(28-delay) if self:IsMythic() then timerShadowRiposteCD:Start(9.5-delay) end end if self:IsNormal() or self:IsMythic() then berserkTimer:Start(480-delay) else berserkTimer:Start(-delay) end end function mod:OnCombatEnd() if self.Options.RangeFrame then DBM.RangeCheck:Hide() end if self.Options.HudMapOnChakram then DBMHudMap:Disable() end end function mod:SPELL_CAST_START(args) local spellId = args.spellId if spellId == 181912 then self.vb.focusedBlast = self.vb.focusedBlast + 1 specWarnFocusedBlast:Show(self.vb.focusedBlast) if not UnitDebuff("player", corruption) and not UnitDebuff("player", realFelBomb) and not UnitDebuff("player", phantasmalFelBomb) and not UnitDebuff("player", darkBindings) then--Filter debuffs that kill other players voiceFocusedBlast:Play("gather") end timerFocusedBlast:Start() elseif spellId == 181827 or spellId == 187998 then--Both versions of it. I assume the 5 second version is probably LFR/Normal timerFelConduitCD:Start(args.sourceGUID) if playerHasAnzu then--Able to interrupt specWarnFelConduit:Show(args.sourceName) if self:IsHealer() then--It's still on healer that did last dispel, they need to throw to better interruptor, probably tank specWarnThrowAnzu:Show(TANK) voiceThrowAnzu:Play("179202m") --throw to melee (maybe change to throw to tank, in strat i saw, it was best to bounce eye between tank and healer since throwing to tank also made immune to Phantasmal Corruption as added bonus) else voiceFelConduit:Play("kickcast") end else warnFelConduit:Show() end elseif spellId == 181873 then--Air phase start (Shadow Escape) self.vb.escapeCount = self.vb.escapeCount + 1 self.vb.focusedBlast = 0 --Timers pause, save times self.vb.savedChakram = timerChakramCD:GetRemaining() self.vb.savedWinds = timerPhantasmalWindsCD:GetRemaining() self.vb.savedWounds = timerPhantasmalWoundsCD:GetRemaining() if self:IsMythic() then self.vb.savedRiposte = timerShadowRiposteCD:GetRemaining() if self.Options.SetIconOnAdds then self:ScanForMobs(93625, 2, 8, 1, 0.2, 15)--Mythic Add self:ScanForMobs(91543, 2, 7, 1, 0.2, 15)--Bomb Add if self.vb.escapeCount >= 2 then self:ScanForMobs(91541, 2, 6, 1, 0.2, 15)--Construct Add end if self.vb.escapeCount == 3 then self:ScanForMobs(91539, 2, 5, 1, 0.2, 15)--Raven Add end end else if self.Options.SetIconOnAdds then self:ScanForMobs(91543, 2, 8, 1, 0.2, 15)--Bomb Add if self.vb.escapeCount >= 2 then self:ScanForMobs(91541, 2, 7, 1, 0.2, 15)--Construct Add end if self.vb.escapeCount == 3 then self:ScanForMobs(91539, 2, 6, 1, 0.2, 15)--Raven Add end end end --Clear. Sure I could just do GetTime+39 and call it a day, but this is prettier timerChakramCD:Stop() timerPhantasmalWindsCD:Stop() countdownPhantasmalWinds:Cancel() timerPhantasmalWoundsCD:Stop() timerDarkBindingsCD:Stop() timerShadowRiposteCD:Stop() elseif spellId == 185345 and not args:IsSrcTypePlayer() then if playerHasAnzu then specWarnShadowRiposte:Show() else warnShadowRiposte:Show() end end end function mod:SPELL_CAST_SUCCESS(args) local spellId = args.spellId if spellId == 182178 then table.wipe(chakramTargets) timerChakramCD:Start() elseif spellId == 181956 then if self:IsNormal() then timerPhantasmalWindsCD:Start(46) countdownPhantasmalWinds:Start(46) else timerPhantasmalWindsCD:Start() countdownPhantasmalWinds:Start() end elseif spellId == 181912 and self.vb.focusedBlast == 2 then--Air phase over immediately after he finishes casting 2nd blast. --Timers resume with +3-7, sometimes more. Extreme cases I suspect just got delayed by laser or some other channeled spell timerChakramCD:Start(self.vb.savedChakram+3) timerPhantasmalWindsCD:Start(self.vb.savedWinds+5) --countdownPhantasmalWinds:Start(self.vb.savedWinds+5)--no countdown for this one unless made accurate enough timerPhantasmalWoundsCD:Start(self.vb.savedWounds+5) if self:IsMythic() then timerShadowRiposteCD:Start(self.vb.savedRiposte+5) end self.vb.savedChakram = nil self.vb.savedWinds = nil self.vb.savedWounds = nil self.vb.savedRiposte = nil elseif spellId == 185510 then timerDarkBindingsCD:Start(args.sourceGUID) elseif spellId == 185345 and not args:IsSrcTypePlayer() then timerShadowRiposteCD:Start() end end function mod:SPELL_AURA_APPLIED(args) local spellId = args.spellId if spellId == 179202 then--Eye of Anzu! warnEyeofAnzu:Show(args.destName) if self.Options.SetIconOnAnzu then self:SetIcon(args.destName, 1) end if args:IsPlayer() then playerHasAnzu = true --Check for bombs or winds and show action warnings if self.vb.bombActive then if self:IsHealer() then--Can dispel specWarnFelBombDispel:Show(self.vb.bombActive) voiceFelBombDispel:Play("dispelnow") else--Cannot dispel, get eye to a healer asap! specWarnThrowAnzu:Show(HEALER) voiceThrowAnzu:Play("179202h") end elseif self.vb.windsTargets > 0 then specWarnThrowAnzu:Show(GetSpellInfo(181957)) voiceThrowAnzu:Play("179202") else--No bombs or winds, show generic "eye on you" warning specWarnEyeofAnzu:Show() end end elseif spellId == 181957 then warnPhantasmalWinds:CombinedShow(0.3, args.destName) self.vb.windsTargets = self.vb.windsTargets + 1 if args:IsPlayer() then specWarnPhantasmalWinds:Show() yellPhantasmalWinds:Yell() end if self.Options.SetIconOnWinds and not self:IsLFR() then self:SetSortedIcon(0.5, args.destName, 3)--Start at 3 and count up end if playerHasAnzu and self:AntiSpam(3, 1) then specWarnThrowAnzu:Show(args.spellName) voiceThrowAnzu:Play("179202") end elseif spellId == 182325 then warnPhantasmalWounds:CombinedShow(1, args.destName)--It goes out kind of slow if self:AntiSpam(5, 2) then if self:IsNormal() then timerPhantasmalWoundsCD:Start(40) else timerPhantasmalWoundsCD:Start() end end if args:IsPlayer() then specWarnPhantasmalWounds:Show() yellPhantasmalWounds:Yell() end elseif spellId == 181824 or spellId == 187990 then warnPhantasmalCorruption:Show(args.destName) if self:IsNormal() then timerPhantasmalCorruptionCD:Start(21, args.sourceGUID) countdownCorruption:Start(21) else timerPhantasmalCorruptionCD:Start(args.sourceGUID) countdownCorruption:Start() end if args:IsPlayer() then updateRangeFrame(self) specWarnPhantasmalCorruption:Show() yellPhantasmalCorruption:Yell() else if playerHasAnzu then specWarnThrowAnzu:Show(args.destName) voiceThrowAnzu:Play("179202") end end elseif spellId == 179219 then warnPhantasmalFelBomb:CombinedShow(0.3, args.destName) if args:IsPlayer() then updateRangeFrame(self) specWarnPhantasmalFelBomb:Schedule(0.3) yellPhantasmalFelBomb:Schedule(0.3) end elseif spellId == 181753 then self.vb.bombActive = args.destName warnFelBomb:Show(args.destName) if self:IsNormal() then timerFelBombCD:Start(23, args.sourceGUID) countdownFelBomb:Start(23) else timerFelBombCD:Start(args.sourceGUID) countdownFelBomb:Start() end if args:IsPlayer() then updateRangeFrame(self) specWarnPhantasmalFelBomb:Cancel() yellPhantasmalFelBomb:Cancel() specWarnFelBomb:Show() yellFelBomb:Yell() if self.Options.RangeFrame then DBM.RangeCheck:Show(15) end else if playerHasAnzu then if self:IsHealer() then--Can dispel specWarnFelBombDispel:Show(args.destName) voiceFelBombDispel:Play("dispelnow") else--Cannot dispel, get eye to a healer asap! specWarnThrowAnzu:Show(HEALER) voiceThrowAnzu:Play("179202h") end end end if self.Options.SetIconOnFelBomb then self:SetIcon(args.destName, 2) end elseif spellId == 185510 then warnDarkBindings:CombinedShow(0.3, args.destName) if args:IsPlayer() then specWarnDarkBindings:Show() end if playerHasAnzu and self:AntiSpam(3, 3) then specWarnThrowAnzu:Show(args.spellName) voiceThrowAnzu:Play("179202") end elseif spellId == 182178 or spellId == 182200 then chakramTargets[#chakramTargets+1] = args.destName self:Unschedule(showChakram) if #chakramTargets == 3 then showChakram(self) else self:Schedule(0.5, showChakram, self) end if args:IsPlayer() then specWarnFelChakram:Show() voiceFelChakram:Play("runout") yellFelChakram:Yell() end --Check if it's a tank local uId = DBM:GetRaidUnitId(args.destName) if self:IsTanking(uId, "boss1") and not UnitIsUnit("player", uId) then --It is a tank and we're not tanking. Fire taunt warning specWarnFelChakramTank:Show(args.destName) voiceFelChakram:Play("tauntboss") end end end mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED function mod:SPELL_AURA_REMOVED(args) local spellId = args.spellId if spellId == 179202 then if self.Options.SetIconOnAnzu then self:SetIcon(args.destName, 0) end if args:IsPlayer() then playerHasAnzu = false end elseif spellId == 181957 and self.Options.SetIconOnWinds then self.vb.windsTargets = self.vb.windsTargets - 1 self:SetIcon(args.destName, 0) elseif (spellId == 181824 or spellId == 187990) then if args:IsPlayer() then updateRangeFrame(self) end elseif spellId == 179219 then if args:IsPlayer() then updateRangeFrame(self) end elseif spellId == 181753 then self.vb.bombActive = nil if args:IsPlayer() then updateRangeFrame(self) end if self.Options.SetIconOnFelBomb then self:SetIcon(args.destName, 0) end elseif spellId == 182178 or spellId == 182200 then -- if self.Options.HudMapOnChakram then -- DBMHudMap:FreeEncounterMarkerByTarget(182178, args.destName) -- end end end function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId) if spellId == 182600 and destGUID == UnitGUID("player") and self:AntiSpam(2, 4) then specWarnFelLaserGTFO:Show() voiceFelLaser:Play("runaway") end end mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE function mod:RAID_BOSS_WHISPER(msg) if msg:find("spell:182582") then specWarnFelLaser:Show() yellFelLaser:Yell() voiceFelLaser:Play("runout") end end --per usual, use transcriptor message to get messages from both bigwigs and DBM, all without adding comms to this mod at all function mod:CHAT_MSG_ADDON(prefix, msg, channel, targetName) if prefix ~= "Transcriptor" then return end if msg:find("spell:182582") then-- targetName = Ambiguate(targetName, "none") if self:AntiSpam(5, targetName) then--Antispam sync by target name, since this doesn't use dbms built in onsync handler. warnLaser:Show(targetName) end end end function mod:INSTANCE_ENCOUNTER_ENGAGE_UNIT() for i = 1, 5 do local unitGUID = UnitGUID("boss"..i) if unitGUID and not AddsSeen[unitGUID] then AddsSeen[unitGUID] = true local cid = self:GetCIDFromGUID(unitGUID) if cid == 91543 then--Corrupted Talonpriest timerFelBombCD:Start(14, unitGUID) countdownFelBomb:Start(14) elseif cid == 91541 then--Shadowfel Warden timerFelConduitCD:Start(4, unitGUID) elseif cid == 91539 then--Fel Raven timerPhantasmalCorruptionCD:Start(16, unitGUID) countdownCorruption:Start(16) elseif cid == 93625 then--Phantasmal Resonance timerDarkBindingsCD:Start(23.6, unitGUID) end end end end function mod:UNIT_DIED(args) local cid = self:GetCIDFromGUID(args.destGUID) if cid == 91543 then--Corrupted Talonpriest timerFelBombCD:Cancel(args.destGUID) countdownFelBomb:Cancel() elseif cid == 91541 then--Shadowfel Warden timerFelConduitCD:Cancel(args.destGUID) elseif cid == 91539 then--Fel Raven timerPhantasmalCorruptionCD:Cancel(args.destGUID) countdownCorruption:Cancel() elseif cid == 93625 then--Phantasmal Resonance timerDarkBindingsCD:Cancel(args.destGUID) end end function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, _, spellId) if spellId == 182582 or spellId == 184630 then--Fel Incineration if self:IsNormal() then timerFelLaserCD:Start(23) else timerFelLaserCD:Start() end end end
-- Documentation: http://nodemcu.readthedocs.io/en/master/ -- Tutorial: https://github.com/hackhitchin/esp8266-co-uk/blob/master/tutorials/introduction-to-gpio-api.md -- Most of this will be like arduino -- I will coment when something is different pinLed1 = 3 pinButton1 = 1 -- GPIO stands for General Purpose Input/Output gpio.mode(pinLed1, gpio.OUTPUT) gpio.write(pinLed1, gpio.LOW); gpio.mode(pinButton1, gpio.INT, gpio.PULLUP) -- gpio.INT (interrupt mode), everytime it change will call a callback function local ledstate = false local function callback(level, timestamp, eventcount) print(level, timestamp, eventcount) ledstate = not ledstate if(ledstate == true) then gpio.write(pinLed1, gpio.HIGH) else gpio.write(pinLed1, gpio.LOW) end end gpio.trig(pinButton1, "down", callback) -- trig == trigger -- Will watch the pin -- And when it change to the state X -- It will call the callback function -- NOTE: The callback function can receives -- 3 parameters => level, timestamp, eventcount
local _, ns = ... local select = select local tostring = tostring local concat = table.concat local f -- [[ The Copy Window ]] -- local function CreateCopyFrame() f = CreateFrame('Frame', "AbuCopyChatFrame", UIParent) f:SetHeight(220) f:SetBackdropColor(0, 0, 0, 1) f:SetPoint('BOTTOMLEFT', ChatFrame1EditBox, 'TOPLEFT', 3, 10) f:SetPoint('BOTTOMRIGHT', ChatFrame1EditBox, 'TOPRIGHT', -3, 10) f:SetFrameStrata('DIALOG') AbuGlobal.CreateBorder(f, 12) f:SetBackdrop({ bgFile = 'Interface\\DialogFrame\\UI-DialogBox-Background', edgeFile = '', tile = true, tileSize = 16, edgeSize = 16, insets = {left = 3, right = 3, top = 3, bottom = 3 }}) f:Hide() f.t = f:CreateFontString(nil, 'OVERLAY') f.t:SetFont('Fonts\\ARIALN.ttf', 18) f.t:SetPoint('TOPLEFT', f, 8, -8) f.t:SetTextColor(1, 1, 0) f.t:SetShadowOffset(1, -1) f.t:SetJustifyH('LEFT') f.b = CreateFrame('EditBox', nil, f) f.b:SetMultiLine(true) f.b:SetMaxLetters(20000) f.b:SetSize(450, 270) f.b:SetAutoFocus(true) f.b:SetScript('OnEscapePressed', function() f:Hide() end) f.s = CreateFrame('ScrollFrame', '$parentScrollBar', f, 'UIPanelScrollFrameTemplate') f.s:SetPoint('TOPLEFT', f, 'TOPLEFT', 8, -30) f.s:SetPoint('BOTTOMRIGHT', f, 'BOTTOMRIGHT', -30, 8) f.s:SetScrollChild(f.b) f.c = CreateFrame('Button', nil, f, 'UIPanelCloseButton') f.c:SetPoint('TOPRIGHT', f, 'TOPRIGHT', 0, -1) end local function GetChatLines(...) local count, line, lines = 1, nil, {} for i = select('#', ...), 1, -1 do local region = select(i, ...) if (region:GetObjectType() == 'FontString') then line = tostring(region:GetText()) lines[count] = line:gsub("(|TInterface(.*)|t)", "") count = count + 1 end end return count - 1, lines end -- [[ Getting the Text ]] -- local function copyChat(self) local chat = _G[self:GetName()] local _, fontSize = chat:GetFont() FCF_SetChatWindowFontSize(self, chat, 0.1) local lineCount, lines = GetChatLines(chat:GetRegions()) FCF_SetChatWindowFontSize(self, chat, fontSize) if (lineCount > 0) then if not f then CreateCopyFrame() end ToggleFrame(f) f.t:SetText(chat:GetName()) local f1, f2, f3 = ChatFrame1:GetFont() f.b:SetFont(f1, f2, f3) local text = concat(lines, '\n', 1, lineCount) f.b:SetText(text) end end -- [[ Creating Buttons ]] -- table.insert(ns.onInit, function(self) self.Copy = CreateFrame('Button', self:GetName()..'CopyChatButton', _G[self:GetName()]) self.Copy:SetSize(20, 20) self.Copy:SetPoint('TOPRIGHT', self, -5, -5) self.Copy:SetNormalTexture('Interface\\AddOns\\AbuEssentials\\Textures\\Chat\\textureCopyNormal') self.Copy:GetNormalTexture():SetSize(20, 20) self.Copy:SetHighlightTexture('Interface\\AddOns\\AbuEssentials\\Textures\\Chat\\textureCopyHighlight') self.Copy:GetHighlightTexture():SetAllPoints(self.Copy:GetNormalTexture()) local tab = _G[self:GetName()..'Tab'] hooksecurefunc(tab, 'SetAlpha', function() self.Copy:SetAlpha(tab:GetAlpha()*0.55) end) self.Copy:SetScript('OnMouseDown', function(self) self:GetNormalTexture():ClearAllPoints() self:GetNormalTexture():SetPoint('CENTER', 1, -1) end) self.Copy:SetScript('OnMouseUp', function() self.Copy:GetNormalTexture():ClearAllPoints() self.Copy:GetNormalTexture():SetPoint('CENTER') if (self.Copy:IsMouseOver()) then copyChat(self) end end) end)
ValueSquare = Object:extend() function ValueSquare:new() self.valueVertices = {} for _ = 1, 4 do self:addVertex(0, 0, 0) end end function ValueSquare:addVertex(value, x, y) local valueVertex = { value = value, x = x, y = y } table.insert(self.valueVertices, valueVertex) end function ValueSquare:replaceVertex(pos, value, x, y) local valueVertix if (type(value) == "number") then valueVertex = { value = value or 0, x = x, y = y} elseif (type(value) == "table") then valueVertex = { value = value[1] or 0, x = value[2], y = value[3]} end self.valueVertices[pos] = valueVertex end function ValueSquare:empty() for i,v in ipairs(self.valueVertices) do if not (v.value == 0) then return false end end return true end function ValueSquare:intraprolated(middleValue) if not (self.valueVertices[1].value + self.valueVertices[2].value + self.valueVertices[3].value + self.valueVertices[4].value < 0.5) then local values = isoValueIntraprolation(self.valueVertices[1], self.valueVertices[2], self.valueVertices[3], self.valueVertices[4], middleValue) local triangleVertices = {} for i = 1, 4 do if not (values[i*2-i%2] == 1/0) then table.insert(triangleVertices, {values[i*2-1], values[i*2]}) end end if (#triangleVertices == 0) then if (self.valueVertices[1].value >= 0.5 and self.valueVertices[2].value >= 0.5 and self.valueVertices[3].value >= 0.5 and self.valueVertices[4].value >= 0.5) then return {{self.valueVertices[1].x, self.valueVertices[1].y}, {self.valueVertices[2].x, self.valueVertices[2].y}, {self.valueVertices[3].x, self.valueVertices[3].y}, {self.valueVertices[1].x, self.valueVertices[1].y}, {self.valueVertices[4].x, self.valueVertices[4].y}, {self.valueVertices[3].x, self.valueVertices[3].y}} end return {} elseif (#triangleVertices == 3) then for i = 1, 3 do if (triangleVertices[i][1] == triangleVertices[i%3 + 1][1]) then table.remove(triangleVertices, i%3 + 1) break end end end for i, vertex in ipairs(self.valueVertices) do if (vertex.value >= 0.5) then table.insert(triangleVertices, {vertex.x, vertex.y}) for j = i + 1, #self.valueVertices do local vertex2 = self.valueVertices[j] if (vertex2.value >= 0.5) then table.insert(triangleVertices, triangleVertices[#triangleVertices-1]) if (j + i == 3) then triangleVertices[#triangleVertices] = triangleVertices[1] end table.insert(triangleVertices, triangleVertices[#triangleVertices-1]) table.insert(triangleVertices, {vertex2.x, vertex2.y}) for k = j + 1, #self.valueVertices do local vertex3 = self.valueVertices[k] if (vertex3.value >= 0.5) then if (i + j + k == 9) then triangleVertices[6] = {vertex3.x, vertex3.y} elseif (i + j + k == 7) then triangleVertices[3] = {vertex3.x, vertex3.y} triangleVertices[5] = {vertex3.x, vertex3.y} elseif (i + j + k == 6) then triangleVertices[6] = {vertex3.x, vertex3.y} end table.insert(triangleVertices, {vertex.x, vertex.y}) table.insert(triangleVertices, {vertex2.x, vertex2.y}) table.insert(triangleVertices, {vertex3.x, vertex3.y}) break end end break end end break end end if (#triangleVertices%3 == 0) then return triangleVertices end end return {} end function isoValueIntraprolation(valueVertex1, valueVertex2, valueVertex3, valueVertex4, middleValue) local function linearIntraprolation(valueVertex1, valueVertex2) local intraValue = (middleValue - valueVertex1.value)/(valueVertex2.value - valueVertex1.value) local intraprolatedX = valueVertex1.x + (valueVertex2.x - valueVertex1.x)*intraValue local intraprolatedY = valueVertex1.y + (valueVertex2.y - valueVertex1.y)*intraValue return intraprolatedX, intraprolatedY end local intraX1, intraY1 = linearIntraprolation(valueVertex1, valueVertex2) local intraX2, intraY2 = linearIntraprolation(valueVertex2, valueVertex3) local intraX3, intraY3 = linearIntraprolation(valueVertex3, valueVertex4) local intraX4, intraY4 = linearIntraprolation(valueVertex1, valueVertex4) if (intraX1 < valueVertex1.x or intraX1 > valueVertex2.x) then intraX1 = 1/0 end if (intraY2 < valueVertex2.y or intraY2 > valueVertex3.y) then intraY2 = 1/0 end if (intraX3 < valueVertex4.x or intraX3 > valueVertex3.x) then intraX3 = 1/0 end if (intraY4 < valueVertex1.y or intraY4 > valueVertex4.y) then intraY4 = 1/0 end return {intraX1, valueVertex1.y, valueVertex2.x, intraY2, intraX3, valueVertex3.y, valueVertex4.x, intraY4} end
Inherit = 'PageView' OnNext = function(self) for k, v in pairs(self.Bedrock.SettingsValues) do self.Bedrock.Settings[k] = v end System.AnimateShutdown(true, true) end
local AddonName, Addon = ... local string = string local strsplit = strsplit local tonumber = tonumber local UnitGUID = UnitGUID local GetItemInfo = GetItemInfo Addon.Frames = {} Addon.Functions = {} Addon.Util = {} Addon.Events = CreateFrame("Frame") Addon.Events:SetScript("OnEvent", function(self, event, ...) if not self[event] then return end self[event](self, ...) end) -- Given an itemLink it returns the relative itemString function Addon.Util.GetItemStringFromItemLink(itemLink) local itemString = string.match(itemLink, "item[(%-?%d):]+") return itemString end -- local itemID = string.match(text, "item:(%d+):") -- Given an itemLink it returns the relative itemID as a number function Addon.Util.GetItemIdFromItemLink(itemLink) --local itemID = string.find(itemLink, "item:(%d+):") local _, _, _, _, Id = string.find(itemLink, "|?c?f?f?(%x*)|?H?([^:]*):?(%d+):?(%d*):?(%d*):?(%d*):?(%d*):?(%d*):?(%-?%d*):?(%-?%d*):?(%d*):?(%d*):?(%-?%d*)|?h?%[?([^%[%]]*)%]?|?h?|?r?") return tonumber(Id) end -- return the id of the targeted npc function Addon.Util.GetNPCId() local guid = UnitGUID("target") local _, _, _, _, _, npc_id= strsplit("-",guid) return tonumber(npc_id) end function Addon.Util.GetItemLinkFromId(itemID) _, itemLink = GetItemInfo(itemID) return itemLink end
--- libdas: DENG asset management library --- licence: Apache, see LICENCE file --- file: libdas.lua - libdas library build configuration --- author: Karl-Mihkel Ott local Libdas = {} function Libdas.build() project "das" kind "SharedLib" language "C++" cppdialect "C++17" files { "include/*", "src/*.cpp", } -- Most of these files are for legacy references -- removefiles { "src/DASTool.cpp", "src/GLTFCompiler.cpp" -- This list is incomplete, you can help by expanding it :))) } configuration "vs2019" defines { "LIBDAS_EXPORT_LIBRARY" } end return Libdas
local config = dofile 'ffvii-config.lua' dofile 'ffvii-util.lua' local MATERIA_REVIVE = 0x37 local function getCharacterWithRevive(game_context) for party_index = 0,2 do local character_index = game_context.party[party_index].id for materia_index = 0,15 do if mainmemory.read_u8(0x09C738 + (character_index * 0x84) + 0x40 + (materia_index * 4)) == MATERIA_REVIVE then if game_context.party[party_index].current_hp > 0 then return party_index end end end end return nil end ReviveCharacterState = State:new() function ReviveCharacterState:needToRun(game_context, bot_context, keys) bot_context.party_member_to_revive = nil if game_context.battle.is_in_battle then return false end for party_index = 0,2 do local character = game_context.party[party_index] if character.current_hp == 0 then -- make sure we have someone who can cast revive local p = getCharacterWithRevive(game_context) if p ~= nil then bot_context.party_member_to_revive = party_index return true end end end return false end function ReviveCharacterState:writeText(game_context, bot_context) gui.text(0, 0, "revive character") end function ReviveCharacterState:run(game_context, bot_context, keys) -- a party member needs to have the "RESTORE" materia, otherwise we can't do anything local p = getCharacterWithRevive(game_context) if p == nil or game_context.party[p].current_mp < 5 then -- TODO: travel to town and buy items ?? return end if not game_context.menu.is_in_menu then pressAndRelease(bot_context, keys, "Triangle") elseif game_context.menu.main_menu_index < 1 then pressAndRelease(bot_context, keys, "Down") elseif game_context.menu.main_menu_index > 1 then pressAndRelease(bot_context, keys, "Up") elseif game_context.menu.active_menu_page == 0 and not game_context.menu.is_selecting_character then pressAndRelease(bot_context, keys, "Circle") elseif game_context.menu.is_selecting_character and game_context.menu.selected_character_index < p then pressAndRelease(bot_context, keys, "Down") elseif game_context.menu.is_selecting_character and game_context.menu.selected_character_index > p then pressAndRelease(bot_context, keys, "Up") elseif game_context.menu.is_selecting_character and game_context.menu.selected_character_index == p then pressAndRelease(bot_context, keys, "Circle") elseif game_context.menu.active_menu_page == 2 and game_context.menu.magic_submenu == 0 then pressAndRelease(bot_context, keys, "Circle") elseif game_context.menu.active_menu_page == 2 and game_context.menu.magic_submenu == 2 then local life_spell_index = 3 if game_context.menu.magic_spell_y * 3 + game_context.menu.magic_spell_x < life_spell_index then pressAndRelease(bot_context, keys, "Right") elseif game_context.menu.magic_spell_y * 3 + game_context.menu.magic_spell_x > life_spell_index then pressAndRelease(bot_context, keys, "Left") else pressAndRelease(bot_context, keys, "Circle") end elseif game_context.menu.active_menu_page == 2 and game_context.menu.magic_submenu == 1 then if game_context.menu.magic_selected_character_index < bot_context.party_member_to_revive then pressAndRelease(bot_context, keys, "Down") elseif game_context.menu.magic_selected_character_index > bot_context.party_member_to_revive then pressAndRelease(bot_context, keys, "Up") else pressAndRelease(bot_context, keys, "Circle") end end end
local app = app local libcore = require "core.libcore" local Env = require "Env" local Class = require "Base.Class" local ViewControl = require "Unit.ViewControl" local Scales = require "core.Quantizer.Scales" local ply = app.SECTION_PLY local PitchCircle = Class {} PitchCircle:include(ViewControl) function PitchCircle:init(args) local name = args.name or app.logError("%s.init: name is missing.", self) local width = args.width or (2 * ply) local quantizer = args.quantizer or app.logError("%s.init: quantizer is missing.", self) ViewControl.init(self, name) self:setClassName("PitchCircle") local graphic graphic = app.Graphic(0, 0, width, 64) self.pDisplay = libcore.PitchCircle(0, 0, width, 64) graphic:addChild(self.pDisplay) self:setMainCursorController(self.pDisplay) self:setControlGraphic(graphic) -- add spots for i = 1, (width // ply) do self:addSpotDescriptor{ center = (i - 0.5) * ply } end -- sub display self.subGraphic = app.Graphic(0, 0, 128, 64) self.scaleList = app.SlidingList(0, 0, 88, 64) self.subGraphic:addChild(self.scaleList) self.notesList = app.SlidingList(88, 0, 40, 64) self.subGraphic:addChild(self.notesList) self:refreshScales() self:setQuantizer(quantizer) end function PitchCircle:refreshScales() local selectedText = self.scaleList:selectedText() local selectedIndex = self.notesList:selectedIndex() self.scaleList:clear() self.notesList:clear() local order = Scales.getKeys() for i, name in ipairs(order) do local scale = Scales.getScale(name) if scale and #scale > 0 then self.scaleList:add(name) self.notesList:add(#scale) end end if self.scaleList:select(selectedText) then self.notesList:select(selectedIndex) end end function PitchCircle:setQuantizer(q) self.pDisplay:setQuantizer(q) self.quantizer = q self:loadBuiltinScale(self.scaleList:selectedText()) end function PitchCircle:loadScalaFile(filename) if self.quantizer and filename then self.quantizer:loadScalaFile(filename) end end function PitchCircle:serialize() local t = ViewControl.serialize(self) t.selectedScale = self.scaleList:selectedText() return t end function PitchCircle:deserialize(t) ViewControl.deserialize(self, t) if t.selectedScale then if self.scaleList:select(t.selectedScale) then self.notesList:select(self.scaleList:selectedIndex()) self:loadBuiltinScale(t.selectedScale) else app.logInfo("%s.deserialize:invalid scale:%s ", self, t.selectedScale) end else app.logInfo("%s.deserialize:selectedScale missing", self) end end function PitchCircle:loadBuiltinScale(name) if self.quantizer and name then local scale = Scales.getScale(name) if scale then local quantizer = self.quantizer quantizer:beginScale() for i, pitch in ipairs(scale) do quantizer:addPitch(pitch) end quantizer:endScale() end end end function PitchCircle:onFocused() self:refreshScales() end local threshold = Env.EncoderThreshold.SlidingList function PitchCircle:encoder(change, shifted) self.notesList:encoder(change, shifted, threshold) if self.scaleList:encoder(change, shifted, threshold) and self.quantizer then self:loadBuiltinScale(self.scaleList:selectedText()) end return true end return PitchCircle
local taskContinueTip = require(ViewPath.."hall/task/taskContinueTip"); require("hall/recharge/data/rechargeDataInterface"); TaskContinueTip = class(CommonGameLayer,false); TaskContinueTip.s_controls= { root = 0; subView = 1; bg = 2; numText = 3; nameText = 4; rewardImage = 5; okBtn = 6; closeBtn = 7; } TaskContinueTip.ctor = function(self,data) super(self,taskContinueTip); self.m_ctrl = self.s_controls; self:setFillParent(true,true); self:addToRoot(); self:setLevel(100); self.m_data = data; self:findViews(); self:init(); end TaskContinueTip.dtor = function(self) self.m_data = nil; end TaskContinueTip.findViews = function(self) self.m_subView = self:findViewById(self.m_ctrl.subView); self.m_subView:setTransparency(0); self.m_bg = self:findViewById(self.m_ctrl.bg); self.m_numText = self:findViewById(self.m_ctrl.numText); self.m_nameText = self:findViewById(self.m_ctrl.nameText); self.m_rewardImage = self:findViewById(self.m_ctrl.rewardImage); self.m_okBtn = self:findViewById(self.m_ctrl.okBtn); self.m_closeBtn = self:findViewById(self.m_ctrl.closeBtn); end TaskContinueTip.init = function(self) if not table.isEmpty(self.m_data) then local continueInfos = TaskRewardDataInterface.getInstance():getContinueInfos(); local continueConfig = table.verify(continueInfos.config); local awardItemName = table.verify(RechargeDataInterface.getInstance():getGoodInfoByTypeId(self.m_data.type)).item_name or "奖励"; if self.m_data.type == 0 then awardItemName = "银币"; elseif self.m_data.type == 2 then awardItemName = "钻石"; end local ratio = self.m_data.ratio or 1; local awardItemNum = tonumber(self.m_data.award)*tonumber(ratio); --获得个数 if self.m_data.continue_days and continueConfig[tostring(self.m_data.continue_days)] then local imagePath = continueConfig[tostring(self.m_data.continue_days)].icon or "";--获得图片链接 ImageCache.getInstance():request(imagePath or "",self,self.onUpdateRewardIconImage);--下载图片 end local tempText; if self.m_data.continue_days and tostring(self.m_data.continue_days) == "0" then tempText = "满月"; else --todo tempText = string.concat(self.m_data.continue_days or "7","天"); end self.m_numText:setText(string.concat("恭喜你连续签到 ",tempText)); self.m_nameText:setText(string.concat(awardItemName,"",awardItemNum)); end end TaskContinueTip.onUpdateRewardIconImage = function(self,url,imagePath) if imagePath then self.m_rewardImage:setFile(imagePath); self.m_imagePath = imagePath; end end TaskContinueTip.onCloseClick = function(self) if self.m_data.type == 0 or self.m_data.type == 1 or self.m_data.type == 2 then AnimManager.getInstance():playAnim(AnimIds.MoneyDropPar, 100); else --播放飞向背包的动画 local _x,_y = self.m_rewardImage:getAbsolutePos(); local _absPos = {x=_x,y=_y }; local _image = self.m_imagePath; if _absPos and (_image and _image ~= "") then local _class = require("hall/animation/animBackpack"); local _param = {image = _image,startPos = _absPos}; local ani = new(_class,_param); ani:play(); end end delete(self);--props end TaskContinueTip.onBgTouch = function(self) end TaskContinueTip.s_controlConfig = { [TaskContinueTip.s_controls.subView]={"subView"}; [TaskContinueTip.s_controls.bg]={"bg"}; [TaskContinueTip.s_controls.numText]={"bg","numText"}; [TaskContinueTip.s_controls.nameText]={"bg","nameText"}; [TaskContinueTip.s_controls.rewardImage]={"bg","Image1","rewardImage"}; [TaskContinueTip.s_controls.okBtn]={"bg","okBtn"}; [TaskContinueTip.s_controls.closeBtn]={"bg","closeBtn"}; } TaskContinueTip.s_controlFuncMap = { [TaskContinueTip.s_controls.okBtn]=TaskContinueTip.onCloseClick; [TaskContinueTip.s_controls.closeBtn]=TaskContinueTip.onCloseClick; [TaskContinueTip.s_controls.bg]=TaskContinueTip.onBgTouch; }
-- Minetest 0.4 mod: vessels -- See README.txt for licensing and other information. minetest.register_node("vessels:glass_bottle", { description = "Glass Bottle (empty)", drawtype = "plantlike", tiles = {"vessels_glass_bottle.png"}, inventory_image = "vessels_glass_bottle_inv.png", wield_image = "vessels_glass_bottle.png", paramtype = "light", walkable = false, selection_box = { type = "fixed", fixed = {-0.25, -0.5, -0.25, 0.25, 0.4, 0.25} }, groups = {vessel=1,dig_immediate=3,attached_node=1}, sounds = default.node_sound_glass_defaults(), }) minetest.register_craft( { output = "vessels:glass_bottle 10", recipe = { { "default:glass", "", "default:glass" }, { "default:glass", "", "default:glass" }, { "", "default:glass", "" } } }) minetest.register_node("vessels:drinking_glass", { description = "Drinking Glass (empty)", drawtype = "plantlike", tiles = {"vessels_drinking_glass.png"}, inventory_image = "vessels_drinking_glass_inv.png", wield_image = "vessels_drinking_glass.png", paramtype = "light", walkable = false, selection_box = { type = "fixed", fixed = {-0.25, -0.5, -0.25, 0.25, 0.4, 0.25} }, groups = {vessel=1,dig_immediate=3,attached_node=1}, sounds = default.node_sound_glass_defaults(), }) minetest.register_craft( { output = "vessels:drinking_glass 14", recipe = { { "default:glass", "", "default:glass" }, { "default:glass", "", "default:glass" }, { "default:glass", "default:glass", "default:glass" } } }) minetest.register_node("vessels:steel_bottle", { description = "Heavy Steel Bottle (empty)", drawtype = "plantlike", tiles = {"vessels_steel_bottle.png"}, inventory_image = "vessels_steel_bottle_inv.png", wield_image = "vessels_steel_bottle.png", paramtype = "light", walkable = false, selection_box = { type = "fixed", fixed = {-0.25, -0.5, -0.25, 0.25, 0.4, 0.25} }, groups = {vessel=1,dig_immediate=3,attached_node=1}, sounds = default.node_sound_defaults(), }) minetest.register_craft( { output = "vessels:steel_bottle 5", recipe = { { "default:steel_ingot", "", "default:steel_ingot" }, { "default:steel_ingot", "", "default:steel_ingot" }, { "", "default:steel_ingot", "" } } }) -- Make sure we can recycle them minetest.register_craftitem("vessels:glass_fragments", { description = "Pile of Glass Fragments", inventory_image = "vessels_glass_fragments.png", }) minetest.register_craft( { type = "shapeless", output = "vessels:glass_fragments", recipe = { "vessels:glass_bottle", "vessels:glass_bottle", }, }) minetest.register_craft( { type = "shapeless", output = "vessels:glass_fragments", recipe = { "vessels:drinking_glass", "vessels:drinking_glass", }, }) minetest.register_craft({ type = "cooking", output = "default:glass", recipe = "vessels:glass_fragments", }) minetest.register_craft( { type = "cooking", output = "default:steel_ingot", recipe = "vessels:steel_bottle", })
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --Children folder includes includeFile("static/structure/tatooine/jawa/serverobjects.lua") -- Server Objects includeFile("static/structure/tatooine/antenna_tatt_style_1.lua") includeFile("static/structure/tatooine/antenna_tatt_style_2.lua") includeFile("static/structure/tatooine/beam_tatooine_overhead_style_01.lua") includeFile("static/structure/tatooine/beam_tatooine_overhead_style_02.lua") includeFile("static/structure/tatooine/bridge_tatooine_small_style_01.lua") includeFile("static/structure/tatooine/bridge_tatooine_small_style_02.lua") includeFile("static/structure/tatooine/bridge_tatooine_small_style_03.lua") includeFile("static/structure/tatooine/concrete_slab_tatooine_16x8.lua") includeFile("static/structure/tatooine/debris_tatt_crate_1.lua") includeFile("static/structure/tatooine/debris_tatt_crate_metal_1.lua") includeFile("static/structure/tatooine/debris_tatt_drum_dented_1.lua") includeFile("static/structure/tatooine/debris_tatt_drum_storage_1.lua") includeFile("static/structure/tatooine/debris_tatt_drum_storage_2.lua") includeFile("static/structure/tatooine/debris_tatt_pipe_dual_unconnected.lua") includeFile("static/structure/tatooine/debris_tatt_pipe_narrow_1.lua") includeFile("static/structure/tatooine/debris_tatt_pipe_narrow_2.lua") includeFile("static/structure/tatooine/debris_tatt_pipe_widemouth.lua") includeFile("static/structure/tatooine/debris_tatt_radar_dish.lua") includeFile("static/structure/tatooine/guild_ball_free_style_01.lua") includeFile("static/structure/tatooine/guild_banner_free_style_01.lua") includeFile("static/structure/tatooine/guild_statue_free_style_01.lua") includeFile("static/structure/tatooine/luke_farm_dome.lua") includeFile("static/structure/tatooine/luke_farm_garage.lua") includeFile("static/structure/tatooine/orchard_tatooine_style_01.lua") includeFile("static/structure/tatooine/orchard_tatooine_style_02.lua") includeFile("static/structure/tatooine/palette_tatooine_style_01.lua") includeFile("static/structure/tatooine/pillar_damaged_large_style_01.lua") includeFile("static/structure/tatooine/pillar_pristine_large_style_01.lua") includeFile("static/structure/tatooine/pillar_pristine_small_style_01.lua") includeFile("static/structure/tatooine/pillar_pristine_tall_style_01.lua") includeFile("static/structure/tatooine/pillar_ruined_large_style_01.lua") includeFile("static/structure/tatooine/pillar_ruined_small_style_01.lua") includeFile("static/structure/tatooine/pillar_watto_junkshop.lua") includeFile("static/structure/tatooine/planter_hanging_style_01.lua") includeFile("static/structure/tatooine/planter_window_style_01.lua") includeFile("static/structure/tatooine/shed_junkshop_watto.lua") includeFile("static/structure/tatooine/skeleton_greater_krayt_head.lua") includeFile("static/structure/tatooine/skeleton_greater_krayt_spine_large.lua") includeFile("static/structure/tatooine/skeleton_greater_krayt_spine_medium.lua") includeFile("static/structure/tatooine/skeleton_greater_krayt_spine_small.lua") includeFile("static/structure/tatooine/skeleton_krayt_arm_style_01.lua") includeFile("static/structure/tatooine/skeleton_krayt_arm_style_02.lua") includeFile("static/structure/tatooine/skeleton_krayt_foot.lua") includeFile("static/structure/tatooine/skeleton_krayt_head_style_01.lua") includeFile("static/structure/tatooine/skeleton_krayt_head_style_02.lua") includeFile("static/structure/tatooine/skeleton_krayt_leg_style_01.lua") includeFile("static/structure/tatooine/skeleton_krayt_leg_style_02.lua") includeFile("static/structure/tatooine/skeleton_krayt_ribcage.lua") includeFile("static/structure/tatooine/skeleton_krayt_tail.lua") includeFile("static/structure/tatooine/stair_tatooine_large_style_01.lua") includeFile("static/structure/tatooine/stair_tatooine_large_style_02.lua") includeFile("static/structure/tatooine/stair_tatooine_small_style_01.lua") includeFile("static/structure/tatooine/stair_tatooine_small_style_02.lua") includeFile("static/structure/tatooine/stone_hovel_tatooine_style_01.lua") includeFile("static/structure/tatooine/streetsign_upright_style_01.lua") includeFile("static/structure/tatooine/streetsign_wall_style_01.lua") includeFile("static/structure/tatooine/tato_imprv_bannerpole_s01.lua") includeFile("static/structure/tatooine/tato_imprv_flagpole_s01.lua") includeFile("static/structure/tatooine/tent_house_tatooine_style_01.lua") includeFile("static/structure/tatooine/wall_archway_tatooine_large_style_01.lua") includeFile("static/structure/tatooine/wall_archway_tatooine_wide_style_01.lua") includeFile("static/structure/tatooine/wall_cleft_tatooine_large_style_01.lua") includeFile("static/structure/tatooine/wall_damaged_tatooine_large_style_01.lua") includeFile("static/structure/tatooine/wall_gate_tatooine_style_01.lua") includeFile("static/structure/tatooine/wall_gate_tatooine_style_02.lua") includeFile("static/structure/tatooine/wall_gate_tatooine_style_03.lua") includeFile("static/structure/tatooine/wall_gate_tatooine_wide_style_01.lua") includeFile("static/structure/tatooine/wall_junkshop_watto.lua") includeFile("static/structure/tatooine/wall_pristine_tatooine_large_style_01.lua") includeFile("static/structure/tatooine/wall_pristine_tatooine_large_style_02.lua") includeFile("static/structure/tatooine/wall_pristine_tatooine_small_style_01.lua") includeFile("static/structure/tatooine/wall_pristine_tatooine_tall_style_01.lua") includeFile("static/structure/tatooine/wall_ruined_tatooine_large_style_01.lua") includeFile("static/structure/tatooine/wall_ruined_tatooine_large_style_02.lua") includeFile("static/structure/tatooine/wall_ruined_tatooine_small_style_01.lua")
function normal(shader, t_base, t_second, t_detail) shader:begin ("combine_1", "combine_volumetric") : fog (false) : zb (false, false) : blend (true, blend.one, blend.one) -- : aref (true, 0) -- enable to save bandwith? : sorting (2, false) shader:sampler ("s_vollight") :texture("$user$volumetric") shader:sampler ("s_tonemap") :texture("$user$tonemap") end
require "/lib/stardust/sync.lua" function init() sync.poll("getInfo", onRecvInfo) widget.focus("filter") end function update() sync.runQueue() end function onRecvInfo(rpc) if rpc:succeeded() then local res = rpc:result() widget.setText("filter", res.filter) widget.setText("priority", res.priority .. "") end end function next(wid) widget.focus("priority") end function apply() sync.msg("setInfo", widget.getText("filter"), tonumber(widget.getText("priority")) or 0) pane.dismiss() -- might as well end
-- AutoTouchPlus installation script, simply run to install AutoTouchPlus! -- TODO: Download from releases instead of from GitHub raw content -- You can change the version below to download another version if you want. ----------------------------------------- -- AUTOTOUCHPLUS_VERSION = '0.4.0' ----------------------------------------- -- local BASE_URL = "https://github.com/sentrip/AutoTouchPlus/releases/download/v"..AUTOTOUCHPLUS_VERSION..'/' local BASE_URL = "https://raw.githubusercontent.com/sentrip/AutoTouchPlus/master/" -- Check that cURL is installed local _fcheck = io.popen('dpkg-query -W curl') local curl_not_installed = _fcheck:read('*a') == '' _fcheck:close() assert(not curl_not_installed, 'cURL required to install AutoTouchPlus (install cURL in Cydia)') -- Download fresh copy of a file from GitHub function get(name) local pth = string.format('%s/%s', rootDir(), name):gsub('/+', '/') io.popen("if test -f "..pth.." ; then rm "..pth.."; fi;"):close() io.popen(table.concat({"curl", "-sk", "-o", pth, BASE_URL..name}, " ")):close() end -- Download AutoTouchPlus.lua and tests.lua - errors if fails local failed = false for _, name in pairs{"AutoTouchPlus.lua", "tests.lua"} do local s, r = pcall(get, name) if not s then failed = true alert(r) end end -- Install was successful if not failed then alert("Installation successful!\nNow run tests.lua to check if everything works, and you're ready to go!") end
local M = {} local filter = require "make4ht-filter" local mkutils = require "mkutils" local log = logging.new "staticsite" -- get the published file name local function get_slug(settings) local published_name = mkutils.remove_extension(settings.tex_file) .. ".published" local config = get_filter_settings "staticsite" local file_pattern = config.file_pattern or "%Y-%m-%d-${input}" local time = os.time() -- we must save the published date, so the subsequent compilations at different days -- use the same name if mkutils.file_exists(published_name) then local f = io.open(published_name, "r") local readtime = f:read("*line") time = tonumber(readtime) log:info("Already pubslished", os.date("%Y-%m-%d %H:%M", time)) f:close() else -- escape -- slug must contain the unescaped input name local f = io.open(published_name, "w") f:write(time) f:close() end -- set the updated and publishing times local updated -- the updated time will be set only when it is more than one day from the published time local newtime = os.time() if (newtime - time) > (24 * 3600) then updated = newtime end filter_settings "staticsite" { header = { time = time, updated = updated } } -- make the output file name in the format YYYY-MM-DD-old-filename.html local slug = os.date(file_pattern,time) % settings return slug end -- it is necessary to set correct -jobname in latex_par parameters field -- in order to the get correct HTML file name local function update_jobname(slug, latex_par) local latex_par = latex_par or "" if latex_par:match("%-jobname") then local firstchar=latex_par:match("%-jobname=.") local replace_pattern="%-jobname=[^%s]+" if firstchar == "'" or firstchar=='"' then replace_pattern = "%-jobname=".. firstchar .."[^%"..firstchar.."]+" end return latex_par:gsub(replace_pattern, "-jobname=".. slug) else return latex_par .. "-jobname="..slug end end -- execute the function passed as parameter only once, when the file matching -- starts local function insert_filter(make, pattern, fn) local insert_executed = false table.insert(make.matches, 1, { pattern=pattern, params = {}, command = function() if not insert_executed then fn() end insert_executed = true end }) end local function remove_maketitle(make) -- use DOM filter to remove \maketitle block local domfilter = require "make4ht-domfilter" local process = domfilter { function(dom) local maketitles = dom:query_selector(".maketitle") for _, el in ipairs(maketitles) do log:debug("removing maketitle") el:remove_node() end return dom end } make:match("html$", process) end local function copy_files(filename, par) local function prepare_path(dir, subdir) local path = dir .. "/" .. subdir .. "/" .. filename return path:gsub("//", "/") end -- get extension settings local site_settings = get_filter_settings "staticsite" local site_root = site_settings.site_root or "./" local map = site_settings.map or {} -- default path without subdir, will be used if the file is not matched -- by any pattern in the map local path = prepare_path(site_root, "") for pattern, destination in pairs(map) do if filename:match(pattern) then path = prepare_path(site_root, destination) break end end -- it is possible to use string extrapolation in path, for example for slug mkutils.copy(filename, path % par) end function M.modify_build(make) -- it is necessary to insert the filters for YAML header and file copying as last matches -- we use an bogus match which will be executed only once as the very first one to insert -- the filters -- I should make filter from this local process = filter { "staticsite" } -- detect if we should remove maketitle local site_settings = get_filter_settings "staticsite" -- \maketitle is removed by default, set `remove_maketitle=false` setting to disable that if site_settings.remove_maketitle ~= false then remove_maketitle(make) end local settings = make.params -- get the published file name local slug = get_slug(settings) for _, cmd in ipairs(make.build_seq) do -- all commands must use the published file name cmd.params.input = slug cmd.params.latex_par = update_jobname(slug, cmd.params.latex_par) end local quotepattern = '(['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..'])' local mainfile = string.gsub(slug, quotepattern, "%%%1") -- run the following code once in the first match on the first file insert_filter(make, ".*", function() -- for _, match in ipairs(make.matches) do -- match.params.outdir = outdir -- print(match.pattern, match.params.outdir) -- end make:match("html?$", process) make:match(".*", copy_files, {slug=slug}) end) return make end return M
local BaseGroup = {} -- BaseGroup.metatable = {__index = BaseGroup} function BaseGroup:new(player) local group = { player = player, surface = true, group_members = {}, group_position = {x = 0, y = 0}, created_tick = game.tick, last_update_tick = 0, last_attack_tick = 0, } setmetatable(group, {__index = BaseGroup}) return group end function BaseGroup:add_member(entity) if not self:has_members() then self.surface = entity.surface self.group_position = entity.position end self.group_members[entity.unit_number] = entity self.last_update_tick = game.tick end function BaseGroup:remove_member(entity) self.group_members[entity.unit_number] = nil if not self:has_members() then self.player.print({"messages.group-destroyed", entity.name, string.format("[gps= %d, %d]", self.group_position.x, self.group_position.y)}) end self.last_update_tick = game.tick end function BaseGroup:get_group_position() local count = 0 local position = {x = 0, y = 0} for _, member in pairs(self.group_members) do position.x = position.x + member.position.x position.y = position.y + member.position.y count = count + 1 end self.group_position = {x = (position.x / count), y = (position.y / count)} return self.group_position end function BaseGroup:get_member_count() local count = 0 for _, member in pairs (self.group_members) do if member.valid then count = count + 1 end end return count end function BaseGroup:has_members() if not next(self.group_members) then return false end return true end return BaseGroup
-- tools tab setDefaultTab("bot") -- Locals local boosterId = 17012 -- allows to test/edit bot lua scripts ingame, you can have multiple scripts like this, just change storage.ingame_lua UI.Separator() UI.Button("Ingame macro editor", function(newText) UI.MultilineEditorWindow(storage.ingame_macros_bot or "", {title="Macro editor", description="You can add your custom macros (or any other lua code) here"}, function(text) storage.ingame_macros_bot = text reload() end) end) UI.Button("Ingame hotkey editor", function(newText) UI.MultilineEditorWindow(storage.ingame_hotkeys_bot or "", {title="Hotkeys editor", description="You can add your custom hotkeys/singlehotkeys here"}, function(text) storage.ingame_hotkeys_bot = text reload() end) end) for _, scripts in ipairs({storage.ingame_macros_bot, storage.ingame_hotkeys_bot}) do if type(scripts) == "string" and scripts:len() > 3 then local status, result = pcall(function() assert(load(scripts, "ingame_editor"))() end) if not status then error("Ingame edior error:\n" .. result) end end end UI.Separator() macro(25000, "Booster User", "", function() use(boosterId) end) UI.Separator() function seleccionarMonster(distancia, cantidad, distanciaSelf) if not distancia or not cantidad or not distanciaSelf then return end for _, n in ipairs(getSpectators(false)) do if n:isMonster() and getDistanceBetween(pos(), n:getPosition()) <= distanciaSelf then local count = checkMonsterBox(n, distancia) if count >= cantidad then return n end end end return false end function checkMonsterBox(m, distancia) if not m or not distancia then return end local count = 0 for _, c in ipairs(g_map.getSpectators(m:getPosition(), false)) do if c:isMonster() and getDistanceBetween(m:getPosition(), c:getPosition()) <= distancia then count = count + 1 end end return count end activarCavebot = macro(500, "Activar CaveBot", "", function() local shotId = tonumber(storage.shotRuneId) local amount = 0 local players = 0 local target = nil local checar = nil if storage.runeTarget then checar = tonumber(storage.runaEnTarget) elseif not storage.runeTarget then checar = tonumber(storage.runeEnSelf) end for _, n in ipairs(getSpectators(false)) do if n:isMonster() and getDistanceBetween(pos(), n:getPosition()) <= checar then amount = amount + 1 target = n elseif n:isPlayer() and n:getName() ~= name() then players = players + 1 end end if storage.runeTarget and storage.runeSelf then activarCavebot.setOff() TargetBot.setOff() CaveBot.setOff() g_game.cancelAttack() talkPrivate(name(), "No puedes tener activado Runa Target y Runa Self a la ves, desactivado uno.") return end if amount >= tonumber(storage.pararTargetEnCantidad) and not storage.runeTarget then CaveBot.setOff() TargetBot.setOn() if storage.huntWithSpell and not storage.runeSelf then if manapercent() >= tonumber(storage.spellBotOnMana) and TargetBot.isOn() then say(storage.spellBotLanzar) end elseif storage.runeSelf and storage.huntWithSpell then if manapercent() >= tonumber(storage.spellBotOnMana) and TargetBot.isOn() then say(storage.spellBotLanzar) elseif manapercent() < tonumber(storage.spellBotOnMana) and TargetBot.isOn() then usewith(shotId, player) end elseif storage.runeSelf and not storage.huntWithSpell then if TargetBot.isOn() then usewith(shotId, player) end end return elseif amount < tonumber(storage.pararTargetEnCantidad) and not storage.runeTarget then CaveBot.setOn() TargetBot.setOff() g_game.cancelAttack() end if storage.runeTarget and not storage.runeSelf then local seleccionarTarget = seleccionarMonster(tonumber(storage.runaEnTarget), tonumber(storage.runaEnCatidad), 6) local seleccionarSpell = seleccionarMonster(tonumber(storage.runeEnSelf), tonumber(storage.pararTargetEnCantidad), tonumber(storage.runeEnSelf)) if not seleccionarTarget and storage.runeTarget and not storage.huntWithSpell then CaveBot.setOn() TargetBot.setOff() g_game.cancelAttack() elseif not seleccionarTarget and not seleccionarSpell and storage.runeTarget and storage.huntWithSpell then CaveBot.setOn() TargetBot.setOff() g_game.cancelAttack() end if storage.runeTarget and not storage.huntWithSpell then if seleccionarTarget then CaveBot.setOff() TargetBot.setOn() usewith(shotId, seleccionarTarget) end elseif storage.runeTarget and storage.huntWithSpell then if manapercent() >= tonumber(storage.spellBotOnMana) and seleccionarSpell then CaveBot.setOff() TargetBot.setOn() say(storage.spellBotLanzar) elseif manapercent() < tonumber(storage.spellBotOnMana) and seleccionarSpell then CaveBot.setOff() TargetBot.setOn() usewith(shotId, seleccionarSpell) end end end end) local huntWithSpell = addSwitch("huntWithSpell", "Activar Hunt Spell", function(widget) storage.huntWithSpell = not storage.huntWithSpell widget:setOn(storage.huntWithSpell) end) huntWithSpell:setOn(storage.huntWithSpell) local runeTarget = addSwitch("runeTarget", "Activar Runa Target", function(widget) storage.runeTarget = not storage.runeTarget widget:setOn(storage.runeTarget) end) runeTarget:setOn(storage.runeTarget) local runeSelf = addSwitch("runeSelf", "Activar Runa Self", function(widget) storage.runeSelf = not storage.runeSelf widget:setOn(storage.runeSelf) end) runeSelf:setOn(storage.runeSelf) UI.Label("Pausar en X monsters:") addTextEdit("pararTargetEnCantidad", storage.pararTargetEnCantidad or "5", function(widget, text) storage.pararTargetEnCantidad = text end) UI.Label("Lanzar en X monsters:") addTextEdit("runaEnCatidad", storage.runaEnCatidad or "24", function(widget, text) storage.runaEnCatidad = text end) UI.Label("Distancia monsters (Target):") addTextEdit("runaEnTarget", storage.runaEnTarget or "2", function(widget, text) storage.runaEnTarget = text end) UI.Label("Distancia monsters (Spell - Self):") addTextEdit("runeEnSelf", storage.runeEnSelf or "2", function(widget, text) storage.runeEnSelf = text end) UI.Label("Runa a Lanzar:") addTextEdit("shotRuneId", storage.shotRuneId or "3151", function(widget, text) storage.shotRuneId = text end) UI.Label("Spell en Mana:") addTextEdit("spellBotOnMana", storage.spellBotOnMana or "80", function(widget, text) storage.spellBotOnMana = text end) UI.Label("Spell a Lanzar:") addTextEdit("spellBotLanzar", storage.spellBotLanzar or "exevo gran mas chupala", function(widget, text) storage.spellBotLanzar = text end) UI.Separator() macro(500, "Alarm on PK Red", "", function() local skull = skull() if skull >= 3 then playAlarm() end end) local safeList = {"Boom Locote"} macro(500, "Alarm on player screen", "", function() local players = 0 for _, n in ipairs(getSpectators(false)) do if n:isPlayer() and n:getName() ~= name() and n:getShield() < 3 and n:getEmblem() ~= 1 and not table.find(safeList, n:getName()) then players = players + 1 end end if players > 0 then playAlarm() end end) UI.Separator() macro(200, "Alarm on World Chat(PM)", "", function() local chnl = getChannelId("World Chat") local pm = getChannelId(tostring(storage.enviarMsgA)) local zona = tostring(storage.zoneAlarm) local individual = "El jugador %s va para %s." local varios = "Los jugadores: %s - van para %s." local players = 0 local names = '' for _, n in ipairs(getSpectators(false)) do if n:isPlayer() and n:getName() ~= name() then players = players + 1 if players > 1 then names = ""..names.." y "..n:getName().."" else names = names .. n:getName() end end end if players == 1 then local msg = string.format(individual, names, zona) --sayChannel(chnl, msg) talkPrivate(tostring(storage.enviarMsgA), msg) names = '' delay(5000) elseif players > 1 then local msg = string.format(varios, names, zona) --sayChannel(chnl, msg) talkPrivate(tostring(storage.enviarMsgA), msg) names = '' delay(5000) end end) local autoPMName = addSwitch("alarmaOnMessage", "Activar Alarma (PM)", function(widget) storage.alarmaOnMessage = not storage.alarmaOnMessage widget:setOn(storage.alarmaOnMessage) end, miscTab) autoPMName:setOn(storage.alarmaOnMessage) onTalk(function(name, level, mode, text, channelId, pos) if storage.alarmaOnMessage then if mode == 4 and name == tostring(storage.sonarAlarmaA) then playAlarm() delay(2000) end end end) UI.Label("Nombre de Zona:") addTextEdit("zoneAlarm", storage.zoneAlarm or "Nada", function(widget, text) storage.zoneAlarm = text end) UI.Label("Enviar MSG A:") addTextEdit("enviarMsgA", storage.enviarMsgA or "Ponid", function(widget, text) storage.enviarMsgA = text end) UI.Label("Sonar alarma, mensaje de:") addTextEdit("Sonar Alarma A:", storage.sonarAlarmaA or "Ponid", function(widget, text) storage.sonarAlarmaA = text end) UI.Separator() UI.Button("Pausar Botting", function() activarCavebot.setOff() TargetBot.setOff() CaveBot.setOff() end) UI.Button("Reanudar Botting", function() activarCavebot.setOn() end) UI.Separator() local looting = Panels.Looting(caveTab) UI.Separator()
object_tangible_food_generic_drink_gralinyn_juice = object_tangible_food_generic_shared_drink_gralinyn_juice:new { } ObjectTemplates:addTemplate(object_tangible_food_generic_drink_gralinyn_juice, "object/tangible/food/generic/drink_gralinyn_juice.iff")
object_mobile_boba_fett_eow = object_mobile_shared_boba_fett_eow:new { } ObjectTemplates:addTemplate(object_mobile_boba_fett_eow, "object/mobile/boba_fett_eow.iff")
--Some SE functions (Also keep track of AE ADDITION s) local function twistdirection(gravitydir, dir) --mario.lua if not gravitydir or (gravitydir > math.pi/4*1 and gravitydir <= math.pi/4*3) then if dir == "floor" then return "floor" elseif dir == "left" then return "left" elseif dir == "ceil" then return "ceil" elseif dir == "right" then return "right" end elseif gravitydir > math.pi/4*3 and gravitydir <= math.pi/4*5 then if dir == "floor" then return "left" elseif dir == "left" then return "ceil" elseif dir == "ceil" then return "right" elseif dir == "right" then return "floor" end elseif gravitydir > math.pi/4*5 and gravitydir <= math.pi/4*7 then if dir == "floor" then return "ceil" elseif dir == "left" then return "right" elseif dir == "ceil" then return "floor" elseif dir == "right" then return "left" end else if dir == "floor" then return "right" elseif dir == "left" then return "floor" elseif dir == "ceil" then return "left" elseif dir == "right" then return "ceil" end end end local function unwrap(a) while a < 0 do a = a + (math.pi*2) end while a > (math.pi*2) do a = a - (math.pi*2) end return a end local function angles(a1, a2) local a1 = unwrap(a1)-math.pi local a2 = unwrap(a2)-math.pi local diff = a1-a2 if math.abs(diff) < math.pi then return a1 > a2 else return diff < 0 end end local function anglesdiff(a1, a2) local a1 = unwrap(a1)-math.pi local a2 = unwrap(a2)-math.pi return math.abs(a1-a2) --diff end enemy = class:new() function enemy:init(x, y, t, a, properties) if not enemiesdata[t] then return nil end self.t = t if a then self.a = {unpack(a)} else self.a = {} end --Some standard values.. self.rotation = 0 self.active = true self.static = false self.mask = {} self.gravitydirection = math.pi/2 self.combo = 1 self.falling = false self.shot = false self.outtable = {} self.speedx = 0 self.speedy = 0 --Get our enemy's properties from the property table for i, v in pairs(enemiesdata[self.t]) do self[i] = v end if properties then for i, v in pairs(properties) do self[i] = v end end --right click menu if self.rightclickmenu and self.a[3] then local s = tostring(self.a[3]) if self.rightclickmenutable then if tonumber(self.a[3]) then self.a[3] = tonumber(self.a[3]) end if self.rightclickmenumultipleproperties then local t = self.rightclickmenu[self.a[3]] if t then for i, v in pairs(t) do local name = v[1] local value = v[2] if type(value) == "table" then self[name] = deepcopy(value) else self[name] = value end if name == "quadno" then self.quad = self.quadgroup[self.quadno] end end elseif testinglevel then notice.new("No rightclickmenu entry\nfor number:" .. tostring(self.a[3]), notice.red, 3) end else if type(self.rightclickmenu[self.a[3]]) == "table" then self[self.rightclickmenu[1]] = deepcopy(self.rightclickmenu[self.a[3]]) else self[self.rightclickmenu[1]] = self.rightclickmenu[self.a[3]] end if self.rightclickmenu[1] == "quadno" then self.quad = self.quadgroup[self.quadno] end end else self.a[3] = s:gsub("B", "-") if tonumber(self.a[3]) then self.a[3] = tonumber(self.a[3]) end if self.rightclickmenuboolean then self[self.rightclickmenu[1]] = (self.a[3] == "true") else self[self.rightclickmenu[1]] = self.a[3] end if self.rightclickmenu[1] == "quadno" then self.quad = self.quadgroup[self.quadno] end end end if self.customtimer then self.customtimertimer = 0 self.currentcustomtimerstage = 1 end --Decide on a random movement if it's random.. if self.movementrandoms then self.movement = self.movementrandoms[math.random(#self.movementrandoms)] end self.x = x-.5-self.width/2+(self.spawnoffsetx or 0) self.y = y-self.height+(self.spawnoffsety or 0) if self.animationtype == "mirror" then self.animationtimer = 0 self.animationdirection = "left" elseif self.animationtype == "frames" then self.quadi = self.animationstart self.quad = self.quadgroup[self.quadi] self.animationtimer = 0 if type(self.animationspeed) == "table" then self.animationtimerstage = 1 end elseif self.animationtype == "character" then self.quadi = self.animationstart self.quad = self.quadgroup[self.quadi] self.animationtimer = 0 self.runanimationtimer = 0 end if self.smallanimationstart and self.smallanimationframes then self.smallanimationtimer = 0 self.smallanimationquadi = self.smallanimationstart end if self.stompanimation then self.deathtimer = 0 end if self.shellanimal then self.upsidedown = false self.resettimer = 0 self.wiggletimer = 0 self.wiggleleft = true --self.returntilemaskontrackrelease = true end if self.customscissor then self.customscissor = {unpack(self.customscissor)} self.customscissor[1] = self.customscissor[1] + x - 1 self.customscissor[2] = self.customscissor[2] + y - 1 end if self.starttowardsplayerhorizontal or self.startawayfromplayerhorizontal then --Prize for best property name local closestplayer = 1 self.animationdirection = "right" local closestdist = math.huge for i = 1, #objects["player"] do local v = objects["player"][i] local dist = math.sqrt((v.x-self.x)^2+(v.y-self.y)^2) if dist < closestdist then closestdist = dist closestplayer = i end end if objects["player"][closestplayer] then if objects["player"][closestplayer].x+objects["player"][closestplayer].width/2 < self.x+self.width/2 then self.speedx = -math.abs(self.speedx) if not self.dontmirror then --AE ADDITION self.animationdirection = "right" end if self.movement == "homing" then self.homingrotation = 0 end else self.speedx = math.abs(self.speedx) if not self.dontmirror then --AE ADDITION self.animationdirection = "left" end if self.movement == "homing" then self.homingrotation = math.pi end end if self.startawayfromplayerhorizontal then self.speedx = -self.speedx end end end if self.killsenemiesonsides == nil then self.killsenemiesonsides = true end if self.killsenemiesontop == nil then self.killsenemiesontop = true end if self.killsenemiesonbottom == nil then self.killsenemiesonbottom = true end if self.killsenemiesonleft == nil then self.killsenemiesonleft = true end if self.killsenemiesonright == nil then self.killsenemiesonright = true end if self.killsenemiesonpassive == nil then self.killsenemiesonpassive = true end self.firstmovement = self.movement self.firstanimationtype = self.animationtype self.startoffsetY = self.offsetY self.startquadcenterY = self.quadcenterY self.startgravity = self.gravity self.startx = self.x self.starty = self.y self.startactive = self.active self.startdrawable = self.drawable self.spawnallow = true self.spawnedenemies = {} if self.movement == "piston" then self.pistontimer = self.pistonretracttime self.pistonstate = "retracting" if self.spawnonlyonextended then self.spawnallow = false end elseif self.movement == "flyvertical" or self.movement == "flyhorizontal" then self.flyingtimer = 0 self.startx = self.x self.starty = self.y elseif self.movement == "squid" then self.squidstate = "idle" elseif self.movement == "circle" then self.startx = self.x self.starty = self.y if not self.circletimer then self.circletimer = 0 end elseif self.movement == "path" then self.startx = self.x self.starty = self.y self.movementpathstep = 1 self.movementpathbackwards = false elseif self.movement == "crawl" then if self.crawlfloor == "up" then self.gravity = -self.crawlgravity self.gravityx = 0 if self.crawldirection == "left" then self.speedx = self.crawlspeed else self.speedx = -self.crawlspeed end elseif self.crawlfloor == "left" then self.gravity = 0 self.gravityx = -self.crawlgravity if self.crawldirection == "left" then self.speedy = -self.crawlspeed else self.speedy = self.crawlspeed end elseif self.crawlfloor == "right" then self.gravity = 0 self.gravityx = self.crawlgravity if self.crawldirection == "left" then self.speedy = self.crawlspeed else self.speedy = -self.crawlspeed end else self.gravity = self.crawlgravity if self.crawldirection == "left" then self.speedx = -self.crawlspeed else self.speedx = self.crawlspeed end self.gravityx = 0 end self.ignorelowgravity = true self.aroundcorner = false elseif self.movement == "homing" then if self.starthomingrotationtowardsplayer then --starting rotation is towards player local closestplayer = 1 --find closest player local relativex, relativey, dist for i = 1, players do local v = objects["player"][i] relativex, relativey = (v.x + -self.x), (v.y + -self.y) distance = math.sqrt(relativex*relativex+relativey*relativey) if ((not dist) or (distance < dist)) and not v.dead then closestplayer = i end end local p = objects["player"][closestplayer] if p then local angle = -math.atan2((p.x+p.width/2)-(self.x+self.width/2), (p.y+p.height/2)-(self.y+self.height/2))-math.pi/2 self.homingrotation = unwrap(angle) end end if self.upsidedownifhomingrotationright then if (self.homingrotation >= math.pi*.5 and self.homingrotation <= math.pi*1.5) then self.upsidedown = true end end elseif self.movement == "chase" then self.movedirection = "left" self.movedirectiony = "left" elseif self.movement == "shadow" then self.shadowtable = {} self.shadowrate = self.shadowrate or 0.2 --delay at which position of target is recorded self.shadowlag = self.shadowlag or 1 self.shadowtimer = 0 if self.shadowinterpolate == nil then self.shadowinterpolate = true end end if self.speedxtowardsplayer or self.speedxawayfromplayer then local closestplayer = 1 local closestdist = math.sqrt((objects["player"][1].x-self.x)^2+(objects["player"][1].y-self.y)^2) for i = 2, players do local v = objects["player"][i] local dist = math.sqrt((v.x-self.x)^2+(v.y-self.y)^2) if dist < closestdist then closestdist = dist closestplayer = i end end if objects["player"][closestplayer].x + objects["player"][closestplayer].width/2 > self.x + self.width/2 then self:leftcollide("", {}, "", {}) self.speedx = math.abs(self.speedx) else self:rightcollide("", {}, "", {}) self.speedx = -math.abs(self.speedx) end if self.speedxawayfromplayer then self.speedx = -self.speedx end end if self.lifetimerandoms then self.lifetime = self.lifetimerandoms[math.random(#self.lifetimerandoms)] end if self.lifetime and self.lifetime >= 0 then self.lifetimer = self.lifetime end if self.jumps then self.jumptimer = 0 end if self.spawnsenemy then self.spawnenemytimer = 0 self.spawnenemydelay = self.spawnenemydelays[math.random(#self.spawnenemydelays)] end if self.bounces and (self.bouncedelay or self.bouncedelays) then self.bouncetimer = 0 if self.bouncedelays then if self.bouncedelaysrandoms then self.bouncedelay = self.bouncedelays[math.random(#self.bouncedelays)] else self.bouncetimerstage = 1 self.bouncedelay = self.bouncedelays[self.bouncetimerstage] end end end self.throwanimationstate = 0 if self.chasetime then self.chasetimer = 0 end if self.spawnsound then if self.sound and self.spawnsound == self.t then playsound(self.sound) else playsound(self.spawnsound) end end if self.spawnchildren then if not (self.a and self.a[1] == "ignorespawnchildren") then for i = 1, #self.spawnchildren do local offsetx = self.spawnchildrenoffsetx or 0 if type(self.spawnchildrenoffsetx) == "table" then offsetx = self.spawnchildrenoffsetx[i] end local offsety = self.spawnchildrenoffsety or 0 if type(self.spawnchildrenoffsety) == "table" then offsety = self.spawnchildrenoffsety[i] end local temp = enemy:new(self.x+self.width/2+.5+offsetx, self.y+self.height+offsety, self.spawnchildren[i], {"ignorespawnchildren"}) if self.spawnchildrenparent then temp.parent = self end table.insert(objects["enemy"], temp) end end end if self.carryable then self.rigidgrab = true self.carryparent = false self.userect = adduserect(self.x+self.carryrange[1], self.y+self.carryrange[2], self.carryrange[3], self.carryrange[4], self) if self.throwntime then self.throwntimer = 0 end end if self.jumps or self.noplayercollisiononthrow then --make copy of mask table, otherwise it modifies it for every enemy self.mask = deepcopy(self.mask) end if self.freezable == nil then self.freezable = true --AE ADDITION end if self.movement == "circle" then if self.circletimer ~= 0 then local v = ((self.circletimer/(self.circletime or 1))*math.pi*2) local newx = math.sin(v)*(self.circleradiusx or self.circleradius or 1) + self.startx local newy = math.cos(v)*(self.circleradiusy or self.circleradius or 1) + self.starty self.x = newx self.y = newy end end --snap position to tile grid if self.snapxtogrid then self.x = round(self.x)+(self.snapxtogridoffset or 0) end if self.snapytogrid then self.y = round(self.y)+(self.snapytogridoffset or 0) end --platform collision (ignore side collisions without any callbacks) if self.platformcollisionup then self.PLATFORM = true end if self.platformcollisiondown then self.PLATFORMDOWN = true end if self.platformcollisionleft then self.PLATFORMLEFT = true end if self.platformcollisionright then self.PLATFORMRIGHT = true end --block portals if self.blockportaltile then local t = {math.floor(x), math.floor(y)} if type(self.blockportaltile) == "table" then t = {math.floor(x)+math.floor(self.blockportaltile[1]), math.floor(y)+math.floor(self.blockportaltile[2])} end self.blockportaltilecoordinate = tilemap(t[1], t[2]) blockedportaltiles[self.blockportaltilecoordinate] = true end --trigger animation on spawnn if self.animationtriggeronspawn or self.triggeranimationonspawn then self:triggeranimation(self.animationtriggeronspawn or self.triggeranimationonspawn) end self.outtable = {} end function enemy:update(dt) --Just spawned if self.justspawned then self.justspawned = nil end --Funnels and fuck if self.funnel and not self.infunnel then self:enteredfunnel(true) end if self.infunnel and not self.funnel then self:enteredfunnel(false) end self.funnel = false if self.lifetimer and not self.shot then self.lifetimer = self.lifetimer - dt if self.lifetimer <= 0 then if self.transforms and self:gettransformtrigger("lifetime") then self:transform(self:gettransformsinto("lifetime")) end self:output() self.dead = true return true end end if self.transformkill then if self.transformkilldeath then self:output() else self:output("transformed") end self.dead = true return true elseif self.kill then self:output() self.dead = true return true end if self.stompanimation and self.dead then self.deathtimer = self.deathtimer + dt if self.deathtimer > (self.stompanimationtime or 0.5) then self:output() return true else return false end end if (not self.doesntunrotate) and (not self.rotationanimation) and (not self.rollanimation) then self.rotation = unrotate(self.rotation, self.gravitydirection, dt) end if self.shot then self.speedy = self.speedy + shotgravity*dt self.x = self.x+self.speedx*dt self.y = self.y+self.speedy*dt return false end if self.frozen then return false end if self.rotationanimation then self.rotation = self.rotation + (self.rotationanimationspeed or 1)*dt end if self.rollanimation then self.rotation = self.rotation + self.speedx*math.pi*dt end local oldx, oldy if self.platform or self.animationtype == "character" then oldx, oldy = self.x, self.y end --water if self.watergravity or self.waterdamping or (self.transforms and (self:gettransformtrigger("water") or self:gettransformtrigger("notinwater"))) then --is the enemy in water? local oldwater = self.water or false self.water = underwater if self.risingwater then --how many frames since in water self.risingwater = self.risingwater - 1 self.water = true if self.risingwater < 0 then self.risingwater = false end end if not self.water then --water tiles local x1 = math.floor(self.x)+1 local y1 = math.floor(self.y)+1 local dobreak = false for x2 = math.max(1,x1), math.min(mapwidth,math.floor(self.x+self.width)+1) do for y2 = math.max(1,y1), math.min(mapheight,math.floor(self.y+self.height)+1) do if inmap(x2, y2) and tilequads[map[x2][y2][1]] and tilequads[map[x2][y2][1]].water then dobreak = true self.water = true break end end if dobreak then break end end end if oldwater == false and self.water == true then --in water self:dive(true) if self.transforms and self:gettransformtrigger("water") then self:transform(self:gettransformsinto("water")) return end elseif oldwater == true and self.water == false then --not in water if self.transforms and self:gettransformtrigger("notinwater") then self:transform(self:gettransformsinto("notinwater")) return end end if self.watergravity then self.gravity = self.watergravity else self.gravity = self.startgravity end if self.y+self.height < uwmaxheight and underwater and self.watergravity then self.speedy = uwpushdownspeed end end if self.float then self.risingwater = false end if self.animationtype == "mirror" then self.animationtimer = self.animationtimer + dt while self.animationtimer > self.animationspeed do self.animationtimer = self.animationtimer - self.animationspeed if self.animationdirection == "left" then self.animationdirection = "right" else self.animationdirection = "left" end end elseif self.animationtype == "frames" then self.animationtimer = self.animationtimer + dt if type(self.animationspeed) == "table" then while self.animationtimer > self.animationspeed[self.animationtimerstage] do self.animationtimer = self.animationtimer - self.animationspeed[self.animationtimerstage] self.quadi = self.quadi + 1 if self.quadi > self.animationstart + self.animationframes - 1 then self.quadi = self.quadi - self.animationframes end self.quad = self.quadgroup[self.quadi] self.animationtimerstage = self.animationtimerstage + 1 if self.animationtimerstage > #self.animationspeed then self.animationtimerstage = 1 end end else while self.animationtimer > self.animationspeed do self.animationtimer = self.animationtimer - self.animationspeed self.quadi = self.quadi + 1 if self.quadi > self.animationstart + self.animationframes - 1 then self.quadi = self.quadi - self.animationframes end self.quad = self.quadgroup[self.quadi] end end if not self.dontmirror then --AE ADDITION if self.speedx > 0 then self.animationdirection = "left" elseif self.speedx < 0 then self.animationdirection = "right" end end end if self.spawnsenemy then if lakitoend and self.movement == "follow" and (not self.ignorelakitoend) then self.speedx = -3 return false end local playernear = false if self.dontspawnenemyonplayernear or self.spawnenemyonplayernear then local dist = self.spawnenemydist or self.dontspawnenemydist or 3 if type(dist) == "table" then local col = checkrect(self.x+dist[1], self.y+dist[2], dist[3], dist[4], {"player"}) if #col > 0 then playernear = true end else for i = 1, players do local v = objects["player"][i] if inrange(v.x+v.width/2, self.x+self.width/2-(dist), self.x+self.width/2+(dist)) then playernear = true break end end end if self.spawnenemyonplayernear then playernear = not playernear end end if (not playernear) then self.spawnenemytimer = self.spawnenemytimer + dt while self.spawnenemytimer >= self.spawnenemydelay and self.spawnallow and (not self.spawnmax or self:getspawnedenemies() < self.spawnmax) do if self.spawnsenemyrandoms then self.spawnsenemy = self.spawnsenemyrandoms[math.random(#self.spawnsenemyrandoms)] end self:spawnenemy(self.spawnsenemy) self.spawnenemytimer = 0 self.spawnenemydelay = self.spawnenemydelays[math.random(#self.spawnenemydelays)] self.throwanimationstate = 0 if self.animationtype == "frames" then self.quad = self.quadgroup[self.quadi + self.throwanimationstate] end end if self.throwpreparetime and self.spawnenemytimer >= (self.spawnenemydelay - self.throwpreparetime) then self.throwanimationstate = self.throwquadoffset if self.animationtype == "frames" then self.quad = self.quadgroup[self.quadi + self.throwanimationstate] end end end end if self.bounces and self.bouncedelay and (not self.falling) then self.bouncetimer = self.bouncetimer + dt if self.bouncetimer > self.bouncedelay then local force = self.bounceforce if type(self.bounceforce) == "table" then if self.bouncetimerstage and not self.bounceforcerandom then force = self.bounceforce[self.bouncetimerstage] else force = self.bounceforce[math.floor(#self.bounceforce)] end end self.speedy = -(force or 10) self.bouncetimer = 0 if self.bouncetimerstage then self.bouncetimerstage = self.bouncetimerstage + 1 if self.bouncetimerstage > #self.bouncedelays then self.bouncetimerstage = 1 end self.bouncedelay = self.bouncedelays[self.bouncetimerstage] elseif self.bouncedelaysrandoms then self.bouncedelay = self.bouncedelays[math.random(#self.bouncedelays)] end end end if self.movement == "truffleshuffle" then if self.speedx > 0 then if self.speedx > self.truffleshufflespeed then self.speedx = self.speedx - self.truffleshuffleacceleration*dt*2 if self.speedx < self.truffleshufflespeed then self.speedx = self.truffleshufflespeed end elseif self.speedx < self.truffleshufflespeed then self.speedx = self.speedx + self.truffleshuffleacceleration*dt*2 if self.speedx > self.truffleshufflespeed then self.speedx = self.truffleshufflespeed end end else if self.speedx < -self.truffleshufflespeed then self.speedx = self.speedx + self.truffleshuffleacceleration*dt*2 if self.speedx > -self.truffleshufflespeed then self.speedx = -self.truffleshufflespeed end elseif self.speedx > -self.truffleshufflespeed then self.speedx = self.speedx - self.truffleshuffleacceleration*dt*2 if self.speedx < -self.truffleshufflespeed then self.speedx = -self.truffleshufflespeed end end end if self.turnaroundoncliff and self.falling == false then --check if nothing below local x, y = math.floor(self.x + self.width/2+1), math.floor(self.y + self.height+1.5) if inmap(x, y) and (not checkfortileincoord(x, y)) and ((inmap(x+.5, y) and checkfortileincoord(math.ceil(x+.5), y)) or (inmap(x-.5, y) and checkfortileincoord(math.floor(x-.5), y))) then if self.speedx < 0 then self.x = x-self.width/2 else self.x = x-1-self.width/2 end self.speedx = -self.speedx end end if edgewrapping then --wrap around screen local minx, maxx = -self.width, mapwidth if self.x < minx then self.x = maxx elseif self.x > maxx then self.x = minx end end elseif self.movement == "shell" then if self.small then if self.wakesup then if math.abs(self.speedx) < 0.0001 then self.resettimer = self.resettimer + dt if self.resettimer > self.resettime then self.offsetY = self.startoffsetY self.quadcenterY = self.startquadcenterY self.quad = self.quadgroup[self.animationstart] self.small = false self.speedx = -self.truffleshufflespeed self.resettimer = 0 self.upsidedown = false self.kickedupsidedown = false self.movement = self.firstmovement self.animationtype = self.firstanimationtype if self.chasemarioonwakeup then local px = objects["player"][getclosestplayer(self.x)].x --AE ADDITION (changed x to self.x) if px > self.x then self.speedx = -self.speedx end end elseif self.resettimer > self.resettime-self.wiggletime then self.wiggletimer = self.wiggletimer + dt while self.wiggletimer > self.wiggledelay do self.wiggletimer = self.wiggletimer - self.wiggledelay if self.wiggleleft then if self.wigglequad then self.offsetY = self.wiggleoffsety or self.startoffsetY self.quadcenterY = self.wigglequadcentery or self.startquadcenterY if self.upsidedown then self.offsetY = self.upsidedownwiggleoffsety or self.upsidedownoffsety or 4 self.quadcenterY = self.upsidedownwigglequadcentery or self.wigglequadcentery or self.upsidedownquadcentery or self.startquadcenterY end self.quad = self.quadgroup[self.wigglequad] else self.x = self.x + 1/16 end else if self.wigglequad then self.offsetY = self.startoffsetY self.quadcenterY = self.startquadcenterY if self.upsidedown then self.offsetY = self.upsidedownoffsety or 4 self.quadcenterY = self.upsidedownquadcentery or self.startquadcenterY end self.quad = self.quadgroup[self.smallquad] else self.x = self.x - 1/16 end end self.wiggleleft = not self.wiggleleft end end else self.resettimer = 0 end end if math.abs(self.speedx) >= 0.0001 then --shell animation if self.smallanimationstart and self.smallanimationframes and not self.kickedupsidedown then self.smallanimationtimer = self.smallanimationtimer + dt while self.smallanimationtimer > self.smallanimationspeed do self.smallanimationtimer = self.smallanimationtimer - self.smallanimationspeed self.smallanimationquadi = self.smallanimationquadi + 1 if self.smallanimationquadi > self.smallanimationstart + self.smallanimationframes - 1 then self.smallanimationquadi = self.smallanimationquadi - self.smallanimationframes end self.quad = self.quadgroup[self.smallanimationquadi] end end end end if edgewrapping then --wrap around screen local minx, maxx = -self.width, mapwidth if self.x < minx then self.x = maxx elseif self.x > maxx then self.x = minx end end elseif self.movement == "follow" then local nearestplayer = 1 while objects["player"][nearestplayer] and objects["player"][nearestplayer].dead do nearestplayer = nearestplayer + 1 end if objects["player"][nearestplayer] then local nearestplayerx = objects["player"][nearestplayer].x for i = 2, players do local v = objects["player"][i] if v.x > nearestplayerx and not v.dead then nearestplayer = i end end nearestplayerx = nearestplayerx + objects["player"][nearestplayer].speedx*(self.distancetime or 1) local distance = math.abs(self.x - nearestplayerx) --check if too far in wrong direction if (not self.direction or self.direction == "left") and self.x < nearestplayerx-self.followspace then self.direction = "right" if not self.dontmirror then --AE ADDITION self.animationdirection = "right" end elseif self.direction == "right" and self.x > nearestplayerx+self.followspace then self.direction = "left" if not self.dontmirror then --AE ADDITION self.animationdirection = "left" end end if self.direction == "right" then if self.nofollowspeedup then self.speedx = self.followspeed or 2 else self.speedx = math.max((self.followspeed or 2), round((distance-3)*2)) end else self.speedx = -(self.followspeed or 2) end end elseif self.movement == "chase" then local closestplayer = 1 --find closest player for i = 2, players do local v = objects["player"][i] if math.abs(self.x - v.x) < math.abs(self.x - objects["player"][closestplayer].x) then closestplayer = i end end local p = objects["player"][closestplayer] if self.chasespeed then if self.x+self.width/2 > p.x+p.width/2 + (self.chasespace or 2) then if not self.dontmirror then self.animationdirection = "right" end self.movedirection = "right" elseif self.x+self.width/2 < p.x+p.width/2 - (self.chasespace or 2) then if not self.dontmirror then self.animationdirection = "left" end self.movedirection = "left" end if self.movedirection == "left" then if self.speedx > self.chasespeed then self.speedx = self.speedx - self.chaseacceleration*dt*2 if self.speedx < self.chasespeed then self.speedx = self.chasespeed end elseif self.speedx < self.chasespeed then self.speedx = self.speedx + self.chaseacceleration*dt*2 if self.speedx > self.chasespeed then self.speedx = self.chasespeed end end else if self.speedx < -self.chasespeed then self.speedx = self.speedx + self.chaseacceleration*dt*2 if self.speedx > -self.chasespeed then self.speedx = -self.chasespeed end elseif self.speedx > -self.chasespeed then self.speedx = self.speedx - self.chaseacceleration*dt*2 if self.speedx < -self.chasespeed then self.speedx = -self.chasespeed end end end end if self.chasespeedy then if self.y+self.height/2 > p.y+p.height/2 + (self.chasespacey or 2) then if not self.dontmirror then self.animationdirectiony = "right" end self.movedirectiony = "right" elseif self.y+self.height/2 < p.y+p.height/2 - (self.chasespacey or 2) then if not self.dontmirror then self.animationdirectiony = "left" end self.movedirectiony = "left" end if self.movedirectiony == "left" then if self.speedy > self.chasespeedy then self.speedy = self.speedy - self.chaseaccelerationy*dt*2 if self.speedy < self.chasespeedy then self.speedy = self.chasespeedy end elseif self.speedy < self.chasespeedy then self.speedy = self.speedy + self.chaseaccelerationy*dt*2 if self.speedy > self.chasespeedy then self.speedy = self.chasespeedy end end else if self.speedy < -self.chasespeedy then self.speedy = self.speedy + self.chaseaccelerationy*dt*2 if self.speedy > -self.chasespeedy then self.speedy = -self.chasespeedy end elseif self.speedy > -self.chasespeedy then self.speedy = self.speedy - self.chaseaccelerationy*dt*2 if self.speedy < -self.chasespeedy then self.speedy = -self.chasespeedy end end end end if self.turnaroundoncliff and self.falling == false then --check if nothing below local x, y = math.floor(self.x + self.width/2+1), math.floor(self.y + self.height+1.5) if inmap(x, y) and tilequads[map[x][y][1]]:getproperty("collision", x, y) == false and ((inmap(x+.5, y) and tilequads[map[math.ceil(x+.5)][y][1]]:getproperty("collision", math.ceil(x+.5), y)) or (inmap(x-.5, y) and tilequads[map[math.floor(x-.5)][y][1]]:getproperty("collision", math.floor(x-.5), y))) then if self.speedx < 0 then self.x = x-self.width/2 self.movedirection = "right" else self.x = x-1-self.width/2 self.movedirection = "left" end self.speedx = -self.speedx end end if edgewrapping then --wrap around screen local minx, maxx = -self.width, mapwidth if self.x < minx then self.x = maxx elseif self.x > maxx then self.x = minx end end elseif self.movement == "piston" then self.pistontimer = self.pistontimer + dt if self.pistonstate == "extending" then --move X if self.x > self.startx + self.pistondistx then self.x = self.x - self.pistonspeedx*dt if self.x < self.startx + self.pistondistx then self.x = self.startx + self.pistondistx end elseif self.x < self.startx + self.pistondistx then self.x = self.x + self.pistonspeedx*dt if self.x > self.startx + self.pistondistx then self.x = self.startx + self.pistondistx end end --move Y if self.y > self.starty + self.pistondisty then self.y = self.y - self.pistonspeedy*dt if self.y < self.starty + self.pistondisty then self.y = self.starty + self.pistondisty end elseif self.y < self.starty + self.pistondisty then self.y = self.y + self.pistonspeedy*dt if self.y > self.starty + self.pistondisty then self.y = self.starty + self.pistondisty end end if self.x == self.startx + self.pistondistx and self.y == self.starty + self.pistondisty and not self.spawnallow then self.spawnallow = true self.spawnenemytimer = self.spawnenemydelay end if self.pistontimer > self.pistonextendtime then self.pistontimer = 0 self.spawnallow = false self.pistonstate = "retracting" end else --retracting --move X if self.x > self.startx then self.x = self.x - self.pistonspeedx*dt if self.x < self.startx then self.x = self.startx end elseif self.x < self.startx then self.x = self.x + self.pistonspeedx*dt if self.x > self.startx then self.x = self.startx end end --move Y if self.y > self.starty then self.y = self.y - self.pistonspeedy*dt if self.y < self.starty then self.y = self.starty end elseif self.y < self.starty then self.y = self.y + self.pistonspeedy*dt if self.y > self.starty then self.y = self.starty end end if self.inactiveonretracted and self.x == self.startx and self.y == self.starty then self.active = false end if self.pistontimer > self.pistonretracttime then local playernear = false for i = 1, players do local v = objects["player"][i] if inrange(v.x+v.width/2, self.x+self.width/2-(self.dontpistondist or 3), self.x+self.width/2+(self.dontpistondist or 3)) then playernear = true break end end if not self.dontpistonnearplayer or not playernear then self.pistontimer = 0 self.pistonstate = "extending" self.active = true end end end elseif self.movement == "wiggle" and (not self.track) then if self.speedx < 0 then if self.x < self.startx-self.wiggledistance then self.speedx = self.wigglespeed or 1 end elseif self.speedx > 0 then if self.x > self.startx then self.speedx = -self.wigglespeed or 1 end else self.speedx = self.wigglespeed or 1 end elseif self.movement == "verticalwiggle" and (not self.track) then if self.speedy < 0 then if self.y < self.starty-self.verticalwiggledistance then self.speedy = self.verticalwigglespeed or 1 end elseif self.speedy > 0 then if self.y > self.starty then self.speedy = -self.verticalwigglespeed or 1 end else self.speedy = self.verticalwigglespeed or 1 end elseif self.movement == "rocket" then if self.y > self.starty+(self.rocketdistance or 15) and self.speedy > 0 then self.y = self.starty+(self.rocketdistance or 15) self.speedy = -math.sqrt(2*(self.gravity or yacceleration)*(self.rocketdistance or 15)) end if self.speedy < 0 then self.upsidedown = false else self.upsidedown = true end elseif self.movement == "squid" and (not self.track) then local closestplayer = 1 local closestdist = math.sqrt((objects["player"][1].x-self.x)^2+(objects["player"][1].y-self.y)^2) for i = 2, players do local v = objects["player"][i] local dist = math.sqrt((v.x-self.x)^2+(v.y-self.y)^2) if dist < closestdist then closestdist = dist closestplayer = i end end if self.squidstate == "idle" then self.speedy = self.squidfallspeed --get if change state to upward if (self.y+self.speedy*dt) + self.height + 0.0625 >= (objects["player"][closestplayer].y - (24/16 - objects["player"][closestplayer].height)) then self.squidstate = "upward" self.upx = self.x self.speedx = 0 self.speedy = 0 if self.animationtype == "squid" then self.quad = self.quadgroup[2] end --get if to change direction if true then--math.random(2) == 1 then if self.direction == "right" then if self.x > objects["player"][closestplayer].x then self.direction = "left" end else if self.x < objects["player"][closestplayer].x then self.direction = "right" end end end end elseif self.squidstate == "upward" then if self.direction == "right" then self.speedx = self.speedx + self.squidacceleration*dt if self.speedx > self.squidxspeed then self.speedx = self.squidxspeed end else self.speedx = self.speedx - self.squidacceleration*dt if self.speedx < -self.squidxspeed then self.speedx = -self.squidxspeed end end self.speedy = self.speedy - self.squidacceleration*dt if self.speedy < -self.squidupspeed then self.speedy = -self.squidupspeed end if math.abs(self.x - self.upx) >= (self.squidhordistance or 2) then self.squidstate = "downward" self.downy = self.y self.speedx = 0 end elseif self.squidstate == "downward" then self.speedy = self.squidfallspeed if self.y > self.downy + self.squiddowndistance then self.squidstate = "idle" end if self.animationtype == "squid" then self.quad = self.quadgroup[1] end end elseif self.movement == "targety" and (not self.track) then if self.y > self.targety then self.y = self.y - self.targetyspeed*dt if self.y < self.targety then self.y = self.targety end elseif self.y < self.targety then self.y = self.y + self.targetyspeed*dt if self.y > self.targety then self.y = self.targety end end elseif self.movement == "flyvertical" and (not self.track) then self.flyingtimer = self.flyingtimer + dt while self.flyingtimer > (self.flyingtime or 7) do self.flyingtimer = self.flyingtimer - (self.flyingtime or 7) end local newy = self:func(self.flyingtimer/(self.flyingtime or 7))*(self.flyingdistance or 7.5) + self.starty self.y = newy elseif self.movement == "flyhorizontal" and (not self.track) then self.flyingtimer = self.flyingtimer + dt while self.flyingtimer > (self.flyingtime or 7) do self.flyingtimer = self.flyingtimer - (self.flyingtime or 7) end local newx = self:func(self.flyingtimer/(self.flyingtime or 7))*(self.flyingdistance or 7.5) + self.startx if not self.dontmirror then if newx > self.x then --AE ADDITION self.animationdirection = "left" else self.animationdirection = "right" end end self.x = newx elseif self.movement == "circle" then --AE ADDITION self.circletimer = self.circletimer + dt while self.circletimer > math.abs(self.circletime or 1) do self.circletimer = self.circletimer - math.abs(self.circletime or 1) end local v = ((self.circletimer/(self.circletime or 1))*math.pi*2) local newx = math.sin(v)*(self.circleradiusx or self.circleradius or 1) + self.startx local newy = math.cos(v)*(self.circleradiusy or self.circleradius or 1) + self.starty self.x = newx self.y = newy elseif self.movement == "homing" then --AE ADDITION local p local pass, onlyrotatepass = true, false if self.homingatenemy then local dist for i, v in pairs(objects["enemy"]) do if (type(self.homingatenemy) == "string" and v.t == self.homingatenemy) or (type(self.homingatenemy) == "table" and tablecontains(self.homingatenemy, v.t)) then local relativex, relativey = (v.x + -self.x), (v.y + -self.y) local distance = math.sqrt(relativex*relativex+relativey*relativey) if ((not dist) or (distance < dist)) then p = v; dist = distance end end end else local closestplayer = 1 --find closest player local relativex, relativey, dist, distance for i = 1, players do local v = objects["player"][i] relativex, relativey = (v.x + -self.x), (v.y + -self.y) distance = math.sqrt(relativex*relativex+relativey*relativey) if ((not dist) or (distance < dist)) and (not v.dead) then closestplayer = i; dist = distance end end p = objects["player"][closestplayer] end if p and self.stophomingdist then --stop homing if player is too close local relativex, relativey = (p.x + -self.x), (p.y + -self.y) if math.sqrt(relativex*relativex+relativey*relativey) < self.stophomingdist then self.speedx, self.speedy = 0, 0 pass = false onlyrotatepass = self.stophomingdistrotate--stay still, but allow enemy to rotate end end if p and (pass or onlyrotatepass) then local oldhomingrotation = self.homingrotation local angle = -math.atan2((p.x+p.width/2)-(self.x+self.width/2), (p.y+p.height/2)-(self.y+self.height/2))-math.pi/2 local turnDir1 = angles(angle, self.homingrotation) if turnDir1 then self.homingrotation = self.homingrotation + self.homingturnspeed*dt else self.homingrotation = self.homingrotation - self.homingturnspeed*dt end local turnDir2 = angles(angle, self.homingrotation) if turnDir1 ~= turnDir2 then --correct rotation if it over-shoots self.homingrotation = angle end if pass then --sometimes the enemy is only allowed to aim if self.onlymovewhenhomingrotationatplayer and anglesdiff(angle, self.homingrotation) > self.onlymovewhenhomingrotationatplayerthreshold then --stop chasing if not facing player self.speedx, self.speedy = 0, 0 else self.speedx, self.speedy = math.cos(self.homingrotation+math.pi)*(self.homingspeed), math.sin(self.homingrotation+math.pi)*(self.homingspeed) if self.dontchangehomingrotationwhenmoving then self.homingrotation = oldhomingrotation end end end end if self.rotationishomingrotation then self.rotation = self.homingrotation end elseif self.movement == "path" then local speedx, speedy = 0, 0 local oldx, oldy = self.x, self.y local timedist = dt --how much time passed while timedist > 0 do local movedpasttarget = false local tx, ty = self.startx+self.movementpath[self.movementpathstep][1]+(self.movementpathoffsetx or 0), self.starty+self.movementpath[self.movementpathstep][2]+(self.movementpathoffsety or 0) local angle = -math.atan2(tx-self.x, ty-self.y)-math.pi/2 local speed = self.movementpathspeed if type(self.movementpathspeed) == "table" then speed = self.movementpathspeed[self.movementpathstep] end self.x = self.x + (math.cos(angle+math.pi)*(speed))*timedist self.y = self.y + (math.sin(angle+math.pi)*(speed))*timedist --face or rotate if self.rotatetowardsmovementpath then self.rotation = angle else if not self.dontmirror then if self.x > oldx then self.animationdirection = "left" else self.animationdirection = "right" end end end --check if it is past target if ((oldx < tx and self.x > tx) or (oldx > tx and self.x < tx)) or ((oldy < ty and self.y > ty) or (oldy > ty and self.y < ty)) then movedpasttarget = true end if movedpasttarget then local distancemoved = math.sqrt((oldx-self.x)*(oldx-self.x)+(oldy-self.y)*(oldy-self.y)) local targetdistance = math.sqrt((oldx-tx)*(oldx-tx)+(oldy-ty)*(oldy-ty)) if self.movementpathbackwards then self.movementpathstep = self.movementpathstep - 1 if self.movementpathstep < 1 then self.movementpathbackwards = false self.movementpathstep = 2 end else self.movementpathstep = self.movementpathstep + 1 --end of path, either loop back or bounce if self.movementpathstep > #self.movementpath then if self.transforms and self:gettransformtrigger("movementpathend") then self:transform(self:gettransformsinto("movementpathend")) return end if self.movementpathturnaround then self.movementpathstep = math.max(1, self.movementpathstep - 2) self.movementpathbackwards = true else self.movementpathstep = 1 end end end self.x = tx self.y = ty oldx, oldy = self.x, self.y timedist = timedist - math.abs(distancemoved-targetdistance)/speed else timedist = 0 end end elseif self.movement == "crawl" then if self.crawlrotation then if self.crawlfloor == "down" then self.rotation = 0 elseif self.crawlfloor == "up" then self.rotation = math.pi elseif self.crawlfloor == "right" then self.rotation = math.pi*1.5 elseif self.crawlfloor == "left" then self.rotation = math.pi*.5 end end if not self.dontmirror then if self.crawldirection == "right" then self.animationdirection = "left" else self.animationdirection = "right" end end if not self.aroundcorner then --go around corner? if self.crawldirection == "left" then if self.crawlfloor == "left" or self.crawlfloor == "right" then if self.speedx > 0 and self.crawlfloor == "right" then self.speedx = self.crawlspeed self.speedy = 0 self.gravity = -(self.crawlgravity or yacceleration) self.gravityx = 0 self.aroundcorner = true self.crawlfloor = "up" elseif self.speedx < 0 and self.crawlfloor == "left" then self.speedx = -self.crawlspeed self.speedy = 0 self.gravity = (self.crawlgravity or yacceleration) self.gravityx = 0 self.aroundcorner = true self.crawlfloor = "down" end elseif self.crawlfloor == "up" or self.crawlfloor == "down" then if self.speedy > 0 and self.crawlfloor == "down" then self.speedy = self.crawlspeed self.speedx = 0 self.gravity = 0 self.gravityx = (self.crawlgravity or yacceleration) self.aroundcorner = true self.crawlfloor = "right" elseif self.speedy < 0 and self.crawlfloor == "up" then self.speedy = -self.crawlspeed self.speedx = 0 self.gravity = 0 self.gravityx = -(self.crawlgravity or yacceleration) self.aroundcorner = true self.crawlfloor = "left" end end else if self.crawlfloor == "left" or self.crawlfloor == "right" then if self.speedx > 0 and self.crawlfloor == "right" then self.speedx = self.crawlspeed self.speedy = 0 self.gravity = (self.crawlgravity or yacceleration) self.gravityx = 0 self.aroundcorner = true self.crawlfloor = "down" elseif self.speedx < 0 and self.crawlfloor == "left" then self.speedx = -self.crawlspeed self.speedy = 0 self.gravity = -(self.crawlgravity or yacceleration) self.gravityx = 0 self.aroundcorner = true self.crawlfloor = "up" end elseif self.crawlfloor == "up" or self.crawlfloor == "down" then if self.speedy > 0 and self.crawlfloor == "down" then self.speedy = self.crawlspeed self.speedx = 0 self.gravity = 0 self.gravityx = -(self.crawlgravity or yacceleration) self.aroundcorner = true self.crawlfloor = "left" elseif self.speedy < 0 and self.crawlfloor == "up" then self.speedy = -self.crawlspeed self.speedx = 0 self.gravity = 0 self.gravityx = (self.crawlgravity or yacceleration) self.aroundcorner = true self.crawlfloor = "right" end end end end elseif self.movement == "shadow" then local length = self.shadowlag/self.shadowrate if length >= 2 or self.shadowlag == 0 then local target if self.shadowtarget == "player" and self.shadowtargetplayer then target = objects["player"][self.shadowtargetplayer] elseif self.shadowtarget == "parent" then if self.parent and not self.parent.delete then target = self.parent end elseif self.shadowtarget and objects[self.shadowtarget] then --find closest target local x1, y1 = self.x+self.width/2, self.y+self.height/2 local dist = math.huge for j, w in pairs(objects[self.shadowtarget]) do if w ~= self and w.x and (not w.dead) then if self.shadowtarget == "enemy" and self.shadowtargetenemy then if w.t == self.shadowtargetenemy then local dist2 = ((x1-(w.x+w.width/2))*(x1-(w.x+w.width/2)))+((y1-(w.y+w.height/2))*(y1-(w.y+w.height/2))) if dist2 < dist then dist = dist2 target = w end end else local dist2 = ((x1-(w.x+w.width/2))*(x1-(w.x+w.width/2)))+((y1-(w.y+w.height/2))*(y1-(w.y+w.height/2))) if dist2 < dist then dist = dist2 target = w end end end end end if target and target.x then --record target's position local ox = target.width/2 local oy = target.height/2 if self.shadowfromtargetbottom then oy = target.height end local tx = target.x+ox local ty = target.y+oy if self.shadowlag == 0 then self.shadowtable[1] = tx self.shadowtable[2] = ty else self.shadowtimer = self.shadowtimer + dt while self.shadowtimer > self.shadowrate do if (not self.shadowiftargetmoving) or (#self.shadowtable == 0 or (tx ~= self.shadowtable[#self.shadowtable-1] and ty ~= self.shadowtable[#self.shadowtable])) then if #self.shadowtable/2 >= length then table.remove(self.shadowtable,1) table.remove(self.shadowtable,1) end table.insert(self.shadowtable, tx) table.insert(self.shadowtable, ty) end self.shadowtimer = self.shadowtimer - self.shadowrate end end end local poof = false local ox = self.width/2 local oy = self.height/2 if self.shadowfromtargetbottom then oy = self.height end if self.shadowlag == 0 and target and target.x then self.x = (self.shadowtable[1] or self.x) -ox -(self.shadowoffsetx or 0) self.y = (self.shadowtable[2] or self.y) -oy -(self.shadowoffsety or 0) if self.shadowwaiting then self.shadowwaiting = false self.drawable = self.startdrawable self.active = self.startactive poof = true end elseif #self.shadowtable/2 >= length and self.shadowlag ~= 0 then if self.shadowwaiting then self.shadowwaiting = false self.drawable = self.startdrawable self.active = self.startactive poof = true end --set to position (and interpolate) local teleport = false if self.shadowteleportdist then local dist = ((self.shadowtable[1]-self.shadowtable[3])*(self.shadowtable[1]-self.shadowtable[3]))+((self.shadowtable[2]-self.shadowtable[4])*(self.shadowtable[2]-self.shadowtable[4])) if dist > self.shadowteleportdist*self.shadowteleportdist then teleport = true end end if self.shadowinterpolate and not teleport then local v = self.shadowtimer/self.shadowrate self.x = self.shadowtable[1]*(1-v)+self.shadowtable[3]*v -ox -(self.shadowoffsetx or 0) self.y = self.shadowtable[2]*(1-v)+self.shadowtable[4]*v -oy -(self.shadowoffsety or 0) else self.x = self.shadowtable[1] -ox -(self.shadowoffsetx or 0) self.y = self.shadowtable[2] -oy -(self.shadowoffsety or 0) end elseif self.shadownotactivewhenwaiting then if self.shadowwaiting == false then poof = true end self.drawable = false self.active = false self.shadowwaiting = true end if poof and self.shadowpoof then local t = self.shadowpoof if type(t) ~= "string" then t = "poof" end makepoof(self.x+self.width/2,self.y+self.height/2,t) end end end if (self.friction or self.airfriction) and self.movement ~= "truffleshuffle" then local friction = friction if self.airfriction and self.falling then friction = self.airfriction elseif type(self.friction) == "number" then friction = self.friction end if self.speedx > 0 then self.speedx = self.speedx - friction*dt if self.speedx < 0 then self.speedx = 0 end else self.speedx = self.speedx + friction*dt if self.speedx > 0 then self.speedx = 0 end end end if (self.verticalfriction or self.verticalairfriction) then local friction = friction if self.verticalairfriction and self.falling then friction = self.verticalairfriction elseif type(self.verticalfriction) == "number" then friction = self.verticalfriction end if self.speedy > 0 then self.speedy = self.speedy - friction*dt if self.speedy < 0 then self.speedy = 0 end else self.speedy = self.speedy + friction*dt if self.speedy > 0 then self.speedy = 0 end end end if self.xrelativetocamera then self.x = xscroll + self.xrelativetocamera end if self.yrelativetocamera then self.y = yscroll + self.yrelativetocamera end if self.sticktonearestplayer then --moves to where player is local closestplayer = 1 local closestdist = math.sqrt((objects["player"][1].x-self.x)^2+(objects["player"][1].y-self.y)^2) for i = 2, players do local v = objects["player"][i] local dist = math.sqrt((v.x-self.x)^2+(v.y-self.y)^2) if dist < closestdist then closestdist = dist; closestplayer = i end end self.sticktoplayer = closestplayer end if self.sticktoplayer then local p = objects["player"][self.sticktoplayer] if p then local ox, oy = self.sticktoplayeroffsetx or 0, self.sticktoplayeroffsety or 0 self.x = p.x+p.width/2-self.width/2+ox self.y = p.y+p.height/2-self.height/2+oy end end if self.teleportnearestplayer then --teleports player to enemy's position local closestplayer = 1 local closestdist = math.sqrt((objects["player"][1].x-self.x)^2+(objects["player"][1].y-self.y)^2) for i = 2, players do local v = objects["player"][i] local dist = math.sqrt((v.x-self.x)^2+(v.y-self.y)^2) if dist < closestdist then closestdist = dist; closestplayer = i end end self.teleportplayer = closestplayer end if self.teleportplayer then local startp, endp = self.teleportplayer, self.teleportplayer if type(self.teleportplayer) == "boolean" then startp, endp = 1, players end for i = startp, endp do local p = objects["player"][i] if p then local ox, oy = self.teleportplayeroffsetx or 0, self.teleportplayeroffsety or 0 p.x = (self.x+self.width/2)-(p.width/2)+ox p.y = (self.y+self.height/2)-(p.height/2)+oy if self.teleportplayerspeedx and self.teleportplayerspeedy then p.speedx = self.teleportplayerspeedx p.speedy = self.teleportplayerspeedy end end end end if self.jumps then self.jumptimer = self.jumptimer + dt if self.jumptimer > self.jumptime then self.jumptimer = self.jumptimer - self.jumptime --decide whether up or down local dir if self.y+self.height-0.01 > (mapheight-(self.jumponlyupdistfrombottom or 4)) then dir = "up" elseif self.y < 6 then dir = "down" else if math.random(2) == 1 then dir = "up" else dir = "down" end end if dir == "up" then self.speedy = -self.jumpforce self.mask[2] = true self.jumping = "up" self.falling = true else self.speedy = -self.jumpforcedown self.mask[2] = true self.jumping = "down" self.jumpingy = self.y self.falling = true end end if self.jumping then if self.jumping == "up" then if self.speedy > 0 then self.jumping = false self.mask[2] = false end elseif self.jumping == "down" then if self.y > self.jumpingy + self.height+1.1 then self.jumping = false self.mask[2] = false end end end end if self.facesplayer then local closestplayer = 1 local closestdist = math.sqrt((objects["player"][1].x-self.x)^2+(objects["player"][1].y-self.y)^2) for i = 2, players do local v = objects["player"][i] local dist = math.sqrt((v.x-self.x)^2+(v.y-self.y)^2) if dist < closestdist then closestdist = dist closestplayer = i end end if objects["player"][closestplayer].x + objects["player"][closestplayer].width/2 > self.x + self.width/2 then self.animationdirection = "left" else self.animationdirection = "right" end end if self.chasetime then if self.chasetimer > self.chasetime then local closestplayer = 1 local closestdist = math.sqrt((objects["player"][1].x-self.x)^2+(objects["player"][1].y-self.y)^2) for i = 2, players do local v = objects["player"][i] local dist = math.sqrt((v.x-self.x)^2+(v.y-self.y)^2) if dist < closestdist then closestdist = dist closestplayer = i end end if objects["player"][closestplayer].x + objects["player"][closestplayer].width/2 < self.x + self.width/2 then self.speedx = -(self.chasespeed or 1.5) self.chasemariowasleft = true elseif self.chasemariowasleft then self.chasemariowasleft = nil self.chasetimer = 0 self.startx = self.x end else self.chasetimer = self.chasetimer + dt end end if self.animationtype == "character" then if self.oldx then --Mario-like animation local xdiff = self.x-self.oldx local ydiff = self.y-self.oldy local running = math.abs(xdiff) > 0.001 local jumping = math.abs(ydiff) > 0.001 local falling = ydiff > 0.001 local runstart = self.idleframes+1 local jumpstart = self.idleframes+self.runframes+1 local fallstart = self.idleframes+self.runframes+self.jumpframes+1 if self.fallframes > 0 and falling then if self.quadi < fallstart or self.quadi > fallstart+self.fallframes-1 then self.quadi = fallstart self.animationtimer = 0 end self.animationtimer = self.animationtimer + dt if self.quadi <= fallstart+self.fallframes-1 then while self.animationtimer > (self.fallanimationspeed or 0.1) do self.animationtimer = self.animationtimer - (self.fallanimationspeed or 0.1) self.quadi = math.min(fallstart+self.fallframes-1, (self.quadi+1 -fallstart)%(self.fallframes) +fallstart) end end elseif self.jumpframes > 0 and jumping then if self.quadi < jumpstart or self.quadi > jumpstart+self.jumpframes-1 then self.quadi = jumpstart self.animationtimer = 0 end self.animationtimer = self.animationtimer + dt if self.quadi <= jumpstart+self.jumpframes-1 then while self.animationtimer > (self.jumpanimationspeed or 0.1) do self.animationtimer = self.animationtimer - (self.jumpanimationspeed or 0.1) self.quadi = math.min(jumpstart+self.jumpframes-1, (self.quadi+1 -jumpstart)%(self.jumpframes) +jumpstart) end end elseif self.runframes > 0 and running then if self.quadi < runstart or self.quadi > runstart+self.runframes-1 then self.quadi = runstart self.animationtimer = 0 end self.animationtimer = self.animationtimer + dt while self.animationtimer > (self.runanimationspeed or 0.1) do self.animationtimer = self.animationtimer - (self.runanimationspeed or 0.1) self.quadi = (self.quadi+1 -runstart)%(self.runframes) +runstart end elseif self.idleframes > 1 then if self.quadi < 1 or self.quadi > 1+self.runframes-1 then self.quadi = 1 self.animationtimer = 0 end while self.animationtimer > (self.idleanimationspeed or 0.1) do self.animationtimer = self.animationtimer - (self.idleanimationspeed or 0.1) self.quadi = (self.quadi+1 -1)%(self.idleframes-1) +1 end else if self.quadi < 1 or self.quadi > 1+self.runframes-1 then self.quadi = 1 end self.quadi = 1 end self.quad = self.quadgroup[self.quadi] if not self.dontmirror then if xdiff > 0 then self.animationdirection = "left" elseif xdiff < 0 then self.animationdirection = "right" end end end self.oldx = self.x self.oldy = self.y end --transform if falling if self.transforms and self.falling and self:gettransformtrigger("falling") then self:transform(self:gettransformsinto("falling")) return true end --platform if self.platform and self.platformchecktable and (not (self.trackplatform and self.tracked)) then local xdiff = self.speedx*dt if self.speedx == 0 and self.x ~= oldx then xdiff = self.x-oldx end local ydiff = self.speedy*dt if self.speedy == 0 and self.y ~= oldy then ydiff = self.y-oldy end local condition = false if ydiff < 0 then condition = "ignoreplatforms" end for i, v in pairs(self.platformchecktable) do for j, w in pairs(objects[v]) do if w.width and (not w.ignoreplatform) then if (not self.noplatformcarrying) and inrange(w.x, self.x-w.width, self.x+self.width) then --vertical carry if ((w.y == self.y - w.height) or ((self.movement == "circle" or self.movement == "flyvertical" or self.movement == "path" or self.speedy ~= 0) and w.y+w.height >= self.y-0.1 and w.y+w.height < self.y+0.1)) and (not w.jumping) and not (self.speedy > 0 and w.speedy < 0) then --and w.speedy >= self.speedy if #checkrect(w.x+xdiff, self.y-w.height, w.width, w.height, {"exclude", w}, true, condition) == 0 then w.x = w.x + xdiff w.y = self.y-w.height w.falling = false w.speedy = self.speedy end end end if self.platformpush and xdiff ~= 0 then --horizontal push if inrange(w.y+w.height/2, self.y, self.y+self.height) then if xdiff > 0 and w.x < self.x+self.width and w.x+w.width > self.x+self.width then --right if #checkrect(self.x+self.width, w.y, w.width, w.height, {"exclude", w}, true, "ignoreplatforms") == 0 then w.x = self.x+self.width end elseif xdiff < 0 and w.x+w.width > self.x and w.x < self.x then if #checkrect(self.x-w.width, w.y, w.width, w.height, {"exclude", w}, true, "ignoreplatforms") == 0 then w.x = self.x-w.width end end end end end end end end --Check if player is near if self.transforms and (self:gettransformtrigger("playernear") or self:gettransformtrigger("playernotnear")) then if type(self.playerneardist) == "number" then for i = 1, players do local v = objects["player"][i] if inrange(v.x+v.width/2, self.x+self.width/2-(self.playerneardist or 3), self.x+self.width/2+(self.playerneardist or 3)) then if self:gettransformtrigger("playernear") then self:transform(self:gettransformsinto("playernear")) return end elseif self:gettransformtrigger("playernotnear") then self:transform(self:gettransformsinto("playernotnear")) return end end elseif type(self.playerneardist) == "table" and #self.playerneardist == 4 then local col = checkrect(self.x+self.playerneardist[1], self.y+self.playerneardist[2], self.playerneardist[3], self.playerneardist[4], {"player"}) if #col > 0 then if self:gettransformtrigger("playernear") then self:transform(self:gettransformsinto("playernear")) return end elseif self:gettransformtrigger("playernotnear") then self:transform(self:gettransformsinto("playernotnear")) return end end end --Check if player if facing the enemy if self.staticifseen or self.staticifnotseen or (self.transforms and (self:gettransformtrigger("seen") or self:gettransformtrigger("notseen"))) then local lookedat = false for i = 1, players do local v = objects["player"][i] if v.x+(self.width/2) > self.x+(self.width/2) then if v.portals ~= "none" then --AE ADDITION (change) if v.pointingangle > 0 then lookedat = true end else if v.animationdirection == "left" then lookedat = true end end else if v.portals ~= "none" then --AE ADDITION (change) if v.pointingangle < 0 then lookedat = true end else if v.animationdirection == "right" then lookedat = true end end end end if (self.transforms and self:gettransformtrigger("notseen")) or self.staticifnotseen then lookedat = not lookedat end if lookedat then if self.staticifseen or self.staticifnotseen then self.static = true else if self:gettransformtrigger("seen") then self:transform(self:gettransformsinto("seen")) else self:transform(self:gettransformsinto("notseen")) end return end else if self.staticifseen or self.staticifnotseen then self.static = false end end end if self.rotatetowardsplayer then for i = 1, players do local v = objects["player"][i] if not v.dead then self.rotation = (-math.atan2((v.x+v.width/2)-(self.x+self.width/2), (v.y+v.height/2)-(self.y+self.height/2-3/16)))-math.pi/2 end end end if self.carryable then if self.thrown then if self.throwntime then self.throwntimer = self.throwntimer - dt if self.throwntimer < 0 then if self.fliponcarry then self.flipped = false end if self.noplayercollisiononthrow then self.mask[3] = not self.mask[1] --no player collision end self.thrown = false if self.speedx > 0 then if not self.dontmirror then self.animationdirection = "left" end self.speedx = math.abs(self.speedx) elseif self.speedx < 0 then if not self.dontmirror then self.animationdirection = "right" end self.speedx = -math.abs(self.speedx) end end end elseif self.carryparent then local oldx = self.x local oldy = self.y local offsetx = (self.carryoffsetx or 0) if self.carryoffsetx then if self.carryparent.pointingangle > 0 then offsetx = -offsetx end end self.x = (self.carryparent.x+self.carryparent.width/2-self.width/2) + offsetx self.y = (self.carryparent.y-self.height)+(self.carryoffsety or 0) if self.carryquad then self.quadi = self.carryquad self.quad = self.quadgroup[self.quadi] end if self.emancipatecheck then for h, u in pairs(emancipationgrills) do if u.active then if u.dir == "hor" then if inrange(self.x+6/16, u.startx-1, u.endx, true) and inrange(u.y-14/16, oldy, self.y, true) then self:emancipate(h) end else if inrange(self.y+6/16, u.starty-1, u.endy, true) and inrange(u.x-14/16, oldx, self.x, true) then self:emancipate(h) end end end end end --drop if not holding button if self.carryifholdingrunbutton and not runkey(self.carryparent.playernumber) then self.carryparent:use() end else self.pickupready = false for j, w in pairs(objects["player"]) do local col = checkrect(self.x+self.carryrange[1], self.y+self.carryrange[2], self.carryrange[3], self.carryrange[4], {"player"}) if #col > 0 then w.pickupready = self self.pickupready = true --carry if holding button if (self.carryifholdingrunbutton and runkey(w.playernumber)) and not w.pickup then self:used(w.playernumber) w.pickupready = false break end end end self.userect.x, self.userect.y = self.x+self.carryrange[1], self.y+self.carryrange[2] end end --blow entities kreygasm if self.blowrange then local col = checkrect(self.x+self.blowrange[1], self.y+self.blowrange[2], self.blowrange[3], self.blowrange[4], self.blowchecktable) for j = 1, #col, 2 do local a, b = col[j], objects[col[j]][col[j+1]] if (b.active or self.blownotactiveenemies) and ((not b.static) or self.blowstaticenemies) and b.blowable ~= false and (b.speedx or self.blowstrong) then if self.blowstrong then local fx, fy = b.x+(self.blowspeedx or 0)*dt, b.y+(self.blowspeedy or 0)*dt --future position local condition = "ignoreplatforms" if fy > b.y then condition = false end if not checkintile(fx, fy, b.width, b.height, tileentities, b, condition) then b.x = fx b.y = fy end else b.speedx = b.speedx+(self.blowspeedx or 0)*dt b.speedy = b.speedy+(self.blowspeedy or 0)*dt end if b.speedx then if self.blowminspeedx then b.speedx = math.max(self.blowminspeedx, b.speedx) end if self.blowmaxspeedx then b.speedx = math.min(self.blowmaxspeedx, b.speedx) end if self.blowminspeedy then b.speedy = math.max(self.blowminspeedy, b.speedy) end if self.blowmaxspeedy then b.speedy = math.min(self.blowmaxspeedy, b.speedy) end end if (not self.blowstrong) and a == "player" and b.speedy < 0 then b.falling = true end end end end if self.customtimer then self.customtimertimer = self.customtimertimer + dt while self.customtimertimer > self.customtimer[self.currentcustomtimerstage][1] do self.customtimertimer = self.customtimertimer - self.customtimer[self.currentcustomtimerstage][1] self:customtimeraction(self.customtimer[self.currentcustomtimerstage][2], self.customtimer[self.currentcustomtimerstage][3], self.customtimer[self.currentcustomtimerstage][4]) self.currentcustomtimerstage = self.currentcustomtimerstage + 1 if self.currentcustomtimerstage > #self.customtimer then self.currentcustomtimerstage = 1 if self.dontloopcustomtimer then self.customtimer = false break end end end end end function enemy:addoutput(a, t) table.insert(self.outtable, {a, t}) end function enemy:shotted(dir, cause, high, fireball, star) if self.resistseverything then return false end if fireball and self.resistsfire then return false end if star and self.resistsstar then return false end if cause and cause == "dkhammer" and self.resistsdkhammer then return false end if self.shothealth then if self.shothealth > 1 then self.shothealth = self.shothealth - 1 if self.transforms then if self:gettransformtrigger("shotdamage") then self:transform(self:gettransformsinto("shotdamage")) return elseif self:gettransformtrigger("damage") then self:transform(self:gettransformsinto("damage")) return end end return end elseif self.health then --AE ADDITION if self.health > 1 then self.health = self.health - 1 if self.transforms then if self:gettransformtrigger("damage") then self:transform(self:gettransformsinto("damage")) return end end return end end if self.givecoinwhenshot then collectcoin(nil, nil, tonumber(self.givecoinwhenshot) or 1) end if not self.noshotsound then playsound("shot") end if self.transforms then if self:gettransformtrigger("shot") then self:transform(self:gettransformsinto("shot"), nil, "death") return elseif self:gettransformtrigger("death") then self:transform(self:gettransformsinto("death"), nil, "death") return end end self.speedy = -(self.shotjumpforce or shotjumpforce) if high then self.speedy = self.speedy*2 end self.direction = dir or "right" self.gravity = shotgravity if self.direction == "left" then self.speedx = -(self.shotspeedx or shotspeedx) else self.speedx = self.shotspeedx or shotspeedx end if self.shellanimal then self.small = true self.quad = self.quadgroup[self.smallquad] if cause == true then --below self.upsidedown = true self.kickedupsidedown = true self.offsetY = self.upsidedownoffsety or 4 self.quadcenterY = self.upsidedownquadcentery or self.startquadcenterY self.movement = self.smallmovement self.animationtype = "none" else self.shot = true self.active = false end else if self.shotframe then self.quad = self.quadgroup[self.shotframe] end self.shot = true self.active = false end if self.doesntflyawayonfireball then self.kill = true self.drawable = false end return true end function enemy:customtimeraction(action, arg) --set to a variable local ogarg = arg if arg and type(arg) == "table" and arg[1] and arg[2] and arg[1] == "property" then arg = self[arg[2]] end if type(action) == "table" then --The new *better* custom timer format local a = action[1] --action local p = action[2] --parameter if a == "set" then self[p] = arg if p == "quadno" then --update frame self.quad = self.quadgroup[self.quadno] end elseif a == "add" then self[p] = self[p] + arg elseif a == "subtract" then self[p] = self[p] - arg elseif a == "multiply" then self[p] = self[p] * arg elseif a == "divide" then self[p] = self[p] / arg elseif a == "reverse" then if type(self[p]) == "boolean" then self[p] = not self[p] else self[p] = -self[p] end elseif a == "random" then if type(arg) == "number" then self[p] = math.random()*arg else self[p] = arg[math.random(#arg)] end elseif a == "abs" then self[p] = math.abs(self[p]) elseif a == "sqrt" then self[p] = math.sqrt(self[p]) elseif a == "mod" then self[p] = self[p]%arg elseif a == "pow" then self[p] = math.pow(self[p],arg) elseif a == "round" then self[p] = math.floor(self[p]+0.5) elseif a == "floor" then self[p] = math.floor(self[p]) elseif a == "ceil" then self[p] = math.ceil(self[p]) elseif a == "sin" then self[p] = math.sin(arg) elseif a == "cos" then self[p] = math.cos(arg) elseif a == "tan" then self[p] = math.tan(arg) elseif a == "atan2" then local in1, in2 = ogarg[1],ogarg[2] if ogarg[1] and type(ogarg[1]) == "table" and ogarg[1][1] and ogarg[1][2] and ogarg[1][1] == "property" then in1 = self[ogarg[1]] end if ogarg[2] and type(ogarg[2]) == "table" and ogarg[2][1] and ogarg[2][2] and ogarg[2][1] == "property" then in2 = self[ogarg[2]] end self[p] = math.atan2(in1,in2) elseif a == "min" then self[p] = math.min(self[p],arg) elseif a == "max" then self[p] = math.max(self[p],arg) elseif a == "tonumber" then self[p] = tonumber(self[p]) elseif a == "tostring" then self[p] = tostring(self[p]) end else --backwards compatibility if action == "bounce" then if self.speedy == 0 then self.speedy = -(arg or 10) end elseif action == "playsound" then if self.sound and arg == self.t then playsound(self.sound) else playsound(arg) end elseif action == "spawnenemy" then if self.spawnsenemyrandoms then self.spawnsenemy = self.spawnsenemyrandoms[math.random(#self.spawnsenemyrandoms)] end self:spawnenemy(self.spawnsenemy) elseif string.sub(action, 0, 7) == "reverse" then local parameter = string.sub(action, 8, string.len(action)) self[parameter] = -self[parameter] elseif string.sub(action, 0, 3) == "add" then local parameter = string.sub(action, 4, string.len(action)) self[parameter] = self[parameter] + arg elseif string.sub(action, 0, 8) == "multiply" then local parameter = string.sub(action, 9, string.len(action)) self[parameter] = self[parameter] * arg elseif action == "setframe" then self.quad = self.quadgroup[arg] elseif string.sub(action, 0, 3) == "set" then self[string.sub(action, 4, string.len(action))] = arg end end end function enemy:func(i) -- 0-1 in please return (-math.cos(i*math.pi*2)+1)/2 end function enemy:globalcollide(a, b, c, d, dir) if a == "tile" then if not self.resistsspikes then dir = twistdirection(self.gravitydirection, dir) if dir == "ceil" and tilequads[map[b.cox][b.coy][1]]:getproperty("spikesdown", b.cox, b.coy) then self:shotted() return false elseif dir == "right" and tilequads[map[b.cox][b.coy][1]]:getproperty("spikesleft", b.cox, b.coy) then self:shotted() return false elseif dir == "left" and tilequads[map[b.cox][b.coy][1]]:getproperty("spikesright", b.cox, b.coy) then self:shotted() return false elseif dir == "floor" and tilequads[map[b.cox][b.coy][1]]:getproperty("spikesup", b.cox, b.coy) then self:shotted() return false end end end if a == "platform" or a == "seesawplatform" then if dir == "floor" then if self.jumping and self.speedy < -jumpforce + 0.1 then return true end else return true end end if a == "player" and self.removeonmariocontact then if self.transforms then if self:gettransformtrigger("mariocontact") then self:transform(self:gettransformsinto("mariocontact"), nil, "death") elseif self:gettransformtrigger("death") then self:transform(self:gettransformsinto("death"), nil, "death") return end end self.kill = true self.drawable = false return true end if self.kickable then if a == "player" then if b.x+b.width/2 > self.x+self.width/2 then self:kick("left") else self:kick("right") end return true end end if self.meltice and b.meltsice and self.transforms and self:gettransformtrigger("melt") then self:transform(self:gettransformsinto("melt")) end if b.meltice and self.meltsice then return true end if self.transforms and (self:gettransformtrigger("globalcollide") or self:gettransformtrigger("collide")) and (not self.justspawned) then if self:gettransformtrigger("globalcollide") then if self:handlecollisiontransform("globalcollide",a,b) then if not self.dotransformaftercollision then return true end end else if self:handlecollisiontransform("collide",a,b) then if not self.dotransformaftercollision then return true end end end elseif self.transforms and dir == "passive" and self:gettransformtrigger("passivecollide") and (not self.justspawned) then if self:handlecollisiontransform("passivecollide",a,b) then if not self.dotransformaftercollision then return true end end end if self.thrown and (not self.dontkillwhenthrown) and not (b.resistsenemykill or b.resistseverything) then if a == "enemy" then if b:shotted("right", false, false, true) ~= false then addpoints(b.firepoints or 200, self.x, self.y) if self.throwncollisionignore then return true end end if not self.throwncombo then self.thrown = false self:shotted(self.animationdirection) elseif self.throwncombospeedx and self.throwncombospeedy then if self.speedx > 0 then self.speedx = self.throwncombospeedx else self.speedx = -self.throwncombospeedx end self.speedy = self.throwncombospeedy end elseif fireballkill[a] then if b:shotted("right") ~= false and a ~= "bowser" then addpoints(firepoints[a] or 200, self.x, self.y) if self.throwncollisionignore then return true end end if not self.throwncombo then self.thrown = false self:shotted(self.animationdirection) elseif self.throwncombospeedx and self.throwncombospeedy then if self.speedx > 0 then self.speedx = self.throwncombospeedx else self.speedx = -self.throwncombospeedx end self.speedy = self.throwncombospeedy end end end if self.killsenemies and ((self.killsenemiesonsides and (dir == "left" or dir == "right")) or (self.killsenemiesonbottom and dir == "floor") or (self.killsenemiesontop and dir == "ceil") or (self.killsenemiesonleft and dir == "left") or (self.killsenemiesonright and dir == "right") or (self.killsenemiesonpassive and dir == "passive")) and a == "enemy" and not (b.resistsenemykill or b.resistseverything) then return true end if a ~= "enemy" then if self.freezesenemies then if iceballfreeze[a] then if b.freezable and (not b.frozen) then table.insert(objects["ice"], ice:new(b.x+b.width/2, b.y+b.height, b.width, b.height, a, b)) end end end if self.killsenemies and ((self.killsenemiesonsides and (dir == "left" or dir == "right")) or (self.killsenemiesonbottom and dir == "floor") or (self.killsenemiesontop and dir == "ceil") or (self.killsenemiesonleft and dir == "left") or (self.killsenemiesonright and dir == "right") or (self.killsenemiesonpassive and dir == "passive")) then --AE ADDITION if b.shotted and not (b.resistsenemykill or b.resistseverything) then local dir = "right" if self.speedx < 0 then dir = "left" end if b:shotted(dir) ~= false then if self.bouncesonenemykill then self.speedy = -(self.bounceforce or 10) end addpoints((firepoints[b.t] or 200), self.x, self.y) return true end end end end if a == "fireball" and self.resistsfire then return true end if b.freezesenemies and self.freezable then if (not self.frozen) then table.insert(objects["ice"], ice:new(self.x+self.width/2, self.y+self.height, self.width, self.height, "enemy", self)) return true end end if (b.killsenemies and ((b.killsenemiesonsides and (dir == "left" or dir == "right")) or (b.killsenemiesonbottom and dir == "ceil") or (b.killsenemiesontop and dir == "floor") or (b.killsenemiesonleft and dir == "right") or (b.killsenemiesonright and dir == "left") or (b.killsenemiesonpassive and dir == "passive"))) and (not (self.resistsenemykill or self.resistseverything)) then local dir = "right" if b.speedx < 0 then dir = "left" end if b.enemykillsdontflyaway then self.doesntflyawayonfireball = true end self:shotted(dir) if b.bouncesonenemykill then b.speedy = -(b.bounceforce or 10) end if b.enemykillsinstantly then self.instantdelete = true self.output() end addpoints((firepoints[self.t] or 200), self.x, self.y) return true end if self.breaksblocks then if (self.breakblockside == nil or self.breakblockside == "global") then if a == "tile" then if self.breakshardblocks and (tilequads[map[b.cox][b.coy][1]].coinblock or (tilequads[map[b.cox][b.coy][1]].debris and blockdebrisquads[tilequads[map[b.cox][b.coy][1]].debris])) then -- hard block destroyblock(b.cox, b.coy) else hitblock(b.cox, b.coy, self, true) end elseif a == "flipblock" then if self.breaksflipblocks then b:destroy() end end end end if self.nocollidestops or b.nocollidestops then return true end end function enemy:leftcollide(a, b, c, d) if self:globalcollide(a, b, c, d, "left") then return false end if self.ignoreleftcollide or b.ignorerightcollide then --AE ADDITION return false end if a == "tile" then --AE ADDITION --slant if self.onslant == "right" and self.y+self.height-2/16 <= b.y then self.y = b.y-self.height return false end end if a == "pixeltile" and b.dir == "right" and self.y < b.y then --AE ADDITION self.y = self.y - b.step return false end if self.transforms and self:gettransformtrigger("leftcollide") and (not self.justspawned) then if self:handlecollisiontransform("leftcollide",a,b) then if not self.dotransformaftercollision then return end end end if a == "player" then --AE ADDITION return false end if self.movement == "crawl" then if (a == "tile" or a == "buttonblock" or a == "flipblock" or a == "frozencoin" or (a == "enemy" and b.static)) then if self.crawlfloor ~= "left" then if self.crawldirection == "left" then self.speedy = -self.crawlspeed else self.speedy = self.crawlspeed end end self.speedx = 0 self.gravity = 0 self.gravityx = -(self.crawlgravity or yacceleration) self.crawlfloor = "left" self.aroundcorner = false return true elseif self.crawlfloor == "up" or self.crawlfloor == "down" then if self.crawldirection == "left" then self.crawldirection = "right" else self.crawldirection = "left" end self.speedx = self.crawlspeed return true end end if (not self.frozen) and (self.reflects or self.reflectsx) then self.speedx = math.abs(self.speedx) end if self.breaksblocks then if (self.breakblockside == "sides" or self.breakblockside == "left") then if a == "tile" then if self.breakshardblocks and (tilequads[map[b.cox][b.coy][1]].coinblock or (tilequads[map[b.cox][b.coy][1]].debris and blockdebrisquads[tilequads[map[b.cox][b.coy][1]].debris])) then -- hard block destroyblock(b.cox, b.coy) else hitblock(b.cox, b.coy, self, true) end elseif a == "flipblock" then if self.breaksflipblocks then b:destroy() end end end end if self.gel then if a == "tile" then local x, y = b.cox, b.coy if (inmap(x+1, y) and tilequads[map[x+1][y][1]].collision) or (inmap(x, y) and tilequads[map[x][y][1]].collision == false) then return end --see if adjsajcjet tile is a better fit if math.floor(self.y+self.height/2)+1 ~= y then if inmap(x, math.floor(self.y+self.height/2)+1) and tilequads[map[x][math.floor(self.y+self.height/2)+1][1]].collision then y = math.floor(self.y+self.height/2)+1 end end self:applygel("right", x, y) elseif a == "lightbridgebody" and b.dir == "ver" then self:applygel("right", b) end end if self.movement == "chase" and self.chasebounceforcex then self.speedx = self.chasebounceforcex if self.speedy == 0 and self.chasebounceforcey then self.speedy = -self.chasebounceforcey end return false end if (not self.frozen) and self.movement == "truffleshuffle" then self.speedx = self.truffleshufflespeed if not self.dontmirror then self.animationdirection = "left" end return false elseif (not self.frozen) and self.small then if (a ~= "enemy" and not tablecontains(enemies, a)) or (b.resistsenemykill or b.resistseverything) then self.speedx = self.smallspeed if not self.kickedupsidedown then if a == "tile" then hitblock(b.cox, b.coy, self, true) else playsound("blockhit") end end return false end end end function enemy:rightcollide(a, b, c, d) if self:globalcollide(a, b, c, d, "right") then return false end if self.ignorerightcollide or b.ignoreleftcollide then --AE ADDITION return false end if a == "tile" then --AE ADDITION --slant if self.onslant == "left" and self.y+self.height-2/16 <= b.y then self.y = b.y-self.height return false end end if a == "pixeltile" and b.dir == "left" and self.y < b.y then --AE ADDITION self.y = self.y - b.step return false end if self.transforms and self:gettransformtrigger("rightcollide") and (not self.justspawned) then if self:handlecollisiontransform("rightcollide",a,b) then if not self.dotransformaftercollision then return end end end if a == "player" then --AE ADDITION return false end if self.movement == "crawl" then if (a == "tile" or a == "buttonblock" or a == "flipblock" or a == "frozencoin" or (a == "enemy" and b.static)) then if self.crawlfloor ~= "right" then if self.crawldirection == "left" then self.speedy = self.crawlspeed else self.speedy = -self.crawlspeed end end self.speedx = 0 self.gravity = 0 self.gravityx = (self.crawlgravity or yacceleration) self.crawlfloor = "right" self.aroundcorner = false return true elseif self.crawlfloor == "up" or self.crawlfloor == "down" then if self.crawldirection == "right" then self.crawldirection = "left" else self.crawldirection = "right" end self.speedx = -self.crawlspeed return true end end if (not self.frozen) and (self.reflects or self.reflectsx) then self.speedx = -math.abs(self.speedx) end if self.breaksblocks then if (self.breakblockside == "sides" or self.breakblockside == "right") then if a == "tile" then if self.breakshardblocks and (tilequads[map[b.cox][b.coy][1]].coinblock or (tilequads[map[b.cox][b.coy][1]].debris and blockdebrisquads[tilequads[map[b.cox][b.coy][1]].debris])) then -- hard block destroyblock(b.cox, b.coy) else hitblock(b.cox, b.coy, self, true) end elseif a == "flipblock" then if self.breaksflipblocks then b:destroy() end end end end if self.gel then if a == "tile" then local x, y = b.cox, b.coy if (inmap(x-1, y) and tilequads[map[x-1][y][1]].collision) or (inmap(x, y) and tilequads[map[x][y][1]].collision == false) then return end --see if adjsajcjet tile is a better fit if math.floor(self.y+self.height/2)+1 ~= y then if inmap(x, math.floor(self.y+self.height/2)+1) and tilequads[map[x][math.floor(self.y+self.height/2)+1][1]].collision then y = math.floor(self.y+self.height/2)+1 end end self:applygel("left", x, y) elseif a == "lightbridgebody" and b.dir == "ver" then self:applygel("left", b) end end if self.movement == "chase" and self.chasebounceforcex then self.speedx = -self.chasebounceforcex if self.speedy == 0 and self.chasebounceforcey then self.speedy = -self.chasebounceforcey end return false end if (not self.frozen) and self.movement == "truffleshuffle" then self.speedx = -self.truffleshufflespeed if not self.dontmirror then self.animationdirection = "right" end return false elseif (not self.frozen) and self.small then if (a ~= "enemy" and not tablecontains(enemies, a)) or (b.resistsenemykill or b.resistseverything) then self.speedx = -self.smallspeed if not self.kickedupsidedown then if a == "tile" then hitblock(b.cox, b.coy, self, true) else playsound("blockhit") end end return false end end end function enemy:ceilcollide(a, b, c, d) if self:globalcollide(a, b, c, d, "ceil") then return false end if self.ignoreceilcollide or b.ignorefloorcollide then --AE ADDITION return false end if self.transforms and self:gettransformtrigger("ceilcollide") and (not self.justspawned) then if self:handlecollisiontransform("ceilcollide",a,b) then if not self.dotransformaftercollision then return end end end if a == "player" then --AE ADDITION return false end if self.movement == "crawl" then if (a == "tile" or a == "buttonblock" or a == "flipblock" or a == "frozencoin" or (a == "enemy" and b.static)) then if self.crawlfloor ~= "up" then if self.crawldirection == "left" then self.speedx = self.crawlspeed else self.speedx = -self.crawlspeed end end self.speedy = 0 self.gravity = -(self.crawlgravity or yacceleration) self.gravityx = 0 self.aroundcorner = false self.crawlfloor = "up" return true elseif self.crawlfloor == "left" or self.crawlfloor == "right" then if self.crawldirection == "left" then self.crawldirection = "right" else self.crawldirection = "left" end self.speedy = self.crawlspeed return true end end if (not self.frozen) and (self.reflects or self.reflectsy) then self.speedy = math.abs(self.speedy) end if self.breaksblocks then if self.breakblockside == "ceil" then if a == "tile" then if self.breakshardblocks and (tilequads[map[b.cox][b.coy][1]].coinblock or (tilequads[map[b.cox][b.coy][1]].debris and blockdebrisquads[tilequads[map[b.cox][b.coy][1]].debris])) then -- hard block destroyblock(b.cox, b.coy) else hitblock(b.cox, b.coy, self, true) end elseif a == "flipblock" then if self.breaksflipblocks then b:destroy() end end end end if self.gel then if a == "tile" then local x, y = b.cox, b.coy if not inmap(x, y+1) or tilequads[map[x][y+1][1]].collision == false then local x, y = b.cox, b.coy self:applygel("bottom", x, y) end elseif a == "lightbridgebody" and b.dir == "hor" then self:applygel("bottom", b) end end end function enemy:floorcollide(a, b, c, d) if self:globalcollide(a, b, c, d, "floor") then return false end if self.ignorefloorcollide or b.ignoreceilcollide then --AE ADDITION return false end --Shake Ground --AE ADDITION if self.shakesground and (a == "tile") and self.falling and onscreen(self.x, self.y, self.width, self.height) then for i = 1, players do objects["player"][i]:groundshock() end earthquake = 4 playsound(thwompsound) self.speedy = 0 end if self.transforms and self:gettransformtrigger("floorcollide") and (not self.justspawned) then if self:handlecollisiontransform("floorcollide",a,b) then if not self.dotransformaftercollision then return end end end if a == "player" then --AE ADDITION return false end if self.movement == "crawl" then if (a == "tile" or a == "buttonblock" or a == "flipblock" or a == "frozencoin" or (a == "enemy" and b.static)) then if self.crawlfloor ~= "down" then if self.crawldirection == "right" then self.speedx = self.crawlspeed else self.speedx = -self.crawlspeed end end self.speedy = 0 self.gravity = (self.crawlgravity or yacceleration) self.gravityx = 0 self.aroundcorner = false self.crawlfloor = "down" return true elseif self.crawlfloor == "left" or self.crawlfloor == "right" then if self.crawldirection == "right" then self.crawldirection = "left" else self.crawldirection = "right" end self.speedy = -self.crawlspeed return true end end --slants/slopes --AE ADDITION local onslant = (a == "pixeltile") if onslant then self.onslant = b.dir self.onslantstep = b.step else self.onslant = false end if (not self.frozen) and (self.reflects or self.reflectsy) then self.speedy = -math.abs(self.speedy) end if self.kickedupsidedown then self.speedx = 0 self.kickedupsidedown = false end if self.thrown then if self.thrownbounce then self.speedy = -math.abs(self.speedy)*self.thrownbounce if self.throwndamping then self.speedx = self.speedx*self.throwndamping end end if self.throwntimeendonfloorcollide then self.throwntimer = 0 end end if self.breaksblocks then if self.breakblockside == "floor" then if a == "tile" then if self.breakshardblocks and (tilequads[map[b.cox][b.coy][1]].coinblock or (tilequads[map[b.cox][b.coy][1]].debris and blockdebrisquads[tilequads[map[b.cox][b.coy][1]].debris])) then -- hard block destroyblock(b.cox, b.coy) else hitblock(b.cox, b.coy, self, true) end elseif a == "flipblock" then if self.breaksflipblocks then b:destroy() end end end end if self.gel then if a == "tile" then local x, y = b.cox, b.coy if (inmap(x, y-1) and tilequads[map[x][y-1][1]].collision) or (inmap(x, y) and tilequads[map[x][y][1]].collision == false) then return end --see if adjsajcjet tile is a better fit if math.floor(self.x+self.width/2)+1 ~= x then local t = map[x][y][1] if inmap(x, y) and tilequads[t].collision and (not (tilequads[t].invisible or tilequads[t].grate)) then x = math.floor(self.x+self.width/2)+1 end end if inmap(x, y) and tilequads[map[x][y][1]].collision then if map[x][y]["gels"]["top"] == self.gel or (self.gel == 5 and not map[x][y]["gels"]["top"]) then if self.speedx > 0 then for cox = x+1, x+self.speedx*0.2 do if inmap(cox, y-1) and tilequads[map[cox][y][1]].collision == true and tilequads[map[cox][y-1][1]].collision == false then if self:applygel("top", cox, y) then break end else break end end elseif self.speedx < 0 then for cox = x-1, x+self.speedx*0.2, -1 do if inmap(cox, y-1) and tilequads[map[cox][y][1]].collision and tilequads[map[cox][y-1][1]].collision == false then if self:applygel("top", cox, y) then break end else break end end end else self:applygel("top", x, y) end end elseif a == "lightbridgebody" and b.dir == "hor" then self:applygel("top", b) end end self.falling = false if (not self.frozen) and self.bounces and (not self.bouncedelay) then self.speedy = -(self.bounceforce or 10) self.falling = true end end function enemy:passivecollide(a, b, c, d) if self:globalcollide(a, b, c, d, "passive") then return false end if a == "player" then --AE ADDITION return false end end function enemy:startfall() self.falling = true end function enemy:stomp(x, b) if self.stompable or (self.shellanimal and self.small) then if self.pushmariowhenstomped and b then b.y = self.y - b.height-1/16 end if self.stomphealth then if self.stomphealth > 1 then self.stomphealth = self.stomphealth - 1 if self.transforms then if self:gettransformtrigger("stompdamage") then self:transform(self:gettransformsinto("stompdamage")) return elseif self:gettransformtrigger("damage") then self:transform(self:gettransformsinto("damage")) return end end return end elseif self.health then --AE ADDITION if self.health > 1 then self.health = self.health - 1 if self.transforms then if self:gettransformtrigger("damage") then self:transform(self:gettransformsinto("damage")) return end end return end end if self.transforms then if self:gettransformtrigger("stomp") then self:transform(self:gettransformsinto("stomp"), nil, "death") return elseif self:gettransformtrigger("death") then self:transform(self:gettransformsinto("death"), nil, "death") return end end if self.givecoinwhenstomped then collectcoin(nil, nil, tonumber(self.givecoinwhenstomped) or 1) end if self.shellanimal then if not self.small then self.quadcenterY = self.smallquadcentery or 19--self.startquadcenterY self.offsetY = self.smalloffsety or 0--self.startoffsetY self.quad = self.quadgroup[self.smallquad] self.small = true self.trackable = false self.movement = self.smallmovement self.speedx = 0 self.animationtype = "none" elseif self.speedx == 0 then if self.x > x then self.speedx = self.smallspeed self.x = x+12/16+self.smallspeed*gdt if b then self.size = b.size else self.size = 1 end self.killsenemies = true else self.speedx = -self.smallspeed self.x = x-self.width-self.smallspeed*gdt if b then self.size = b.size else self.size = 1 end self.killsenemies = true end else self.speedx = 0 self.combo = 1 self.quad = self.quadgroup[self.smallquad] end else self.active = false if self.stompanimation then self.quad = self.quadgroup[self.stompedframe] if self.fallswhenstomped then self.shot = true self.gravity = shotgravity else self.dead = true end elseif self.doesntflyawayonstomp then self.kill = true self.drawable = false else self.shot = true self.gravity = shotgravity end end end end function enemy:autodeleted() self.dead = true if self.shot then self:output() else self:output("autodeleted") end end function enemy:output(transformed) if (not self.outtable) or self.outputted then --for some reason the enemy hasn't spawned correctly return false end self.outputted = true for i = 1, #self.outtable do if self.outtable[i][1].input then self.outtable[i][1]:input("toggle", self.outtable[i][2]) end end if self.fireballthrower then self.fireballthrower:fireballcallback(self.t) end if self.carryparent then self.carryparent.pickup = nil self.userect.delete = true self.destroying = true end if self.userect and not self.userect.delete then self.userect.delete = true end if self.blockportaltile and not self.dontremoveblockportaltileondeath then blockedportaltiles[self.blockportaltilecoordinate] = false end if (not transformed) or self.treattransformasdeath then --only happen on real deaths if self.givecoinondeath then --AE ADDITION collectcoin(nil, nil, tonumber(self.givecoinondeath) or 1) end if self.givekeyondeath then --AE ADDITIONlocal closestplayer = 1 local closestdist = math.huge local closestplayer = 1 for i = 2, #objects["player"] do local v = objects["player"][i] local dist = math.sqrt((v.x-self.x)^2+(v.y-self.y)^2) if dist < closestdist then closestdist = dist closestplayer = i end end objects["player"][closestplayer].key = objects["player"][closestplayer].key+1 end if self.deathsound then --AE ADDITION if self.sound and self.deathsound == self.t then playsound(self.sound) else playsound(self.deathsound) end end if self.droplevelballondeath then local obj = levelball:new(self.x+self.width/2, self.y+self.height/2) obj.y = self.y+self.height-obj.height-1/16 table.insert(objects["levelball"], obj) end if self.animationtriggerondeath or self.triggeranimationondeath then self:triggeranimation(self.animationtriggerondeath or self.triggeranimationondeath) end if self.transformenemyanimationondeath then transformenemyanimation(self.transformenemyanimationondeath) end end end function enemy:triggeranimation(s) if animationtriggerfuncs[s] then for i = 1, #animationtriggerfuncs[s] do local anim = animationtriggerfuncs[s][i] if anim.running and self.queueanimationtrigger then --you ever notice how queue has 4 silent letters? table.insert(anim.queue, "enemy") else anim:trigger() end end end end function enemy:portaled(exitdir) if self.killsenemiesafterportal then self.killsenemies = true end if self.transforms and self:gettransformtrigger("portaled") then self:transform(self:gettransformsinto("portaled")) end end function enemy:spawnenemy(t) local speedx, speedy = 0, 0 if self.spawnenemyspeedx then speedx = self.spawnenemyspeedx end if self.spawnenemyspeedy then speedy = self.spawnenemyspeedy end if (self.spawnenemyspeedxrandomstart and self.spawnenemyspeedxrandomend) then speedx = math.random()*(self.spawnenemyspeedxrandomend-self.spawnenemyspeedxrandomstart) + self.spawnenemyspeedxrandomstart end if (self.spawnenemyspeedyrandomstart and self.spawnenemyspeedyrandomend) then speedy = math.random()*(self.spawnenemyspeedyrandomend-self.spawnenemyspeedyrandomstart) + self.spawnenemyspeedyrandomstart end local closestplayer = 1 local closestdist = math.sqrt((objects["player"][1].x-self.x)^2+(objects["player"][1].y-self.y)^2) for i = 2, players do local v = objects["player"][i] local dist = math.sqrt((v.x-self.x)^2+(v.y-self.y)^2) if dist < closestdist then closestdist = dist closestplayer = i end end if self.spawnenemytowardsplayer then local a = -math.atan2(objects["player"][closestplayer].x-self.x, objects["player"][closestplayer].y-self.y)+math.pi/2 speedx = math.cos(a)*self.spawnenemyspeed speedy = math.sin(a)*self.spawnenemyspeed end if self.spawnenemyspeedxtowardsplayer then if objects["player"][closestplayer].x + objects["player"][closestplayer].width/2 > self.x + self.width/2 then speedx = math.abs(speedx) else speedx = -math.abs(speedx) end end local xoffset = self.spawnenemyoffsetx or 0 local yoffset = self.spawnenemyoffsety or 0 local properties --set parameters before spawn if self.spawnpassedparametersbeforespawn then if not properties then properties = {} end if self.spawnpassedparameters then --pass parameters for i = 1, #self.spawnpassedparameters do if self.spawnpassedparameters[i] ~= nil then properties[self.spawnpassedparameters[i]] = self[self.spawnpassedparameters[i]] end end end end if self.spawnsetparametersbeforespawn then if not properties then properties = {} end if self.spawnsetparameters then --set new parameters for i = 1, #self.spawnsetparameters do if self.spawnsetparameters[i] ~= nil then properties[self.spawnsetparameters[i][1]] = self.spawnsetparameters[i][2] end end end end local temp = enemy:new(self.x+self.width/2+.5+xoffset, self.y+self.height+yoffset, t, {}, properties) temp.justspawned = true if not self.spawnpassedparametersbeforespawn then if self.spawnpassedparameters then --pass parameters for i = 1, #self.spawnpassedparameters do if self.spawnpassedparameters[i] ~= nil then temp[self.spawnpassedparameters[i]] = self[self.spawnpassedparameters[i]] end end end end if not self.spawnsetparametersbeforespawn then if self.spawnsetparameters then --set new parameters for i = 1, #self.spawnsetparameters do if self.spawnsetparameters[i] ~= nil then temp[self.spawnsetparameters[i][1]] = self.spawnsetparameters[i][2] end end end end table.insert(objects["enemy"], temp) temp.speedx = speedx temp.speedy = speedy if temp.movement == "truffleshuffle" and temp.speedx > 0 then temp.animationdirection = "left" end table.insert(self.spawnedenemies, temp) temp.spawner = self end function enemy:transform(t, returntransform, death) if self.justspawned then return false end if (self.kill or self.transformkill) and self.drawable == false then --already transformed! return false end local xoffset = self.transformsoffsetx or 0 local yoffset = self.transformsoffsety or 0 if self.transformsintorandoms then self.transformsinto = self.transformsintorandoms[math.random(#self.transformsintorandoms)] t = self.transformsinto end local properties --set parameters before spawn if self.transformpassedparametersbeforespawn then if self.transformpassedparameters then if not properties then properties = {} end for i = 1, #self.transformpassedparameters do if self.transformpassedparameters[i] ~= nil then properties[self.transformpassedparameters[i]] = self[self.transformpassedparameters[i]] end end end end if self.transformsetparametersbeforespawn then if self.transformsetparameters then --set new parameters if not properties then properties = {} end for i = 1, #self.transformsetparameters do if self.transformsetparameters[i] ~= nil then properties[self.transformsetparameters[i][1]] = self.transformsetparameters[i][2] end end end end local temp = enemy:new(self.x+self.width/2+.5+xoffset, self.y+self.height+yoffset, t, {}, properties) temp.justspawned = true --set parameters after spawn if not self.transformpassedparametersbeforespawn then if self.transformpassedparameters then for i = 1, #self.transformpassedparameters do if self.transformpassedparameters[i] ~= nil then temp[self.transformpassedparameters[i]] = self[self.transformpassedparameters[i]] end end end end if not self.transformsetparametersbeforespawn then if self.transformsetparameters then --set new parameters for i = 1, #self.transformsetparameters do if self.transformsetparameters[i] ~= nil then temp[self.transformsetparameters[i][1]] = self.transformsetparameters[i][2] end end end end if self.frozen and (not self.dontpassfrozen) and self.iceblock then --TODO FIX self.iceblock.enemy = temp temp:freeze() end if self.supersized then supersizeentity(temp) end table.insert(objects["enemy"], temp) if self.spawner then table.insert(self.spawner.spawnedenemies, temp) end self.active = false self.transformkill = true if death then self.transformkilldeath = true --still do output death stuff end if self.tracked or self.clearpipe then self.transformedinto = temp end if self.fireenemyrideaftertransform then --DON'T set this property --is mario riding the enemy? should he still ride after enemy transforms? local v = self.fireenemyrideaftertransform v.fireenemyride = temp temp.fireenemyrideaftertransform = self.fireenemyrideaftertransform self.fireenemyrideaftertransform = nil end --self.kill = true self.drawable = false if returntransform then return temp end end function enemy:gettransformtrigger(n) --AE ADDITION if not self.transformtrigger then return false elseif type(self.transformtrigger) == "table" then return tablecontainsi(self.transformtrigger, n) else return (self.transformtrigger == n) end end function enemy:gettransformsinto(n) --AE ADDITION if not self.transformsinto then return false elseif type(self.transformsinto) == "table" and type(self.transformtrigger) == "table" then local i = tablecontainsi(self.transformtrigger, n) return self.transformsinto[i] else return self.transformsinto end end function enemy:emancipate() if not self.kill then table.insert(emancipateanimations, emancipateanimation:new(self.x, self.y, self.width, self.height, self.graphic, self.quad, self.speedx, self.speedy, self.rotation, self.offsetX, self.offsetY, self.quadcenterX, self.quadcenterY)) self.kill = true self.drawable = false if self.carryparent then self.carryparent:cubeemancipate() end end end function enemy:laser(guns, pewpew) if not self.laserresistant then self:shotted() end end function enemy:enteredfunnel(inside) if inside then self.infunnel = true else self.infunnel = false self.gravity = self.startgravity end end function enemy:getspawnedenemies() local count = 0 for i, v in pairs(self.spawnedenemies) do if not v.dead then count = count + 1 end end return count end function enemy:dive(water) --AE ADDITION if water then --self.water = true --self.speedx = self.speedx*waterdamping self.speedy = self.speedy*(self.waterdamping or waterdamping) else --self.water = false if self.speedy < 0 then self.speedy = -waterjumpforce end end end function enemy:used(id) if self.thrown or self.frozen then return false end if self.dontcarryifmoving and math.abs(self.speedx) > 0.0001 then return false end if self.transforms and self:gettransformtrigger("carry") then local temp = self:transform(self:gettransformsinto("carry"), "returntransform") if temp and temp.carryable then temp:used(id) end return false end self.carryparent = objects["player"][id] self.active = self.activeoncarry self.startstatic = self.static self.static = true self.trackable = false if self.tracked then self.startstatic = false end if self.fliponcarry then self.flipped = true end objects["player"][id]:pickupbox(self) self.pickupready = false if self.grabsound then if self.sound and self.grabsound == self.t then playsound(self.sound) else playsound(self.grabsound) end elseif not self.nograbsound then playsound(grabsound) end end function enemy:dropped(gravitydir) self.active = self.activeonthrow self.static = self.startstatic if self.staticonthrow ~= nil then self.static = self.staticonthrow end if self.noplayercollisiononthrow then self.mask[3] = self.mask[1] --no player collision end self.thrown = true if self.throwntime then self.throwntimer = self.throwntime or 1.3 end self.speedy = self.thrownspeedy or 0 if not self.thrownignorecarryspeed then if self.carryparent.pointingangle > 0 then --left self.speedx = self.carryparent.speedx-(self.thrownspeedx or 0) else self.speedx = self.carryparent.speedx+(self.thrownspeedx or 0) end else if self.carryparent.pointingangle > 0 then --left self.speedx = -(self.thrownspeedx or 0) else self.speedx = (self.thrownspeedx or 0) end end local offsetx = (self.carryoffsetx or 0) if self.carryoffsetx and self.carryparent.pointingangle > 0 then offsetx = -offsetx end self.x = (self.carryparent.x+self.carryparent.width/2-self.width/2) + offsetx self.y = (self.carryparent.y-self.height)+(self.carryoffsety or 0) if self.throwsound then playsound(self.throwsound) elseif not self.nothrowsound then playsound(throwsound) end self.carryparent = nil if self.transforms and self:gettransformtrigger("thrown") then self:transform(self:gettransformsinto("thrown")) end end function enemy:freeze() if self.transforms and self:gettransformtrigger("freeze") then self:transform(self:gettransformsinto("freeze")) return end self.frozen = true self.speedx = 0 self.speedy = 0 end function enemy:kick(dir) if not (math.abs(self.speedx) < self.kickspeed*0.8) then return false end if not self.nokicksound then playsound(shotsound) end if dir == "left" then self.speedx = -self.kickspeed if not self.dontmirror then self.animationdirection = "right" end else self.speedx = self.kickspeed if not self.dontmirror then self.animationdirection = "left" end end self.speedy = self.kickspeedy end function enemy:dotrack() self.track = true end function enemy:applygel(side, x, y) if x and (not y) then local b = x local id = b.gels[side] if id and id == 5 then --can't put gel return false elseif self.gel == 5 then b.gels[side] = nil else b.gels[side] = self.gel end else local id = map[x][y]["gels"][side] if id and id == 5 then --can't put gel return false elseif self.gel == 5 then map[x][y]["gels"][side] = false else map[x][y]["gels"][side] = self.gel end if id ~= self.gel then return true end end return false end function enemy:handlecollisiontransform(side,a,b) local docancel = false if self.transformtriggerenemycollide then --mutliple enemy collides if type(self.transformtriggerenemycollide) == "table" and type(self.transformtrigger) == "table" then for i, s in pairs(self.transformtrigger) do if s == side and a == "enemy" and self.transformtriggerenemycollide[i] == b.t then if type(self.transformsinto) == "table" then self:transform(self.transformsinto[i]) else self:transform(self:gettransformsinto(side)) end if self.transformtriggerenemycollidekill then if self.enemykillsdontflyaway then b.doesntflyawayonfireball = true end b:shotted(dir) end return true end end else if a == "enemy" and b.t == self.transformtriggerenemycollide then self:transform(self:gettransformsinto(side)) if self.transformtriggerenemycollidekill then if self.enemykillsdontflyaway then b.doesntflyawayonfireball = true end b:shotted(dir) end return true end end docancel = true end if self.transformtriggerobjectcollide then --mutliple entity collides if type(self.transformtriggerobjectcollide) == "table" and type(self.transformtrigger) == "table" then for i, s in pairs(self.transformtrigger) do if s == side and self.transformtriggerobjectcollide[i] == a then if type(self.transformsinto) == "table" then self:transform(self.transformsinto[i]) else self:transform(self:gettransformsinto(side)) end return true end end else if a == self.transformtriggerobjectcollide then self:transform(self:gettransformsinto(side)) return true end end docancel = true end if docancel then return false end self:transform(self:gettransformsinto(side)) return true end function enemy:dosupersize() --set a custom set of properties when supersized if self.supersizeproperties then for i, v in pairs(self.supersizeproperties) do local name = i if name ~= "offsetX" and name ~= "offsetY" and name ~= "quadcenterX" and name ~= "quadcenterY" then name = name:lower() end self[name] = v if name == "quadno" then self.quad = self.quadgroup[self.quadno] end end end end
lines = {} for line in io.lines() do table.insert(lines, line) -- add the line to the list of lines end
function createIndexIfNil(t, i, v) if not (type(i)=="nil") then if (type(t[i])=="nil") then t[i] = v or {} end end end
addEvent("race_loadVehicleData", true) addEvent("race_saveVehicleData", true) addEvent("race_removeVehicleData", true) addEvent("onClientMapStopping") local g_Stack = {} local function loadVehData(remove) --outputDebugString("loadVehData "..tostring(remove).." "..#g_Stack, 3) local veh = source local data = g_Stack[#g_Stack] if(not data) then return false end if(remove) then g_Stack[#g_Stack] = nil end setElementModel(veh, data.model) --respawnVehicle(veh) setElementPosition(veh, unpack(data.pos)) setElementRotation(veh, unpack(data.rot)) setElementVelocity(veh, unpack(data.vel)) setVehicleTurnVelocity(veh, unpack(data.turnVel)) setElementHealth(veh, data.hp) if(data.landingGearDown ~= nil) then setVehicleLandingGearDown(veh, data.landingGearDown) end if(data.nitro) then addVehicleUpgrade(veh, data.nitro) end if(data.adjProp) then setVehicleAdjustableProperty(veh, data.adjProp) end if(data.rotorSpeed) then setHelicopterRotorSpeed(veh, data.rotorSpeed) end end local function saveVehData() local veh = source local data = {} data.model = getElementModel(veh) data.pos = {getElementPosition(veh)} data.rot = {getElementRotation(veh)} data.vel = {getElementVelocity(veh)} data.turnVel = {getVehicleTurnVelocity(veh)} data.hp = getElementHealth(veh) data.nitro = getVehicleUpgradeOnSlot(veh, 8) data.landingGearDown = getVehicleLandingGearDown(veh) data.adjProp = getVehicleAdjustableProperty(veh) data.rotorSpeed = getHelicopterRotorSpeed(veh) table.insert(g_Stack, data) end local function removeVehData() g_Stack[#g_Stack] = nil end local function destroyVehData() --outputDebugString("destroyVehData", 3) g_Stack = {} end addEventHandler("race_loadVehicleData", g_Root, loadVehData) addEventHandler("race_saveVehicleData", g_Root, saveVehData) addEventHandler("race_removeVehicleData", g_Root, removeVehData) addEventHandler("onClientMapStopping", g_Root, destroyVehData)
--[[ TheNexusAvenger Runs the game. --]] local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local ServerScriptServiceProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ServerScriptService")) --Create the folders. local GameState = Instance.new("Folder") GameState.Name = "GameState" GameState.Parent = ReplicatedStorage local GameReplication = Instance.new("Folder") GameReplication.Name = "GameReplication" GameReplication.Parent = ReplicatedStorage --Initialize the services. for _,ServiceModule in pairs(ServerScriptServiceProject:GetResource("Service"):GetChildren()) do ServerScriptServiceProject:GetResource("Service."..ServiceModule.Name) end --Initialize the resources before loading players. --These resources are required by the players on join. local InventoryService = ServerScriptServiceProject:GetResource("Service.InventoryService") InventoryService:LoadCharacterAssets() --Load the NPC models. Can't be saved directly --to a model file and imported with Rojo. local NPCService = ServerScriptServiceProject:GetResource("Service.NPCService") NPCService:LoadNPCModels() --Get the services. local CharacterService = ServerScriptServiceProject:GetResource("Service.CharacterService") local PlayerDataService = ServerScriptServiceProject:GetResource("Service.PlayerDataService") local QuestService = ServerScriptServiceProject:GetResource("Service.QuestService") local MapDiscoveryService = ServerScriptServiceProject:GetResource("Service.MapDiscoveryService") local EnergyService = ServerScriptServiceProject:GetResource("Service.EnergyService") --[[ Handles a player being added. --]] local function PlayerAdded(Player) PlayerDataService:LoadPlayer(Player) QuestService:LoadPlayer(Player) InventoryService:LoadPlayer(Player) CharacterService:SpawnCharacter(Player) MapDiscoveryService:LoadPlayer(Player) EnergyService:LoadPlayer(Player) end --[[ Handles a player being removed. --]] local function PlayerRemoved(Player) MapDiscoveryService:ClearPlayer(Player) QuestService:ClearPlayer(Player) InventoryService:ClearPlayer(Player) PlayerDataService:ClearPlayer(Player) end --Set up players joining. Players.PlayerAdded:Connect(PlayerAdded) Players.PlayerRemoving:Connect(PlayerRemoved) for _,Player in pairs(Players:GetPlayers()) do coroutine.wrap(function() PlayerAdded(Player) end)() end
function get_value(e, p, data, default) if data == nil then return default or 0 elseif type(data) == "function" then return data(e, p) elseif type(data) == "number" then return data elseif data.x != nil then return data:copy() elseif type(data.min) == "number" then return rnd_float( data.min, data.max) else return vec2(rnd_float( data.min.x, data.max.x ), rnd_float( data.min.y, data.max.y )) end end
-- Tests for 'directory' option. -- - ".", in same dir as file -- - "./dir", in directory relative to file -- - "dir", in directory relative to current dir local helpers = require('test.functional.helpers')(after_each) local lfs = require('lfs') local insert, eq = helpers.insert, helpers.eq local neq, eval = helpers.neq, helpers.eval local clear, execute = helpers.clear, helpers.execute local wait, write_file = helpers.wait, helpers.write_file local function ls_dir_sorted(dirname) local files = {} for f in lfs.dir(dirname) do if f ~= "." and f~= ".." then table.insert(files, f) end end table.sort(files) return files end describe("'directory' option", function() setup(function() local text = [[ start of testfile line 2 Abcdefghij line 3 Abcdefghij end of testfile ]] write_file('Xtest1', text) lfs.mkdir('Xtest.je') lfs.mkdir('Xtest2') write_file('Xtest2/Xtest3', text) clear() end) teardown(function() execute('qall!') helpers.rmdir('Xtest.je') helpers.rmdir('Xtest2') os.remove('Xtest1') end) it('is working', function() insert([[ start of testfile line 2 Abcdefghij line 3 Abcdefghij end of testfile]]) execute('set swapfile') execute('set dir=.,~') -- sanity check: files should not exist yet. eq(nil, lfs.attributes('.Xtest1.swp')) execute('e! Xtest1') wait() eq('Xtest1', eval('buffer_name("%")')) -- Verify that the swapfile exists. In the legacy test this was done by -- reading the output from :!ls. neq(nil, lfs.attributes('.Xtest1.swp')) execute('set dir=./Xtest2,.,~') execute('e Xtest1') wait() -- swapfile should no longer exist in CWD. eq(nil, lfs.attributes('.Xtest1.swp')) eq({ "Xtest1.swp", "Xtest3" }, ls_dir_sorted("Xtest2")) execute('set dir=Xtest.je,~') execute('e Xtest2/Xtest3') eq(1, eval('&swapfile')) wait() eq({ "Xtest3" }, ls_dir_sorted("Xtest2")) eq({ "Xtest3.swp" }, ls_dir_sorted("Xtest.je")) end) end)
-- {{{ Tags -- -- Only 12 keys will be used for tags (keyboard order). Tags are -- indexed in top-row natural keyboard order [1,2,3,...,0,'-',=']. This -- indexing corresponds to the alt+-prefixed keybindings they receive -- elsewhere and gives a pretty good reasonable total of 12 tags per -- screen. That extends the number of available tags beyond the awesome -- default of 9 (1 ... 9). Tags can have arbitrary names, one per line, -- in TAGS_FILE. -- TAGS_FILE = table.concat({config_dir, "tags.txt"}, "/") -- get tag names from file local tagslist = {} for tag in io.lines( TAGS_FILE ) do table.insert(tagslist, tag) end -- allow for fewer than 12 tags TAGS_MAX = math.min(12, #tagslist) -- sanity check if #tagslist > TAGS_MAX then log("warn: " .. TAGS_MAX .. " tags max, " .. math.abs( TAGS_MAX-#tagslist ) .. " will be ignored") end -- take first #tagslist, ignore remainder if any mytags = {} for i=1, TAGS_MAX do mytags[i] = tagslist[i] end -- create a tag table per screen tags = {} for s = 1, screen.count() do tags[s] = awful.tag(mytags, s, layouts[1]) end -- }}} -- -- Tag rules TODO -- -- -- -- name_rules = { -- { name = "vim", tag = "vim" } -- } -- -- local function tag_index_from_name(n) -- -- for i=1, #tags[1] do -- if string.match(tags[1][i].name, n) then -- return i -- end -- end -- return nil -- end -- -- function dispatch_tags(c) -- -- dynamic tagging -- -- -- -- get client name ("title" in xterm parlance; WM_NAME in xprop) -- -- local client_name = c.name -- -- -- -- get client class (WM_NAME in xprop) -- -- local client_class = c.name -- -- -- for i=1, #name_rules do -- -- local rule = name_rules[i] -- -- if string.match(client_name, rule.name) then -- -- -- name matched, move to tag -- -- -- -- -- local t = awful.tag.gettags(c.screen) -- -- local tag_exists = false -- -- for j=1, #t do -- -- if t[j].name == rule.tag then -- -- tag_exists = true -- -- end -- -- end -- -- if not tag_exists then -- -- awful.tag.add(rule.tag) -- -- end -- -- awful.client.movetotag(tags[c.screen][tag_index_from_name(rule.tag)], c) -- -- end -- -- end -- -- -- dispatch by name first (handle more specific case first) -- end
local Bezier = require(script.Parent.Bezier) local function RevBack(T) T = 1 - T return 1 - (math.sin(T * 1.5707963267949) + (math.sin(T * 3.1415926535898) * (math.cos(T * 3.1415926535898) + 1) / 2)) end local function Linear(T) return T end -- @specs https://material.io/guidelines/motion/duration-easing.html#duration-easing-natural-easing-curves local Sharp = Bezier(0.4, 0, 0.6, 1) local Standard = Bezier(0.4, 0, 0.2, 1) -- used for moving. local Acceleration = Bezier(0.4, 0, 1, 1) -- used for exiting. local Deceleration = Bezier(0, 0, 0.2, 1) -- used for entering. -- @specs https://developer.microsoft.com/en-us/fabric#/styles/web/motion#basic-animations local FabricStandard = Bezier(0.8, 0, 0.2, 1) -- used for moving. local FabricAccelerate = Bezier(0.9, 0.1, 1, 0.2) -- used for exiting. local FabricDecelerate = Bezier(0.1, 0.9, 0.2, 1) -- used for entering. -- @specs https://docs.microsoft.com/en-us/windows/uwp/design/motion/timing-and-easing local UWPAccelerate = Bezier(0.7, 0, 1, 0.5) -- @specs https://www.ibm.com/design/language/elements/motion/basics -- Productivity and Expression are both essential to an interface. Reserve Expressive motion for occasional, important moments to better capture user’s attention, and offer rhythmic break to the productive experience. -- Use standard-easing when an element is visible from the beginning to end of a motion. Tiles expanding and table rows sorting are good examples. local StandardProductive = Bezier(0.2, 0, 0.38, 0.9) local StandardExpressive = Bezier(0.4, 0.14, 0.3, 1) -- Use entrance-easing when adding elements to the view such as a modal or toaster appearing, or moving in response to users’ input, such as dropdown opening or toggle. An element quickly appears and slows down to a stop. local EntranceProductive = Bezier(0, 0, 0.38, 0.9) local EntranceExpressive = Bezier(0, 0, 0.3, 1) -- Use exit-easing when removing elements from view, such as closing a modal or toaster. The element speeds up as it exits from view, implying that its departure from the screen is permanent. local ExitProductive = Bezier(0.2, 0, 1, 0.9) local ExitExpressive = Bezier(0.4, 0.14, 1, 1) -- @specs https://design.firefox.com/photon/motion/duration-and-easing.html local MozillaCurve = Bezier(0.07, 0.95, 0, 1) local function Smooth(T) return T * T * (3 - 2 * T) end local function Smoother(T) return T * T * T * (T * (6 * T - 15) + 10) end local function RidiculousWiggle(T) return math.sin(math.sin(T * 3.1415926535898) * 1.5707963267949) end local function Spring(T) return 1 + (-math.exp(-6.9 * T) * math.cos(-20.106192982975 * T)) end local function SoftSpring(T) return 1 + (-math.exp(-7.5 * T) * math.cos(-10.053096491487 * T)) end local function OutBounce(T) if T < 0.36363636363636 then return 7.5625 * T * T elseif T < 0.72727272727273 then return 3 + T * (11 * T - 12) * 0.6875 elseif T < 0.090909090909091 then return 6 + T * (11 * T - 18) * 0.6875 else return 7.875 + T * (11 * T - 21) * 0.6875 end end local function InBounce(T) if T > 0.63636363636364 then T -= 1 return 1 - T * T * 7.5625 elseif T > 0.272727272727273 then return (11 * T - 7) * (11 * T - 3) / -16 elseif T > 0.090909090909091 then return (11 * (4 - 11 * T) * T - 3) / 16 else return T * (11 * T - 1) * -0.6875 end end local EasingFunctions = setmetatable({ InLinear = Linear; OutLinear = Linear; InOutLinear = Linear; OutInLinear = Linear; OutSmooth = Smooth; InSmooth = Smooth; InOutSmooth = Smooth; OutInSmooth = Smooth; OutSmoother = Smoother; InSmoother = Smoother; InOutSmoother = Smoother; OutInSmoother = Smoother; OutRidiculousWiggle = RidiculousWiggle; InRidiculousWiggle = RidiculousWiggle; InOutRidiculousWiggle = RidiculousWiggle; OutInRidiculousWiggle = RidiculousWiggle; OutRevBack = RevBack; InRevBack = RevBack; InOutRevBack = RevBack; OutInRevBack = RevBack; OutSpring = Spring; InSpring = Spring; InOutSpring = Spring; OutInSpring = Spring; OutSoftSpring = SoftSpring; InSoftSpring = SoftSpring; InOutSoftSpring = SoftSpring; OutInSoftSpring = SoftSpring; InSharp = Sharp; InOutSharp = Sharp; OutSharp = Sharp; OutInSharp = Sharp; InAcceleration = Acceleration; InOutAcceleration = Acceleration; OutAcceleration = Acceleration; OutInAcceleration = Acceleration; InStandard = Standard; InOutStandard = Standard; OutStandard = Standard; OutInStandard = Standard; InDeceleration = Deceleration; InOutDeceleration = Deceleration; OutDeceleration = Deceleration; OutInDeceleration = Deceleration; InFabricStandard = FabricStandard; InOutFabricStandard = FabricStandard; OutFabricStandard = FabricStandard; OutInFabricStandard = FabricStandard; InFabricAccelerate = FabricAccelerate; InOutFabricAccelerate = FabricAccelerate; OutFabricAccelerate = FabricAccelerate; OutInFabricAccelerate = FabricAccelerate; InFabricDecelerate = FabricDecelerate; InOutFabricDecelerate = FabricDecelerate; OutFabricDecelerate = FabricDecelerate; OutInFabricDecelerate = FabricDecelerate; InUWPAccelerate = UWPAccelerate; InOutUWPAccelerate = UWPAccelerate; OutUWPAccelerate = UWPAccelerate; OutInUWPAccelerate = UWPAccelerate; InStandardProductive = StandardProductive; InStandardExpressive = StandardExpressive; InEntranceProductive = EntranceProductive; InEntranceExpressive = EntranceExpressive; InExitProductive = ExitProductive; InExitExpressive = ExitExpressive; OutStandardProductive = StandardProductive; OutStandardExpressive = StandardExpressive; OutEntranceProductive = EntranceProductive; OutEntranceExpressive = EntranceExpressive; OutExitProductive = ExitProductive; OutExitExpressive = ExitExpressive; InOutStandardProductive = StandardProductive; InOutStandardExpressive = StandardExpressive; InOutEntranceProductive = EntranceProductive; InOutEntranceExpressive = EntranceExpressive; InOutExitProductive = ExitProductive; InOutExitExpressive = ExitExpressive; OutInStandardProductive = StandardProductive; OutInStandardExpressive = StandardProductive; OutInEntranceProductive = EntranceProductive; OutInEntranceExpressive = EntranceExpressive; OutInExitProductive = ExitProductive; OutInExitExpressive = ExitExpressive; OutMozillaCurve = MozillaCurve; InMozillaCurve = MozillaCurve; InOutMozillaCurve = MozillaCurve; OutInMozillaCurve = MozillaCurve; InQuad = function(T) return T * T end; OutQuad = function(T) return T * (2 - T) end; InOutQuad = function(T) if T < 0.5 then return 2 * T * T else return 2 * (2 - T) * T - 1 end end; OutInQuad = function(T) if T < 0.5 then T *= 2 return T * (2 - T) / 2 else T *= 2 - 1 return (T * T) / 2 + 0.5 end end; InCubic = function(T) return T * T * T end; OutCubic = function(T) return 1 - (1 - T) * (1 - T) * (1 - T) end; InOutCubic = function(T) if T < 0.5 then return 4 * T * T * T else T -= 1 return 1 + 4 * T * T * T end end; OutInCubic = function(T) if T < 0.5 then T = 1 - (T * 2) return (1 - T * T * T) / 2 else T *= 2 - 1 return T * T * T / 2 + 0.5 end end; InQuart = function(T) return T * T * T * T end; OutQuart = function(T) T -= 1 return 1 - T * T * T * T end; InOutQuart = function(T) if T < 0.5 then T *= T return 8 * T * T else T -= 1 return 1 - 8 * T * T * T * T end end; OutInQuart = function(T) if T < 0.5 then T *= 2 - 1 return (1 - T * T * T * T) / 2 else T *= 2 - 1 return T * T * T * T / 2 + 0.5 end end; InQuint = function(T) return T * T * T * T * T end; OutQuint = function(T) T -= 1 return T * T * T * T * T + 1 end; InOutQuint = function(T) if T < 0.5 then return 16 * T * T * T * T * T else T -= 1 return 16 * T * T * T * T * T + 1 end end; OutInQuint = function(T) if T < 0.5 then T *= 2 - 1 return (T * T * T * T * T + 1) / 2 else T *= 2 - 1 return T * T * T * T * T / 2 + 0.5 end end; InBack = function(T) return T * T * (3 * T - 2) end; OutBack = function(T) return (T - 1) * (T - 1) * (T * 2 + T - 1) + 1 end; InOutBack = function(T) if T < 0.5 then return 2 * T * T * (2 * 3 * T - 2) else return 1 + 2 * (T - 1) * (T - 1) * (2 * 3 * T - 2 - 2) end end; OutInBack = function(T) if T < 0.5 then T *= 2 return ((T - 1) * (T - 1) * (T * 2 + T - 1) + 1) / 2 else T *= 2 - 1 return T * T * (3 * T - 2) / 2 + 0.5 end end; InSine = function(T) return 1 - math.cos(T * 1.5707963267949) end; OutSine = function(T) return math.sin(T * 1.5707963267949) end; InOutSine = function(T) return (1 - math.cos(3.1415926535898 * T)) / 2 end; OutInSine = function(T) if T < 0.5 then return math.sin(T * 3.1415926535898) / 2 else return (1 - math.cos((T * 2 - 1) * 1.5707963267949)) / 2 + 0.5 end end; OutBounce = OutBounce; InBounce = InBounce; InOutBounce = function(T) if T < 0.5 then return InBounce(2 * T) / 2 else return OutBounce(2 * T - 1) / 2 + 0.5 end end; OutInBounce = function(T) if T < 0.5 then return OutBounce(2 * T) / 2 else return InBounce(2 * T - 1) / 2 + 0.5 end end; InElastic = function(T) return math.exp((T * 0.96380736418812 - 1) * 8) * T * 0.96380736418812 * math.sin(4 * T * 0.96380736418812) * 1.8752275007429 end; OutElastic = function(T) return 1 + (math.exp(8 * (0.96380736418812 - 0.96380736418812 * T - 1)) * 0.96380736418812 * (T - 1) * math.sin(4 * 0.96380736418812 * (1 - T))) * 1.8752275007429 end; InOutElastic = function(T) if T < 0.5 then return (math.exp(8 * (2 * 0.96380736418812 * T - 1)) * 0.96380736418812 * T * math.sin(2 * 4 * 0.96380736418812 * T)) * 1.8752275007429 else return 1 + (math.exp(8 * (0.96380736418812 * (2 - 2 * T) - 1)) * 0.96380736418812 * (T - 1) * math.sin(4 * 0.96380736418812 * (2 - 2 * T))) * 1.8752275007429 end end; OutInElastic = function(T) -- This isn't actually correct, but it is close enough. if T < 0.5 then T *= 2 return (1 + (math.exp(8 * (0.96380736418812 - 0.96380736418812 * T - 1)) * 0.96380736418812 * (T - 1) * math.sin(4 * 0.96380736418812 * (1 - T))) * 1.8752275007429) / 2 else T *= 2 - 1 return (math.exp((T * 0.96380736418812 - 1) * 8) * T * 0.96380736418812 * math.sin(4 * T * 0.96380736418812) * 1.8752275007429) / 2 + 0.5 end end; InExpo = function(T) return T * T * math.exp(4 * (T - 1)) end; OutExpo = function(T) return 1 - (1 - T) * (1 - T) / math.exp(4 * T) end; InOutExpo = function(T) if T < 0.5 then return 2 * T * T * math.exp(4 * (2 * T - 1)) else return 1 - 2 * (T - 1) * (T - 1) * math.exp(4 * (1 - 2 * T)) end end; OutInExpo = function(T) if T < 0.5 then T *= 2 return (1 - (1 - T) * (1 - T) / math.exp(4 * T)) / 2 else T *= 2 - 1 return (T * T * math.exp(4 * (T - 1))) / 2 + 0.5 end end; InCirc = function(T) return -(math.sqrt(1 - T * T) - 1) end; OutCirc = function(T) T -= 1 return math.sqrt(1 - T * T) end; InOutCirc = function(T) T *= 2 if T < 1 then return -(math.sqrt(1 - T * T) - 1) / 2 else T -= 2 return (math.sqrt(1 - T * T) - 1) / 2 end end; OutInCirc = function(T) if T < 0.5 then T *= 2 - 1 return math.sqrt(1 - T * T) / 2 else T *= 2 - 1 return (-(math.sqrt(1 - T * T) - 1)) / 2 + 0.5 end end; }, { __index = function(_, Index) error(tostring(Index) .. " is not a valid easing function.", 2) end; }) return EasingFunctions
--[[ 字体管理器 --]] local THIS_MODULE = ... -- 模块名 local C_MODULE_NAME = "__Font__" -- 注册模块元数据配置 metaMgr:registerModule(C_MODULE_NAME, "src/fonts/", "res/fonts/") local FontManager = class("FontManager") -- 获得单例对象 local instance = nil function FontManager:getInstance() if instance == nil then instance = FontManager:create() end return instance end -- 注册元数据 function FontManager:registerMeta(type, meta) metaMgr:registerMeta(C_MODULE_NAME, type, meta) end -- 释放元数据 function FontManager:releaseMetas() metaMgr:releaseMetas(C_MODULE_NAME) end -- 释放字体 function FontManager:releaseFonts(preload) metaMgr:releaseClasses(C_MODULE_NAME, preload) end -- 获得字体 function FontManager:getFont(fname) return metaMgr:getClass(C_MODULE_NAME, fname) end -- 根据字体创建标签 function FontManager:createLabel(fname, ftext, fparams) return metaMgr:createObject(C_MODULE_NAME, fname, ftext, fparams) end -- 预加载字体 function FontManager:preloadFont(fname) metaMgr:preloadClass(C_MODULE_NAME, fname) end -- 获取所有字体 function FontManager:getAllFonts() return metaMgr:getAllClasses(C_MODULE_NAME) end -- 加载所有字体 function FontManager:loadAllFonts() metaMgr:loadAllClasses(C_MODULE_NAME) end -- 输出管理器当前状态 function FontManager:dump() metaMgr:dumpModule(C_MODULE_NAME) end return FontManager
local utils = require 'utils' local nmap = utils.nmap local nmap_silent = utils.nmap_silent local fs = {} function fs.plugins(use) -- use 'junegunn/fzf' -- use 'junegunn/fzf.vim' use 'djoshea/vim-autoread' use { 'kyazdani42/nvim-tree.lua', commit = '71122d798482e30c599d78aa7ae4a756c6e81a79' } use { 'nvim-telescope/telescope.nvim', requires = {{'nvim-lua/popup.nvim'}, {'nvim-lua/plenary.nvim'}} } end function fs.configure() -- File tree nmap_silent('<localleader>nn', ':NvimTreeToggle<CR>') nmap_silent('<localleader>nr', ':NvimTreeRefresh<CR>') nmap_silent('<localleader>nf', ':NvimTreeFindFile<CR>') g.nvim_tree_git_hl = 1 g.nvim_tree_lsp_diagnostics = 1 g.nvim_tree_add_trailing = 1 g.nvim_tree_auto_close = 1 g.nvim_tree_width = 40 local tree_cmd = require'nvim-tree.config'.nvim_tree_callback vim.g.nvim_tree_bindings = { { key = "R", cb = tree_cmd("refresh") }, { key = "q", cb = tree_cmd("close") }, { key = "<CR>", cb = tree_cmd("edit") }, { key = "h", cb = tree_cmd("close_node") }, { key = "l", cb = tree_cmd("edit") }, { key = "<C-h>", cb = tree_cmd("dir_up") }, { key = "<C-l>", cb = tree_cmd("cd") }, { key = "<C-v>", cb = tree_cmd("vsplit") }, { key = "<C-s>", cb = tree_cmd("split") }, { key = "<", cb = tree_cmd("prev_sibling") }, { key = ">", cb = tree_cmd("next_sibling") }, { key = "<Tab>", cb = tree_cmd("preview") }, { key = ".", cb = tree_cmd("toggle_ignored") }, { key = "a", cb = tree_cmd("create") }, { key = "d", cb = tree_cmd("remove") }, { key = "r", cb = tree_cmd("rename") }, { key = "x", cb = tree_cmd("cut") }, { key = "y", cb = tree_cmd("copy") }, { key = "p", cb = tree_cmd("paste") }, { key = "Y", cb = tree_cmd("copy_path") }, } -- g.nvim_tree_gitignore = 1 -- g.nvim_tree_auto_open = 1 require('telescope').setup { defaults = { prompt_prefix = "λ ", sorting_strategy = "ascending", layout_config = { width = 0.8, prompt_position = "top", preview_cutoff = 120, }, color_devicons = true, use_less = true, } } -- Fuzzy file finder if utils.fexists('.git') then nmap_silent('<leader>f', ':Telescope git_files<cr>') else nmap_silent('<leader>f', ':Telescope find_files<cr>') end -- Global content search nmap_silent('<c-f>', ':Telescope live_grep<cr>') nmap_silent('<leader>mm', ':Telescope marks<cr>') -- Tag navigation nmap_silent('<c-c>', ':Telescope tags<cr>') -- Set buffer file type nmap_silent('<leader>cf', ':Telescope filetypes<cr>') exec [[autocmd StdinReadPre * let s:std_in=1autocmd StdinReadPre * let s:std_in=1]] exec [[autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists("s:std_in") | exec 'bd' | endif]] end return fs
return function(a, GenerateFluff, useTD) GenerateFluff = GenerateFluff or function() return "" end local a2 = "" math.randomseed(os and os.time() or tick()) local __X = math.random() a2 = [[ math.randomseed(]] .. __X .. [[) local ____ ____ = { function(...) local t = { ...} return ____[8](t) end, print, game, math.frexp, math.random(1, 1100), string.dump, string.sub, table.concat, wait, tick, loadstring, "t", function(x) local x2 = loadstring(x) if x2 then return ____[tonumber("\50\48")](function() x2() end) else return nil end end, "InsertService", 1234567890, getfenv, "", "wai", 7.2, pcall, math.pi, "" } ]] .. GenerateFluff() .. [[local ___ = ____[5] ]] .. GenerateFluff() .. [[local _ = function(x) return string.char(x / ___) end ]] .. GenerateFluff() .. [[local __ = {]] math.randomseed(__X) local ___X = math.random(1, 1100) local a3 = { } if useTD then -- TODO: SHA256 Hash checking end for i = 1, a:len() do table.insert(a3, table.concat{ "_(", (string.byte(a:sub(i, i)) * ___X), "), " }) end a2 = a2 .. table.concat(a3, "") a2 = a2 .. " } \n" a2 = a2 .. GenerateFluff() if useTD then a2 = a2 .. "return ____[11](assert(#(____[8](__))==" .. #a3 .. " and (____[8](__)) or nil, '" .. XFuscator.DumpString("Tampering detected") .. "'), ____[#____])()\n" else a2 = a2 .. "return ____[11]((____[8](__)), ____[#____])()\n" end return a2 end
-- -- Created by IntelliJ IDEA. -- User: apatterson -- Date: 6/28/18 -- Time: 7:44 PM -- To change this template use File | Settings | File Templates. -- local keyStroke = hs.eventtap.keyStroke function logDefault() print('default') end function pressReturn() keyStroke({}, "return") end function pressShiftReturn() keyStroke({"shift"}, "return") end function fullScreen() keyStroke({"alt", "cmd"}, "f") end function rightScreen() keyStroke({"alt", "cmd"}, "right") end function leftScreen() keyStroke({"alt", "cmd"}, "left") end return { ["pad1"]=nil, ["pad2"]=nil, ["pad3"]=nil, ["pad4"]=nil, ["pad5"]=nil, ["pad6"]=nil, ["pad7"]=nil, ["pad8"]=nil, ["pad9"]=nil, ["pad0"]=nil, ["pad-"]=nil, ["pad+"]=nil, ["ctrl_pad1"]=nil, ["ctrl_pad2"]=nil, ["ctrl_pad3"]=nil, ["ctrl_pad4"]=nil, ["ctrl_pad5"]=nil, ["ctrl_pad6"]=nil, ["ctrl_pad7"]=nil, ["ctrl_pad8"]=nil, ["ctrl_pad9"]=nil, ["ctrl_pad0"]=leftScreen, ["ctrl_pad-"]=rightScreen, ["ctrl_pad+"]=fullScreen }
class "sTuner" function sTuner:__init() Events:Subscribe( "PlayerJoin", self, self.PlayerJoin ) for p in Server:GetPlayers() do if p:GetValue( "NeonColor" ) then if p:GetValue( "NeonColor" ) == p:GetColor() then p:SetNetworkValue( "NeonColor", p:GetColor() ) end end end Network:Subscribe( "UpdateNeonColor", self, self.UpdateNeonColor ) Network:Subscribe( "ToggleSyncNeon", self, self.ToggleSyncNeon ) Network:Subscribe( "ActivateThrust", self, self.ActivateThrust ) Network:Subscribe( "ActivateAngularThrust", self, self.ActivateAngularThrust ) Network:Subscribe( "SyncTune", self, self.syncTune ) end function sTuner:PlayerJoin( args ) if args.player:GetVehicle() then if args.player:GetColor():GetVehicle() then args.player:GetColor():GetVehicle():SetNetworkValue( "NeonColor", args.player:GetColor() ) end end end function sTuner:UpdateNeonColor( args, sender ) if sender:GetVehicle() then sender:GetVehicle():SetNetworkValue( "NeonColor", args.neoncolor ) end end function sTuner:ToggleSyncNeon( args, sender ) if sender:GetVehicle():GetValue( "Neon" ) then sender:GetVehicle():SetNetworkValue( "Neon", nil ) else sender:GetVehicle():SetNetworkValue( "Neon", true ) end end function sTuner:ActivateThrust( infoTable ) if IsValid(infoTable.Vehicle) then infoTable.Vehicle:SetLinearVelocity( infoTable.Thrust ) end end function sTuner:ActivateAngularThrust( infoTable ) if IsValid(infoTable.Vehicle) then infoTable.Vehicle:SetAngularVelocity( infoTable.Thrust ) end end function sTuner:syncTune( args, sender ) local v = Vehicle.GetById(args.vehid) if not IsValid(v) then return end v:SetNetworkValue( "vehid", args.vehid ) v:SetNetworkValue( "modelid", args.modelid ) v:SetNetworkValue( "clutch_delay", args.clutch_delay ) v:SetNetworkValue( "reverse_ratio", args.reverse_ratio ) v:SetNetworkValue( "primary_transmission_ratio", args.primary_transmission_ratio ) v:SetNetworkValue( "airdensity", args.airdensity ) v:SetNetworkValue( "frontalarea", args.frontalarea ) v:SetNetworkValue( "dragcoeff", args.dragcoeff ) v:SetNetworkValue( "liftcoeff", args.liftcoeff ) v:SetNetworkValue( "gravity", args.gravity ) if args.gear_ratios[1] then v:SetNetworkValue( "gear_ratios1", args.gear_ratios[1] ) end if args.gear_ratios[2] then v:SetNetworkValue( "gear_ratios2", args.gear_ratios[2] ) end if args.gear_ratios[3] then v:SetNetworkValue( "gear_ratios3", args.gear_ratios[3] ) end if args.gear_ratios[4] then v:SetNetworkValue( "gear_ratios4", args.gear_ratios[4] ) end if args.gear_ratios[5] then v:SetNetworkValue( "gear_ratios5", args.gear_ratios[5] ) end if args.gear_ratios[6] then v:SetNetworkValue( "gear_ratios6", args.gear_ratios[6] ) end if args.gear_ratios[7] then v:SetNetworkValue( "gear_ratios7", args.gear_ratios[7] ) end if args.wheels[1] then v:SetNetworkValue( "wheel1_length", args.wheels[1].length ) v:SetNetworkValue( "wheel1_strength", args.wheels[1].strength ) v:SetNetworkValue( "wheel1_direction", args.wheels[1].direction ) v:SetNetworkValue( "wheel1_position", args.wheels[1].position ) v:SetNetworkValue( "wheel1_dampcompression", args.wheels[1].dampcompression ) v:SetNetworkValue( "wheel1_damprelaxation", args.wheels[1].damprelaxation ) end if args.wheels[2] then v:SetNetworkValue( "wheel2_length", args.wheels[2].length ) v:SetNetworkValue( "wheel2_strength", args.wheels[2].strength ) v:SetNetworkValue( "wheel2_direction", args.wheels[2].direction ) v:SetNetworkValue( "wheel2_position", args.wheels[2].position ) v:SetNetworkValue( "wheel2_dampcompression", args.wheels[2].dampcompression ) v:SetNetworkValue( "wheel2_damprelaxation", args.wheels[2].damprelaxation ) end if args.wheels[3] then v:SetNetworkValue( "wheel3_length", args.wheels[3].length ) v:SetNetworkValue( "wheel3_strength", args.wheels[3].strength ) v:SetNetworkValue( "wheel3_direction", args.wheels[3].direction ) v:SetNetworkValue( "wheel3_position", args.wheels[3].position ) v:SetNetworkValue( "wheel3_dampcompression", args.wheels[3].dampcompression ) v:SetNetworkValue( "wheel3_damprelaxation", args.wheels[3].damprelaxation ) end if args.wheels[4] then v:SetNetworkValue( "wheel4_length", args.wheels[4].length ) v:SetNetworkValue( "wheel4_strength", args.wheels[4].strength ) v:SetNetworkValue( "wheel4_direction", args.wheels[4].direction ) v:SetNetworkValue( "wheel4_position", args.wheels[4].position ) v:SetNetworkValue( "wheel4_dampcompression", args.wheels[4].dampcompression ) v:SetNetworkValue( "wheel4_damprelaxation", args.wheels[4].damprelaxation ) end if args.wheels[5] then v:SetNetworkValue( "wheel5_length", args.wheels[5].length ) v:SetNetworkValue( "wheel5_strength", args.wheels[5].strength ) v:SetNetworkValue( "wheel5_direction", args.wheels[5].direction ) v:SetNetworkValue( "wheel5_position", args.wheels[5].position ) v:SetNetworkValue( "wheel5_dampcompression", args.wheels[5].dampcompression ) v:SetNetworkValue( "wheel5_damprelaxation", args.wheels[5].damprelaxation ) end if args.wheels[6] then v:SetNetworkValue( "wheel6_length", args.wheels[6].length ) v:SetNetworkValue( "wheel6_strength", args.wheels[6].strength ) v:SetNetworkValue( "wheel6_direction", args.wheels[6].direction ) v:SetNetworkValue( "wheel6_position", args.wheels[6].position ) v:SetNetworkValue( "wheel6_dampcompression", args.wheels[6].dampcompression ) v:SetNetworkValue( "wheel6_damprelaxation", args.wheels[6].damprelaxation ) end if args.wheels[7] then v:SetNetworkValue( "wheel7_length", args.wheels[7].length ) v:SetNetworkValue( "wheel7_strength", args.wheels[7].strength ) v:SetNetworkValue( "wheel7_direction", args.wheels[7].direction ) v:SetNetworkValue( "wheel7_position", args.wheels[7].position ) v:SetNetworkValue( "wheel7_dampcompression", args.wheels[7].dampcompression ) v:SetNetworkValue( "wheel7_damprelaxation", args.wheels[7].damprelaxation ) end if args.wheels[8] then v:SetNetworkValue( "wheel8_length", args.wheels[8].length ) v:SetNetworkValue( "wheel8_strength", args.wheels[8].strength ) v:SetNetworkValue( "wheel8_direction", args.wheels[8].direction ) v:SetNetworkValue( "wheel8_position", args.wheels[8].position ) v:SetNetworkValue( "wheel8_dampcompression", args.wheels[8].dampcompression ) v:SetNetworkValue( "wheel8_damprelaxation", args.wheels[8].damprelaxation ) end if args.wheel_ratios[1] then v:SetNetworkValue( "wheel_ratios1", args.wheel_ratios[1] ) end if args.wheel_ratios[2] then v:SetNetworkValue( "wheel_ratios2", args.wheel_ratios[2] ) end if args.wheel_ratios[3] then v:SetNetworkValue( "wheel_ratios3", args.wheel_ratios[3] ) end if args.wheel_ratios[4] then v:SetNetworkValue( "wheel_ratios4", args.wheel_ratios[4] ) end if args.wheel_ratios[5] then v:SetNetworkValue( "wheel_ratios5", args.wheel_ratios[5] ) end if args.wheel_ratios[6] then v:SetNetworkValue( "wheel_ratios6", args.wheel_ratios[6] ) end if args.wheel_ratios[7] then v:SetNetworkValue( "wheel_ratios7", args.wheel_ratios[7] ) end if args.wheel_ratios[8] then v:SetNetworkValue( "wheel_ratios8", args.wheel_ratios[8] ) end end sTuner = sTuner()
local load_module = require('utils.helpers').load_module local trouble = load_module 'trouble' if trouble == nil then return false end local nvim = require 'neovim' local get_icon = require('utils.helpers').get_icon local has_devicon = pcall(require, 'nvim-web-devicons') trouble.setup { position = 'bottom', height = 10, width = 50, mode = 'lsp_document_diagnostics', -- "lsp_workspace_diagnostics", "quickfix", "lsp_references", "loclist" auto_close = true, icons = has_devicon, use_lsp_diagnostic_signs = false, signs = { error = get_icon 'error', warning = get_icon 'warn', hint = get_icon 'hint', information = get_icon 'info', other = '﫠', }, action_keys = { toggle_fold = { 'zA', 'za', '=' }, }, } vim.keymap.set('n', '=T', function() local lsp_document_diagnostics = vim.diagnostic and vim.diagnostic.get(0) or vim.lsp.diagnostic.get(0) local lsp_workspace_diagnostics = vim.diagnostic and vim.diagnostic.get() or vim.lsp.diagnostic.get_all() local has_workspace_diagnostics = false for _, diagnostics in pairs(lsp_workspace_diagnostics) do if #diagnostics > 0 then has_workspace_diagnostics = true break end end local loc_diagnostics = vim.fn.getloclist(nvim.get_current_win()) local qf_diagnostics = vim.fn.getqflist() local trouble_open = false for _, win in pairs(nvim.tab.list_wins(0)) do local buf = nvim.win.get_buf(win) if vim.bo[buf].filetype == 'Trouble' then trouble_open = true nvim.ex.TroubleClose() break end end if not trouble_open then if #lsp_document_diagnostics > 0 then vim.notify('Document Diagnostics', 'INFO', { title = 'Trouble' }) nvim.ex.Trouble 'lsp_document_diagnostics' elseif has_workspace_diagnostics then vim.notify('Workspace Diagnostics', 'INFO', { title = 'Trouble' }) nvim.ex.Trouble 'lsp_workspace_diagnostics' elseif #loc_diagnostics > 0 then vim.notify('Location list', 'INFO', { title = 'Trouble' }) nvim.ex.Trouble 'loclist' elseif #qf_diagnostics > 0 then vim.notify('Quicfix', 'INFO', { title = 'Trouble' }) nvim.ex.Trouble 'quickfix' else vim.notify('Nothing to check !', 'WARN', { title = 'Trouble' }) end end end, { noremap = true, silent = true }) return true
-- https://github.com/itinero/routing/blob/develop/samples/Sample.Shape/car.lua -- car globals name = "nwb.car" -- whitelists for profile and meta -- "BST_CODE", "BAANSUBSRT", "RIJRICHTNG", "WEGBEHSRT", "HECTO_LTTR" profile_whitelist = { "BST_CODE", "BAANSUBSRT", "RIJRICHTNG", "WEGBEHSRT", "HECTO_LTTR" } meta_whitelist = { "STT_NAAM" } -- default speed profiles speed_profiles = { ["BVD"] = { speed = 50, oneway = nil }, ["AF"] = { speed = 70, oneway = nil }, ["OP"] = { speed = 70, oneway = nil }, ["HR"] = { speed = 120, oneway = nil }, ["MRB"] = { speed = 30, oneway = true}, ["NRB"] = { speed = 30, oneway = true} } -- profile definitions linking a function to a profile profiles = { { name = "", function_name = "factor_and_speed", metric = "time" }, { name = "shortest", function_name = "factor_and_speed", metric = "distance", } } -- the main function turning attributes into a factor_and_speed and a tag whitelist function factor_and_speed (attributes, result) result.speed = 0 result.direction = 0 result.canstop = true result.attributes_to_keep = {} -- get default speed profiles local BST_CODE = attributes.BST_CODE -- code of road type. local speed_profile = speed_profiles[BST_CODE] local speed = 70 local direction = 0 -- bidirectional default result.attributes_to_keep.BST_CODE = true -- keep this code. if speed_profile then speed = speed_profile.speed if speed_profile.oneway then direction = 1 -- this type of edge is oneway forward by default end end local RIJRICHTNG = attributes.RIJRICHTNG -- oneway code. if RIJRICHTNG then result.attributes_to_keep.RIJRICHTNG = true -- keep the oneway stuff if RIJRICHTNG == "H" then direction = 1 elseif RIJRICHTNG == "T" then direction = 2 end end result.speed = speed -- speed in km/h result.direction = direction result.canstop = true end -- instruction generators instruction_generators = { { applies_to = "", -- applies to all profiles when empty generators = { { name = "start", function_name = "get_start" }, { name = "stop", function_name = "get_stop" }, { name = "roundabout", function_name = "get_roundabout" }, { name = "turn", function_name = "get_turn" } } } } -- gets the first instruction function get_start (route_position, language_reference, instruction) if route_position.is_first() then local direction = route_position.direction() instruction.text = itinero.format(language_reference.get("Start {0}."), language_reference.get(direction)); instruction.shape = route_position.shape return 1 end return 0 end -- gets the last instruction function get_stop (route_position, language_reference, instruction) if route_position.is_last() then instruction.text = language_reference.get("Arrived at destination."); instruction.shape = route_position.shape return 1 end return 0 end function contains (attributes, key, value) if attributes then return localvalue == attributes[key]; end end -- gets a roundabout instruction function get_roundabout (route_position, language_reference, instruction) if (route_position.attributes.BST_CODE == "NRB" or route_position.attributes.BST_CODE == "MRB") and (not route_position.is_last()) then local attributes = route_position.next().attributes if attributes.junction then else local exit = 1 local count = 1 local previous = route_position.previous() while previous and (previous.attributes.BST_CODE == "NRB" or previous.attributes.BST_CODE == "MRB") do local branches = previous.branches if branches then branches = branches.get_traversable() if branches.count > 0 then exit = exit + 1 end end count = count + 1 previous = previous.previous() end instruction.text = itinero.format(language_reference.get("Take the {0}th exit at the next roundabout."), "" .. exit) if exit == 1 then instruction.text = itinero.format(language_reference.get("Take the first exit at the next roundabout.")) elseif exit == 2 then instruction.text = itinero.format(language_reference.get("Take the second exit at the next roundabout.")) elseif exit == 3 then instruction.text = itinero.format(language_reference.get("Take the third exit at the next roundabout.")) end instruction.type = "roundabout" instruction.shape = route_position.shape return count end end return 0 end -- gets a turn function get_turn (route_position, language_reference, instruction) local relative_direction = route_position.relative_direction().direction local turn_relevant = false local branches = route_position.branches if branches then branches = branches.get_traversable() if relative_direction == "straighton" and branches.count >= 2 then turn_relevant = true -- straight on at cross road end if relative_direction != "straighton" and branches.count > 0 then turn_relevant = true -- an actual normal turn end end if turn_relevant then local next = route_position.next() local name = nil if next then name = next.attributes.STT_NAAM end if name then instruction.text = itinero.format(language_reference.get("Go {0} on {1}."), language_reference.get(relative_direction), name) instruction.shape = route_position.shape else instruction.text = itinero.format(language_reference.get("Go {0}."), language_reference.get(relative_direction)) instruction.shape = route_position.shape end return 1 end return 0 end
---@class CS.FairyGUI.PixelHitTestData ---@field public pixelWidth number ---@field public scale number ---@field public pixels Byte[] ---@field public pixelsLength number ---@field public pixelsOffset number ---@type CS.FairyGUI.PixelHitTestData CS.FairyGUI.PixelHitTestData = { } ---@return CS.FairyGUI.PixelHitTestData function CS.FairyGUI.PixelHitTestData.New() end ---@param ba CS.FairyGUI.Utils.ByteBuffer function CS.FairyGUI.PixelHitTestData:Load(ba) end return CS.FairyGUI.PixelHitTestData
if tweak_data and tweak_data.SCSuiteConfiguration.toggle_equipment_enabled then if not _PlayerStandard__check_use_item then _PlayerStandard__check_use_item = PlayerStandard._check_use_item end function PlayerStandard:_check_use_item( t, input ) if input.btn_use_item_press and self:is_deploying() then self:_interupt_action_use_item() return false elseif input.btn_use_item_release then return false end return _PlayerStandard__check_use_item(self, t, input) end end
ICDP_DISCS = ICDP_DISCS or {} ICDP_DISCS[5] = { disc_name = "ICDPCDDisc5", artist_name = "Metallica", album_title = "Metallica", album_cover = "Metallica-Metallica-1993"; content_disc = "Trash-Metal", track_names = { [1] = "01. Enter Sandman", [2] = "02. Sad But True", [3] = "03. Holier Than Thou", [4] = "04. The Unforgiven", [5] = "05. Wherever I May Roam", [6] = "06. Don't Tread on Me", [7] = "07. Through the Never", [8] = "08. Nothing Else Matters", [9] = "09. Of Wolf and Man", [10] = "10. The God That Failed", [11] = "11. My Friend of Misery", [12] = "12. The Struggle Within", }, tracks = { [1] = {"Metallica 01. Enter Sandman", 331}, [2] = {"Metallica 02. Sad But True", 324}, [3] = {"Metallica 03. Holier Than Thou", 227}, [4] = {"Metallica 04. The Unforgiven", 387}, [5] = {"Metallica 05. Wherever I May Roam", 404}, [6] = {"Metallica 06. Don't Tread on Me", 240}, [7] = {"Metallica 07. Through the Never", 244}, [8] = {"Metallica 08. Nothing Else Matters", 388}, [9] = {"Metallica 09. Of Wolf and Man", 256}, [10] = {"Metallica 10. The God That Failed", 308}, [11] = {"Metallica 11. My Friend of Misery", 409}, [12] = {"Metallica 12. The Struggle Within", 233}, }, } ICDP_DISCS[5].track_sum = #ICDP_DISCS[5].tracks
local parent, ns = ... local Compat = ns.Compat local unitExists = Compat.Private.UnitExists local QuickDispatch = Compat.Private.QuickDispatch local format = string.format local strmatch = string.match local select = select local GetNumPartyMembers = GetNumPartyMembers local GetNumRaidMembers = GetNumRaidMembers local UnitIsDeadOrGhost = UnitIsDeadOrGhost local UnitAffectingCombat = UnitAffectingCombat local IsPartyLeader = IsPartyLeader local IsRaidLeader = IsRaidLeader local GetPartyLeaderIndex = GetPartyLeaderIndex local GetRaidRosterInfo = GetRaidRosterInfo function Compat.IsInGroup() return (GetNumRaidMembers() > 0 or GetNumPartyMembers() > 0) end function Compat.IsInRaid() return (GetNumRaidMembers() > 0) end function Compat.GetNumSubgroupMembers() return GetNumPartyMembers() end function Compat.GetNumGroupMembers() return Compat.IsInRaid() and GetNumRaidMembers() or GetNumPartyMembers() end function Compat.GetGroupTypeAndCount() if Compat.IsInRaid() then return "raid", 1, GetNumRaidMembers() elseif Compat.IsInGroup() then return "party", 0, GetNumPartyMembers() else return nil, 0, 0 end end do local rmem, pmem, step, count local function SelfIterator(excPets) while step do local unit, owner if step == 1 then unit, owner, step = "player", nil, 2 elseif step == 2 then if not excPets then unit, owner = "playerpet", "player" end step = nil end if unitExists(unit) then return unit, owner end end end local function PartyIterator(excPets) while step do local unit, owner if step <= 2 then unit, owner = SelfIterator(excPets) step = step or 3 elseif step == 3 then unit, owner, step = format("party%d", count), nil, 4 elseif step == 4 then if not excPets then unit, owner = format("partypet%d", count), format("party%d", count) end count = count + 1 step = count <= pmem and 3 or nil end if unitExists(unit) then return unit, owner end end end local function RaidIterator(excPets) while step do local unit, owner if step == 1 then unit, owner, step = format("raid%d", count), nil, 2 elseif step == 2 then if not excPets then unit, owner = format("raidpet%d", count), format("raid%d", count) end count = count + 1 step = count <= rmem and 1 or nil end if unitExists(unit) then return unit, owner end end end function Compat.UnitIterator(excPets) rmem, step = GetNumRaidMembers(), 1 if rmem == 0 then pmem = GetNumPartyMembers() if pmem == 0 then return SelfIterator, excPets end count = 1 return PartyIterator, excPets end count = 1 return RaidIterator, excPets end end function Compat.IsGroupDead() for unit in Compat.UnitIterator(true) do if not UnitIsDeadOrGhost(unit) then return false end end return true end function Compat.IsGroupInCombat() for unit in Compat.UnitIterator() do if UnitAffectingCombat(unit) then return true end end return false end function Compat.GroupIterator(func, ...) for unit, owner in Compat.UnitIterator() do QuickDispatch(func, unit, owner, ...) end end function Compat.UnitIsGroupLeader(unit) if not Compat.IsInGroup() then return false elseif unit == "player" then return (Compat.IsInRaid() and IsRaidLeader() or IsPartyLeader()) else local index = strmatch(unit, "%d+") if Compat.IsInRaid() then return (index and select(2, GetRaidRosterInfo(index)) == 2) end return (index and GetPartyLeaderIndex() == tonumber(index)) end end function Compat.UnitIsGroupAssistant(unit) if not Compat.IsInRaid() then return false end local index = strmatch(unit, "%d+") return (index and select(2, GetRaidRosterInfo(index)) == 1) end
package.path = "../?.lua;" .. package.path local EventDataSerializer = {} function EventDataSerializer:new () -- "Object Oriented" Lua examples: https://habr.com/post/259265/ local public = {} -- return event_key, event_data function EventDataSerializer:OnClose () return nil, nil end function EventDataSerializer:PublisherOnline () return nil, nil end function EventDataSerializer:PublisherOffline (signal) return nil, nil end function EventDataSerializer:OnFirm (firm) return nil, nil end function EventDataSerializer:OnAllTrade (alltrade) return nil, nil end function EventDataSerializer:OnTrade (trade) return nil, nil end function EventDataSerializer:OnOrder (order) return nil, nil end function EventDataSerializer:OnAccountBalance (acc_bal) return nil, nil end function EventDataSerializer:OnFuturesLimitChange (fut_limit) return nil, nil end function EventDataSerializer:OnFuturesLimitDelete (lim_del) return nil, nil end function EventDataSerializer:OnFuturesClientHolding (fut_pos) return nil, nil end function EventDataSerializer:OnMoneyLimit (mlimit) return nil, nil end function EventDataSerializer:OnMoneyLimitDelete (mlimit_del) return nil, nil end function EventDataSerializer:OnDepoLimit (dlimit) return nil, nil end function EventDataSerializer:OnDepoLimitDelete (dlimit_del) return nil, nil end function EventDataSerializer:OnAccountPosition (acc_pos) return nil, nil end function EventDataSerializer:OnNegDeal (neg_deal) return nil, nil end function EventDataSerializer:OnNegTrade (neg_trade) return nil, nil end function EventDataSerializer:OnStopOrder (stop_order) return nil, nil end function EventDataSerializer:OnTransReply (trans_reply) return nil, nil end function EventDataSerializer:OnParam (class_code, sec_code) return nil, nil end function EventDataSerializer:OnQuote (class_code, sec_code) return nil, nil end function EventDataSerializer:OnDisconnected () return nil, nil end function EventDataSerializer:OnConnected (flag) return nil, nil end function EventDataSerializer:OnCleanUp () return nil, nil end function EventDataSerializer:OnDataSourceUpdate (update_info) return nil, nil end setmetatable(public, self) self.__index = self return public end return EventDataSerializer
object_building_player_sandcrawler_house = object_building_player_shared_sandcrawler_house:new { } ObjectTemplates:addTemplate(object_building_player_sandcrawler_house, "object/building/player/sandcrawler_house.iff")
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf" module('BceChangeSeat_pb', package.seeall) local BCECHANGESEAT = protobuf.Descriptor(); BCECHANGESEAT.name = "BceChangeSeat" BCECHANGESEAT.full_name = ".com.xinqihd.sns.gameserver.proto.BceChangeSeat" BCECHANGESEAT.nested_types = {} BCECHANGESEAT.enum_types = {} BCECHANGESEAT.fields = {} BCECHANGESEAT.is_extendable = false BCECHANGESEAT.extensions = {} BceChangeSeat = protobuf.Message(BCECHANGESEAT) _G.BCECHANGESEAT_PB_BCECHANGESEAT = BCECHANGESEAT
local w,h = ScrW(),ScrH() hook.Add("HUDPaint","DrawAmmo",function() local lp = LocalPlayer() local wep = lp:GetActiveWeapon() if (!IsValid(wep)) then return end local Ammo = lp:GetAmmoCount(wep:GetPrimaryAmmoType()) local Clip = wep:Clip1() if (Clip > -1) then DrawTextShadow(Clip,"MZS_Font80",w-210,h-110,MAIN_WHITECOLOR,2,MAIN_BLACKCOLOR,2) DrawTextShadow(Ammo,"MZS_Font36",w-100,h-75,MAIN_WHITECOLOR,2,MAIN_BLACKCOLOR,2) end end)
-- @okarosa local characterNameCache = {} local characterIDCache = {} local searched = {} local refreshCacheRate = 10 --Minutes function getCharacterNameFromID( id ) if not id or not tonumber(id) then return false else id = tonumber(id) end if characterNameCache[id] then return characterNameCache[id] end for i, player in pairs(getElementsByType("player")) do if id == getElementData(player, "dbid") then characterNameCache[id] = exports.mrp_global:getPlayerName(player) return characterNameCache[id] end end if not searched[id] or getTickCount() - searched[id] > refreshCacheRate*1000*60 then searched[id] = getTickCount() triggerServerEvent("requestCharacterNameCacheFromServer", localPlayer, id) else return false end return "Loading.." end function retrieveCharacterNameCacheFromServer(characterName, id) if characterName and id then characterNameCache[id] = characterName end end addEvent("retrieveCharacterNameCacheFromServer", true) addEventHandler("retrieveCharacterNameCacheFromServer", root, retrieveCharacterNameCacheFromServer) function getCharacterIDFromName( name ) if not name then return false else name = tostring(name):gsub(" ", "_") end if characterIDCache[name] then return characterNameCache[id] end for i, player in pairs(getElementsByType("player")) do if name == getPlayerName(player) then characterIDCache[name] = tonumber(getElementData(player, "dbid")) return characterIDCache[name] end end if searched[name] then return false end searched[name] = true triggerServerEvent("requestCharacterIDCacheFromServer", localPlayer, name) setTimer(function() local index = id searched[index] = nil end, refreshCacheRate*1000*60, 1) return "Loading.." end function retrieveCharacterIDCacheFromServer(characterName, id) if characterName and id then characterIDCache[characterName] = id end end addEvent("retrieveCharacterIDCacheFromServer", true) addEventHandler("retrieveCharacterIDCacheFromServer", root, retrieveCharacterIDCacheFromServer)
-- sci component -- electronics sci local refsubgroup = data.raw["item-subgroup"][data.raw.item["iron-stick"].subgroup] data:extend({ { type = "item-subgroup", name = "momo-science-materials", group = refsubgroup.group, order = refsubgroup.order .. "1" } }) local subgroup = "momo-science-materials" local ICON = "__MomosTweak__/graphics/icons/" function momoTweak.newsciItem(Name) data:extend({ { type = "item", name = Name, icon = ICON .. Name .. ".png", icon_size = 32, subgroup = subgroup, order = "f[" .. Name .. "]", stack_size = 200 } }) end momoTweak.newsciItem("momo-vial") --1 momoTweak.newsciItem("red-sci") momoTweak.newsciItem("building-pack") momoTweak.newsciItem("pre-dark-sci") momoTweak.newsciItem("product-sci") momoTweak.newsciItem("cyan-sci") momoTweak.newsciItem("pre-high-sci") -- 6 momoTweak.newsciItem("green-sci") momoTweak.newsciItem("movement-pack") momoTweak.newsciItem("bronze-pack") momoTweak.newsciItem("dark-chip") -- 10 momoTweak.newsciItem("pre-cyan-sci") momoTweak.newsciItem("cpy") momoTweak.newsciItem("logistic-express") momoTweak.newsciItem("py-nxag-matrix") momoTweak.newsciItem("py-superconductor") -- 15 momoTweak.newsciItem("plate-pack-1") if (momoTweak.mods.sct or momoTweak.py.coal) then momoTweak.newsciItem("sct-2") momoTweak.newsciItem("sct-gun") momoTweak.newsciItem("sct-3") momoTweak.newsciItem("sct-production") momoTweak.newsciItem("sct-logistic") momoTweak.newsciItem("sct-high") end
local http = require("http"); local data = require("data"); local auth = string.format('Basic %s', data.tobase64(string.format("%s:%s", settings.login, settings.password))); --@help set_label set_label = function(state) layout.current_state.text = string.format("Current state: %s", state.id); layout.current_state.color = state.color; end --@help get_url get_url = function(url) return string.format('%s%s', settings.url, url) end --@help get_info get_info = function () local headers = { Authorization = auth }; local req = { method = "get", url = get_url('/info'), mime = "text/json", headers = headers }; http.request(req, function (err, resp) if (err) then return; end local data = data.fromjson(resp.content); set_label(data.current_state); for state_id, state in pairs(data.states) do state_button = layout[string.format("state_%s", state_id)]; state_button.text = state.id; state_button.color = state.color; end layout.info.text = string.format("AlarMe v%s", data.app.version); end); end --@help set_state set_state = function(state) local headers = { Authorization = auth, ["Content-Type"] = "application/x-www-form-urlencoded" }; local req = { method = "post", url = get_url('/control'), mime = "text/plain", headers = headers, content = string.format("behaviour=%s", state) }; http.request(req, function (err, resp) if (err) then return; end get_info(); end); end --@help set_state_start actions.set_state_start = function() set_state("start"); end --@help set_state_disable actions.set_state_disable = function() set_state("disable"); end --@help set_state_pass actions.set_state_pass = function() set_state("pass"); end --@help set_state_exit actions.set_state_exit = function() set_state("exit"); end --@help set_state_stay actions.set_state_stay = function() set_state("stay"); end --@help set_state_guard actions.set_state_guard = function() set_state("guard"); end --@help set_state_alarm actions.set_state_alarm = function() set_state("alarm"); end --@help reload actions.reload = function() get_info(); end events.create = get_info; events.focus = get_info;
----------------------------------- -- Area: La Theine Plateau -- Mob: Nihniknoovi ----------------------------------- require("scripts/globals/status"); require("scripts/quests/tutorial") ----------------------------------- function onMobInitialize(mob) mob:setMobMod(tpz.mobMod.IDLE_DESPAWN, 600); end; function onMobDeath(mob, player, isKiller) tpz.tutorial.onMobDeath(player) end;
require('config.keymaps') require('config.options') require('config.autogroups')
local announcementStopServerLayout= { name="announcementStopServerLayout",type=0,typeName="View",time=0,report=0,x=0,y=0,width=1280,height=720,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTopLeft, { name="shadeBg",type=1,typeName="Image",time=31057625,report=0,x=0,y=0,width=1280,height=720,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,file="hall/common/bg_shiled.png" }, { name="centerView",type=0,typeName="View",time=77698533,report=0,x=0,y=0,width=808,height=482,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter, { name="bg",type=1,typeName="Image",time=77699401,report=0,x=0,y=0,width=808,height=482,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTopLeft,file="hall/common/popupWindow/popupWindow_bg_55_55_55_55.png",gridLeft=55,gridRight=55,gridTop=55,gridBottom=55 }, { name="titleBg",type=1,typeName="Image",time=77698535,report=0,x=0,y=-54,width=617,height=190,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="hall/common/popupWindow/popupWindow_title.png", { name="title",type=4,typeName="Text",time=77698536,report=0,x=0,y=-5,width=108,height=50,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=36,textAlign=kAlignCenter,colorRed=246,colorGreen=229,colorBlue=194,string=[[小提示]],colorA=1 } }, { name="tips",type=0,typeName="Text",time=122812856,x=68,y=96,width=168,height=28,nodeAlign=kAlignTopLeft,visible=1,fillParentWidth=0,fillParentHeight=0,string=[[亲爱的玩家:]],fontSize=28,textAlign=kAlignLeft,colorRed=142,colorGreen=93,colorBlue=32,colorA=1 }, { name="content_centre",type=5,typeName="TextView",time=42629912,report=0,x=0,y=8,width=672,height=220,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=28,textAlign=kAlignTopLeft,colorRed=118,colorGreen=72,colorBlue=18,string=[[因为运营商机房故障,导致部分玩家登录异常或支付失败,对此我们深表歉意。为了充分保障大家的账户安全,我们决定进行紧急停服维护。有任何疑问,请致电官方客服。]],colorA=1 }, { name="bottomView",type=0,typeName="View",time=77698546,report=0,x=0,y=0,width=808,height=115,fillTopLeftX=0,fillTopLeftY=362,fillBottomRightX=0,fillBottomRightY=5,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft, { name="twoBtnsView",type=0,typeName="View",time=30964892,report=0,x=0,y=0,width=808,height=100,visible=1,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignCenter, { name="btn2",type=2,typeName="Button",time=30962483,report=0,x=112,y=0,width=254,height=80,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,file="hall/common/btns/btn_orange_164x89_l25_r25_t25_b25.png",gridLeft=25,gridRight=25,gridTop=25,gridBottom=25, { name="btn2Text",type=4,typeName="Text",time=30963316,report=0,x=0,y=-3,width=254,height=36,visible=1,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=36,textAlign=kAlignCenter,colorRed=255,colorGreen=250,colorBlue=200,string=[[致电客服]] } }, { name="btn1",type=2,typeName="Button",time=30962525,report=0,x=112,y=0,width=254,height=80,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignRight,file="hall/common/btns/btn_green_164x89_l25_r25_t25_b25.png",gridLeft=25,gridRight=25,gridTop=25,gridBottom=25, { name="btn1Text",type=4,typeName="Text",time=30963332,report=0,x=0,y=-3,width=254,height=36,visible=1,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=36,textAlign=kAlignCenter,colorRed=255,colorGreen=250,colorBlue=200,string=[[等会再来]],colorA=1 } } }, { name="singleBtnView",type=0,typeName="View",time=30965176,report=0,x=0,y=0,width=808,height=100,visible=1,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignCenter, { name="btn1",type=2,typeName="Button",time=93464281,report=0,x=0,y=0,width=254,height=80,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="hall/common/btns/btn_green_164x89_l25_r25_t25_b25.png",gridLeft=25,gridRight=25,gridTop=25,gridBottom=25, { name="btn1Text",type=4,typeName="Text",time=93464282,report=0,x=0,y=-3,width=254,height=36,visible=1,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=36,textAlign=kAlignCenter,colorRed=255,colorGreen=250,colorBlue=200,string=[[等会再来]] } } } } } } return announcementStopServerLayout;
--- Provides utility methods for MarketplaceService -- @module MarketplaceUtil local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local MarketplaceService = game:GetService("MarketplaceService") local Promise = require("Promise") local MarketplaceUtil = {} function MarketplaceUtil.promisePlayerOwnsAsset(player, assetId) assert(typeof(player) == "Instance") assert(type(assetId) == "number") return Promise.spawn(function(resolve, reject) local result local ok, err = pcall(function() result = MarketplaceService:PlayerOwnsAsset(player, assetId) end) if not ok then return reject(err) end if type(result) ~= "boolean" then return reject("Bad result type") end return resolve(result) end) end function MarketplaceUtil.promiseUserOwnsGamePass(player, gamePassId) assert(typeof(player) == "Instance") assert(type(gamePassId) == "number") return Promise.spawn(function(resolve, reject) local result local ok, err = pcall(function() result = MarketplaceService:UserOwnsGamePassAsync(player, gamePassId) end) if not ok then return reject(err) end if type(result) ~= "boolean" then return reject("Bad result type") end return resolve(result) end) end return MarketplaceUtil
local updated = 0 local respawnHospital = false RegisterNetEvent('five_roleplay_core:setHealth') AddEventHandler('five_roleplay_core:setHealth', function(result) Citizen.Wait(3000) SetEntityHealth(PlayerPedId(),result) end) AddEventHandler("playerSpawned", function() TriggerServerEvent('five_roleplay_core:spawn') end) function check_player() local ped = PlayerId() if IsPlayerDead(ped) then PlayerResurected = false else PlayerResurected = true end end function resetvariable() updated = 0 PlayerResurected = false end Citizen.CreateThread(function() while true do Citizen.Wait(0) local ped = PlayerId() if IsPlayerDead(ped) then check_player() PlayerResurected = false end if IsPlayerDead(ped) and updated == 0 then TriggerServerEvent('five_roleplay_core:update', GetEntityHealth(ped)) updated = 1 print('Personnage mort ' .. GetEntityHealth(ped)) elseif not IsPlayerDead(ped) and updated == 1 then resetvariable() PlayerResurected = false if not respawnHospital then TriggerServerEvent('five_roleplay_core:update', 0) Citizen.Wait(1000) SetEntityHealth(PlayerPedId(),101) Citizen.Wait(10000) TriggerServerEvent('five_roleplay_core:update', 0) respawnHospital = false end updated = 0 end end end) Citizen.CreateThread(function() while true do Citizen.Wait(60000) local ped = PlayerPedId() if updated == 0 then TriggerServerEvent('five_roleplay_core:update', GetEntityHealth(ped)) end end end) --------------------------------------------------------------- ---- DEAD SCREEN --------------------------------------------------------------- Citizen.CreateThread(function() while true do Citizen.Wait(0) if IsEntityDead(PlayerPedId())then StartScreenEffect("DeathFailOut", 0, 0) ShakeGameplayCam("DEATH_FAIL_IN_EFFECT_SHAKE", 1.0) local scaleform = RequestScaleformMovie("MP_BIG_MESSAGE_FREEMODE") if HasScaleformMovieLoaded(scaleform) then Citizen.Wait(0) PushScaleformMovieFunction(scaleform, "SHOW_SHARD_WASTED_MP_MESSAGE") BeginTextComponent("STRING") AddTextComponentString("~r~Vous êtes dans le coma") EndTextComponent() PopScaleformMovieFunctionVoid() Citizen.Wait(500) while IsEntityDead(PlayerPedId()) do DrawScaleformMovieFullscreen(scaleform, 255, 255, 255, 255) Citizen.Wait(0) end StopScreenEffect("DeathFailOut") end end end end)
slot0 = class("SVSalvageResult", import("view.base.BaseSubView")) slot0.HideView = "SVSalvageResult.HideView" slot0.getUIName = function (slot0) return "SVSalvageResult" end slot0.OnLoaded = function (slot0) return end slot0.OnInit = function (slot0) slot0.rtPanel = slot0._tf:Find("window/display_panel") setText(slot0.rtPanel:Find("info/Text"), i18n("world_catsearch_help_1")) setText(slot0.rtPanel:Find("info/items_btn/Text"), i18n("world_catsearch_help_2")) onButton(slot0, slot0.rtPanel:Find("info/items_btn"), function () slot0:emit(BaseUI.ON_DROP_LIST, { item2Row = true, itemList = _.map(pg.gameset.world_catsearchdrop_show.description, function (slot0) return { type = slot0[1], id = slot0[2], count = slot0[3] } end), content = i18n("world_catsearch_help_6") }) end, SFX_PANEL) onButton(slot0, slot0._tf:Find("bg"), function () slot0:Hide() end, SFX_CANCEL) slot0.btnBack = slot0._tf.Find(slot1, "window/top/btnBack") onButton(slot0, slot0.btnBack, function () slot0:Hide() end, SFX_CANCEL) slot0.btnCanel = slot0._tf.Find(slot1, "window/button_container/custom_button_2") onButton(slot0, slot0.btnCanel, function () slot0:Hide() end, SFX_CANCEL) slot0.btnHelp = slot0.rtPanel.Find(slot1, "info/help") onButton(slot0, slot0.btnHelp, function () slot0:Hide() slot0.Hide:emit(WorldScene.SceneOp, "OpOpenLayer", Context.New({ mediator = WorldHelpMediator, viewComponent = WorldHelpLayer, data = { titleId = 3, pageId = 10 } })) end, SFX_PANEL) slot0.btnConfirm = slot0._tf.Find(slot1, "window/button_container/custom_button_1") onButton(slot0, slot0.btnConfirm, function () slot0:Hide() slot0.Hide:emit(WorldScene.SceneOp, "OpReqCatSalvage", slot0.fleetId) end, SFX_CONFIRM) end slot0.OnDestroy = function (slot0) return end slot0.Show = function (slot0) setActive(slot0._tf, true) pg.UIMgr.GetInstance():BlurPanel(slot0._tf) end slot0.Hide = function (slot0) pg.UIMgr.GetInstance():UnblurPanel(slot0._tf, slot0._parentTf) setActive(slot0._tf, false) end slot0.Setup = function (slot0, slot1) slot0.fleetId = slot1 end return slot0
addEventHandler('onClientResourceStart', resourceRoot, function() triggerServerEvent('nickProtectionLoaded', getLocalPlayer()) end )
local PANEL_Browser = {} PANEL_Browser.Base = "DFrame" function PANEL_Browser:Init() self.HTML = vgui.Create( "HTML", self ) if ( !self.HTML ) then print( "SteamOverlayReplace: Failed to create HTML element" ) self:Remove() return end self.HTML:Dock( FILL ) self.HTML:SetOpenLinksExternally( true ) self:SetTitle( "Steam overlay replacement" ) self:SetSize( ScrW() * 0.75, ScrH() * 0.75 ) self:SetSizable( true ) self:Center() self:MakePopup() end function PANEL_Browser:SetURL( url ) self.HTML:OpenURL( url ) end -- Called from the engine function GMOD_OpenURLNoOverlay( url ) local BrowserInst = vgui.CreateFromTable( PANEL_Browser ) BrowserInst:SetURL( url ) timer.Simple( 0, function() if ( !gui.IsGameUIVisible() ) then gui.ActivateGameUI() end end ) end ---------------------------------------------- local PANEL = {} PANEL.Base = "DFrame" function PANEL:Init() self.Type = "openurl" self:SetTitle( "#openurl.title" ) self.Garble = vgui.Create( "DLabel", self ) self.Garble:SetText( "#openurl.text" ) self.Garble:SetContentAlignment( 5 ) self.Garble:Dock( TOP ) self.URL = vgui.Create( "DTextEntry", self ) self.URL:SetDisabled( true ) self.URL:Dock( TOP ) self.CustomPanel = vgui.Create( "DLabel", self ) self.CustomPanel:Dock( TOP ) self.CustomPanel:SetContentAlignment( 5 ) self.CustomPanel:DockMargin( 0, 5, 0, 0 ) self.CustomPanel:SetVisible( false ) self.CustomPanel.Color = Color( 0, 0, 0, 0 ) self.CustomPanel.Paint = function( s, w, h ) draw.RoundedBox( 0, 0, 0, w, h, s.Color ) end self.Buttons = vgui.Create( "Panel", self ) self.Buttons:Dock( TOP ) self.Buttons:DockMargin( 0, 5, 0, 0 ) self.Disconnect = vgui.Create( "DButton", self.Buttons ) self.Disconnect:SetText( "#openurl.disconnect" ) self.Disconnect.DoClick = function() self:DoNope() RunConsoleCommand( "disconnect" ) end self.Disconnect:Dock( LEFT ) self.Disconnect:SizeToContents() self.Disconnect:SetWide( self.Disconnect:GetWide() + 10 ) self.Nope = vgui.Create( "DButton", self.Buttons ) self.Nope:SetText( "#openurl.nope" ) self.Nope.DoClick = function() self:DoNope() end self.Nope:DockMargin( 0, 0, 5, 0 ) self.Nope:Dock( RIGHT ) self.Yes = vgui.Create( "DButton", self.Buttons ) self.Yes:SetText( "#openurl.yes" ) self.Yes.DoClick = function() self:DoYes() end self.Yes:DockMargin( 0, 0, 5, 0 ) self.Yes:Dock( RIGHT ) self.YesPerma = vgui.Create( "DCheckBoxLabel", self.Buttons ) self.YesPerma:SetText( "#openurl.yes_remember" ) self.YesPerma:DockMargin( 0, 0, 5, 0 ) self.YesPerma:Dock( RIGHT ) self.YesPerma:SetVisible( false ) self:SetSize( 680, 104 ) self:Center() self:MakePopup() self:DoModal() hook.Add( "Think", self, self.AlwaysThink ) if ( !IsInGame() ) then self.Disconnect:SetVisible( false ) end end function PANEL:LoadServerInfo() self.CustomPanel:SetVisible( true ) self.CustomPanel:SetText( "Loading server info..." ) self.CustomPanel:SizeToContents() serverlist.PingServer( self:GetURL(), function( ping, name, desc, map, players, maxplayers, bot, pass, lp, ip, gamemode ) if ( !IsValid( self ) ) then return end if ( !ping ) then self.CustomPanel.Color = Color( 200, 50, 50 ) self.CustomPanel:SetText( "#askconnect.no_response" ) else self.CustomPanel:SetText( string.format( "%s\n%i/%i players | %s | %s | %ims", name, players, maxplayers, map, desc, ping ) ) end self.CustomPanel:SizeToContents() end ) end function PANEL:AlwaysThink() -- Ping the server for details if ( SysTime() - self.StartTime > 0.1 && self.Type == "askconnect" && !self.CustomPanel:IsVisible() ) then self:LoadServerInfo() end if ( self.StartTime + 1 > SysTime() ) then return end if ( !self.Yes:IsEnabled() ) then self.Yes:SetEnabled( true ) end if ( !gui.IsGameUIVisible() ) then self:Remove() end end function PANEL:PerformLayout( w, h ) DFrame.PerformLayout( self, w, h ) self:SizeToChildren( false, true ) end function PANEL:SetURL( url ) self.URL:SetText( url ) self.StartTime = SysTime() self.Yes:SetEnabled( false ) self.CustomPanel:SetVisible( false ) self.CustomPanel.Color = Color( 0, 0, 0, 0 ) self:InvalidateLayout() end function PANEL:GetURL() return self.URL:GetText() end function PANEL:DoNope() self:Remove() gui.HideGameUI() end function PANEL:DoYes() if ( self.StartTime + 1 > SysTime() ) then return end local saveYes = self.YesPerma:GetChecked() self:DoYesAction( !saveYes ) self:Remove() gui.HideGameUI() end function PANEL:DoYesAction( bSessionOnly ) if ( self.Type == "openurl" ) then gui.OpenURL( self.URL:GetText() ) elseif ( self.Type == "askconnect" ) then permissions.Grant( "connect", bSessionOnly ) permissions.Connect( self.URL:GetText() ) elseif ( self.Type == "permission" ) then permissions.Grant( self.URL:GetText(), bSessionOnly ) else ErrorNoHaltWithStack( "Unhandled confirmation type '" .. tostring( self.Type ) .. "'!" ) end end function PANEL:SetType( t ) self.Type = t self:SetTitle( "#" .. t .. ".title" ) self.Garble:SetText( "#" .. t .. ".text" ) if ( self.Type == "permission" || self.Type == "askconnect" ) then self.YesPerma:SetVisible( true ) end end local PanelInst = nil local function OpenConfirmationDialog( address, confirm_type ) if ( IsValid( PanelInst ) && PanelInst:GetURL() == address ) then return end if ( !IsValid( PanelInst ) ) then PanelInst = vgui.CreateFromTable( PANEL ) end PanelInst:SetType( confirm_type ) PanelInst:SetURL( address ) timer.Simple( 0, function() if ( !gui.IsGameUIVisible() ) then gui.ActivateGameUI() end end ) end -- Called from the engine function RequestOpenURL( url ) OpenConfirmationDialog( url, "openurl" ) end function RequestConnectToServer( serverip ) if ( permissions.IsGranted( "connect" ) ) then permissions.Connect( serverip ) else OpenConfirmationDialog( serverip, "askconnect" ) end end function RequestPermission( perm ) -- OpenConfirmationDialog( perm, "permission" ) end
-- Test .event io.write 'cord.event' require 'site' local Nylon = require 'nylon.core'() Nylon.cord( 'failsafe', function(cord) cord:sleep(1.5); os.exit(99); end ) local okay = false local c1 = Nylon.cord( 'c1', function(cord) cord.event.red() -- events can be posted though the handler hasn't been set yet, and will be processed when the handler is set local count = 0 cord.event.red = function() count = count + 1 end cord.event.blue = function() count = count + 1 end -- this is a little weird, because I'm not sure what guarantees I can -- actually make about the order in which events will be processed. -- explicit message box priorities might allow stricter guarantees? -- it seems to work as is FWIW but I don't know that this is guaranteed. cord.event.green = function( wake ) if count == 2 then okay = true end wake() end while true do cord:sleep() end end ) Nylon.cord( 'c2', function(cord) cord:sleep_manual( function( wake ) c1.event.blue() c1.event.green( wake ) end ) -- print( 'exiting', okay ) os.exit( okay and 0 or 1) end ) Nylon.run()
--for command bar thing local targetModel = workspace.LowerBody local modelDescendants = targetModel:GetDescendants() local folder = Instance.new("Folder") folder.Parent = targetModel folder.Name = "Motor6DValues" for i, descendant in pairs(modelDescendants) do if descendant:IsA("Motor6D") then local object = Instance.new("ObjectValue") object.Value = descendant object.Name = descendant.Name object.Parent = folder end end return nothing
----------------------------------- -- Area: Beaucedine Glacier -- NM: Calcabrina ----------------------------------- require("scripts/globals/mobs") ----------------------------------- function onMobInitialize(mob) mob:setMobMod(tpz.mobMod.ADD_EFFECT, 1); end; function onAdditionalEffect(mob, target, damage) return tpz.mob.onAddEffect(mob, target, damage, tpz.mob.ae.HP_DRAIN) end function onMobDeath(mob, player, isKiller) end; function onMobDespawn(mob) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random(5400,6000)); end;
function momoIRTweak.finalFixes.Electronics() --using local eles = momoIRTweak.electronics local ITEM = momoIRTweak.FastItem local AddIng = momoIRTweak.recipe.AddIngredient --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- if (momoIRTweak.electronics.isHarder) then ---- SPEED -- 1 AddIng("program-speed-module", ITEM(eles.pcb1.name, 4)) -- 2 AddIng("program-speed-module-2", ITEM(eles.pcb2.name, 8)) -- 3 AddIng("program-speed-module-3", ITEM(eles.pcb3.name, 8)) ---- PRODUCTIVITY -- 1 AddIng("program-productivity-module", ITEM(eles.pcb1.name, 8)) -- 2 AddIng("program-productivity-module-2", ITEM(eles.pcb2.name, 16)) -- 3 AddIng("program-productivity-module-3", ITEM(eles.pcb3.name, 16)) ---- EFFECTIVITY -- 1 AddIng("program-effectivity-module", ITEM(eles.pcb1.name, 2)) -- 2 AddIng("program-effectivity-module-2", ITEM(eles.pcb2.name, 4)) -- 3 AddIng("program-effectivity-module-3", ITEM(eles.pcb3.name, 4)) end --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- if (settings.startup["momo-harderModule"].value) then ---- SPEED -- 1 AddIng("program-speed-module", ITEM("iron-incinerator", 1)) -- 2 AddIng("program-speed-module-2", ITEM("engine-unit", 2)) AddIng("program-speed-module-2", ITEM("k-circuit-board", 4)) -- 3 AddIng("program-speed-module-3", ITEM("electric-engine-unit", 2)) AddIng("program-speed-module-3", ITEM("k-ram", 8)) AddIng("program-speed-module-3", ITEM("k-processor", 2)) ---- PRODUCTIVITY -- 1 AddIng("program-productivity-module", ITEM("copper-scrapper", 1)) -- 2 AddIng("program-productivity-module-2", ITEM("iron-scrapper", 1)) AddIng("program-productivity-module-2", ITEM("k-circuit-board", 4)) -- 3 AddIng("program-productivity-module-3", ITEM("iron-scrapper", 2)) AddIng("program-productivity-module-3", ITEM("k-ram", 16)) AddIng("program-productivity-module-3", ITEM("k-processor", 4)) ---- EFFECTIVITY -- 1 -- 2 AddIng("program-effectivity-module-2", ITEM("iron-incinerator", 1)) AddIng("program-effectivity-module-2", ITEM("k-circuit-board", 2)) -- 3 AddIng("program-effectivity-module-3", ITEM("engine-unit", 1)) AddIng("program-effectivity-module-3", ITEM("k-ram", 4)) AddIng("program-effectivity-module-3", ITEM("k-processor", 1)) end end
object_static_item_eqp_camping_tent_s3 = object_static_item_shared_eqp_camping_tent_s3:new { } ObjectTemplates:addTemplate(object_static_item_eqp_camping_tent_s3, "object/static/item/eqp_camping_tent_s3.iff")
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('XTemplate', { __is_kind_of = "XContentTemplate", group = "PreGame", id = "PGMissionSubtitle", PlaceObj('XTemplateWindow', { '__class', "XContentTemplate", 'Dock', "top", 'RespawnOnContext', false, }, { PlaceObj('XTemplateMode', { 'mode', "items", }, { PlaceObj('XTemplateTemplate', { '__template', "DialogTitleSmall", 'Id', "idTitle", 'Margins', box(55, 1, 0, 0), }), PlaceObj('XTemplateCode', { 'run', function (self, parent, context) parent.idTitle:SetTitle(GetDialogModeParam(parent).title) end, }), }), }), })
---@class IsoRegionsLogger.IsoRegionLog : zombie.iso.areas.isoregion.IsoRegionsLogger.IsoRegionLog ---@field private str String ---@field private type IsoRegionLogType ---@field private col Color IsoRegionsLogger_IsoRegionLog = {} ---@public ---@return IsoRegionLogType function IsoRegionsLogger_IsoRegionLog:getType() end ---@public ---@return Color function IsoRegionsLogger_IsoRegionLog:getColor() end ---@public ---@return String function IsoRegionsLogger_IsoRegionLog:getStr() end
-- BELOVE IS YOUR SETTINGS, CHANGE THEM TO WHATEVER YOU'D LIKE & MORE SETTINGS WILL COME IN THE FUTURE! -- local useBilling = true -- OPTIONS: (true/false) local useCameraSound = true -- OPTIONS: (true/false) local useFlashingScreen = true -- OPTIONS: (true/false) local useBlips = true -- OPTIONS: (true/false) local alertPolice = true -- OPTIONS: (true/false) local alertSpeed = 150 -- OPTIONS: (1-5000 KMH) local defaultPrice60 = 100 -- THIS IS THE DEFAULT PRICE WITHOUT EXTRA COST FOR 60 ZONES local defaultPrice80 = 300 -- THIS IS THE DEFAULT PRICE WITHOUT EXTRA COST FOR 80 ZONES local defaultPrice120 = 500 -- THIS IS THE DEFAULT PRICE WITHOUT EXTRA COST FOR 120 ZONES local extraZonePrice10 = 100 -- THIS IS THE EXTRA COST IF 10 KM/H ABOVE LIMIT (REQUIRES "useBilling" to be set to true) local extraZonePrice20 = 500 -- THIS IS THE EXTRA COST IF 20 KM/H ABOVE LIMIT (REQUIRES "useBilling" to be set to true) local extraZonePrice30 = 1000 -- THIS IS THE EXTRA COST IF 30 KM/H ABOVE LIMIT (REQUIRES "useBilling" to be set to true) -- ABOVE IS YOUR SETTINGS, CHANGE THEM TO WHATEVER YOU'D LIKE & MORE SETTINGS WILL COME IN THE FUTURE! -- ESX = nil local hasBeenCaught = false local finalBillingPrice = 0; Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end end) RegisterNetEvent('esx:playerLoaded') AddEventHandler('esx:playerLoaded', function(xPlayer) PlayerData = xPlayer end) function hintToDisplay(text) SetTextComponentFormat("STRING") AddTextComponentString(text) DisplayHelpTextFromStringLabel(0, 0, 1, -1) end -- BLIP FOR SPEEDCAMERAS local blips = { -- 60KM/H ZONES {title="Speedcamera (60KM/H)", colour=1, id=1, x = -524.2645, y = -1776.3569, z = 21.3384}, -- 60KM/H ZONE -- 80KM/H ZONES {title="Speedcamera (80KM/H)", colour=1, id=1, x = 2506.0671, y = 4145.2431, z = 38.1054}, -- 80KM/H ZONE {title="Speedcamera (80KM/H)", colour=1, id=1, x = 1258.2006, y = 789.4199, z = 104.2190}, -- 80KM/H ZONE {title="Speedcamera (80KM/H)", colour=1, id=1, x = 980.9982, y = 407.4164, z = 92.2374}, -- 80KM/H ZONE -- 120KM/H ZONES {title="Speedcamera (120KM/H)", colour=1, id=1, x = 1584.9281, y = -993.4557, z = 59.3923}, -- 120KM/H ZONE {title="Speedcamera (120KM/H)", colour=1, id=1, x = 2442.2006, y = -134.6004, z = 88.7765}, -- 120KM/H ZONE {title="Speedcamera (120KM/H)", colour=1, id=1, x = 2871.7951, y = 3540.5795, z = 53.0930} -- 120KM/H ZONE } Citizen.CreateThread(function() for _, info in pairs(blips) do if useBlips == true then info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 0.5) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end end) -- AREAS local Speedcamera60Zone = { {x = -524.2645,y = -1776.3569,z = 21.3384} } local Speedcamera80Zone = { {x = 2506.0671,y = 4145.2431,z = 38.1054}, {x = 1258.2006,y = 789.4199,z = 103.2190}, {x = 980.9982,y = 407.4164,z = 92.2374} } local Speedcamera120Zone = { {x = 1584.9281,y = -993.4557,z = 59.3923}, {x = 2442.2006,y = -134.6004,z = 88.7765}, {x = 2871.7951,y = 3540.5795,z = 53.0930} } -- ZONES Citizen.CreateThread(function() while true do Citizen.Wait(10) -- 60 zone for k in pairs(Speedcamera60Zone) do local plyCoords = GetEntityCoords(GetPlayerPed(-1), false) local dist = Vdist(plyCoords.x, plyCoords.y, plyCoords.z, Speedcamera60Zone[k].x, Speedcamera60Zone[k].y, Speedcamera60Zone[k].z) if dist <= 20.0 then local playerPed = GetPlayerPed(-1) local playerCar = GetVehiclePedIsIn(playerPed, false) local veh = GetVehiclePedIsIn(playerPed) local SpeedKM = GetEntitySpeed(playerPed)*3.6 local maxSpeed = 60.0 -- THIS IS THE MAX SPEED IN KM/H if SpeedKM > maxSpeed then if IsPedInAnyVehicle(playerPed, false) then if (GetPedInVehicleSeat(playerCar, -1) == playerPed) then if hasBeenCaught == false then if GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE2" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE3" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE4" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICEB" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICET" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "SHERIFF" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "FIRETRUK" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "AMBULAN" then -- BLACKLISTED VEHICLE -- VEHICLES ABOVE ARE BLACKLISTED else -- ALERT POLICE (START) if alertPolice == true then if SpeedKM > alertSpeed then local x,y,z = table.unpack(GetEntityCoords(GetPlayerPed(-1), false)) TriggerServerEvent('esx_phone:send', 'police', ' Someone passed the speed camera, above ' .. alertSpeed.. ' KMH', true, {x =x, y =y, z =z}) end end -- ALERT POLICE (END) -- FLASHING EFFECT (START) if useFlashingScreen == true then TriggerServerEvent('esx_speedcamera:openGUI') end if useCameraSound == true then TriggerServerEvent("InteractSound_SV:PlayOnSource", "speedcamera", 0.5) end if useFlashingScreen == true then Citizen.Wait(200) TriggerServerEvent('esx_speedcamera:closeGUI') end -- FLASHING EFFECT (END) TriggerEvent("pNotify:SendNotification", {text = "You've been caught by the speedcamera in a 60 zone! Your speed: " .. math.floor(SpeedKM) .. " KM/H", type = "error", timeout = 5000, layout = "centerLeft"}) if useBilling == true then if SpeedKM >= maxSpeed + 30 then finalBillingPrice = defaultPrice60 + extraZonePrice30 elseif SpeedKM >= maxSpeed + 20 then finalBillingPrice = defaultPrice60 + extraZonePrice20 elseif SpeedKM >= maxSpeed + 10 then finalBillingPrice = defaultPrice60 + extraZonePrice10 else finalBillingPrice = defaultPrice60 end TriggerServerEvent('esx_billing:sendBill', GetPlayerServerId(PlayerId()), 'society_police', 'Speedcamera (60KM/H) - Your speed: ' .. math.floor(SpeedKM) .. ' KM/H - ', finalBillingPrice) -- Sends a bill from the police else TriggerServerEvent('esx_speedcamera:PayBill60Zone') end hasBeenCaught = true Citizen.Wait(5000) -- This is here to make sure the player won't get fined over and over again by the same camera! end end end end hasBeenCaught = false end end end -- 80 zone for k in pairs(Speedcamera80Zone) do local plyCoords = GetEntityCoords(GetPlayerPed(-1), false) local dist = Vdist(plyCoords.x, plyCoords.y, plyCoords.z, Speedcamera80Zone[k].x, Speedcamera80Zone[k].y, Speedcamera80Zone[k].z) if dist <= 20.0 then local playerPed = GetPlayerPed(-1) local playerCar = GetVehiclePedIsIn(playerPed, false) local veh = GetVehiclePedIsIn(playerPed) local SpeedKM = GetEntitySpeed(playerPed)*3.6 local maxSpeed = 80.0 -- THIS IS THE MAX SPEED IN KM/H if SpeedKM > maxSpeed then if IsPedInAnyVehicle(playerPed, false) then if (GetPedInVehicleSeat(playerCar, -1) == playerPed) then if hasBeenCaught == false then if GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE2" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE3" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE4" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICEB" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICET" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "FIRETRUK" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "AMBULAN" then -- BLACKLISTED VEHICLE -- VEHICLES ABOVE ARE BLACKLISTED else -- ALERT POLICE (START) if alertPolice == true then if SpeedKM > alertSpeed then local x,y,z = table.unpack(GetEntityCoords(GetPlayerPed(-1), false)) TriggerServerEvent('esx_phone:send', 'police', ' Someone passed the speed camera, above ' .. alertSpeed.. ' KMH', true, {x =x, y =y, z =z}) end end -- ALERT POLICE (END) -- FLASHING EFFECT (START) if useFlashingScreen == true then TriggerServerEvent('esx_speedcamera:openGUI') end if useCameraSound == true then TriggerServerEvent("InteractSound_SV:PlayOnSource", "speedcamera", 0.5) end if useFlashingScreen == true then Citizen.Wait(200) TriggerServerEvent('esx_speedcamera:closeGUI') end -- FLASHING EFFECT (END) TriggerEvent("pNotify:SendNotification", {text = "You've been caught by the speedcamera in a 80 zone! Your speed: " .. math.floor(SpeedKM) .. " KM/H", type = "error", timeout = 5000, layout = "centerLeft"}) if useBilling == true then if SpeedKM >= maxSpeed + 30 then finalBillingPrice = defaultPrice80 + extraZonePrice30 elseif SpeedKM >= maxSpeed + 20 then finalBillingPrice = defaultPrice80 + extraZonePrice20 elseif SpeedKM >= maxSpeed + 10 then finalBillingPrice = defaultPrice80 + extraZonePrice10 else finalBillingPrice = defaultPrice80 end TriggerServerEvent('esx_billing:sendBill', GetPlayerServerId(PlayerId()), 'society_police', 'Speedcamera (80KM/H) - Your speed: ' .. math.floor(SpeedKM) .. ' KM/H - ', finalBillingPrice) -- Sends a bill from the police else TriggerServerEvent('esx_speedcamera:PayBill80Zone') end hasBeenCaught = true Citizen.Wait(5000) -- This is here to make sure the player won't get fined over and over again by the same camera! end end end end hasBeenCaught = false end end end -- 120 zone for k in pairs(Speedcamera120Zone) do local plyCoords = GetEntityCoords(GetPlayerPed(-1), false) local dist = Vdist(plyCoords.x, plyCoords.y, plyCoords.z, Speedcamera120Zone[k].x, Speedcamera120Zone[k].y, Speedcamera120Zone[k].z) if dist <= 20.0 then local playerPed = GetPlayerPed(-1) local playerCar = GetVehiclePedIsIn(playerPed, false) local veh = GetVehiclePedIsIn(playerPed) local SpeedKM = GetEntitySpeed(playerPed)*3.6 local maxSpeed = 120.0 -- THIS IS THE MAX SPEED IN KM/H if SpeedKM > maxSpeed then if IsPedInAnyVehicle(playerPed, false) then if (GetPedInVehicleSeat(playerCar, -1) == playerPed) then if hasBeenCaught == false then if GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE2" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE3" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICE4" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICEB" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "POLICET" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "FIRETRUK" then -- BLACKLISTED VEHICLE elseif GetDisplayNameFromVehicleModel(GetEntityModel(veh)) == "AMBULAN" then -- BLACKLISTED VEHICLE -- VEHICLES ABOVE ARE BLACKLISTED else -- ALERT POLICE (START) if alertPolice == true then if SpeedKM > alertSpeed then local x,y,z = table.unpack(GetEntityCoords(GetPlayerPed(-1), false)) TriggerServerEvent('esx_phone:send', 'police', ' Someone passed the speed camera, above ' .. alertSpeed.. ' KMH', true, {x =x, y =y, z =z}) end end -- ALERT POLICE (END) -- FLASHING EFFECT (START) if useFlashingScreen == true then TriggerServerEvent('esx_speedcamera:openGUI') end if useCameraSound == true then TriggerServerEvent("InteractSound_SV:PlayOnSource", "speedcamera", 0.5) end if useFlashingScreen == true then Citizen.Wait(200) TriggerServerEvent('esx_speedcamera:closeGUI') end -- FLASHING EFFECT (END) TriggerEvent("pNotify:SendNotification", {text = "You've been caught by the speedcamera in a 120 zone! Your speed: " .. math.floor(SpeedKM) .. " KM/H", type = "error", timeout = 5000, layout = "centerLeft"}) if useBilling == true then if SpeedKM >= maxSpeed + 30 then finalBillingPrice = defaultPrice120 + extraZonePrice30 elseif SpeedKM >= maxSpeed + 20 then finalBillingPrice = defaultPrice120 + extraZonePrice20 elseif SpeedKM >= maxSpeed + 10 then finalBillingPrice = defaultPrice120 + extraZonePrice10 else finalBillingPrice = defaultPrice120 end TriggerServerEvent('esx_billing:sendBill', GetPlayerServerId(PlayerId()), 'society_police', 'Speedcamera (120KM/H) - Your speed: ' .. math.floor(SpeedKM) .. ' KM/H - ', finalBillingPrice) -- Sends a bill from the police else TriggerServerEvent('esx_speedcamera:PayBill120Zone') end hasBeenCaught = true Citizen.Wait(5000) -- This is here to make sure the player won't get fined over and over again by the same camera! end end end end hasBeenCaught = false end end end end end) RegisterNetEvent('esx_speedcamera:openGUI') AddEventHandler('esx_speedcamera:openGUI', function() SetNuiFocus(false,false) SendNUIMessage({type = 'openSpeedcamera'}) end) RegisterNetEvent('esx_speedcamera:closeGUI') AddEventHandler('esx_speedcamera:closeGUI', function() SendNUIMessage({type = 'closeSpeedcamera'}) end)
TransportRouteInteractionHandler = {} function TransportRouteInteractionHandler:NewRoute() return {from = false, to = false, obj_at_source = false} end function TransportRouteInteractionHandler:UpdateCursorText(dialog) local res_dlg = GetDialog("ResourceItems") local choosing_res = res_dlg and res_dlg.context and IsKindOf(res_dlg.context.object, "RCTransport") if not choosing_res then if not (dialog.created_route and dialog.created_route.from) then return T(7974, "Load Resource") else return T(7975, "Unload Resource") end end end function TransportRouteInteractionHandler:UpdateTooltip(dialog) end function TransportRouteInteractionHandler:UpdateRouteVisuals(dialog) if dialog.created_route and dialog.created_route.from and not dialog.created_route.to then if not dialog.route_visuals then dialog.route_visuals = { PlaceObjectIn("WireFramedPrettification", ActiveMapID, {entity = "RoverTransport", construction_stage = 0, GetSelectionRadiusScale = RCTransport_AutoRouteRadius}) } dialog.route_visuals[1]:SetAngle(0) ShowHexRanges(UICity, false, dialog.route_visuals[1]) if IsValid(dialog.cursor_obj) then DoneObject(dialog.cursor_obj) dialog.cursor_obj = false end end dialog.route_visuals[1]:SetPos(dialog.created_route.from) --dialog.route_visuals:SetAngle(CalcOrientation(dialog.created_route.from, dialog.last_mouse_pos or point20)) elseif not dialog.created_route or dialog.created_route and not dialog.created_route.from and not dialog.created_route.to then if dialog.route_visuals then DoneObjects(dialog.route_visuals) dialog.route_visuals = false end end end function TransportRouteInteractionHandler:CreateRoute(dialog, terrain_pt) if not dialog.created_route.from then if dialog.interaction_obj ~= dialog.created_route.obj_at_source then dialog.created_route.obj_at_source = dialog.interaction_obj end CityUnitController[UICity]:InteractWithObject(dialog.interaction_obj, dialog.interaction_mode) self:SetRoutePoint(dialog, "from", terrain_pt or GetTerrainCursor()) else self:SetRoutePoint(dialog, "to", terrain_pt or GetTerrainCursor()) end dialog:UpdateCursorText() end function TransportRouteInteractionHandler:OnRouteCreated(dialog) if dialog.created_route and dialog.created_route.from and dialog.created_route.to then CityUnitController[UICity]:SetTransportRoute(dialog.created_route) dialog.created_route = false SetUnitControlInteractionMode(dialog.unit, false) DoneObjects(dialog.route_visuals) dialog.route_visuals = false SetupRouteVisualsForTransport(dialog.unit) if self:IsThreadRunning("GamepadCursorUpdate") then self:DeleteThread("GamepadCursorUpdate") end if GetUIStyleGamepad() then self:UpdateCursorObj() end end end function TransportRouteInteractionHandler:SetRoutePoint(dialog, type, pt) assert(dialog.created_route) if not dialog.created_route then return end dialog.created_route[type] = pt:SetTerrainZ(1*guim) if dialog.created_route.from and dialog.created_route.to then if dialog.created_route and dialog.created_route.from and dialog.created_route.to then CityUnitController[UICity]:SetTransportRoute(dialog.created_route) dialog.created_route = false SetUnitControlInteractionMode(dialog.unit, false) DoneObjects(dialog.route_visuals) dialog.route_visuals = false SetupRouteVisualsForTransport(dialog.unit) if dialog:IsThreadRunning("GamepadCursorUpdate") then dialog:DeleteThread("GamepadCursorUpdate") end if GetUIStyleGamepad() then dialog:UpdateCursorObj() end end else self:UpdateRouteVisuals(dialog) end end function TransportRouteInteractionHandler:UpdateCursorObj(dialog, pos) --cursor obj management if not dialog.created_route.from and not dialog.cursor_obj then HideGamepadCursor("construction") dialog.cursor_obj = PlaceObjectIn("WireFramedPrettification", ActiveMapID, {entity = "RoverTransport", construction_stage = 0, GetSelectionRadiusScale = RCTransport_AutoRouteRadius}) dialog.cursor_obj:SetAngle(0) local rad = PlaceObjectIn("RangeHexMovableRadius", ActiveMapID) dialog.cursor_obj:Attach(rad) rad:SetScale(RCTransport_AutoRouteRadius) elseif not dialog.created_route.from and dialog.cursor_obj.construction_stage == 1 then dialog.cursor_obj.construction_stage = 0 dialog.cursor_obj:UpdateConstructionShaderParams() elseif dialog.created_route.from and not dialog.cursor_obj then HideGamepadCursor("construction") dialog.cursor_obj = PlaceObjectIn("WireFramedPrettification", ActiveMapID, {entity = "RoverTransport", construction_stage = 1, GetSelectionRadiusScale = RCTransport_AutoRouteRadius}) dialog.cursor_obj:SetAngle(0) local rad = PlaceObjectIn("RangeHexMovableRadius", ActiveMapID) dialog.cursor_obj:Attach(rad) rad:SetScale(RCTransport_AutoRouteRadius) elseif dialog.created_route.from and dialog.cursor_obj.construction_stage == 0 then dialog.cursor_obj.construction_stage = 1 dialog.cursor_obj:UpdateConstructionShaderParams() end dialog.cursor_obj:SetPos(pos:SetTerrainZ(1*guim)) end
--[[ Copyright 2016-2020 The Node.lua Authors. All Rights Reserved. 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 core = require('core') local utils = require('util') local exports = {} ------------------------------------------------------------------------------- -- Methods -- 常见的 RTSP 方法 exports.METHODS = { 'ANNOUNCE', 'DESCRIBE', 'GET_PARAMETER', 'OPTIONS', 'PAUSE', 'PLAY', 'RECORD', 'REDIRECT', 'SET_PARAMETER', 'SETUP', 'TEARDOWN' } ------------------------------------------------------------------------------- -- Status Codes -- 常见的 RTSP 状态码 local STATUS_CODES = { [100] = 'Continue', [101] = 'Switching Protocols', [102] = 'Processing', [200] = 'OK', [201] = 'Created', -- RECORD [250] = 'Low on Storage Space', -- RECORD -- RFC 4918 [300] = 'Multiple Choices', [301] = 'Moved Permanently', [302] = 'Moved Temporarily', [303] = 'See Other', [304] = 'Not Modified', [400] = 'Bad Request', [401] = 'Unauthorized', [402] = 'Payment Required', [403] = 'Forbidden', [404] = 'Not Found', [405] = 'Method Not Allowed', [406] = 'Not Acceptable', [407] = 'Proxy Authentication Required', [408] = 'Request Time-out', [409] = 'Conflict', [410] = 'Gone', [411] = 'Length Required', [412] = 'Precondition Failed', -- DESCRIBE, SETUP [413] = 'Request Entity Too Large', [414] = 'Request-URI Too Large', [415] = 'Unsupported Media Type', [451] = 'Invalid parameter', -- SETUP [452] = 'Illegal Conference Identifier', -- SETUP [453] = 'Not Enough Bandwidth', -- SETUP [454] = 'Session Not Found', [455] = 'Method Not Valid In This State', [456] = 'Header Field Not Valid', [457] = 'Invalid Range', -- PLAY [458] = 'Parameter Is Read-Only', -- SET_PARAMETER [459] = 'Aggregate Operation Not Allowed', [460] = 'Only Aggregate Operation Allowed', [461] = 'Unsupported Transport', [462] = 'Destination Unreachable', [500] = 'Internal Server Error', [501] = 'Not Implemented', [502] = 'Bad Gateway', [503] = 'Service Unavailable', [504] = 'Gateway Time-out', [505] = 'RTSP Version not supported', [551] = 'Option not support' } exports.STATUS_CODES = STATUS_CODES exports.realm = "rtspd" exports.nonce = "66bb9f0bf5ac93a909ac8e88877ae727" ------------------------------------------------------------------------------- local function _hash(token1, token2, token3) local sb = StringBuffer:new() sb:append(token1) if (token2) then sb:append(':') sb:append(token2) end if (token3) then sb:append(':') sb:append(token3) end return utils.md5string(sb:toString()):lower() end local function _parseQString(value) if (type(value) ~= 'string') then return "" end if (value:byte(1) ~= 34) then return value end local s, n = value:find('"', 2) if (s) then value = value:sub(2, s - 1) end return value or "" end ------------------------------------------------------------------------------- -- RtspHeaderMeta -- Provide a nice case insensitive interface to headers. local RtspHeaderMeta = { __index = function(list, name) if type(name) ~= "string" then return rawget(list, name) end name = name:lower() for i = 1, #list do local key, value = table.unpack(list[i]) if key:lower() == name then return value end end end, __newindex = function(list, name, value) -- non-string keys go through as-is. if (not name) then return elseif type(name) ~= "string" then return rawset(list, name, value) end -- First remove any existing pairs with matching key local lowerName = name:lower() for i = #list, 1, -1 do if list[i][1]:lower() == lowerName then table.remove(list, i) end end -- If value is nil, we're done if value == nil then return end -- Otherwise, set the key(s) if (type(value) == "table") then -- We accept a table of strings for i = 1, #value do rawset(list, #list + 1, { name, tostring(value[i]) }) end else -- Or a single value interperted as string rawset(list, #list + 1, { name, tostring(value) }) end end, } exports.RtspHeaderMeta = RtspHeaderMeta ------------------------------------------------------------------------------- -- RtspMessage ---@class RtspMessage local RtspMessage = core.Object:extend() exports.RtspMessage = RtspMessage function RtspMessage:initialize() local headers = setmetatable({}, RtspHeaderMeta) self.headers = headers self.method = nil self.path = nil self.scheme = "RTSP" self.statusCode = nil self.statusMessage = nil self.version = 1.0 end function RtspMessage:checkAuthorization(request, callback) local value = request:getHeader('Authorization') if (value) then local params = exports.parseAuthenticate(value) local username = params.username local password = callback(username) local ha1 = _hash(username, params.realm, password) local ha2 = _hash(request.method, request.uriString) local response = _hash(ha1, params.nonce, ha2) if (response == params.response) then self:removeHeader('WWW-Authenticate') self:setStatusCode(200) return true end end local sb = StringBuffer:new() sb:append('Digest'):append(' ') sb:append('realm="'):append(exports.realm or ''):append('", ') sb:append('nonce="'):append(exports.nonce or ''):append('", ') sb:append('stale='):append('"FALSE"') self:setHeader('WWW-Authenticate', sb:toString()) self:setStatusCode(401) return false end function RtspMessage:getHeader(name) return self.headers[name] end function RtspMessage:removeHeader(name) self.headers[name] = nil end function RtspMessage:setAuthorization(params, username, password) local sb = StringBuffer:new() if (params.METHOD == 'Basic') then sb:append(params.METHOD):append(' ') local ha = username .. ':' .. password; local response = utils.base64Encode(ha); sb:append(response) else local uriString = self.uriString or self.path or '' sb:append(params.METHOD):append(' ') sb:append('username="'):append(username or ''):append('", ') sb:append('realm="'):append(params.realm or ''):append('", ') sb:append('nonce="'):append(params.nonce or ''):append('", ') sb:append('uri="'):append(uriString or ''):append('", ') local ha1 = _hash(username, params.realm, password) local ha2 = _hash(self.method, uriString) local ha3 = _hash(ha1, params.nonce, ha2) sb:append('response="'):append(ha3 or ''):append('"') end self:setHeader('Authorization', sb:toString()) end function RtspMessage:setHeader(name, value) self.headers[name] = value end function RtspMessage:setStatusCode(statusCode, statusMessage) self.statusCode = statusCode or 200 self.statusMessage = statusMessage or STATUS_CODES[self.statusCode] or 'OK' end ------------------------------------------------------------------------------- -- exports function exports.newDateHeader(time) return os.date("%a, %d %b %Y %H:%M:%S GMT", time or os.time()) end function exports.newRequest(method, path) local request = RtspMessage:new() request.method = method or 'OPTIONS' request.path = path or '/' request.version = 1.0 request.uriString = request.path return request end function exports.newResponse(statusCode, statusMessage) local response = RtspMessage:new() response.statusCode = statusCode or 200 response.statusMessage = statusMessage or STATUS_CODES[statusCode] or 'OK' response.version = 1.0 return response end ---@param value string function exports.parseAuthenticate(value) local pos, _ = value:find(' ') --print('value', s, n) if (not pos) then return nil end local method = value:sub(1, pos - 1) value = value:sub(pos + 1) local params = {} --print('value', method, value) local tokens = value:split(",") for _, v in pairs(tokens) do local start, _ = v:find('=') if (start) then local key = v:sub(1, start - 1):trim() local data = _parseQString(v:sub(start + 1):trim()) params[key] = data end end params.METHOD = method return params end return exports
--Senya bt local m=37564331 local cm=_G["c"..m] if not pcall(function() require("expansions/script/c37564765") end) then require("script/c37564765") end function cm.initial_effect(c) c:EnableReviveLimit() aux.AddFusionProcCode2(c,37564813,37564043,true,true) local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(m,0)) e2:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetCode(EVENT_CHAINING) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCondition(cm.discon) e2:SetTarget(cm.distg) e2:SetOperation(cm.disop) c:RegisterEffect(e2) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(m) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_MZONE) c:RegisterEffect(e2) end function cm.discon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsStatus(STATUS_BATTLE_DESTROYED) then return false end return Duel.IsChainNegatable(ev) end function cm.distg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0) if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0) end end function cm.disop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not Duel.NegateActivation(ev) then return end if re:GetHandler():IsRelateToEffect(re) then Duel.Destroy(eg,REASON_EFFECT) end local e1=Effect.CreateEffect(c) e1:SetDescription(re:GetDescription()) e1:SetCategory(re:GetCategory()) local t=re:GetType() local cd=re:GetCode() if bit.band(t,EFFECT_TYPE_ACTIVATE)~=0 then t=bit.bor(t-EFFECT_TYPE_ACTIVATE,EFFECT_TYPE_QUICK_O) end if bit.band(t,EFFECT_TYPE_XMATERIAL)~=0 then t=t-EFFECT_TYPE_XMATERIAL end if bit.band(t,EFFECT_TYPE_QUICK_F)~=0 then t=bit.bor(t-EFFECT_TYPE_QUICK_F,EFFECT_TYPE_QUICK_O) end if bit.band(t,EFFECT_TYPE_TRIGGER_F)~=0 then t=bit.bor(t-EFFECT_TYPE_TRIGGER_F,EFFECT_TYPE_TRIGGER_O) end if bit.band(t,EFFECT_TYPE_IGNITION)~=0 then t=bit.bor(t-EFFECT_TYPE_IGNITION,EFFECT_TYPE_QUICK_O) cd=EVENT_FREE_CHAIN end e1:SetType(t) e1:SetCode(cd) if cd==EVENT_FREE_CHAIN then e1:SetHintTiming(0,0x1e0) end e1:SetRange(LOCATION_MZONE) e1:SetLabel(re:GetLabel()) e1:SetLabelObject(re:GetLabelObject()) e1:SetProperty(bit.bor(re:GetProperty(),EFFECT_FLAG_NO_TURN_RESET)) e1:SetCountLimit(1) e1:SetCondition(function(e) return e:GetHandler():IsHasEffect(m) end) local tg=re:GetTarget() if tg then e1:SetTarget(tg) end local op=re:GetOperation() if op then e1:SetOperation(op) end e1:SetReset(0x1fe1000) c:RegisterEffect(e1,true) end
local PLUGIN = PLUGIN or {}; function PLUGIN:LoadData() for k, v in pairs(nut.util.ReadTable("vendors")) do local position = v.pos local angles = v.angles local data = v.data local factionData = v.factionData local classData = v.classData local vendorAction = v.vendorAction local buyadjustment = v.buyadjustment local money = v.money local name = v.name local desc = v.desc local model = v.model local entity = ents.Create("nut_vendor") entity:SetPos(position) entity:SetAngles(angles) entity:Spawn() entity:Activate() entity:SetNetVar("data", data) entity:SetNetVar("factiondata", factionData) entity:SetNetVar("classdata", classData) entity:SetNetVar("name", name) entity:SetNetVar("desc", desc) entity:SetNetVar("vendoraction", vendorAction) entity:SetNetVar("buyadjustment", buyadjustment) entity:SetNetVar("money", money) entity:SetModel(model) entity:SetAnim() end end function PLUGIN:SaveData() local data = {} for k, v in pairs(ents.FindByClass("nut_vendor")) do data[#data + 1] = { pos = v:GetPos(), angles = v:GetAngles(), data = v:GetNetVar("data", {}), factionData = v:GetNetVar("factiondata", {}), classData = v:GetNetVar("classdata", {}), vendorAction = v:GetNetVar("vendoraction", { sell = true, buy = false} ), buyadjustment = v:GetNetVar("buyadjustment", .5), money = v:GetNetVar("money", 100), name = v:GetNetVar("name", "설정되지 않음"), desc = v:GetNetVar("desc", nut.lang.Get("no_desc")), model = v:GetModel() } end nut.util.WriteTable("vendors", data) end
local color = {} local current = {} current.fg = {} current.bg = {} local target = {} target.fg = {} target.bg = {} local speed = {} speed.fg = {} speed.bg = {} color.setColor = function(fg, bg) current.fg = {unpack(fg)} current.bg = {unpack(bg)} target.fg = {unpack(fg)} target.bg = {unpack(bg)} speed.fg = {0, 0, 0} speed.bg = {0, 0, 0} end color.setTarget = function(fg, bg) target.fg = {unpack(fg)} target.bg = {unpack(bg)} speed.fg = {target.fg[1] - current.fg[1], target.fg[2] - current.fg[2], target.fg[3] - current.fg[3]} speed.bg = {target.bg[1] - current.bg[1], target.bg[2] - current.bg[2], target.bg[3] - current.bg[3]} end color.update = function(dt) for i = 1, 3 do local new_fg = current.fg[i] + speed.fg[i] * dt if new_fg <= target.fg[i] and current.fg[i] >= target.fg[i] or new_fg >= target.fg[i] and current.fg[i] <= target.fg[i] then new_fg = target.fg[i] end current.fg[i] = new_fg local new_bg = current.bg[i] + speed.bg[i] * dt if new_bg <= target.bg[i] and current.bg[i] >= target.bg[i] or new_bg >= target.bg[i] and current.bg[i] <= target.bg[i] then new_bg = target.bg[i] end current.bg[i] = new_bg end love.graphics.setColor(current.fg) love.graphics.setBackgroundColor(current.bg) end color.bg = function() return current.bg end color.fg = function() return current.fg end return color
vim.opt.completeopt = { "menu", "menuone", "noselect" } -- Don't show the dumb matching stuff. -- vim.opt.shortmess:append "c" local lspkind = require "lspkind" lspkind.init() local cmp = require "cmp" cmp.setup { mapping = { ["<C-d>"] = cmp.mapping.scroll_docs(-4), ["<C-f>"] = cmp.mapping.scroll_docs(4), ["<C-e>"] = cmp.mapping.close(), ["<Tab>"] = cmp.mapping.confirm({select = true}), }, sources = { { name = "nvim_lua" }, { name = "nvim_lsp" }, { name = "path" }, { name = "vsnip" }, { name = "buffer", keyword_length = 4 }, }, snippet = { expand = function(args) vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users. -- require('luasnip').lsp_expand(args.body) -- For `luasnip` users. -- vim.fn["UltiSnips#Anon"](args.body) -- For `ultisnips` users. -- require'snippy'.expand_snippet(args.body) -- For `snippy` users. end, }, formatting = { -- Youtube: How to set up nice formatting for your sources. format = lspkind.cmp_format { with_text = true, menu = { buffer = "[buf]", nvim_lsp = "[LSP]", nvim_lua = "[api]", path = "[path]", vsnip = "[snip]", }, }, }, experimental = { native_menu = false, ghost_text = true, }, } -- Setup lspconfig. local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()) -- Replace <YOUR_LSP_SERVER> with each lsp server you've enabled. -- from nvim-lsp-install default dir -- local lsp_dir = function(lsp) vim.fn.stdpath "data" .. "lsp_servers" -- require('lspconfig')['pyright'].setup { capabilities = capabilities } -- require('lspconfig')['sumneko_lua'].setup { capabilities = capabilities, cmd = { '/home/elsimmons/.local/share/nvim/lsp_servers/sumneko_lua/extension/server/bin/Linux/lua-language-server' } } -- require('lspconfig')[''].setup { -- capabilities = capabilities -- }
--[[---------------------------------------------------------------- | ▄▀▄▄▄▄ ▄▀▀▄ ▄▀▄ ▄▀▀█▄▄ ▄▀▀▄ ▄▀▄ | | █ █ ▌ █ █ ▀ █ █ ▄▀ █ █ █ █ | | ▐ █ ▐ █ █ ▐ █ █ ▐ ▀▄▀ | | █ █ █ █ █ ▄▀ █ | | ▄▀▄▄▄▄▀ ▄▀ ▄▀ ▄▀▄▄▄▄▀ █ ▄▀ | | █ ▐ █ █ █ ▐ ▄▀ ▄▀ | | ▐ ▐ ▐ ▐ █ ▐ | | ▐ ▐ ▐ ▐ █ ▐ | |------------------------------------------------------------------| | Credits: | Binds & Info: | | pigeon#1818 | U Open and close output | | hz#4777 | RShift Fill suggestion | | Curvn#2646 | ; Focus on CMDBar | | -------------- | Q Open and close | | | LShift+Bksp Clear CMDbar | | | | | | .cmds List commands | ----------------------------------------------------------------]]-- loadstring(game:HttpGet("https://raw.githubusercontent.com/CMD-X/CMD-X/master/Source",true))()
module("luci.controller.tencentddns",package.seeall) function index() local page = entry({"admin", "tencentcloud"}, firstchild(), "腾讯云设置") page.order = 30 page.dependent = false page.acl_depends = { "luci-app-tencentddns" } entry({"admin", "tencentcloud", "tencentddns"},cbi("tencentddns"),_("TencentDDNS"),2) end
require 'caffe' prototxt_name = '/opt/caffe/models/bvlc_reference_caffenet/deploy.prototxt' binary_name = '/opt/caffe/models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel' net = caffe.Net(prototxt_name, binary_name, 'test') input = torch.randn(10,3,227,227):float() output = net:forward(input) gradInput = net:backward(input, output)
--ULX/ULib hooks if SERVER then local Commands = { NameChange = { --A user changed their name. Enabled = true, Color = '5EFF00', Webhook = {'default'}, Title = 'Name Change', Hook = 'ULibPlayerNameChanged', Hookname = 'LcastLogsULXNameChangeLog' }, ULXCommandCalled = { --A user executed a ULX command. Enabled = true, Color = '5EFF00', Webhook = {'default'}, Title = 'ULX Command', Hook = 'ULibCommandCalled', Hookname = 'LcastLogsULXCommandLog', ArgExceptions = 'ulx teleport;', --Commands here will not be logged at all. They are in "ULX COMMAND;" format. always end with a semicolon. NoArgExceptions = 'ulx noclip;ulx motd;', --Commands here will not be logged if they have no arguments. They are in "ULX COMMAND;" format. always end with a semicolon. }, MetaData = 'ulx' } LcastLogsRegisterCommands(Commands) end
--[[ @author Sebastian "CrosRoad95" Jura <sebajura1234@gmail.com> @copyright 2011-2021 Sebastian Jura <sebajura1234@gmail.com> @license MIT ]]-- createBlip(-2283.61,-146.74,35.32, 27,2,0,0,0,0,0,275) local stanowiskaSwiatla = { stanowiskoDoherty={ mpos={-2277.28, -130.55, 35.32}, -- marker cpos={-2278.2587890625, -132.13179016113, 33.934448242188, 7.9, 16.1, 6.1}, -- cuboid job_id="tuner-sf", -- (id) frakcja która będzie miała dostęp text="Montaż tuningu" }, } for i,v in pairs(stanowiskaSwiatla) do v.cuboid=createColCuboid(unpack(v.cpos)) v.marker=createMarker(v.mpos[1], v.mpos[2], v.mpos[3]-1, "cylinder", 1.5, 0, 0, 255, 100) setElementData(v.marker,"marker:duty",v.job_id) setElementData(v.marker,"marker:cuboid",v.cuboid) t=createElement("text") setElementData(t,"name",v.text) setElementPosition(t,v.mpos[1], v.mpos[2], v.mpos[3]) addEventHandler("onMarkerHit", v.marker, function(el,md) if getElementType(el)~= "player" then return end local cs=getElementData(source, "marker:cuboid") if not cs then return end local job=getElementData(source,"marker:duty") local ljob=getElementData(el,"player:duty") if job ~= ljob then outputChatBox("* Nie jesteś zatrudniony w tym warsztacie.", el, 255, 0, 0) return end local vehicles=getElementsWithinColShape(cs,"vehicle") if #vehicles < 1 then outputChatBox("* Na stanowisku montażu nie ma żadnego pojazdu.", el,255, 0, 0) return end if #vehicles > 1 then outputChatBox("* Na stanowisku montażu jest zbyt dużo pojazdów.", el,255, 0, 0) return end if getElementHealth(vehicles[1]) < 900 then outputChatBox("* Pojazd jest zbyt uszkodzony aby zamontować światła.", el, 255, 0, 0) return end triggerClientEvent(el,"pokazPanelTuningu", el , vehicles[1]) end) end local t=createElement("text") setElementData(t,"name","Pieniądze za tuning lub demontaż system pobiera od mechanika\nJeżeli jakiś cię oszukał zgłoś to do Admina!") setElementPosition(t, -2275.01,-117.85,36.32)
local a = true local b = false local function fun(a, b) if a and b then return "both true" elseif a then return "b false" elseif b then return "a false" else return "both false" end end print(fun(true, true) == "both true") print(fun(true, false) == "b false") print(fun(false, true) == "a false") print(fun(false, false) == "both false")
-------------------------------------------------------------------------------- -- Module declaration -- local mod, CL = BigWigs:NewBoss("Gal'darah", 604, 596) if not mod then return end mod:RegisterEnableMob(29306) mod.engageId = 1981 mod.respawnTime = 30 -------------------------------------------------------------------------------- -- Localization -- local L = mod:GetLocale() if L then L.forms = "Forms" L.forms_desc = "Warn before Gal'darah changes forms." L.form_rhino = "Rhino Form" L.form_troll = "Troll Form" end -------------------------------------------------------------------------------- -- Initialization -- function mod:GetOptions() return { "forms", 59827, -- Impaling Charge 59825, -- Whirling Slash } end function mod:OnBossEnable() self:RegisterUnitEvent("UNIT_SPELLCAST_SUCCEEDED", nil, "boss1") self:Log("SPELL_CAST_SUCCESS", "ImpalingCharge", 59827, 54956) -- Heroic, Normal self:Log("SPELL_AURA_APPLIED", "WhirlingSlash", 59825, 55249) -- Heroic, Normal self:Log("SPELL_AURA_APPLIED_DOSE", "WhirlingSlash", 59825, 55249) -- Heroic, Normal end function mod:OnEngage() self:CDBar("forms", 32.5, L.form_rhino, "ability_hunter_pet_rhino") self:DelayedMessage("forms", 27.5, "yellow", CL.soon:format(L.form_rhino)) end -------------------------------------------------------------------------------- -- Event Handlers -- function mod:UNIT_SPELLCAST_SUCCEEDED(_, _, _, spellId) if spellId == 55297 then -- Rhino Form self:CDBar("forms", 34.1, L.form_troll, "achievement_character_troll_male") self:DelayedMessage("forms", 29, "yellow", CL.soon:format(L.form_troll)) elseif spellId == 55299 then -- Troll Form self:CDBar("forms", 33.6, L.form_rhino, "ability_hunter_pet_rhino") self:DelayedMessage("forms", 28.5, "yellow", CL.soon:format(L.form_rhino)) end end function mod:ImpalingCharge(args) self:TargetMessage(59827, args.destName, "yellow", "Info", nil, nil, true) end do local prev = 0 function mod:WhirlingSlash(args) if self:Me(args.destGUID) then local t = GetTime() if t-prev > 1.5 then prev = t self:Message(59825, "blue", "Alarm", CL.underyou:format(args.spellName)) end end end end
--[[ Main entry point for plugin. ]] require 'strict' local LrDialogs = import( 'LrDialogs' ) local LrApplication = import( 'LrApplication' ) local LrDate = import( 'LrDate' ) JSON=require 'JSON' require 'Dialogs' require 'Post' require 'Process' require 'Logger' local publishServiceProvider = {} publishServiceProvider.small_icon = "Small-icon.png" publishServiceProvider.supportsIncrementalPublish = 'only' -- only publish. No export facility publishServiceProvider.allowFileFormats = { 'JPEG' } -- jpeg only publishServiceProvider.hidePrintResolution = true -- hide print res controls publishServiceProvider.canExportVideo = false -- video is not supported through this plug-in publishServiceProvider.hideSections = { 'exportLocation' } -- hide export location publishServiceProvider.processRenderedPhotos = processRenderedPhotos -- see process.jua publishServiceProvider.startDialog = dialogs.startDialog -- see dialogs.lua publishServiceProvider.sectionsForTopOfDialog = dialogs.sectionsForTopOfDialog publishServiceProvider.exportPresetFields = { { key = "siteURL", default = "" }, { key = "loginName", default = "" }, { key = "loginPassword", default = "" }, } -- menu titles, Albums, Galleries per NG rather then Collections & Sets publishServiceProvider.titleForPublishedCollection = "NextGen Gallery" publishServiceProvider.titleForPublishedCollectionSet = "NextGen Album" publishServiceProvider.titleForPublishedSmartCollection = "Smart NextGen Album" -- collection or collection set rename callback function publishServiceProvider.renamePublishedCollection( publishSettings, info ) local collection = info.publishedCollection local newName = info.name local remoteID = collection:getRemoteId() Log( "Rename: " .. collection:getName() .. " to " .. newName ) if collection:type() == 'LrPublishedCollectionSet' then Log( "Renaming set to: ", newName ) local result = Post( "album/rename", { aid = remoteID, name = newName }, publishSettings ) Log( "rename returns", result ) elseif collection:type() == 'LrPublishedCollection' then Log( "Renaming collection to: ", newName ) local result = Post( "gallery/rename", { gid = remoteID, name = newName }, publishSettings ) Log( "rename returns", result ) end end -- reparent collection or collection set callback function publishServiceProvider.reparentPublishedCollection( publishSettings, info ) local data = {} local collection = info.publishedCollection local thisRemoteId = collection:getRemoteId() if #info.parents ~= 0 then local newRemoteParentId = info.parents[#info.parents].remoteCollectionId local newRemoteParentName = info.parents[#info.parents].name data.newparent = newRemoteParentId Log( "new parent: ", data.newparent ) end local parent = collection:getParent() if parent ~= nil then -- not a root collection data.parent = parent:getRemoteId() Log( "old parent: ", data.parent ) end if collection:type() == 'LrPublishedCollectionSet' then Log( "Reparenting set/album: ", thisRemoteId ) data.aid = thisRemoteId local result = Post( "reparent", data, publishSettings ) elseif collection:type() == 'LrPublishedCollection' then Log( "Reparenting collection/gallery: ", thisRemoteId ) data.gid = thisRemoteId local result = Post( "reparent", data, publishSettings ) end end -- image delete callback. function publishServiceProvider.deletePhotosFromPublishedCollection( publishSettings, arrayOfPhotoIds, deletedCallback ) for i, photoId in ipairs( arrayOfPhotoIds ) do Log( string.format( "Deleting id: %d", photoId )); local result = Post( "image/delete", { pid = photoId }, publishSettings ) -- call the delete callback even if it fails on the Wordpress end -- ToDo: Need to fix it so REST doesn't return an error if the delete fails -- there's still a potential conflict here if the image is out of -- kilter between the server and the local. --if result ~= nil then deletedCallback( photoId ) --end end end -- called when a collection or collection set is deleted function publishServiceProvider.deletePublishedCollection( publishSettings, info ) local collection = info.publishedCollection local remoteID = collection:getRemoteId(); local collectionName = collection:getName() -- ToDo: LR quits the op if there's even one failure. Need to delete all we can !! is this fixed?? if collection:type() == 'LrPublishedCollectionSet' then Log( "Deleting set/album: ", remoteID ) local result = Post( "album/delete", { aid = remoteID, name = collectionName }, publishSettings ) elseif collection:type() == 'LrPublishedCollection' then Log( "Deleting collection/gallery: ", remoteID ) local result = Post( "gallery/delete", { gid = remoteID, name = collectionName }, publishSettings ) end end -- called when collection (gallery) is added or renamed. function publishServiceProvider.updateCollectionSettings( publishSettings, info ) local data = {} -- the data table we'll be sending to WP local collection = info.publishedCollection local remoteID = collection:getRemoteId() -- null if not yet published data.name = collection:getName() -- parenting -- WP needs to add the new album to the parent's list of children. local parentSet = collection:getParent() if parentSet then data.parent = parentSet:getRemoteId() end if remoteID == nil then -- remote gallery doesn't exist yet, create new one Log( "Creating gallery", data.name ) local result = Post( "gallery/create", data, publishSettings ) if result ~= nil then local gid = result.gid local catalog = LrApplication.activeCatalog() catalog:withWriteAccessDo( "setGID", function( context ) collection:setRemoteId( gid ) -- set remote gallery id Log( "Set remote album id: ", gid ) end ) end else Log( "Remote Gallery Exists already. Doing nothing") end end -- called when a publish collection set (album) is added or changed. (renamed) function publishServiceProvider.updateCollectionSetSettings( publishSettings, info ) Log( "update Collection Set Settings, creating new album", info.publishedCollection ) --LrTasks.startAsyncTask( function() local data = {} -- the data table we'll be sending to WP local collection = info.publishedCollection local remoteID = collection:getRemoteId() -- null if not yet published data.name = collection:getName() -- parenting -- WP needs to add the new album to the parent's list of children. local parentSet = collection:getParent() if parentSet then data.parent = parentSet:getRemoteId() end if remoteID == nil then -- remote album doesn't exist yet, create new one local result = Post( "album/create", data, publishSettings ) if result ~= nil then local aid = result.aid -- set the remote id for this collection set local catalog = LrApplication.activeCatalog() catalog:withWriteAccessDo( "setAID", function( context ) collection:setRemoteId( aid ) -- set remote gallery id Log( "Set remote album id: ", aid ) end ) end else -- gallery has been changed in some other way. Rename, possibly? --LrDialogs.showBezel( "Remote Album Exists", 3 ) Log( "Remote Album Exists already. Doing nothing") end --end) -- lrTasks end publishServiceProvider.supportsCustomSortOrder = true -- this must be set for ordering function publishServiceProvider.imposeSortOrderOnPublishedCollection( publishSettings, info, remoteIdSequence ) -- ToDo: LR gives an empty id sequence if count of images is 2 or less. Maybe -- why 2?? if #remoteIdSequence == 0 then Log( "Sort: zero length id sequence. Nothing to sort") return end local result = Post( "gallery/sort", { sequence = remoteIdSequence }, publishSettings ) end return publishServiceProvider
dofile "utils.lua" local luv = require "luv" local argc = select("#", ...)-2 local format = szfmt..string.rep("z", argc) local message = {nil, string.pack(format, argc-1, select(3, ...))} message[1] = string.pack(szfmt, #message[2]) local function readsize(chunk) local size, index = string.unpack(szfmt, chunk) chunk = string.sub(chunk, index) return print, { chunk }, size-#chunk end local flags = { socktype = "stream", family = "inet6", } assert(luv.getaddrinfo(host, port, flags, function (err, addresses) assert(not err, err) local address = assert(addresses[1]) local conn = assert(luv.new_tcp()) assert(conn:connect(address.addr, address.port, function (err) assert(not err, err) assert(conn:write(message, function (err) assert(not err, err) local buffer = {} local missing = szlen local action = readsize assert(conn:read_start(function (err, chunk) assert(not err, err) table.insert(buffer, chunk) missing = missing-#chunk while missing <= 0 do chunk = table.concat(buffer) action, buffer, missing = action(chunk) if action == nil then conn:read_stop() conn:close() break end end end)) end)) end)) end)) luv.run()
--[[ AI核心代码,估值100亿美金 --]] while (true) do local str = io.read() str = string.gsub(str, "吗", '') str = string.gsub(str, "?", '!') str = string.gsub(str, "?", '!') print(string.format('冰冰:%s', str)) end