content
stringlengths
5
1.05M
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetModel( "models/press-plates/press_handle.mdl" ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_NONE ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType(SIMPLE_USE) local phys = self:GetPhysicsObject() end function ENT:Use(call) if not call:isArrested() then call:ChatPrint("This job is only for people who are arrested.") return end self:GetParent():OnHandlePressed(self) end
local state = {} state._NAME = ... local Body = require'Body' local t_entry, t_update, t_exit local timeout = 10.0 require'hcm' require'wcm' local movement_stage=0 local t_next local timeout_min=2 local timeout_max=9 local table_dist_max = 0.7 local table_depth_max = 0.25 head_move={ {{0,0,1},3,4.5}, {{0,-15,1},3,6.5}, } function state.entry() print(state._NAME..' Entry' ) local t_entry_prev = t_entry t_entry = Body.get_time() t_update = t_entry movement_stage=1 wcm.set_object_reset(1) wcm.set_object_detection_enable(0) hcm.set_head_target(head_move[movement_stage][1]) hcm.set_head_execute(1) t_observe=t_entry+head_move[movement_stage][2]+Config.t_movement_delay t_next=t_entry+head_move[movement_stage][3]+Config.t_movement_delay end function update_shelf_objects() local obj_num=wcm.get_object_num() local obj_posex=wcm.get_object_posex() local obj_posey=wcm.get_object_posey() local obj_posez=wcm.get_object_posez() local obj_type=wcm.get_object_type() local shelf_pose=wcm.get_shelf_pose() local shelf_obj_num=0 local obj_levels=wcm.get_shelfobject_level() local shelf_obj_dy=wcm.get_shelfobject_dy() local shelf_obj_dx=wcm.get_shelfobject_dx() local shelf_obj_type=wcm.get_shelfobject_type() local shelf_obj_posex=wcm.get_shelfobject_posex() local shelf_obj_posey=wcm.get_shelfobject_posey() local shelf_obj_posez=wcm.get_shelfobject_posez() for i=1,obj_num do local level=-1 if obj_posez[i]>Config.shelf_heights[3]+0.30 then elseif obj_posez[i]>Config.shelf_heights[3] then level=3 elseif obj_posez[i]>Config.shelf_heights[2] then level=2 elseif obj_posez[i]>Config.shelf_heights[1] then level=1 end print(string.format("Shelf object %d: (%.2f %.2f %.2f)", i,obj_posex[i],i,obj_posey[i],i,obj_posez[i] )) if level>0 then local rel_obj=util.pose_relative({obj_posex[i],obj_posey[i],0},shelf_pose) if math.abs(rel_obj[2]) <Config.shelfitem_maxy and math.abs(rel_obj[1]) <Config.shelfitem_maxx then shelf_obj_num=shelf_obj_num+1 obj_levels[shelf_obj_num]=level shelf_obj_dx[shelf_obj_num]=rel_obj[1] shelf_obj_dy[shelf_obj_num]=rel_obj[2] shelf_obj_type[shelf_obj_num]=obj_type[i] shelf_obj_posex[shelf_obj_num]=obj_posex[i] shelf_obj_posey[shelf_obj_num]=obj_posey[i] shelf_obj_posez[shelf_obj_num]=obj_posez[i] print(string.format("Object %d: %s height %.2f level %d relpos (%.2f, %.2f)\n", shelf_obj_num, Config.object_name_list[obj_type[i]][1], obj_posez[i], level, rel_obj[1], rel_obj[2] )) end end end print("Total shelf objects:",shelf_obj_num) wcm.set_shelfobject_num(shelf_obj_num) wcm.set_shelfobject_level(obj_levels) wcm.set_shelfobject_dx(shelf_obj_dx) wcm.set_shelfobject_dy(shelf_obj_dy) wcm.set_shelfobject_posex(shelf_obj_posex) wcm.set_shelfobject_posey(shelf_obj_posey) wcm.set_shelfobject_posez(shelf_obj_posez) wcm.set_shelfobject_type(shelf_obj_type) wcm.set_shelfobject_scanned(1) end function state.update() local t = Body.get_time() local dt = t - t_update if t>t_observe then if t<t_next then wcm.set_object_detection_enable(1) else wcm.set_object_detection_enable(0) movement_stage=movement_stage+1 print("NEXT") if movement_stage>#head_move then update_shelf_objects() return 'done' else hcm.set_head_target(head_move[movement_stage][1]) hcm.set_head_execute(1) t_observe=t+head_move[movement_stage][2] t_next=t+head_move[movement_stage][3] end end end end function state.exit() print(state._NAME..' Exit' ) -- wcm.set_object_detection_enable(0) end return state
local ActiveRecord = require 'charon.ActiveRecord' local test = {} test.should_error_if_file_not_exists = function() ActiveRecord.reset() ActiveRecord.config = "config/file_not_exists.json" local status, message = pcall(ActiveRecord.loadConfig) assert( status == false ) assert( message:contains('file config/file_not_exists.json not exists') == true, message ) end test.should_error_if_file_not_contain_json_table = function() ActiveRecord.config = "util/config/active-record-not-valid.json" local status, message = pcall(ActiveRecord.loadConfig) assert( status == false ) assert( message:contains('util/config/active-record-not-valid.json invalid') == true, message ) end test.should_return_test_environment = function() ActiveRecord.config = "util/config/active-record-valid.json" local config = ActiveRecord.loadConfig() assert(config.database == ':memory:', config.database ) end return test
return { pfsoundsample = { -- not sure if this should be in the fmodtypes unit type = 'pfsoundsample', fields = { } }, fsound_free = { -- not sure if this should be in the fmodtypes unit type = 'integer' }, fsound_all = { -- not sure if this should be in the fmodtypes unit type = 'integer' } }
---@class CS.FairyEditor.FButton : CS.FairyEditor.ComExtention ---@field public changeStageOnClick boolean ---@field public COMMON string ---@field public CHECK string ---@field public RADIO string ---@field public UP string ---@field public DOWN string ---@field public OVER string ---@field public SELECTED_OVER string ---@field public DISABLED string ---@field public SELECTED_DISABLED string ---@field public icon string ---@field public selectedIcon string ---@field public title string ---@field public text string ---@field public selectedTitle string ---@field public titleColor CS.UnityEngine.Color ---@field public titleColorSet boolean ---@field public titleFontSize number ---@field public titleFontSizeSet boolean ---@field public sound string ---@field public volume number ---@field public soundSet boolean ---@field public soundVolumeSet boolean ---@field public downEffect string ---@field public downEffectValue number ---@field public selected boolean ---@field public mode string ---@field public controller string ---@field public controllerObj CS.FairyEditor.FController ---@field public page string ---@type CS.FairyEditor.FButton CS.FairyEditor.FButton = { } ---@return CS.FairyEditor.FButton function CS.FairyEditor.FButton.New() end ---@return CS.FairyEditor.FTextField function CS.FairyEditor.FButton:GetTextField() end ---@return boolean function CS.FairyEditor.FButton:HandleGrayChanged() end ---@param c CS.FairyEditor.FController function CS.FairyEditor.FButton:HandleControllerChanged(c) end function CS.FairyEditor.FButton:Create() end function CS.FairyEditor.FButton:Dispose() end ---@return CS.System.Object ---@param index number function CS.FairyEditor.FButton:GetProp(index) end ---@param index number ---@param value CS.System.Object function CS.FairyEditor.FButton:SetProp(index, value) end ---@param xml CS.FairyGUI.Utils.XML function CS.FairyEditor.FButton:Read_editMode(xml) end ---@return CS.FairyGUI.Utils.XML function CS.FairyEditor.FButton:Write_editMode() end ---@param xml CS.FairyGUI.Utils.XML ---@param strings CS.System.Collections.Generic.Dictionary_CS.System.String_CS.System.String function CS.FairyEditor.FButton:Read(xml, strings) end ---@return CS.FairyGUI.Utils.XML function CS.FairyEditor.FButton:Write() end return CS.FairyEditor.FButton
Inherit = 'ScrollView' UpdateDrawBlacklist = {['NeedsItemUpdate']=true} TextColour = colours.black BackgroundColour = colours.white HeadingColour = colours.lightGrey SelectionBackgroundColour = colours.blue SelectionTextColour = colours.white Items = false CanSelect = false Selected = nil NeedsItemUpdate = false ItemMargin = 1 HeadingMargin = 0 TopMargin = 0 OnDraw = function(self, x, y) if self.NeedsItemUpdate then self:UpdateItems() end Drawing.DrawBlankArea(x, y, self.Width, self.Height, self.BackgroundColour) end local function AddItem(self, v, x, y, group) local toggle = false if not self.CanSelect then toggle = nil elseif v.Selected then toggle = true end local item = { ["Width"]=self.Width, ["X"]=x, ["Y"]=y, ["Name"]="ListViewItem", ["Type"]="Button", ["TextColour"]=self.TextColour, ["BackgroundColour"]=0, ["ActiveTextColour"]=self.SelectionTextColour, ["ActiveBackgroundColour"]=self.SelectionBackgroundColour, ["Align"]='Left', ["Toggle"]=toggle, ["Group"]=group, OnClick = function(itm) if self.CanSelect then self:SelectItem(itm) elseif self.OnSelect then self:OnSelect(itm.Text) end end } if type(v) == 'table' then for k, _v in pairs(v) do item[k] = _v end else item.Text = v end local itm = self:AddObject(item) if v.Selected then self:SelectItem(itm) end end UpdateItems = function(self) if not self.Items or type(self.Items) ~= 'table' then self.Items = {} end self.Selected = nil self:RemoveAllObjects() local groupMode = false for k, v in pairs(self.Items) do if type(k) == 'string' then groupMode = true break end end if not groupMode then for i, v in ipairs(self.Items) do AddItem(self, v, self.ItemMargin, i) end else local y = self.TopMargin for k, v in pairs(self.Items) do y = y + 1 AddItem(self, {Text = k, TextColour = self.HeadingColour, IgnoreClick = true}, self.HeadingMargin, y) for i, _v in ipairs(v) do y = y + 1 AddItem(self, _v, 1, y, k) end y = y + 1 end end self:UpdateScroll() self.NeedsItemUpdate = false end OnKeyChar = function(self, event, keychar) if keychar == keys.up or keychar == keys.down then local n = self:GetIndex(self.Selected) if keychar == keys.up then n = n - 1 else n = n + 1 end local new = self:GetNth(n) if new then self:SelectItem(new) end elseif keychar == keys.enter and self.Selected then self.Selected:Click('mouse_click', 1, 1, 1) end end --returns the index/'n' of the given item GetIndex = function(self, obj) local n = 1 for i, v in ipairs(self.Children) do if not v.IgnoreClick then if obj == v then return n end n = n + 1 end end end --gets the 'nth' list item (does not include headings) GetNth = function(self, n) local _n = 1 for i, v in ipairs(self.Children) do if not v.IgnoreClick then if n == _n then return v end _n = _n + 1 end end end SelectItem = function(self, item) for i, v in ipairs(self.Children) do v.Toggle = false end self.Selected = item item.Toggle = true if self.OnSelect then self:OnSelect(item.Text) end end OnUpdate = function(self, value) if value == 'Items' then self.NeedsItemUpdate = true end end
Button = File.LoadLua("button/button.lua")() Global = File.LoadLua("global/global.lua")() Fonts = File.LoadLua("global/fonts.lua")() Colors = File.LoadLua("global/colors.lua")() Popup = File.LoadLua("global/popup.lua")() Control = File.LoadLua("global/control.lua")() Context = File.LoadLua("global/context.lua")() context = Context.create_context() introscreenversion = "introscreen alpha v0.05 " Login_state= Screen.GetState("Login state") ------------------------------------------------------- --[[ SUPER IMPORTANT OBJECT --- Loginstate_container will hold the data associated with the current login stage from it you can get data that is only available when you are in that state. The "Logged out" state currently has two values: An event sink to start the login process and whether or not there was an error (set to "Yes" if a previous login failed) The "Logging in" state contains data about the current step in the login process and "Logged in" contains the serverlist - used in the missionscreen function. ]] Loginstate_container = Loginstate_container ------------------------------------------------------------------ resolution = Screen.GetResolution() xres = Point.X(resolution) yres = Point.Y(resolution) UIScaleFactor = Number.Min(Number.Clamp(xres/1366,0.6,1.1), Number.Clamp(yres/768,0.6, 1.1)) checktext = Number.ToString(UIScaleFactor*1000) fontheader1 = Fonts.create_scaled("Trebuchet MS", 26*UIScaleFactor, {Bold=true}) fontheader2 = Fonts.create_scaled("Trebuchet MS", 23*UIScaleFactor, {Italic=true, Bold=true}) fontheader4 = Fonts.create_scaled("Trebuchet MS", 19*UIScaleFactor, {Bold=true}) e_errormessage = String.CreateEventSink("") -- declare recurring variables used by multiple functions button_width = UIScaleFactor*200 -- used below and in render_list() button_normal_color = Color.Create(0.9, 0.9, 1, 0.8) button_hover_color = Color.Create(1, 0.9, 0.8, 0.8) button_selected_color = Color.Create(1,1,0.9, 0.95) button_shadow_color = Color.Create(0.4,0.4,0.4,0.7) logo = Image.Group({ Image.Justify( Image.Multiply(Image.File("menuintroscreen/images/menuintroscreen_logo.png"),button_normal_color), Point.Create(278,78), Justify.Topright ), }) -- -- declare recurring variables outside of function mainbtn_bg1 = Image.File("menuintroscreen/images/introBtn_border.png") --btnimage_position = Point.Create(0,0) local e_hovertext = String.CreateEventSink("") function updatehovertext() end function create_mainbutton(event_sink, argimage, arglabel, arghovertext, argfunction) argimageheight = Point.Y(Image.Size(argimage)) scaledpt = Point.Create(UIScaleFactor, UIScaleFactor) function create_stringimages(label) --labelsize = 25*UIScaleFactor return { normal = Image.String(fontheader1, button_normal_color, label), shadow = Image.String(fontheader1, button_shadow_color, label), hover = Image.String(fontheader1, button_hover_color, label), selected = Image.String(fontheader1, button_selected_color, label), } end label = create_stringimages(arglabel) btnsize = Point.Create(button_width, UIScaleFactor*(argimageheight+25+1)) -- 25 is 25px height of h1 font, 1px is for text shadow offset. image_n = Image.Group({ Image.Justify(Image.Scale(Image.Multiply(argimage, button_normal_color),scaledpt),btnsize, Justify.Top), Image.Justify(Image.Group({ Image.Translate(label.shadow, Point.Create(1,1)), label.normal, }), btnsize, Justify.Bottom), }) image_h = Image.Group({ Image.Justify(Image.Scale(Image.Multiply(mainbtn_bg1, button_hover_color),scaledpt),btnsize, Justify.Top), Image.Justify(Image.Scale(Image.Multiply(argimage, button_hover_color),scaledpt),btnsize, Justify.Top), Image.Justify(Image.Group({ Image.Translate(label.shadow, Point.Create(1,1)), label.hover, }), btnsize, Justify.Bottom) }) -- selected doesnt need color multiply. image_s = Image.Group({ Image.Justify(Image.Scale(mainbtn_bg1,scaledpt), btnsize, Justify.Top), Image.Justify(Image.Scale(argimage,scaledpt), btnsize, Justify.Top), Image.Justify(Image.Group({ Image.Translate(label.shadow, Point.Create(1,1)), label.selected, }), btnsize, Justify.Bottom) }) button = Button.create_image_button(image_n, image_h, image_s, arghovertext) --hovertext = hovertext .. button.hovertext --[[ concatenates the hoverstring with the contents of the toplevel one. Since there's only one non-empty string we should wind up with only the text for the button currently hovered over... ]] Event.OnEvent(e_hovertext, button.events.enter, function() return arghovertext end) Event.OnEvent(e_hovertext, button.events.leave, function() return "" end) Event.OnEvent(e_hovertext, button.events.click, function() return "" end) if argfunction then Event.OnEvent(event_sink, button.events.click, argfunction) else Event.OnEvent(event_sink, button.events.click) end return button.image end function render_list(list) translated_list = {} offset = button_width -- this number indicates the spaces between buttons offset_x = #list * offset for i, item in pairs(list) do offset_x = offset_x - offset translated_list[#translated_list+1] = Image.Translate(item, Point.Create(offset_x, 0)) end return Image.Group(translated_list) end ------- INTROSCREEN -------- ---------------------------------------------- function make_introscreen(Loginstate_container) function create_button_list() list = {} list[#list+1] = create_mainbutton(Screen.GetExternalEventSink("open.exit"), Image.File("menuintroscreen/images/introBtnExit.png"), "EXIT", "Exit the game.") list[#list+1] = create_mainbutton(Screen.GetExternalEventSink("open.options"), Image.File("menuintroscreen/images/introBtnSettings.png"), "OPTIONS", "Change your graphics, audio and game settings.") list[#list+1] = create_mainbutton(Screen.GetExternalEventSink("open.training"), Image.File("menuintroscreen/images/introBtnHelp.png"), "TRAINING", "Learn how to play the game.") list[#list+1] = create_mainbutton(Screen.CreateOpenWebsiteSink("https://discord.gg/WcEJ9VH"), Image.File("menuintroscreen/images/introBtnDiscord.png"), "DISCORD", "Join the community Discord server.") list[#list+1] = create_mainbutton(Screen.GetExternalEventSink("open.lan"), Image.File("menuintroscreen/images/introBtnLan.png"), "LAN", "Play on a Local Area Network.") list[#list+1] = create_mainbutton(Loginstate_container:GetEventSink("Login"), Image.File("menuintroscreen/images/introBtnOnline.png"), "PLAY", "Play Allegiance.") return list end function errortextImg() return Image.Switch( Loginstate_container:GetState("Has error"), { ["No"] = function(Loginstate_container) return Image.Empty() end, ["Yes"] = function (Loginstate_container) errMsg = Loginstate_container:GetString("Message") errimg = Image.String(fontheader2, Colors.white, Number.Divide(xres,2), errMsg, Justify.Center) return errimg end, }) end return Image.Group({ Image.Translate(Image.Justify(render_list(create_button_list()), resolution, Justify.Bottom), Point.Create(0,-30)), Image.Justify(logo, resolution,Justify.Center), Image.Translate(Image.Justify(errortextImg(), resolution, Justify.Bottom),Point.Create(0, -175)), -- Image.Translate(Image.Justify(create_hovertextimg(hovertext), resolution, Justify.Bottom),Point.Create(0, -150)), }) end ---------------------- Connecting ---------------- ---------------------------------------------------------------------------------------------------------------------------------- function make_spinner(Loginstate_container) local spinner = File.LoadLua("global/loading_icon.lua")() stepMsg = Loginstate_container:GetString("Step message") stepMsgImg = Image.String(fontheader2, button_normal_color, stepMsg, {Width=Number.Divide(xres,2), Justification=Justify.Center}) return Image.Group({ Image.Justify(spinner, resolution,Justify.Center), --spinner, Image.Translate(Image.Justify(stepMsgImg, resolution, Justify.Bottom),Point.Create(0, -150)), }) end --------------- mission SCREEN -------------------------- ------------------------------------------------------ function make_missionscreen(Loginstate_container) hovertext = "" -- this will hold the eventual text for other functions to use cardwidth = 250 cardheight = 280 scaledcardwidth = cardwidth*UIScaleFactor scaledcardheight =cardheight*UIScaleFactor xmargin = Number.Multiply(xres,0.1)*UIScaleFactor ytopmargin = 100*UIScaleFactor --Number.Round(Number.Multiply(yres,0.10),0) ybottommargin = 180*UIScaleFactor scrollbarwidth = 26 xcardsarea = (xres-scrollbarwidth)-(2*xmargin) -- Number.Subtract(xres,Global.list_sum({xmargin, xmargin})) ycardsarea = yres-(ybottommargin+ytopmargin) -- Number.Subtract(yres,Number.Add(ybottommargin,ytopmargin)) cardsarea = Point.Create(xcardsarea+scrollbarwidth,ycardsarea) cardsinnermargin = 15*UIScaleFactor cardsoutermargin = 10*UIScaleFactor --calculate the number of cards that fit into a horizontal row on the screen -- we're using pre-scaled dimensions since we can't render the whole thing in one size -- and scale down/up as needed, because the number of cards we can show -- varies with the screen ratio. cardsrowlen_fl = xcardsarea/(scaledcardwidth+(2*cardsoutermargin)) -- and round down by subtracting the Modulo. cardsrowlen = cardsrowlen_fl - Number.Mod(cardsrowlen_fl,1) --checktext = Number.ToString(cardsrowlen) cardbackground_n = Global.create_backgroundpane(scaledcardwidth, scaledcardheight, {color=button_normal_color}) cardbackground_h = Global.create_backgroundpane(scaledcardwidth, scaledcardheight, {color=button_hover_color, src=Image.File("/global/images/backgroundpane_highlight.png")}) cardbackground_s = Global.create_backgroundpane(scaledcardwidth, scaledcardheight, {color=button_selected_color}) function write(str,fnt,c) fnt = fnt or Fonts.p color = c or Colors.white textblock = Point.Create(scaledcardwidth-cardsinnermargin, 5) return Image.Group({ Image.Extent(textblock, Colors.transparent), Image.Justify(Image.String(fnt, color, str), textblock, Justify.Top), }) end function pos(img, x,y) return Image.Translate(img, Point.Create(x,y)) end -- create the mission creation dialog function create_mission_screen() -- regularlist = {"alpha", "bravo", "charlie", "delta", "echo"} c_servers = Loginstate_container:GetList("Server list") c_cores = Loginstate_container:GetList("Core list") ChosenServer_eventsink = String.CreateEventSink("") ChosenCore_eventsink = String.CreateEventSink("") mission_name = String.CreateEventSink(Loginstate_container:Get("Callsign") .. "'s game") local create_btn = Button.create_standard_textbutton("CREATE", Fonts.h1, 120, 40) Event.OnEvent(Loginstate_container:Get("Create mission"), create_btn.events.click, function () return ChosenServer_eventsink, ChosenCore_eventsink, mission_name end) -- dimensions serverlistboxwidth = 110 listboxheight = 100 -- Point.Y(Image.Size(serverlistbox)) corelistboxwidth = 110 -- functions to pass as arguments to the listboxmaker function local function entry_to_string (c_item) return c_item:GetString("Name") end function entry_renderer(entry, index, target) entryWidth = 100 listboxWidth = 110 entryHeight = 20 string = entry_to_string(entry) is_selected = String.Equals(string, target) return Image.Switch(is_selected, { [ false ] = Image.Group({ Image.Translate(Image.Extent(Point.Create(listboxWidth, entryHeight), Colors.transparent),Point.Create(-10,0)), Image.String(Fonts.p, Colors.white, string, {Width=entryWidth}), }), [ true ] = Image.Group({ Image.Translate(Image.Extent(Point.Create(listboxWidth, entryHeight), Color.Create(0.6,0.6,0.6,0.6)),Point.Create(-10,0)), Image.String(Fonts.pbold, Colors.white, string, {Width=entryWidth}), }), }) end -- make the listboxes serverlistbox = Image.Group({ Image.Translate(Global.create_box(serverlistboxwidth, listboxheight, {background_color=Colors.dark}), Point.Create(-5,0)), Image.Translate( Global.create_vertical_scrolling_container( Control.string.create_listbox(ChosenServer_eventsink, c_servers,{entry_to_label=entry_to_string,entry_to_value=entry_to_string,entry_renderer= entry_renderer}), Point.Create(serverlistboxwidth, listboxheight), button_normal_color ), Point.Create(5, 2) ), }) corelistbox = Image.Group({ Image.Translate(Global.create_box(corelistboxwidth, listboxheight, {background_color=Colors.dark}), Point.Create(-5,0)), Image.Translate( Global.create_vertical_scrolling_container( Control.string.create_listbox(ChosenCore_eventsink, c_cores, {entry_to_label=entry_to_string,entry_to_value=entry_to_string,entry_renderer= entry_renderer}), Point.Create(corelistboxwidth, listboxheight), button_normal_color ), Point.Create(5, 2) ), }) dialogwidth = 450 dialogheight = 400 return Image.Group({ Image.Extent(Point.Create(dialogwidth,dialogheight), Colors.transparent), --Global.create_box(450,400), Image.Justify( Image.StackVertical({ Image.Justify(Image.String(fontheader1, Colors.white, "CREATE MISSION"), Point.Create(dialogwidth, 20),Justify.Center), Image.Justify(Image.String(Fonts.create_scaled("Trebuchet MS", 23, {Bold=true}), Colors.white, "MISSION NAME:", {Width=140}), Point.Create(dialogwidth, 20),Justify.Center), Image.Justify(Control.string.create_input(context, mission_name, {width=dialogwidth-40}), Point.Create(dialogwidth-20, 20), Justify.Center), Image.Extent(Point.Create(0, 10), Colors.transparent), Image.String(fontheader4, Colors.white, "Select a server near your physical location to play on. Then select a game core. \n \n Cores are sets of game rules. Different cores may have different factions, weapons and balance values.", {Width=dialogwidth, Justification=Justify.Center} ), Image.Extent(Point.Create(dialogwidth, 30), Colors.transparent), Image.Justify( Image.Group({ Image.Extent(Point.Create(dialogwidth-200, 30), Colors.transparent), Image.Justify( Image.StackVertical({ Image.String(fontheader4, Colors.white, "Servers"), serverlistbox, }), Point.Create(dialogwidth-200, listboxheight+35), Justify.Left ), Image.Justify( Image.StackVertical({ Image.String(fontheader4, Colors.white, "Cores"), corelistbox, }), Point.Create(dialogwidth-200, listboxheight+35), Justify.Right ), }), Point.Create(dialogwidth, listboxheight+35), Justify.Top ), Image.Switch(Loginstate_container:Get("Server has core")(ChosenServer_eventsink, ChosenCore_eventsink), { [ true ]=create_btn.image }), }), Point.Create(dialogwidth, dialogheight), Justify.Top ), }) end local create_mission_window = Popup.create_popup_window(Image.Lazy(create_mission_screen)) local create_mission_popup = context.create_popup(create_mission_window.image); create_mission_popup.add_close_source(create_mission_window.close_source) local currentpassword = String.CreateEventSink("") function create_joining_popup() function with_transparent_background(img) return Image.Group({ -- make sure we can't click on anything else by having a transparent background Image.Extent(cardsarea, Color.Create(0, 0, 0, 0)), Image.Justify(img, cardsarea, Justify.Center), }) end return Image.Switch(Loginstate_container:GetState("Join mission state"), { Joining=function () return with_transparent_background(Image.String(Fonts.h1, Color.Create(0.8, 0.8, 0.8), "Joining mission...")) end, Idle=function (obj) return Image.Switch(obj:Get("Has error"), { Yes = function (error_obj) local show_error = Boolean.CreateEventSink(true) local cancel_button = Button.create_standard_textbutton("Cancel", Fonts.h1, 120, 40) Event.OnEvent(show_error, cancel_button.events.click, function () return false end) local retry_button = Button.create_standard_textbutton("Retry", Fonts.h1, 120, 40) Event.OnEvent(error_obj:Get("Retry"), retry_button.events.click, function () return currentpassword end) return Image.Switch(show_error, { [ true ]=with_transparent_background(Image.StackVertical({ Image.String(Fonts.h1, Color.Create(0.8, 0.8, 0.8), "Failed: " .. error_obj:Get("Reason")), Image.Switch(error_obj:Get("Reason is incorrect password"), { [ true ] = Image.StackVertical({ Image.StackHorizontal({ Image.String(Fonts.h1, Color.Create(0.8, 0.8, 0.8), "Password: "), Control.string.create_input(context, currentpassword), }), retry_button.image, }) }), cancel_button.image, })) }) end, }) end }) end ---------- ---- MISSION CARDS SECTION ---------- mission_container = Loginstate_container:GetList("Mission list") cardslistImg = Image.Group( List.Map( List.Sort( mission_container, function (mission) -- Negate the count to turn it from asc to desc return 0 - mission:Get("Player count") end ), function (mission, i) j=i+1 row_fl = j/cardsrowlen -- calculate how many rows are needed to display this mission row = row_fl-Number.Mod(row_fl,1) -- rounddown that number because we don't want half a card in view col = j - (row*cardsrowlen) -- calculate the column this mission would be in. missionname = mission:GetString("Name") missionplayercount = mission:GetNumber("Player count") missionnoat = mission:GetNumber("Player noat count") missiont = mission:GetNumber("Time in progress") missionhours = missiont/3600 missionminutes = Number.Mod(missionhours,1) missionhours = missionhours-missionminutes missionminutes = missionminutes*60 missionminutes = missionminutes-Number.Mod(missionminutes,1) missiontime = String.Switch( Number.Clamp(missionminutes-9, 0, 1), { [0]=Number.ToString(missionhours) .. ":0" .. Number.ToString(missionminutes), [1]=Number.ToString(missionhours) .. ":" .. Number.ToString(missionminutes), }) missionserver = mission:GetString("Server name") missioncore = mission:GetString("Core name") mission_playercount_string = Number.ToString(missionplayercount - missionnoat) .. "/" .. Number.ToString(missionplayercount) missionstate = String.Switch( mission:GetBool("Is in progress"),{ [true]="In Progress: " .. missiontime .. " (" .. mission_playercount_string .. ")", [false]="Building Teams" .. " (" .. mission_playercount_string .. ")", }) -- figure out whether there is a single or multiple win condition set for the mission -- first collect all the booleans from the mission container function missionstylebools() lst = {} lst[#lst+1] = { name="CONQUEST", boolval = mission:GetBool("Has goal conquest")} lst[#lst+1] = { name="TERRITORY", boolval = mission:GetBool("Has goal territory")} lst[#lst+1] = { name="PROSPERITY", boolval = mission:GetBool("Has goal prosperity")} lst[#lst+1] = { name="ARTIFACTS", boolval = mission:GetBool("Has goal artifacts")} lst[#lst+1] = { name="FLAGS", boolval = mission:GetBool("Has goal flags")} lst[#lst+1] = { name="DEATHMATCH", boolval = mission:GetBool("Has goal deathmatch")} lst[#lst+1] = { name="COUNTDOWN", boolval = mission:GetBool("Has goal countdown")} -- now loop through the list of booleans. On true concat the list index and add 1 to the counter. selectedstyle = "" trueCount = 0 for k, thing in ipairs(lst) do str = String.Switch( thing.boolval, { [true]=thing.name, [false]="", } ) selectedstyle = selectedstyle .. str trueCount = trueCount + Boolean.ToNumber(thing.boolval) end return { trueCount = trueCount, selected = selectedstyle, } end missionstyledata = missionstylebools() missionstyle = String.Switch( Number.Min(missionstyledata.trueCount,2),{ [0] = "UNKNOWN", [1] = missionstyledata.selected, [2] = "CUSTOM MISSION", } ) function makemissioncardface(cardcolor) carddims = Point.Create(scaledcardwidth, scaledcardheight) missioncardface = Image.Group({ Image.Extent(carddims, Colors.transparent), pos(Image.StackVertical({ write(missionstyle, fontheader1, cardcolor), write(missionstate, fontheader4, cardcolor), write(missionname, fontheader1, cardcolor), write("Server: "..missionserver, fontheader4, cardcolor), write("Core: "..missioncore, fontheader4, cardcolor), }), cardsinnermargin, cardsinnermargin ) }) return missioncardface end joinbtn_n = Image.Group({ --Global.create_backgroundpane(scaledcardwidth, scaledcardheight, {color=button_normal_color}), cardbackground_n, makemissioncardface(button_normal_color) }) joinbtn_h = Image.Group({ --Global.create_backgroundpane(scaledcardwidth, scaledcardheight, {color=button_hover_color, src=Image.File("/global/images/backgroundpane_highlight.png")}), cardbackground_h, makemissioncardface(button_hover_color) }) joinbtn_s = Image.Group({ --Global.create_backgroundpane(scaledcardwidth, scaledcardheight, {color=button_selected_color}), cardbackground_s, makemissioncardface(button_selected_color) }) missionhovertext = String.Switch( mission:GetBool("Is in progress"),{ [true]="Join This Mission." , [false]="Connect To The Lobby For This Mission.", }) checktext = "what the hell?" card = Button.create_image_button(joinbtn_n, joinbtn_h, joinbtn_s) -- hovertext = hovertext .. card.hovertext --concatenates the hoverstring with the contents of the toplevel one. Event.OnEvent(e_hovertext, card.events.enter, function() return missionhovertext end) Event.OnEvent(e_hovertext, card.events.leave, function() return "" end) Event.OnEvent(e_hovertext, card.events.click, function() return "" end) Event.OnEvent(mission:Get("Join"), card.events.click, function () return currentpassword end) --positioning -- we're using pre-scaled dimension because this is also about the space between the cards. posx = col*(scaledcardwidth+cardsoutermargin+cardsoutermargin) -- posy = row*(scaledcardheight+cardsoutermargin+cardsoutermargin) function make_create_missioncard() missionstyle = "NEW MISSION" missionstate = "" missionname = "CREATE NEW MISSION" missionserver = " - " missioncore = " - " joinbtn_n = Image.Group({ Global.create_backgroundpane(scaledcardwidth, scaledcardheight, {color=button_normal_color}), makemissioncardface(button_normal_color) }) joinbtn_h = Image.Group({ Global.create_backgroundpane(scaledcardwidth, scaledcardheight, {color=button_hover_color, src=Image.File("/global/images/backgroundpane_highlight.png")}), makemissioncardface(button_hover_color) }) joinbtn_s = Image.Group({ Global.create_backgroundpane(scaledcardwidth, scaledcardheight, {color=button_selected_color}), makemissioncardface(button_selected_color) }) create_missioncard = Button.create_image_button(joinbtn_n, joinbtn_h, joinbtn_s) create_mission_hovertext = "Create your own game on a server." --hovertext = hovertext .. create_missioncard.hovertext --concatenates the hoverstring with the contents of the toplevel one. Event.OnEvent(e_hovertext, create_missioncard.events.enter, function() return create_mission_hovertext end) Event.OnEvent(e_hovertext, create_missioncard.events.leave, function() return "" end) Event.OnEvent(e_hovertext, create_missioncard.events.click, function() return "" end) create_mission_popup.add_open_source(create_missioncard.events.click) return create_missioncard.image end missioncard = Image.Switch( Number.Clamp(i, 0,1), { [0] = Image.Group({ make_create_missioncard(), pos(card.image,posx,posy), }), [1] = pos(card.image,posx,posy) }) return missioncard end ) ) -- cardslistImg =Image.Extent(Point.Create(xcardsarea, 1250), Colors.transparent) --if the vertical size of the cardimage < cardsarea (if it fits) return 0, otherwise return 1, doWeNeedaScrollbar = Number.Clamp(Point.Y(Image.Size(cardslistImg))-ycardsarea,0,1) missioncards = Image.Group({ Image.Extent(cardsarea, Colors.transparent), Image.Switch( doWeNeedaScrollbar, { [0] = Image.Group({ Image.Translate(Image.Justify(Image.Extent(Point.Create(xcardsarea, 3), button_normal_color), cardsarea, Justify.Top), Point.Create(0,-5)), Image.Justify(cardslistImg,cardsarea, Justify.Center), }), -- then just show the cardsimage, else [1] = Image.Group({ Image.Translate(Global.create_backgroundpane(xcardsarea+50,ycardsarea+20, {color=button_normal_color}), Point.Create(0,-15)), Global.create_vertical_scrolling_container( Image.Justify(cardslistImg,Point.Create(xcardsarea+scrollbarwidth,ycardsarea), Justify.Top), Point.Create(xcardsarea+scrollbarwidth,ycardsarea-10), button_normal_color ), }) }), -- make a scrolling pane image }) function button_list() list = {} list[#list+1] = create_mainbutton(Screen.GetExternalEventSink("open.exit"), Image.File("menuintroscreen/images/introBtnExit.png"), "EXIT", "Exit the game.") list[#list+1] = create_mainbutton(Screen.GetExternalEventSink("open.options"), Image.File("menuintroscreen/images/introBtnSettings.png"), "OPTIONS", "Change your graphics, audio and game settings.") list[#list+1] = create_mainbutton(Screen.GetExternalEventSink("open.training"), Image.File("menuintroscreen/images/introBtnHelp.png"), "TRAINING", "Learn how to play the game.") list[#list+1] = create_mainbutton(Screen.CreateOpenWebsiteSink("https://discord.gg/WcEJ9VH"), Image.File("menuintroscreen/images/introBtnDiscord.png"), "DISCORD", "Join the community Discord server.") list[#list+1] = create_mainbutton(Loginstate_container:GetEventSink("Logout"), Image.File("menuintroscreen/images/introBtnBack.png"), "BACK", "Go Back To The Main Screen.") return list end return Image.Group({ -- logo at top Image.Translate(Image.Justify(Image.Scale(logo, Point.Create(UIScaleFactor,UIScaleFactor)), resolution, Justify.Top), Point.Create(0,15*UIScaleFactor)), -- mission list Image.Translate(missioncards, Point.Create(xmargin, ytopmargin)), --buttonbar Image.Translate(Image.Justify(render_list(button_list()), resolution, Justify.Bottom), Point.Create(0,-30*UIScaleFactor)), -- hovertext -- Image.Translate(Image.Justify(create_hovertextimg("hovertext"..hovertext), resolution, Justify.Bottom),Point.Create(0, -150*UIScaleFactor)), -- popups Image.Justify(create_joining_popup(), resolution, Justify.Center), }) end ---- background image -------- -- combine background image and logo function make_background() bgimageuncut = Image.File("menuintroscreen/images/menuintroscreen_bg.jpg") -- calculate how much of the edges need to be trimmed to fit the resolution xbgcutout = Number.Min(xres,1920) -- less than or equal to 1920 ybgcutout = Number.Min(yres,1080) -- less than or equal to 1080 xbgoffset = Number.Divide(Number.Subtract(1920, xbgcutout),2) ybgoffset = Number.Divide(Number.Subtract(1080, ybgcutout),2) bgimagefileRect = Rect.Create(xbgoffset,ybgoffset, Number.Add(xbgoffset, xbgcutout), Number.Add(ybgoffset, ybgcutout)) -- trim the background image to size return Image.Cut(bgimageuncut, bgimagefileRect) end ---------------------- Final Screen Switch Section --------- function create_credits_button() local credits_window = Popup.create_popup_window(Image.Lazy(function () return File.LoadLua("menuintroscreen/credits.lua")().create(context) end)) local credits_popup = context.create_popup(credits_window.image); local credits_button = Popup.create_simple_text_button("Credits", 14); credits_popup.add_open_source(credits_button.event_click) credits_popup.add_close_source(credits_window.close_source) return credits_button.image end function create_hovertextimg(str) return Image.String(fontheader2, Colors.standard_ui, str, {Width=Number.Divide(xres,2), Justification=Justify.Center}) end statescreen = Image.Switch( Login_state,{ ["Logged out"]=make_introscreen, ["Logging in"]=make_spinner, ["Logged in"]=make_missionscreen, }) return context.create_result_image( resolution, Image.Group({ Image.ScaleFill(make_background(), resolution, Justify.Center), -- we use the same background image for all of them. statescreen, -- credits_popup.get_area(Point.Create( -- Point.X(resolution), -- Point.Y(resolution) - 200 -- )), Image.Translate(Image.Justify(create_hovertextimg(e_hovertext), resolution, Justify.Bottom),Point.Create(0, -150*UIScaleFactor)), Image.Justify(Image.String(Font.Create("Verdana",12), button_normal_color, Button.version.."\n"..introscreenversion.."\n"..Global.version .."\n".. checktext, {Width=200, Justification=Justify.Right}), resolution, Justify.Topright), Image.Justify(create_credits_button(), resolution, Justify.Bottomright), }) )
---@class IsoChunkRegion : zombie.iso.areas.isoregion.regions.IsoChunkRegion ---@field private manager IsoRegionManager ---@field private isInPool boolean ---@field private color Color ---@field private ID int ---@field private zLayer byte ---@field private squareSize byte ---@field private roofCnt byte ---@field private chunkBorderSquaresCnt byte ---@field private enclosed boolean[] ---@field private enclosedCache boolean ---@field private connectedNeighbors ArrayList|Unknown ---@field private allNeighbors ArrayList|Unknown ---@field private isDirtyEnclosed boolean ---@field private isoWorldRegion IsoWorldRegion IsoChunkRegion = {} ---@public ---@return int function IsoChunkRegion:getID() end ---@public ---@return int function IsoChunkRegion:getSquareSize() end ---@protected ---@param arg0 IsoChunkRegion ---@return void function IsoChunkRegion:removeConnectedNeighbor(arg0) end ---@protected ---@return void function IsoChunkRegion:resetChunkBorderSquaresCnt() end ---@public ---@param arg0 IsoChunkRegion ---@return void function IsoChunkRegion:addNeighbor(arg0) end ---@public ---@param arg0 int ---@return boolean function IsoChunkRegion:containsConnectedNeighborID(arg0) end ---@protected ---@return boolean function IsoChunkRegion:isInPool() end ---@public ---@return IsoWorldRegion function IsoChunkRegion:getIsoWorldRegion() end ---@public ---@return void function IsoChunkRegion:addRoof() end ---@protected ---@return void function IsoChunkRegion:removeChunkBorderSquaresCnt() end ---@public ---@param arg0 IsoChunkRegion ---@return void function IsoChunkRegion:addConnectedNeighbor(arg0) end ---@private ---@return void function IsoChunkRegion:resetEnclosed() end ---@public ---@return void function IsoChunkRegion:addChunkBorderSquaresCnt() end ---@public ---@return ArrayList|Unknown function IsoChunkRegion:getDebugConnectedNeighborCopy() end ---@public ---@return void function IsoChunkRegion:addSquareCount() end ---@public ---@return int function IsoChunkRegion:getRoofCnt() end ---@public ---@return boolean function IsoChunkRegion:getIsEnclosed() end ---@public ---@return ArrayList|Unknown function IsoChunkRegion:getConnectedNeighbors() end ---@public ---@return Color function IsoChunkRegion:getColor() end ---@public ---@return void function IsoChunkRegion:resetRoofCnt() end ---@public ---@param arg0 byte ---@param arg1 boolean ---@return void function IsoChunkRegion:setEnclosed(arg0, arg1) end ---@public ---@return int function IsoChunkRegion:getChunkBorderSquaresCnt() end ---@public ---@return int function IsoChunkRegion:getzLayer() end ---@public ---@param arg0 IsoWorldRegion ---@return void function IsoChunkRegion:setIsoWorldRegion(arg0) end ---@protected ---@return IsoChunkRegion function IsoChunkRegion:getFirstNeighborWithIsoWorldRegion() end ---@public ---@param arg0 IsoChunkRegion ---@return boolean function IsoChunkRegion:containsConnectedNeighbor(arg0) end ---@protected ---@return void function IsoChunkRegion:setDirtyEnclosed() end ---@public ---@return int function IsoChunkRegion:getNeighborCount() end ---@public ---@return IsoChunkRegion function IsoChunkRegion:getConnectedNeighborWithLargestIsoWorldRegion() end ---@protected ---@param arg0 IsoChunkRegion ---@return void function IsoChunkRegion:removeNeighbor(arg0) end ---@protected ---@return void function IsoChunkRegion:unlinkNeighbors() end ---@protected ---@return IsoChunkRegion function IsoChunkRegion:reset() end ---@protected ---@param arg0 int ---@param arg1 int ---@return void function IsoChunkRegion:init(arg0, arg1) end ---@protected ---@return ArrayList|Unknown function IsoChunkRegion:getAllNeighbors() end ---@public ---@return IsoWorldRegion function IsoChunkRegion:unlinkFromIsoWorldRegion() end
--- -- unit_types local UnitTypes = { trooper = "trooper" } return UnitTypes
local ParentEquipment = script:GetCustomProperty("ParentEquipment"):WaitForObject() local HidePlayer = script:GetCustomProperty("HidePlayer") local CLASS_ID = ParentEquipment:GetCustomProperty("ClassID") local AnimationStance = ParentEquipment:GetCustomProperty("AnimationStance") function OnEquipped(thisEquipment, player) if HidePlayer then player:SetVisibility(false, false) end player:SetResource("CLASS_MAP", CLASS_ID) player.animationStance = AnimationStance end function OnUnequipped(thisEquipment, player) if HidePlayer then player:SetVisibility(true, false) end player.animationStance = "unarmed_stance" end ParentEquipment.equippedEvent:Connect( OnEquipped ) ParentEquipment.unequippedEvent:Connect( OnUnequipped )
--[[ Copyright 2008-2020 João Cardoso Sushi is distributed under the terms of the GNU General Public License (or the Lesser GPL). This file is part of Sushi. Sushi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Sushi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Sushi. If not, see <http://www.gnu.org/licenses/>. --]] local Header = LibStub('Sushi-3.1').Clickable:NewSushi('Header', 1, 'Button') if not Header then return end --[[ Construct ]]-- function Header:Construct() local b = self:Super(Header):Construct() local string = b:CreateFontString() string:SetJustifyH('LEFT') string:SetPoint('TOPLEFT') local line = b:CreateTexture() line:SetColorTexture(1,1,1, .2) line:SetPoint('BOTTOMRIGHT') line:SetPoint('BOTTOMLEFT') line:SetHeight(1.2) b.Line = line b:SetFontString(string) return b end function Header:New(parent, text, font, underlined) local b = self:Super(Header):New(parent) b:SetUnderlined(underlined) b:SetNormalFontObject(font) b:SetText(text) b:UpdateWidth() if parent.SetCall then parent:SetCall('OnResize', function() b:UpdateWidth() end) end return b end function Header:OnEnter() self:Super(Header):OnEnter() self:GetFontString():SetText(self:GetText():gsub('|c(' .. strrep('%x', 8) .. ')', function(value) return '|c' .. value:gsub('(%x%x)', function(v) return format('%x', min(255, tonumber(v, 16) * self:GetHighlightFactor())) end) end)) end function Header:OnLeave() self:Super(Header):OnLeave() self:GetFontString():SetText(self:GetText()) end --[[ API ]]-- function Header:SetWidth(width) self.manual = true self:Super(Header):SetWidth(width) self:UpdateHeight() end function Header:SetText(text) self.text = text self:Super(Header):SetText(text) self:UpdateHeight() end function Header:GetText() return self.text end function Header:SetNormalFontObject(font) self:Super(Header):SetNormalFontObject(font or GameFontNormal) self:UpdateHeight() end function Header:SetUnderlined(enable) self.Line:SetShown(enable) self:UpdateHeight() end function Header:IsUnderlined() return self.Line:IsShown() end function Header:SetHighlightFactor(factor) self.highlight = factor end function Header:GetHighlightFactor() return self.highlight end --[[ Resize ]]-- function Header:UpdateWidth() if not self.manual and self:GetParent() then self:Super(Header):SetWidth(self:GetParent():GetWidth() - self.left - self.right) self:UpdateHeight() end end function Header:UpdateHeight() self:GetFontString():SetWidth(self:GetWidth()) self:SetHeight(self:GetTextHeight() + (self:IsUnderlined() and 3 or 0)) end --[[ Proprieties ]]-- Header.SetLabel = Header.SetText Header.GetLabel = Header.GetText Header.highlight = 1 Header.bottom = 5 Header.right = 12 Header.left = 12 Header.top = 5
local class = require('opus.class') local UI = require('opus.ui') local colors = _G.colors --[[-- TabBarMenuItem --]]-- UI.TabBarMenuItem = class(UI.Button) UI.TabBarMenuItem.defaults = { UIElement = 'TabBarMenuItem', event = 'tab_select', textColor = colors.black, selectedBackgroundColor = colors.cyan, unselectedBackgroundColor = colors.lightGray, backgroundColor = colors.lightGray, } function UI.TabBarMenuItem:draw() if self.selected then self.backgroundColor = self.selectedBackgroundColor self.backgroundFocusColor = self.selectedBackgroundColor else self.backgroundColor = self.unselectedBackgroundColor self.backgroundFocusColor = self.unselectedBackgroundColor end UI.Button.draw(self) end
local uv = require'lluv' local loop = {} local timeout, default_timeout, active_timer, debug_traceback local function close_all_handles() uv.handles(function(handle) if not(handle:closed() or handle:closing()) then return handle:close() end end) end loop.create_timer = function(secs, on_timeout) local timer default_timeout = secs timer = uv.timer():start((timeout or secs) * 1000, function(self) close_all_handles() assert(timer:closed() or timer:closing()) timer = nil on_timeout() end) active_timer = timer return { stop = function() if timer then timer:stop() active_timer, timer = nil end end } end -- !extension to overwrite busted hardcoded value (1s) loop.set_timeout = function(secs) local old = timeout timeout = secs or default_timeout or 1 if active_timer and active_timer:active() then active_timer:again(timeout * 1000) end return old end -- !extension to check either after test end there exists handles -- which may prevent to stop libuv loop -- @usage -- after_each(function(done) async() -- loop.verify_after() -- done() -- end) loop.verify_after = function () uv.handles(function(handle) if not(handle:closed() or handle:closing()) then if handle:active() and handle:has_ref() then assert.truthy(false, 'Test left active handle: ' .. tostring(handle)) end -- we has no reference so assume we just can close it -- and it is not error in test return handle:close() end end) end loop.set_traceback = function(traceback) debug_traceback = traceback end loop.step = function() uv.run(debug_traceback) end loop.pcall = pcall return loop
-- CmdHandler.lua -- Contains all the command handlers function HandleCatastropheCommand(a_Split, a_Player) -- /catastrophe <catastrophe> -- No name was given. Send the usage of the catastrophe plugin, and a list of available catastrophes. if (not a_Split[2]) then a_Player:SendMessage("Usage: " .. a_Split[1] .. " <catastrophe>") local msg = " Catastrophes: " for Catastrophe in pairs(g_Catastrophes) do msg = msg .. Catastrophe .. ", " end msg = msg:sub(1, -3) a_Player:SendMessage(msg) return true end local CatastropheName = table.concat(a_Split, " ", 2) local Catastrophe = g_Catastrophes[CatastropheName:lower()] if (not Catastrophe) then a_Player:SendMessage("Unknown catastrophe") return true end local CurrentPosition = a_Player:GetPosition():Floor() local CatastropheObj = Catastrophe:new() CatastropheObj:SetPosition(CurrentPosition.x, CurrentPosition.z) CatastropheObj:ImportInWorld(a_Player:GetWorld()) a_Player:SendMessage("You summoned a catastrophe") return true end
local _M = {} function _M:new() return setmetatable({ children = {}, }, {__index = self}) end function _M:append_child(child_key, trie_node) self.children[child_key] = trie_node end function _M:set_value(value) self.value = value end function _M:find_child_by_key(key) if not self.children[key] then for child_key, child in pairs(self.children) do if string.char(string.byte(child_key)) == '{' then return child, key end end return nil end return self.children[key] end function _M:find_child_with_pattern(key) if string.char(string.byte(key)) == '{' then for child_key, child in pairs(self.children) do if string.char(string.byte(child_key)) == '{' then return child, key end end end if not self.children[key] then return nil end return self.children[key] end return _M
----------------------------------- -- Area: Port Bastok -- NPC: Numa -- Standard Merchant NPC ----------------------------------- local ID = require("scripts/zones/Port_Bastok/IDs") require("scripts/globals/shop") function onTrade(player, npc, trade) end function onTrigger(player, npc) local stock = { 12457, 5079, 1, -- Cotton Hachimaki 12585, 7654, 1, -- Cotton Dogi 12713, 4212, 1, -- Cotton Tekko 12841, 6133, 1, -- Cotton Sitabaki 12969, 3924, 1, -- Cotton Kyahan 13205, 3825, 1, -- Silver Obi 12456, 759, 2, -- Hachimaki 12584, 1145, 2, -- Kenpogi 12712, 630, 2, -- Tekko 12840, 915, 2, -- Sitabaki 12968, 584, 2, -- Kyahan 704, 132, 2, -- Bamboo Stick 605, 180, 3, -- Pickaxe 5867, 13500, 3, -- Toolbag (Ino) 5868, 18000, 3, -- Toolbag (Shika) 5869, 18000, 3, -- Toolbag (Cho) } player:showText(npc, ID.text.NUMA_SHOP_DIALOG) tpz.shop.nation(player, stock, tpz.nation.BASTOK) end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
local Column = require('modutram.grid.Column') local Slot = require('modutram.slot.Slot') local GridModule = require('modutram.grid_module.Base') local t = require('modutram.types') local Grid = {} function Grid:new(o) o = o or {} if not o.config then error('Grid MUST have a config attribute') end o.columns = o.columns or {} o.bounds = o.bounds or { top = 0, bottom = 0, left = 0, right = 0 } setmetatable(o, self) self.__index = self return o end function Grid:isEmpty() return next(self.columns) == nil end function Grid:hasAnyModulesAtGridX(gridX) return self:getColumn(gridX) ~= nil end function Grid:getColumn(gridX) return self.columns[gridX] end function Grid:hasColumn(gridX) return self:getColumn(gridX) ~= nil end function Grid:updateBounds(gridX, gridY) self.bounds.left = math.min(self.bounds.left, gridX) self.bounds.right = math.max(self.bounds.right, gridX) self.bounds.top = math.max(self.bounds.top, gridY) self.bounds.bottom = math.min(self.bounds.bottom, gridY) end function Grid:set(gridModule) if self:hasAnyModulesAtGridX(gridModule:getGridX()) then self:getColumn(gridModule:getGridX()):addGridModule(gridModule) else self.columns[gridModule:getGridX()] = Column:new{initialModule = gridModule} end self:updateBounds(gridModule:getGridX(), gridModule:getGridY()) end function Grid:makeVoidModule(gridX, gridY) local slot = Slot:new{id = Slot.makeId({type = t.VOID, gridX = gridX, gridY = gridY})} return GridModule:new{slot = slot} end function Grid:get(gridX, gridY) return self:getColumn(gridX) and self:getColumn(gridX):getGridModule(gridY) or self:makeVoidModule(gridX, gridY) end function Grid:has(gridX, gridY) return self:hasAnyModulesAtGridX(gridX) and self:getColumn(gridX):hasGridModule(gridY) end function Grid:isInBounds(gridX, gridY) return gridX >= -self.config.gridMaxXyPosition and gridX <= self.config.gridMaxXyPosition and gridY >= -self.config.gridMaxXyPosition and gridY <= self.config.gridMaxXyPosition end function Grid:getActiveGridBounds() return self.bounds end function Grid:getActiveGridSlotBounds() return { left = self.bounds.left - 1, right = self.bounds.right + 1, top = self.bounds.top + 1, bottom = self.bounds.bottom - 1, } end function Grid:each(callable) self:eachColumn(function (column) column:eachGridModule(callable) end) end function Grid:eachColumn(callable) for i = self.bounds.left, self.bounds.right do if self:getColumn(i) then callable(self:getColumn(i)) end end end return Grid
SLASH_ARMYDATA1 = "/army" local frame = CreateFrame("FRAME", "ArmyData") frame:RegisterEvent("PLAYER_LOGIN") frame:RegisterEvent("VARIABLES_LOADED") frame:RegisterEvent("PLAYER_MONEY") frame:RegisterEvent("CURRENCY_DISPLAY_UPDATE") frame:RegisterEvent("PLAYER_LOOT_SPEC_UPDATED") local currencies = { -- Resources ["Garrison Resources"] = 824, ["Oil"] = 1101, ["Order Resources"] = 1220, ["War Resources"] = 1560, ["Reservoir Anima"] = 1813, -- Dungeon and Raid ["Valor"] = 1191, -- Player vs. Player ["Honor"] = 1792, ["Conquest"] = 1602, -- Bonus Rolls ["Lesser Charm of Good Fortune"] = 738, ["Elder Charm of Good Fortune"] = 697, ["Mogu Rune of Fate"] = 752, ["Warforged Seal"] = 776, ["Seal of Tempered Fate"] = 994, ["Seal of Inevitable Fate"] = 1129, ["Seal of Broken Fate"] = 1273, ["Seal of Wartorn Fate"] = 1580, -- Events ["Timewarped Badge"] = 1166, ["Darkmoon Prize Ticket"] = 515, ["Trial of Style Token"] = 1379, ["Brawler's Gold"] = 1299, -- Burning Crusade ["Spirit Shard"] = 1704, -- Wrath of the Lich King ["Champion's Seal"] = 241, -- Cataclysm ["Tol Barad Commendation"] = 391, ["Mark of the World Tree"] = 416, ["Mote of Darkness"] = 614, ["Essence of Corrupted Deathwing"] = 615, -- Mists of Pandaria ["Timeless Coin"] = 777, -- Warlords of Draenor ["Apexis Crystal"] = 823, -- Legion ["Curious Coin"] = 1275, ["Sightless Eye"] = 1149, ["Ancient Mana"] = 1155, ["Nethershard"] = 1226, ["Legionfall War Supplies"] = 1342, ["Veiled Argunite"] = 1508, ["Wakening Essence"] = 1533, -- Battle for Azeroth ["Seafarer's Dubloon"] = 1710, ["7th Legion Service Medal"] = 1717, ["Honorbound Service Medal"] = 1716, ["Prismatic Manapearl"] = 1721, ["Titan Residuum"] = 1718, ["Coalescing Visions"] = 1755, ["Corrupted Memento"] = 1744, ["Echoes of Nyalotha"] = 1803, -- Shadowlands ["Grateful Offering"] = 1885, ["Redeemed Soul"] = 1810, ["Stygia"] = 1767, ["Infused Ruby"] = 1820, ["Sinstone Fragments"] = 1816, ["Medallion of Service"] = 1819, ["Cataloged Research"] = 1931, ["Soul Ash"] = 1828, ["Soul Cinders"] = 1906, ["Cosmic Flux"] = 2009, ["Cyphers of the First Ones"] = 1979, -- Cooking ["Epicurean's Award"] = 81, ["Ironpaw Token"] = 402, -- Jewelcrafting ["Dalaran Jewelcrafter's Token"] = 61, ["Illustrious Jewelcrafter's Token"] = 361, -- Pick Pocketing ["Dingy Iron Coins"] = 980, ["Coins of Air"] = 1416, } local items = { -- Legion ["Blood of Sargeras"] = 124124, -- PvP ["Mark of Honor"] = 137642, -- Battle Pets ["Polished Pet Charm"] = 163036, ["Shiny Pet Charm"] = 116415, } local function getKeysSortedByValue(tbl, sortFunction) local keys = {} for key in pairs(tbl) do table.insert(keys, key) end table.sort(keys, function(a, b) return sortFunction(tbl[a], tbl[b]) end) return keys end local function updateData() local name = UnitName("player") local realm = GetRealmName() local _, class, _ = UnitClass("player") local faction,_ = UnitFactionGroup("player") if ArmyDB and realm then local profession, professionIcon = "", 0 local prof1, prof2, archaeology, fishing, cooking = GetProfessions() local prof1Name, prof1Icon, prof2Name, prof2Icon = "", 0, "", 0 if prof1 then prof1Name, prof1Icon = GetProfessionInfo(prof1) end if prof2 then prof2Name, prof2Icon = GetProfessionInfo(prof2) end if prof1Name and prof1Name ~= "Engineering" then profession, professionIcon = prof1Name, prof1Icon elseif prof2Name and prof2Name ~= "Engineering" then profession, professionIcon = prof2Name, prof2Icon end ArmyDB[name.."-"..realm] = { ["Name"] = name, ["Realm"] = realm, ["Faction"] = faction, ["Class"] = class, ["Money"] = GetMoney() or 0, ["Specialization"] = GetLootSpecialization() or 0, ["Profession"] = profession, ["Covenant"] = C_Covenants and C_Covenants.GetActiveCovenantID() or 0, ["Renown"] = C_CovenantSanctumUI and C_CovenantSanctumUI.GetRenownLevel() or 1, ["Currencies"] = {}, ["Items"] = {}, } for currencyName, currencyID in pairs(currencies) do local currencyInfo = C_CurrencyInfo.GetCurrencyInfo(currencyID) or {} ArmyDB[name.."-"..realm]["Currencies"][currencyName] = currencyInfo["quantity"] or 0 end for itemName, itemID in pairs(items) do local amount = GetItemCount(itemID, true) ArmyDB[name.."-"..realm]["Items"][itemName] = amount or 0 end end end function GetSimpleItemInfo(id) if id == 124124 then return "|cff0070ddBlood of Sargeras|r", 1417744 elseif id == 137642 then return "|cff0070ddMark of Honor|r", 1322720 elseif id == 116415 then return "Shiny Pet Charm", 413584 elseif id == 163036 then return "Polished Pet Charm", 2004597 else return id, 134400 end end -- Slash Commands function SlashCmdList.ARMYDATA(msg, editbox) updateData() if currencies[msg] then local currencyName = msg local currencyTable = {} local currencyInfo = C_CurrencyInfo.GetCurrencyInfo(currencies[currencyName]) or {} local name = currencyInfo["name"] or "Unknown" local icon = currencyInfo["iconFileID"] or 0 for character in pairs(ArmyDB) do currencyTable[character] = ArmyDB[character].Currencies[currencyName] or 0 end -- Sort the table local sortedCurrencyTable = getKeysSortedByValue(currencyTable, function(a, b) return a > b end) DEFAULT_CHAT_FRAME:AddMessage("---") DEFAULT_CHAT_FRAME:AddMessage("|T" .. icon .. ":0|t " .. name) for i, k in ipairs(sortedCurrencyTable) do if i <= 7 then DEFAULT_CHAT_FRAME:AddMessage(i .. " - " .. k .. ": " .. FormatLargeNumber(currencyTable[k] or 0)) end end elseif items[msg] then local itemName = msg local itemTable = {} local name, icon = GetSimpleItemInfo(items[itemName]) for character in pairs(ArmyDB) do itemTable[character] = ArmyDB[character].Items[itemName] or 0 end -- Sort the table local sortedItemTable = getKeysSortedByValue(itemTable, function(a, b) return a > b end) DEFAULT_CHAT_FRAME:AddMessage("---") DEFAULT_CHAT_FRAME:AddMessage("|T" .. icon .. ":0|t " .. name) for i, k in ipairs(sortedItemTable) do if i <= 7 then DEFAULT_CHAT_FRAME:AddMessage(i .. " - " .. k .. ": " .. FormatLargeNumber(itemTable[k] or 0)) end end else local totalMoney, realmMoney = 0, 0 local faction,_ = UnitFactionGroup("player") local name = UnitName("player") local realm = GetRealmName() local currencyTable = {} local connectedRealms = { ["Ravenholdt"] = "Ravenholdt", ["Sporeggar"] = "Ravenholdt", ["Scarshield Legion"] = "Ravenholdt", ["The Venture Co"] = "Ravenholdt", ["Defias Brotherhood"] = "Ravenholdt", ["Earthen Ring"] = "Ravenholdt", ["Darkmoon Faire"] = "Ravenholdt", ["Xavius"] = "Xavius", ["Al'Akir"] = "Xavius", ["Skullcrusher"] = "Xavius", ["Burning Legion"] = "Xavius", ["The Sha'tar"] = "Moonglade", ["Moonglade"] = "Moonglade", ["Steamwheedle Cartel"] = "Moonglade", ["Bloodfeather"] = "Bloodfeather", ["Kor'gall"] = "Bloodfeather", ["Executus"] = "Bloodfeather", ["Burning Steppes"] = "Bloodfeather", ["Shattered Hand"] = "Bloodfeather", ["Terokkar"] = "Bloodfeather", ["Saurfang"] = "Bloodfeather", ["Darkspear"] = "Bloodfeather", } if connectedRealms[realm] then realm = connectedRealms[realm] end for k, v in pairs(ArmyDB) do local c = ArmyDB[k] if connectedRealms[c["Realm"]] == realm or c["Realm"] == realm then currencyTable[k] = c["Money"] or 0 realmMoney = realmMoney + c["Money"] end totalMoney = totalMoney + c["Money"] --print(c["Name"], c["Money"]) end -- Sort the table local sortedCurrencyTable = getKeysSortedByValue(currencyTable, function(a, b) return a > b end) DEFAULT_CHAT_FRAME:AddMessage(" ") DEFAULT_CHAT_FRAME:AddMessage("|TInterface/MoneyFrame/UI-GoldIcon:14:14|t Gold (Connected " .. realm .. ")") for i, k in ipairs(sortedCurrencyTable) do if i <= 5 then DEFAULT_CHAT_FRAME:AddMessage(i .. " - " .. k .. ": " .. (currencyTable[k] >= 100000 and FormatLargeNumber(floor((currencyTable[k]) / 10000)) .. " |TInterface/MoneyFrame/UI-GoldIcon:14:14|t" or GetCoinTextureString(currencyTable[k] or 0))) end end DEFAULT_CHAT_FRAME:AddMessage("Connected " .. realm .. ": " .. FormatLargeNumber(floor(realmMoney / 10000)) .. " |TInterface/MoneyFrame/UI-GoldIcon:14:14|t") DEFAULT_CHAT_FRAME:AddMessage("Account Total: " .. FormatLargeNumber(floor(totalMoney / 10000)) .. " |TInterface/MoneyFrame/UI-GoldIcon:14:14|t") end end local function eventHandler(self, event) if event == "VARIABLES_LOADED" then -- Make sure defaults are set if not ArmyDB then ArmyDB = { } end else updateData() end end frame:SetScript("OnEvent", eventHandler)
require("lbase/global") require("lbase/extend") local LBase = { Class = require("lbase/class"), Utils = require("lbase/utils"), Log = require("lbase/log"), LinkedList = require("lbase/linked_list"), Queue = require("lbase/queue"), MinHeap = require("lbase/min_heap"), LruCache = require("lbase/lru_cache"), Event = require("lbase/event"), ModificationCollector = require("lbase/modification_collector"), Debugger = require("lbase/debugger"), WordsSearcher = require("lbase/words_searcher"), } return LBase
local colors = require("colors") local drawing = require("drawing") local missing = {} function missing.draw(room, entity) local x = entity.x or 0 local y = entity.y or 0 drawing.callKeepOriginalColor(function() love.graphics.setColor(colors.entityMissingColor) love.graphics.rectangle("fill", x - 2, y - 2, 5, 5) end) end return missing
object_draft_schematic_droid_droid_super_battle_droid = object_draft_schematic_droid_shared_droid_super_battle_droid:new { } ObjectTemplates:addTemplate(object_draft_schematic_droid_droid_super_battle_droid, "object/draft_schematic/droid/droid_super_battle_droid.iff")
splash = {} splash.list = {} splash.toRemove = {} function splash.new(xPos, yPos, radius) if splash.newSilent(xPos, yPos, radius) then sounds.splash() end end function splash.newSilent(xPos, yPos, radius) if collisions.isLand(xPos, yPos) then return false end local s = { x = xPos, y = yPos, r = radius, vr = radius / 10, alpha = 1, frames = 0, maxFrames = math.random() * 10 + 60 } table.insert(splash.list, s) end function splash.draw() love.graphics.setLineWidth(4) for i, s in ipairs(splash.list) do love.graphics.setColor(1, 1, 1, s.alpha * s.alpha) love.graphics.circle("line", s.x, s.y, s.r) end love.graphics.setColor(1, 1, 1, 1) love.graphics.setLineWidth(1) end function splash.update() for i, s in ipairs(splash.list) do s.r = s.r + s.vr s.frames = s.frames + 1 if s.frames > s.maxFrames then splash.remove(s) end s.alpha = 1 - (s.frames / s.maxFrames) end if #splash.toRemove > 0 then for index, splashToRemove in ipairs(splash.toRemove) do local foundIndex = -1 for i, s in ipairs(splash.list) do if s == splashToRemove then foundIndex = i break end end if foundIndex > -1 then table.remove(splash.list, foundIndex) end end splash.toRemove = {} end end function splash.remove(s) table.insert(splash.toRemove, s) end function splash.removeAll() splash.list = {} splash.toRemove = {} end
-- title: Benchmark -- author: MonstersGoBoom -- desc: several performance tests -- script: lua local runningTime = 0 local t = 0 local RUNNER = {} -- predictable random -- give the same sequence every time local random = {} random.max = 8000 random.count = 0 for x=0,random.max do random[x+1] = math.random(100)/100 end function Random(v) random.count = random.count+1 return random[(random.count%random.max)+1] * v end -- epilepsy warning local Warning = [[ A very small percentage of individuals may experience epileptic seizures or blackouts when exposed to certain light patterns or flashing lights. Exposure to certain patterns or backgrounds on a television screen or when playing video games may trigger epileptic seizures or blackouts in these individuals. These conditions may trigger previously undetected epileptic symptoms or seizures in persons who have no history of prior seizures or epilepsy. If you, or anyone in your family has an epileptic condition or has had seizures of any kind, consult your physician before playing. ]] -- UI stuff local UI = {currentOption=1} -- default UI for each test function UI:bench() print("Press Z",170,130,15) -- back to menu if btnp(4) then RUNNER = nil end end -- main UI function UI:mainmenu() cls(1) print("Let the test run until the bar is full",0,0,15) -- print position local yp = 68-((#UI.options*8)/2) -- what is selected local currentOption = 1+(UI.currentOption % (#UI.options)) -- display options for o=1,#UI.options do color = 6 opt = UI.options[o] if o==currentOption then color = 15 -- if highlighted and press Z -- then start it -- and set to white if btnp(4) then RUNNER = opt[2] -- if we have an INIT then run it random.count = 0 if RUNNER.init ~= nil then RUNNER:init() end RUNNER.count = 0 end end -- display text and results if opt[2]~=nil then if opt[2].count==nil then opt[2].count=0 end s = opt[1] .. ":" .. (opt[2].count * opt[2].callmult) else s = opt[1] end print(s,xp,yp,color) yp=yp+6 end if btnp(0) then UI.currentOption=UI.currentOption-1 end if btnp(1) then UI.currentOption=UI.currentOption+1 end end -- SQRT test local SQRT = { add = 1 , callmult = 2} function SQRT:init() end function SQRT:run() cls(0) local wiggle= t/20 % 20 for y=0,136 do for x=0,RUNNER.count do pix(x%240,y,16-(math.sqrt(wiggle+(x*x + y*y)/136)%16)) end end end -- SINCOS test local SINCOS = { add = 1 , callmult = 5} function SINCOS:init() end function SINCOS:run() cls(0) local wiggle= t/20 % 20 for y=0,136 do for x=0,RUNNER.count do local v = 0 v = v + math.sin(wiggle+x) + math.cos(wiggle+y) v = v + math.cos(wiggle-y) + math.sin(wiggle-x) pix(x%240,y,v%16) end end end -- READ WRITE TEST local PIXELRW = { add = 1 , callmult = 1} function PIXELRW:init() print(Warning,0,0,15) end function PIXELRW:run() local wiggle= t/20 % 120 for y=0,136 do for x=0,RUNNER.count do local a = pix(x+wiggle,y) local b = Random(100) if b<25 then pix(x,y,a) else circb(x,y,4,a+1) end end end end -- WRITE TEST local PIXELW = { add = 5 , callmult = 1} function PIXELW:init() end function PIXELW:run() for y=0,136 do for x=0,RUNNER.count do pix(x&0xff,y,32+(x+(y*8))) end end end -- math.random local MATHRANDOM = { add = 1000 , callmult = 2} function MATHRANDOM:run() cls(0) for rc=0,RUNNER.count do pix(math.random(240),math.random(136),math.random(15)) end end -- circles local SHAPES = { add = 25, callmult = 1} function SHAPES:run() cls(2) for x=0,RUNNER.count do circ(Random(240),Random(136),Random(16),x&1) end end -- map local MAP = { add = 1 , callmult = 1} function MAP:run() cls(10) for x=0,RUNNER.count do map(0,0,30,18,-x,0,10) end end -- sprites local Sprites = { add = 100 , callmult = 1} function Sprites:run() local a = t + 1/RUNNER.count cls(0) for x=0,RUNNER.count do spr(1,120+math.sin(x+a)*120,68+math.cos(x-a)*68) end end -- falling dots local Particles = { add = 0 , callmult = 1} function Particles:init() Particles.list = {} end function Particles:run() cls(0) table.sort(Particles, function(a,b) return a.y>b.y end) if (t//40)&1==0 then if runningTime<16.2 then for x=1,100 do table.insert(Particles.list,{x=Random(240),y=-Random(32),c=1+((x//10)%14),fs=0.5+Random(5)/10.0}) end end end Particles.count = #Particles.list for x=1,#Particles.list do p = Particles.list[x] if p.y<100 then if (pix(p.x,(p.y+p.fs)//1)==0) then p.y=p.y+p.fs else if Random(100)>80 then if (pix(p.x-1,p.y+1)==0) then p.x = p.x-1 elseif (pix(p.x+1,p.y+1)==0) then p.x = p.x+1 end end end end pix(p.x,p.y,p.c) end end -- options UI.options = { {"Shapes",SHAPES}, {"MAP",MAP}, {"Sprites",Sprites}, {"Particles",Particles}, {"Write Screen",PIXELW}, {"Read and Write Screen",PIXELRW}, {"Math.Random",MATHRANDOM}, {"Math.SquareRoot",SQRT}, {"Math.SinCos",SINCOS}, -- {"Packer",test_shapes}, } RUNNER = nil function MAINTIC() local stime = time() if RUNNER~=nil then if RUNNER.count~=nil then if runningTime<16.6 then RUNNER.count=RUNNER.count + RUNNER.add end if runningTime>18.0 then RUNNER.count=RUNNER.count - RUNNER.add end print(RUNNER.count,0,110,15) end if RUNNER.run~=nil then RUNNER.run() runningTime = time() - stime rect(0,119,240,6,0) rect(0,120,runningTime*14.20,4,15) print(string.format("runTime %.2f",runningTime),1,127,0) print(string.format("runTime %.2f",runningTime),0,126,15) if runningTime>16 then UI:bench() end end else UI:mainmenu() end t=t+1 end t=0 function TIC() cls(0) local y = 136-(t/3) if y<0 then y=0 end print(Warning,0,y,15) t=t+1 if (t>60*2) then UI:bench() if btnp(4) then TIC=MAINTIC end end end -- <TILES> -- 000:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -- 001:0333333033777733377aa77337affa7337affa73377aa7733377773303333330 -- 002:fffffeee2222ffee88880fee22280feefff80fff0ff80f0f0ff80f0f0ff80f0f -- 003:efffffffff222222f8888888f8222222f8fffffff8fffffff8ff0ffff8ff0fff -- 004:fffffeee2222ffee88880fee22280feefff80ffffff80f0f0ff80f0f0ff80f0f -- 005:efffffffff222222f8888888f8222222f8fffffff8ff0ffff8ff0ffff8ff0fff -- 006:fffffeee2222ffee88880fee22280feefff80fff0ff80f0f0ff80f0f0ff80f0f -- 007:efffffffff222222f8888888f8222222f8fffffff8ff0ffff8ff0ffff8ff0fff -- 008:fffffeee2222ffee88880fee22280feefff80fff0ff80f0f0ff80f0f0ff80f0f -- 009:efffffffff222222f8888888f8222222f8fffffff8ff0ffff8ff0ffff8ff0fff -- 010:fffffeee2222ffee88880fee22280feefff80fff0ff80f0f0ff80f0f0ff80f0f -- 016:2222222222222222222222222222222222222222222222222222222222222222 -- 017:f8fffffff8888888f888f888f8888ffff8888888f2222222ff000fffefffffef -- 018:fff800ff88880ffef8880fee88880fee88880fee2222ffee000ffeeeffffeeee -- 019:f8fffffff8888888f888f888f8888ffff8888888f2222222ff000fffefffffef -- 020:fff800ff88880ffef8880fee88880fee88880fee2222ffee000ffeeeffffeeee -- 021:f8fffffff8888888f888f888f8888ffff8888888f2222222ff000fffefffffef -- 022:fff800ff88880ffef8880fee88880fee88880fee2222ffee000ffeeeffffeeee -- 023:f8fffffff8888888f888f888f8888ffff8888888f2222222ff000fffefffffef -- 024:fff800ff88880ffef8880fee88880fee88880fee2222ffee000ffeeeffffeeee -- 025:f8fffffff8888888f888f888f8888ffff8888888f2222222ff000fffefffffef -- 026:fff800ff88880ffef8880fee88880fee88880fee2222ffee000ffeeeffffeeee -- 032:0f0f0f0ff0f0f0f00f0f0f0ff0f0f0f00f0f0f0ff0f0f0f00f0f0f0ff0f0f0f0 -- </TILES> -- <MAP> -- 000:010101010101010101010101010101010101010101010101010101010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 001:010101010101010101010101010101010101010101010101010101010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 002:010101010101010101010101010101010101010101010101010101010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 003:010100000000000000000000000000000000000000000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 004:010100000000000000000000000000000000000000000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 005:010100000000000000000000000000000000000000000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 006:010100010101000000000000000001010100000000000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 007:010100010101000000000000000001010100000000000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 008:010100000000000000000000000000000000000000000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 009:010100000000000000000000000000000000000000000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 010:010100000000000000000000000000000000000000000000000000010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 011:010101010101010101000000000001010101010101010101010101010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 012:010000000000000000000000000000000000000000000000000001010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 013:010000000000000000000000000000000000000000000000000000010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 014:010100000000000000000000000000000000000000000000000000010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 015:010100000000010101010100000000000000000000010101010101010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- 016:010101010101010101010101010101010101010101010101010101010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -- </MAP> -- <WAVES> -- 000:00000000ffffffff00000000ffffffff -- 001:0123456789abcdeffedcba9876543210 -- 002:0123456789abcdef0123456789abcdef -- </WAVES> -- <SFX> -- 000:000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000304000000000 -- </SFX> -- <PALETTE> -- 000:140c1c44243430346d4e4a4e854c30346524d04648757161597dced27d2c8595a16daa2cd2aa996dc2cadad45edeeed6 -- </PALETTE>
local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") local UserInputService = game:GetService("UserInputService") local GuiService = game:GetService("GuiService") local Roact = require(ReplicatedStorage.Packages.Roact) local Hooks = require(ReplicatedStorage.Packages.Hooks) local RoactSpring = require(ReplicatedStorage.Packages.RoactSpring) local e = Roact.createElement local buttonProps = { { text = "LOREM", gradient = ColorSequence.new({ ColorSequenceKeypoint.new(0, Color3.fromRGB(240, 215, 72)), ColorSequenceKeypoint.new(1, Color3.fromRGB(236, 147, 57)), }), }, { text = "IPSUM", gradient = ColorSequence.new({ ColorSequenceKeypoint.new(0, Color3.fromRGB(241, 108, 230)), ColorSequenceKeypoint.new(1, Color3.fromRGB(238, 71, 130)), }), }, { text = "DOLOR", gradient = ColorSequence.new({ ColorSequenceKeypoint.new(0, Color3.fromRGB(138, 223, 240)), ColorSequenceKeypoint.new(1, Color3.fromRGB(172, 119, 224)), }), }, { text = "SIT", gradient = ColorSequence.new({ ColorSequenceKeypoint.new(0, Color3.fromRGB(177, 223, 233)), ColorSequenceKeypoint.new(1, Color3.fromRGB(151, 182, 224)), }), } } local function Button(props, hooks) local springs, api = RoactSpring.useSprings(hooks, #buttonProps, function(i) return { from = { Position = UDim2.fromScale(0.5, i * 0.16), Size = UDim2.fromScale(1, 0.13), ZIndex = 1, }, } end) local connection = hooks.useValue() local buttons = {} for index, buttonProp in ipairs(buttonProps) do buttons[index] = e("ImageButton", { AnchorPoint = Vector2.new(0.5, 0.5), Position = springs[index].Position, Size = springs[index].Size, BackgroundColor3 = Color3.fromRGB(255, 255, 255), AutoButtonColor = false, ZIndex = springs[index].ZIndex, [Roact.Event.InputBegan] = function(button, input) if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then connection.value = RunService.Heartbeat:Connect(function() local mousePos = UserInputService:GetMouseLocation() - Vector2.new(0, GuiService:GetGuiInset().Y) local yPos = mousePos.Y local frame = button.Parent api.start(function(i) if i == index then return { Position = UDim2.fromScale(0.5, (yPos - frame.AbsolutePosition.Y) / frame.AbsoluteSize.Y), ZIndex = 10, }, { immediate = true, } end return { ZIndex = 1, }, { immediate = true, } end) api.start(function(i) if i == index then return { Size = UDim2.new(1, 15, 0.13, 15), }, RoactSpring.config.stiff end return {} end) local buttons = frame:GetChildren() table.sort(buttons, function(a, b) return a.AbsolutePosition.Y < b.AbsolutePosition.Y end) local sortedButtonNums = {} for _, v in ipairs(buttons) do table.insert(sortedButtonNums, tonumber(v.Name)) end api.start(function(i) if i ~= index then return { Position = UDim2.fromScale(0.5, (table.find(sortedButtonNums, i) - 1) * 0.16 + 0.16), } end return {} end) end) end end, [Roact.Event.InputEnded] = function(button,input) if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then if connection.value then connection.value:Disconnect() connection.value = nil end local buttons = button.Parent:GetChildren() table.sort(buttons, function(a, b) return a.AbsolutePosition.Y < b.AbsolutePosition.Y end) local sortedButtonNums = {} for _, v in ipairs(buttons) do table.insert(sortedButtonNums, tonumber(v.Name)) end api.start(function(i) return { Position = UDim2.fromScale(0.5, (table.find(sortedButtonNums, i) - 1) * 0.16 + 0.16), Size = UDim2.fromScale(1, 0.13), } end) end end }, { UICorner = e("UICorner"), UIGradient = e("UIGradient", { Color = buttonProp.gradient, }), UIStroke = e("UIStroke", { ApplyStrokeMode = Enum.ApplyStrokeMode.Border, Color = Color3.fromRGB(95, 95, 95), Thickness = 2, Transparency = 0, }, { UIGradient = e("UIGradient", { Rotation = -90, Transparency = NumberSequence.new({ NumberSequenceKeypoint.new(0, 0.85), NumberSequenceKeypoint.new(1, 1), }), }), }), Label = e("TextLabel", { AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.5), Size = UDim2.fromScale(0.7, 0.7), BackgroundTransparency = 1, TextColor3 = Color3.fromRGB(255, 255, 255), Text = buttonProp.text, TextSize = 22, TextXAlignment = Enum.TextXAlignment.Left, ZIndex = springs[index].ZIndex, }), }) end return e("Frame", { AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.5), Size = UDim2.fromScale(0.3, 0.7), BackgroundTransparency = 1, }, buttons) end Button = Hooks.new(Roact)(Button) return function(target) local handle = Roact.mount(e(Button), target, "Button") return function() Roact.unmount(handle) end end
local Runner = require "nvim-test.runner" local cmd = "pytest" if vim.env.VIRTUAL_ENV and vim.fn.filereadable(vim.env.VIRTUAL_ENV .. "/bin/pytest") then cmd = vim.env.VIRTUAL_ENV .. "/bin/pytest" end local pytest = Runner:init({ command = cmd, }, { python = [[ ; Class ((class_definition name: (identifier) @class-name) @scope-root) ; Function ((function_definition name: (identifier) @function-name) @scope-root) ]], }) function pytest:is_test(name) return string.match(name, "[Tt]est") and true end function pytest:build_test_args(tests) return "::" .. table.concat(tests, "::") end return pytest
-- -- xcode11.lua -- Define the Apple XCode 11.0 action and support functions. -- local premake = premake premake.xcode11 = { } local xcode = premake.xcode local xcode10 = premake.xcode10 local xcode11 = premake.xcode11 function xcode11.XCBuildConfiguration_Target(tr, target, cfg) local options = xcode10.XCBuildConfiguration_Target(tr, target, cfg) options.CODE_SIGN_IDENTITY = "-" return options end function xcode11.project(prj) local tr = xcode.buildprjtree(prj) xcode.Header(tr, 48) xcode.PBXBuildFile(tr) xcode.PBXContainerItemProxy(tr) xcode.PBXFileReference(tr,prj) xcode.PBXFrameworksBuildPhase(tr) xcode.PBXGroup(tr) xcode.PBXNativeTarget(tr) xcode.PBXProject(tr, "8.0") xcode.PBXReferenceProxy(tr) xcode.PBXResourcesBuildPhase(tr) xcode.PBXShellScriptBuildPhase(tr) xcode.PBXCopyFilesBuildPhase(tr) xcode.PBXSourcesBuildPhase(tr,prj) xcode.PBXVariantGroup(tr) xcode.PBXTargetDependency(tr) xcode.XCBuildConfiguration(tr, prj, { ontarget = xcode11.XCBuildConfiguration_Target, onproject = xcode10.XCBuildConfiguration_Project, }) xcode.XCBuildConfigurationList(tr) xcode.Footer(tr) end --]] -- -- xcode11 action -- newaction { trigger = "xcode11", shortname = "Xcode 11", description = "Generate Apple Xcode 11 project files", os = "macosx", valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Bundle" }, valid_languages = { "C", "C++" }, valid_tools = { cc = { "gcc" }, }, valid_platforms = { Native = "Native" }, default_platform = "Native", onsolution = function(sln) premake.generate(sln, "%%.xcworkspace/contents.xcworkspacedata", xcode.workspace_generate) premake.generate(sln, "%%.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings", xcode.workspace_settings) premake.generate(sln, "%%.xcworkspace/xcshareddata/xcschemes/-ALL-.xcscheme", xcode.workspace_scheme) end, onproject = function(prj) premake.generate(prj, "%%.xcodeproj/project.pbxproj", xcode11.project) xcode.generate_schemes(prj, "%%.xcodeproj/xcshareddata/xcschemes") end, oncleanproject = function(prj) premake.clean.directory(prj, "%%.xcodeproj") premake.clean.directory(prj, "%%.xcworkspace") end, oncheckproject = xcode.checkproject, xcode = { iOSTargetPlatformVersion = nil, macOSTargetPlatformVersion = nil, tvOSTargetPlatformVersion = nil, }, }
-- Minetest: builtin/features.lua core.features = { glasslike_framed = true, nodebox_as_selectionbox = true, chat_send_player_param3 = true, get_all_craft_recipes_works = true, use_texture_alpha = true, no_legacy_abms = true, texture_names_parens = true, area_store_custom_ids = true, } function core.has_feature(arg) if type(arg) == "table" then local missing_features = {} local result = true for ftr in pairs(arg) do if not core.features[ftr] then missing_features[ftr] = true result = false end end return result, missing_features elseif type(arg) == "string" then if not core.features[arg] then return false, {[arg]=true} end return true, {} end end
QhunCore.AbstractMessage = {} QhunCore.AbstractMessage.__index = QhunCore.AbstractMessage -- constructor function QhunCore.AbstractMessage.new() -- private properties local instance = { _channel = nil, _text = "", _sender = nil } setmetatable(instance, QhunCore.AbstractMessage) return instance end --[[ PUBLIC ABSTRACT FUNCTIONS ]] -- get the current channel function QhunCore.AbstractMessage:getChannel() return self._channel end -- send the message function QhunCore.AbstractMessage:send() -- using the given sender function from the client class if type(self._sender) ~= "function" then return end return self._sender(self._text) end
/******************************* Adv. Consolescreen Wrapper for Wiremod (C) Sebastian J. ********************************/ TOOL.Category = "Wire Extras/Memory" TOOL.Name = "Dynamic Memory" TOOL.Command = nil TOOL.ConfigName = "" TOOL.Tab = "Wire" if ( CLIENT ) then language.Add( "Tool.wire_dynmemory.name", "Dynamic Memory Chip Tool (Wire)" ) language.Add( "Tool.wire_dynmemory.desc", "Spawns a Dynamic Memory Chip" ) language.Add( "Tool.wire_dynmemory.pers", "Persistant Memory" ) language.Add( "Tool.wire_dynmemory.0", "Primary: Create/Update Memory Chip" ) language.Add( "sboxlimit_wire_dynmemorys", "You've hit the Dynamic Memory Chips limit!" ) language.Add( "Undone_WireDynMemory", "Dynamic Memory Chip undone" ) end if (SERVER) then CreateConVar('sbox_maxwire_dynmemorys', 2) end TOOL.ClientConVar[ "model" ] = "models/jaanus/wiretool/wiretool_gate.mdl" TOOL.ClientConVar[ "size" ] = 1 TOOL.ClientConVar[ "persistant" ] = 0 cleanup.Register( "wire_dynmemorys" ) function TOOL:LeftClick( trace ) if trace.Entity:IsPlayer() then return false end if (CLIENT) then return true end local Model = self:GetClientInfo( "model" ) local Size = math.floor(self:GetClientNumber( "size" )) local Pers = self:GetClientNumber( "persistant" ) if ( Size < 1 ) then Size = 1 end if (!self:GetSWEP():CheckLimit( "wire_dynmemorys" ) ) then return false end if (!util.IsValidModel(Model)) then return false end if (!util.IsValidProp(Model)) then return false end local ply = self:GetOwner() local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 ent = MakeWireDynMemory( ply, trace.HitPos, Ang, Size,Model ) if (!ent || !ent:IsValid()) then return false end local min = ent:OBBMins() ent:SetPos( trace.HitPos - trace.HitNormal * min.z ) ent:SetPersistant( Pers > 0 ) local const = WireLib.Weld( ent, trace.Entity, trace.PhysicsBone, true ) undo.Create("WireDynMemory") undo.AddEntity( ent ) undo.AddEntity( const ) undo.SetPlayer( ply ) undo.Finish() ply:AddCleanup( "wire_dynmemorys", ent ) return true end function TOOL:RightClick( trace ) return false end function TOOL:Think() if (!self.GhostEntity || !self.GhostEntity:IsValid() || !self.GhostEntity:GetModel() || self.GhostEntity:GetModel() != self:GetClientInfo( "model" ) ) then self:MakeGhostEntity( self:GetClientInfo( "model" ), Vector(0,0,0), Angle(0,0,0) ) end self:UpdateGhost( self.GhostEntity, self:GetOwner() ) end function TOOL:UpdateGhost( ent, player ) if ( !ent ) then return end if ( !ent:IsValid() ) then return end local trace = player:GetEyeTrace() if (!trace.Hit) then return end if ( trace.Entity && trace.Entity:GetClass() == "gmod_wire_dynamicmemory" || trace.Entity:IsPlayer() ) then ent:SetNoDraw( true ) return end local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 local min = ent:OBBMins() ent:SetPos( trace.HitPos - trace.HitNormal * min.z ) ent:SetAngles( Ang ) ent:SetNoDraw( false ) end if ( SERVER ) then function MakeWireDynMemory( ply, Pos, Ang, Size, Model ) if ( !ply:CheckLimit( "wire_dynmemorys" ) ) then return false end local ent = ents.Create( "gmod_wire_dynamicmemory" ) if (!ent:IsValid()) then return false end ent:SetModel(Model) ent:SetAngles( Ang ) ent:SetPos( Pos ) ent:Spawn() ent:Setup( Size ) ent:SetPlayer( ply ) local ttable = { ply = ply, Model = Model, Size = Size } table.Merge(ent:GetTable(), ttable ) ply:AddCount( "wire_dynmemorys", ent ) return ent end duplicator.RegisterEntityClass("gmod_wire_dynamicmemory", MakeWireDynMemory, "Pos", "Ang", "Size", "Model") end function TOOL.BuildCPanel(panel) panel:AddControl("Slider", { Label = "Memory Size", Type = "Integer", Min = "1", Max = "2097152", Command = "wire_dynmemory_size" }) ModelPlug_AddToCPanel(panel, "gate", "wire_dynmemory", "model:", nil, "Model:") panel:AddControl("Checkbox", { Label = "#Tool.wire_dynmemory.pers", Description = "Saves memory content in duplicator saves!", Command = "wire_dynmemory_persistant" }) end
local a=require("filesystem")local b=require("shell")local c,d=b.parse(...)local e=table.remove(c,1)local f=_G._XAF;local g=f and f._VERSION or''if e then local h="io.github.aquaver"local i="xaf-framework"local j="scripts"local k="pm"if f then if a.exists(a.concat(h,i,j,k,e..".lua"))==true then local l=a.open(a.concat(h,i,j,k,e..".lua"),'r')local m=nil;local n=''local o=l:read(math.huge)local p={}while o do n=n..o;o=l:read(math.huge)end;l:close()m=load(n)p={m(c,d)}return table.unpack(p)else print("--------------------------------------")print("-- XAF Package Manager - Controller --")print("--------------------------------------")print(" >> Cannot find following command 'xaf-pm "..e.."'")print(" >> Use 'xaf-pm list' - for available command list")end else print("--------------------------------------")print("-- XAF Package Manager - Controller --")print("--------------------------------------")print(" >> Cannot execute following command 'xaf-pm "..e.."'")print(" >> Please initialize the API first using 'xaf init'")end else if f then print("--------------------------------------")print("-- XAF Package Manager - Controller --")print("--------------------------------------")print(" >> Successfully detected XAF installed on this computer")print(" >> Package global API version: "..g)print(" >> Use 'xaf-pm list' - for available command list")else print("--------------------------------------")print("-- XAF Package Manager - Controller --")print("--------------------------------------")print(" >> XAF has not been initialized yet...")print(" >> Use 'xaf init' - to initialize the API")end end
--[[ Copyright 2019 The Nakama Authors 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 nk = require("nakama") local ud = {} local function is_initialized(context) local data = { collection = "personal", key = "player_data", user_id = context.user_id, } local result = nk.storage_read({ data }) if next(result) == nil then return false else return true end end local function initialize(context) local data = { level = math.random(100), wins = math.random(100), gamesPlayed = math.random(100) } local data = { collection = "personal", key = "player_data", value = data, user_id = context.user_id, permission_read = 2, permission_write = 1 } nk.storage_write({ data }) end function ud.initialize_data(context) if is_initialized(context) == false then initialize(context) end end return ud
local hud_deathnotice_time = CreateConVar( "hud_deathnotice_time", "6", FCVAR_REPLICATED, "Amount of time to show death notice" ) -- These are our kill icons local Color_Icon = Color( 255, 80, 0, 255 ) local NPC_Color = Color( 250, 50, 50, 255 ) killicon.AddFont( "prop_physics", "HL2MPTypeDeath", "9", Color_Icon ) killicon.AddFont( "weapon_smg1", "HL2MPTypeDeath", "/", Color_Icon ) killicon.AddFont( "weapon_357", "HL2MPTypeDeath", ".", Color_Icon ) killicon.AddFont( "weapon_ar2", "HL2MPTypeDeath", "2", Color_Icon ) killicon.AddFont( "crossbow_bolt", "HL2MPTypeDeath", "1", Color_Icon ) killicon.AddFont( "weapon_shotgun", "HL2MPTypeDeath", "0", Color_Icon ) killicon.AddFont( "rpg_missile", "HL2MPTypeDeath", "3", Color_Icon ) killicon.AddFont( "npc_grenade_frag", "HL2MPTypeDeath", "4", Color_Icon ) killicon.AddFont( "weapon_pistol", "HL2MPTypeDeath", "-", Color_Icon ) killicon.AddFont( "prop_combine_ball", "HL2MPTypeDeath", "8", Color_Icon ) killicon.AddFont( "grenade_ar2", "HL2MPTypeDeath", "7", Color_Icon ) killicon.AddFont( "weapon_stunstick", "HL2MPTypeDeath", "!", Color_Icon ) killicon.AddFont( "npc_satchel", "HL2MPTypeDeath", "*", Color_Icon ) killicon.AddFont( "npc_tripmine", "HL2MPTypeDeath", "*", Color_Icon ) killicon.AddFont( "weapon_crowbar", "HL2MPTypeDeath", "6", Color_Icon ) killicon.AddFont( "weapon_physcannon", "HL2MPTypeDeath", ",", Color_Icon ) local Deaths = {} local function PlayerIDOrNameToString( var ) if ( type( var ) == "string" ) then if ( var == "" ) then return "" end return "#" .. var end local ply = Entity( var ) if ( !IsValid( ply ) ) then return "NULL!" end return ply:Name() end local function RecvPlayerKilledByPlayer() local victim = net.ReadEntity() local inflictor = net.ReadString() local attacker = net.ReadEntity() if ( !IsValid( attacker ) ) then return end if ( !IsValid( victim ) ) then return end GAMEMODE:AddDeathNotice( attacker:Name(), attacker:Team(), inflictor, victim:Name(), victim:Team() ) end net.Receive( "PlayerKilledByPlayer", RecvPlayerKilledByPlayer ) local function RecvPlayerKilledSelf() local victim = net.ReadEntity() if ( !IsValid( victim ) ) then return end GAMEMODE:AddDeathNotice( nil, 0, "suicide", victim:Name(), victim:Team() ) end net.Receive( "PlayerKilledSelf", RecvPlayerKilledSelf ) local function RecvPlayerKilled() local victim = net.ReadEntity() if ( !IsValid( victim ) ) then return end local inflictor = net.ReadString() local attacker = "#" .. net.ReadString() GAMEMODE:AddDeathNotice( attacker, -1, inflictor, victim:Name(), victim:Team() ) end net.Receive( "PlayerKilled", RecvPlayerKilled ) local function RecvPlayerKilledNPC() local victimtype = net.ReadString() local victim = "#" .. victimtype local inflictor = net.ReadString() local attacker = net.ReadEntity() -- -- For some reason the killer isn't known to us, so don't proceed. -- if ( !IsValid( attacker ) ) then return end GAMEMODE:AddDeathNotice( attacker:Name(), attacker:Team(), inflictor, victim, -1 ) local bIsLocalPlayer = ( IsValid(attacker) && attacker == LocalPlayer() ) local bIsEnemy = IsEnemyEntityName( victimtype ) local bIsFriend = IsFriendEntityName( victimtype ) if ( bIsLocalPlayer && bIsEnemy ) then achievements.IncBaddies() end if ( bIsLocalPlayer && bIsFriend ) then achievements.IncGoodies() end if ( bIsLocalPlayer && ( !bIsFriend && !bIsEnemy ) ) then achievements.IncBystander() end end net.Receive( "PlayerKilledNPC", RecvPlayerKilledNPC ) local function RecvNPCKilledNPC() local victim = "#" .. net.ReadString() local inflictor = net.ReadString() local attacker = "#" .. net.ReadString() GAMEMODE:AddDeathNotice( attacker, -1, inflictor, victim, -1 ) end net.Receive( "NPCKilledNPC", RecvNPCKilledNPC ) --[[--------------------------------------------------------- Name: gamemode:AddDeathNotice( Attacker, team1, Inflictor, Victim, team2 ) Desc: Adds an death notice entry -----------------------------------------------------------]] function GM:AddDeathNotice( Attacker, team1, Inflictor, Victim, team2 ) local Death = {} Death.time = CurTime() Death.left = Attacker Death.right = Victim Death.icon = Inflictor if ( team1 == -1 ) then Death.color1 = table.Copy( NPC_Color ) else Death.color1 = table.Copy( team.GetColor( team1 ) ) end if ( team2 == -1 ) then Death.color2 = table.Copy( NPC_Color ) else Death.color2 = table.Copy( team.GetColor( team2 ) ) end if (Death.left == Death.right) then Death.left = nil Death.icon = "suicide" end table.insert( Deaths, Death ) end local function DrawDeath( x, y, death, hud_deathnotice_time ) local w, h = killicon.GetSize( death.icon ) if ( !w || !h ) then return end local fadeout = ( death.time + hud_deathnotice_time ) - CurTime() local alpha = math.Clamp( fadeout * 255, 0, 255 ) death.color1.a = alpha death.color2.a = alpha -- Draw Icon killicon.Draw( x, y, death.icon, alpha ) -- Draw KILLER if ( death.left ) then draw.SimpleText( death.left, "ChatFont", x - ( w / 2 ) - 16, y, death.color1, TEXT_ALIGN_RIGHT ) end -- Draw VICTIM draw.SimpleText( death.right, "ChatFont", x + ( w / 2 ) + 16, y, death.color2, TEXT_ALIGN_LEFT ) return ( y + h * 0.70 ) end function GM:DrawDeathNotice( x, y ) if ( GetConVarNumber( "cl_drawhud" ) == 0 ) then return end local hud_deathnotice_time = hud_deathnotice_time:GetFloat() x = x * ScrW() y = y * ScrH() -- Draw for k, Death in pairs( Deaths ) do if ( Death.time + hud_deathnotice_time > CurTime() ) then if ( Death.lerp ) then x = x * 0.3 + Death.lerp.x * 0.7 y = y * 0.3 + Death.lerp.y * 0.7 end Death.lerp = Death.lerp or {} Death.lerp.x = x Death.lerp.y = y y = DrawDeath( x, y, Death, hud_deathnotice_time ) end end -- We want to maintain the order of the table so instead of removing -- expired entries one by one we will just clear the entire table -- once everything is expired. for k, Death in pairs( Deaths ) do if ( Death.time + hud_deathnotice_time > CurTime() ) then return end end Deaths = {} end
function setToClipboard(content) setClipboard(content) end addEvent("official-interiors:copytoclipboard", true) addEventHandler("official-interiors:copytoclipboard", getLocalPlayer(), setToClipboard)
return {'kultuurkamer','kul','kulas','kulkoek','kullen','kulk','kulik','kuling','kulsdom','kulassen','kulde','kulden','kult'}
--[[ Copyright 2012 The Luvit 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. --]] require("helper") local FS = require('fs') local Path = require('path') local Buffer = require('buffer').Buffer local string = require('string') local filename = Path.join(__dirname, 'tmp', 'truncate-file.txt') local data = string.rep('x', 1024 * 16) local stat -- truncateSync FS.writeFileSync(filename, data) stat = FS.statSync(filename) assert(stat.size == 1024 * 16) FS.truncateSync(filename, 1024) stat = FS.statSync(filename) assert(stat.size == 1024) FS.truncateSync(filename) stat = FS.statSync(filename) assert(stat.size == 0) -- ftruncateSync FS.writeFileSync(filename, data) local fd = FS.openSync(filename, 'a') stat = FS.statSync(filename) assert(stat.size == 1024 * 16) FS.ftruncateSync(fd, 1024) stat = FS.statSync(filename) assert(stat.size == 1024) FS.ftruncateSync(fd) stat = FS.statSync(filename) assert(stat.size == 0) FS.closeSync(fd) function testTruncate(cb) FS.writeFile(filename, data, function(er) if er then return cb(er) end FS.stat(filename, function(er, stat) if er then return cb(er) end assert(stat.size == 1024 * 16) FS.truncate(filename, 1024, function(er) if er then return cb(er) end FS.stat(filename, function(er, stat) if er then return cb(er) end assert(stat.size == 1024) FS.truncate(filename, function(er) if er then return cb(er) end FS.stat(filename, function(er, stat) if er then return cb(er) end assert(stat.size == 0) cb() end) end) end) end) end) end) end function testFtruncate(cb) FS.writeFile(filename, data, function(er) if er then return cb(er) end FS.stat(filename, function(er, stat) if er then return cb(er) end assert(stat.size == 1024 * 16) FS.open(filename, 'w', function(er, fd) if er then return cb(er) end FS.ftruncate(fd, 1024, function(er) if er then return cb(er) end FS.stat(filename, function(er, stat) if er then return cb(er) end assert(stat.size == 1024) FS.ftruncate(fd, function(er) if er then return cb(er) end FS.stat(filename, function(er, stat) if er then return cb(er) end assert(stat.size == 0) FS.close(fd, cb) end) end) end) end) end) end) end) end -- async tests local success = 0 testTruncate(function(er) if er then return er end success = success + 1 testFtruncate(function(er) if er then return er end success = success + 1 end) end) process:on('exit', function() assert(success == 2) p('ok') end)
-------------------------------------------------------------------------------- -- Module Declaration -- local mod, CL = BigWigs:NewBoss("Archdruid Glaidalis", 1466, 1654) if not mod then return end mod:RegisterEnableMob(96512) mod.engageId = 1836 -------------------------------------------------------------------------------- -- Initialization -- function mod:GetOptions() return { 198379, -- Primal Rampage 198408, -- Nightfall {196376, "FLASH"}, -- Grievous Tear } end function mod:OnBossEnable() self:Log("SPELL_CAST_START", "PrimalRampage", 198379) self:Log("SPELL_AURA_APPLIED", "NightfallDamage", 198408) self:Log("SPELL_PERIODIC_DAMAGE", "NightfallDamage", 198408) self:Log("SPELL_PERIODIC_MISSED", "NightfallDamage", 198408) self:Log("SPELL_AURA_APPLIED", "GrievousTearApplied", 196376) end function mod:OnEngage() self:CDBar(198379, 12) -- Primal Rampage self:CDBar(196376, 5) -- Grievous Tear end -------------------------------------------------------------------------------- -- Event Handlers -- function mod:PrimalRampage(args) self:Message(args.spellId, "red", "Warning") self:CDBar(args.spellId, 30) -- pull:12.7, 30.3 / m pull:12.6, 31.6, 29.9, 27.9 end do local prev = 0 function mod:NightfallDamage(args) if self:Me(args.destGUID) then local t = GetTime() if t-prev > 2 then prev = t self:Message(args.spellId, "blue", "Alarm", CL.underyou:format(args.spellName)) end end end end function mod:GrievousTearApplied(args) if self:Me(args.destGUID) then self:Flash(args.spellId) end self:TargetMessage(args.spellId, args.destName, "yellow") self:CDBar(args.spellId, 13) -- pull:5.7, 14.5, 13.3 / m pull:6.8, 15.5, 16.1, 15.3, 12.5, 14.3 end
-- -- Copyright 2010-2014 Branimir Karadzic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- project "geometryc" uuid "8794dc3a-2d57-11e2-ba18-368d09e48fda" kind "ConsoleApp" includedirs { BX_DIR .. "include", BGFX_DIR .. "include", BGFX_DIR .. "3rdparty/forsyth-too", BGFX_DIR .. "examples/common", } files { BGFX_DIR .. "3rdparty/forsyth-too/**.cpp", BGFX_DIR .. "3rdparty/forsyth-too/**.h", BGFX_DIR .. "src/vertexdecl.**", BGFX_DIR .. "tools/geometryc/**.cpp", BGFX_DIR .. "tools/geometryc/**.h", BGFX_DIR .. "examples/common/bounds.**", } configuration { "osx" } links { "Cocoa.framework", } strip()
---------------------------------------- -- -- Copyright (c) 2015, 128 Technology, Inc. -- -- author: Hadriel Kaplan <[email protected]> -- -- This code is licensed under the MIT license. -- -- Version: 1.0 -- ------------------------------------------ --[[ This script is a Lua module (not stand-alone) for handling proto files. This module follows the classic Lua module method of storing its public methods/functions in a table and passing back the table to the caller of this module file. ]]---------------------------------------- -- prevent wireshark loading this file as a plugin if not _G['protbuf_dissector'] then return end -- make sure wireshark is new enough if not GRegex then return nil, "Wireshark is too old: no GRegex library" end local Settings = require "settings" local dprint = Settings.dprint local dprint2 = Settings.dprint2 local dassert = Settings.dassert ---------------------------------------- -- our module table that we return to the caller of this script local FileReader = {} function FileReader:reset() self.results = {} end function FileReader:read(name) end local filepath_rgx = GRegex.new("^(.*)([^/\\\\]+)$", "U") -------------------------------------------------------------------------------- -- the public functions of the module -- returns a separated path and file name function FileReader:getPathFileNames(filename) return filepath_rgx:match(filename) end -- opens and reads a single filename, returns chunk function FileReader:loadFile(name) local file, err = io.open(name, "r") dassert(file, "Error opening file:", name, "\nError message:", err) local output, err2 = file:read("*all") dassert(output, "Error reading file:", name, "\nError message:", err2) file:close() -- remove carriage-return, so it's just linefeeds, and save it return string.gsub(output, "\r", "") end -- opens and reads the files identified in the filenames table -- returns a table of the string contents, indexed by filename -- with the string chunk in a "chunk" sub-table entry function FileReader:loadFiles(filenames) local proto_files = {} for _, name in ipairs(filenames) do local path, filename = self:getPathFileNames(name) dprint2("Got path=", path, "filename=", filename) dassert(filename, "Could not determine filename portion of:", name) dassert(not proto_files[filename], "Asked to read a filename that's already been read") proto_files[filename] = { chunk = self:loadFile(name), ["path"] = path } end return proto_files end return FileReader
-- http://stackoverflow.com/questions/12674345/lua-retrieve-list-of-keys-in-a-table local function keys(tbl) local n = 0 local keyset = {} for k,_ in pairs(tbl) do n = n + 1 keyset[n]=k end return keyset end return keys
---------------------------------------------------------- -- Load RayUI Environment ---------------------------------------------------------- RayUI:LoadEnv("Misc") local M = _Misc local mod = M:NewModule("ObjectiveTracker", "AceEvent-3.0") function mod:Initialize() local screenheight = GetScreenHeight() local ObjectiveTrackerFrameHolder = CreateFrame("Frame", "ObjectiveTrackerFrameHolder", R.UIParent) ObjectiveTrackerFrameHolder:SetWidth(260) ObjectiveTrackerFrameHolder:SetHeight(22) ObjectiveTrackerFrameHolder:SetPoint("RIGHT", R.UIParent, "RIGHT", -80, 290) R:CreateMover(ObjectiveTrackerFrameHolder, "WatchFrameMover", L["任务追踪锚点"], true) ObjectiveTrackerFrameHolder:SetAllPoints(WatchFrameMover) ObjectiveTrackerFrame:ClearAllPoints() ObjectiveTrackerFrame:SetPoint("TOPRIGHT", ObjectiveTrackerFrameHolder, "TOPRIGHT") ObjectiveTrackerFrame:Height(screenheight / 2) hooksecurefunc(ObjectiveTrackerFrame,"SetPoint",function(_,_,parent) if parent ~= ObjectiveTrackerFrameHolder then ObjectiveTrackerFrame:ClearAllPoints() ObjectiveTrackerFrame:SetPoint("TOPRIGHT", ObjectiveTrackerFrameHolder, "TOPRIGHT") end end) end M:RegisterMiscModule(mod:GetName())
----------------------------------- -- Area: Southern San d'Oria -- NPC: Maugie -- Type: General Info NPC ------------------------------------- local ID = require("scripts/zones/Southern_San_dOria/IDs") require("scripts/quests/flyers_for_regine") require("scripts/globals/settings") require("scripts/globals/quests") ------------------------------------- function onTrade(player, npc, trade) quests.ffr.onTrade(player, npc, trade, 12) -- FLYERS FOR REGINE end function onTrigger(player, npc) local grimySignpost = player:getQuestStatus(SANDORIA, tpz.quest.id.sandoria.GRIMY_SIGNPOSTS) if (grimySignpost == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 2) then player:startEvent(45) elseif (grimySignpost == QUEST_ACCEPTED) then if (player:getCharVar("CleanSignPost") == 15) then player:startEvent(44) else player:startEvent(43) end elseif (grimySignpost == QUEST_COMPLETED) then player:startEvent(42) else player:startEvent(46) -- default text end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 45 and option == 0) then player:addQuest(SANDORIA, tpz.quest.id.sandoria.GRIMY_SIGNPOSTS) elseif (csid == 44) then player:setCharVar("CleanSignPost", 0) player:addFame(SANDORIA, 30) player:addGil(GIL_RATE*1500) player:messageSpecial(ID.text.GIL_OBTAINED, GIL_RATE*1500) player:completeQuest(SANDORIA, tpz.quest.id.sandoria.GRIMY_SIGNPOSTS) end end
--[[ shuffles the playlist and moves the currently playing file to the start of the playlist available at: https://github.com/CogentRedTester/mpv-scripts ]]-- function main() mp.command('playlist-shuffle') local pos = mp.get_property_number('playlist-pos') mp.commandv('playlist-move', pos, 0) mp.osd_message('playlist shuffled') end mp.register_script_message('playlist-shuffle', main)
local skynet = require "skynet" local cluster = require "skynet.cluster" local log =require "skynet.log" skynet.start(function() log.info("Server start") local console_port = skynet.getenv("console_port") skynet.uniqueservice("debug_console",console_port) skynet.uniqueservice("static_data") skynet.uniqueservice("replay_cord") skynet.uniqueservice("mysql_pool") -- skynet.uniqueservice("redis_center") skynet.uniqueservice("agent_manager") skynet.exit() end)
local helpers = require "spec.helpers" local cjson = require "cjson" local client = require "resty.websocket.client" local PLUGIN_NAME = "connections-quota" local auth_key = "kong" local auth_key2 = "godzilla" local redis_host = helpers.redis_host local redis_port = 6379 local strategy = "postgres" describe("Websockets [#" .. strategy .. "]", function() local proxy_client lazy_setup(function() local bp = helpers.get_db_utils(strategy, { "routes", "services", "plugins", "consumers", "keyauth_credentials", }, { PLUGIN_NAME }) local service = bp.services:insert { name = "ws", path = "/ws", } bp.routes:insert { protocols = { "http" }, paths = { "/up-ws" }, service = service, strip_path = true, } local consumer = bp.consumers:insert { username = "bob" } bp.keyauth_credentials:insert { key = auth_key, consumer = { id = consumer.id }, } local consumer2 = bp.consumers:insert { username = "go" } bp.keyauth_credentials:insert { key = auth_key2, consumer = { id = consumer2.id }, } bp.plugins:insert { name = PLUGIN_NAME, consumer = { id = consumer.id }, config = { minute = 10, limit = 1, policy = "redis", redis_host = redis_host, redis_port = redis_port } } bp.plugins:insert { name = PLUGIN_NAME, consumer = { id = consumer2.id }, config = { limit = 1, policy = "redis", redis_host = redis_host, redis_port = redis_port } } bp.plugins:insert { name = "key-auth", service = { id = service.id }, config = { key_names = { "apikey", "Authorization", "X-Api-Key" }, hide_credentials = false, } } -- http route local route1 = bp.routes:insert { hosts = { "test1.com" }, } bp.plugins:insert { name = PLUGIN_NAME, route = { id = route1.id }, config = { limit = 1, policy = "redis", redis_host = redis_host, redis_port = redis_port } } assert(helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", plugins = "bundled," .. PLUGIN_NAME, })) end) lazy_teardown(function() helpers.stop_kong(nil, true) end) local function open_socket(uri, auth_key) local wc = assert(client:new()) assert(wc:connect(uri, { headers = { "apikey:" .. auth_key } })) return wc end before_each(function() proxy_client = helpers.proxy_client() end) after_each(function() if proxy_client then proxy_client:close() end end) it("no X-Concurrent-Quota headers in response for regular request", function() local res = proxy_client:get("/status/200", { headers = { Host = "test1.com" }, }) assert.res_status(200, res) assert.equal(nil, res.headers["X-Concurrent-Quota-Limit"]) assert.equal(nil, res.headers["X-Concurrent-Quota-Remaining"]) end) describe("text over ws", function() local function send_text_and_get_echo(uri) local payload = { message = "hello websocket" } local wc = open_socket(uri, auth_key) assert(wc:send_text(cjson.encode(payload))) local frame, typ, err = wc:recv_frame() assert.is_nil(wc.fatal) assert(frame, err) assert.equal("text", typ) assert.same(payload, cjson.decode(frame)) assert(wc:send_close()) end it("sends and gets text without Kong", function() send_text_and_get_echo("ws://127.0.0.1:15555/ws") end) it("sends and gets text with Kong", function() send_text_and_get_echo("ws://" .. helpers.get_proxy_ip(false) .. ":" .. helpers.get_proxy_port(false) .. "/up-ws") end) it("sends and gets text with kong under HTTPS", function() send_text_and_get_echo("wss://" .. helpers.get_proxy_ip(true) .. ":" .. helpers.get_proxy_port(true) .. "/up-ws") end) end) describe("ping pong over ws", function() local function send_ping_and_get_pong(uri) local payload = { message = "give me a pong" } local wc = open_socket(uri, auth_key) assert(wc:send_ping(cjson.encode(payload))) local frame, typ, err = wc:recv_frame() assert.is_nil(wc.fatal) assert(frame, err) assert.equal("pong", typ) assert.same(payload, cjson.decode(frame)) assert(wc:send_close()) end it("plays ping-pong without Kong", function() send_ping_and_get_pong("ws://127.0.0.1:15555/ws") end) it("plays ping-pong with Kong", function() send_ping_and_get_pong("ws://" .. helpers.get_proxy_ip(false) .. ":" .. helpers.get_proxy_port(false) .. "/up-ws") end) it("plays ping-pong with kong under HTTPS", function() send_ping_and_get_pong("wss://" .. helpers.get_proxy_ip(true) .. ":" .. helpers.get_proxy_port(true) .. "/up-ws") end) end) describe("multiple users", function() it("has own quota", function() local payload = { message = "give me a pong" } local uri = "ws://" .. helpers.get_proxy_ip(false) .. ":" .. helpers.get_proxy_port(false) .. "/up-ws" local wc1 = open_socket(uri, auth_key) local wc2 = open_socket(uri, auth_key2) assert(wc1:send_ping(cjson.encode(payload))) local frame, typ, err = wc1:recv_frame() assert.is_nil(wc1.fatal) assert(frame, err) assert.equal("pong", typ) assert(wc2:send_ping(cjson.encode(payload))) frame, typ, err = wc2:recv_frame() assert.is_nil(wc1.fatal) assert(frame, err) assert.equal("pong", typ) wc1:close() wc2:close() end) end) -- NOTE: there is no way to get response headers on websocket connection describe("quota used", function() it("send 429 error code", function() local payload = { message = "give me a pong" } local uri = "ws://" .. helpers.get_proxy_ip(false) .. ":" .. helpers.get_proxy_port(false) .. "/up-ws" local wc1 = open_socket(uri, auth_key) local wc2 = open_socket(uri, auth_key) assert(wc1:send_ping(cjson.encode(payload))) local frame, typ, err = wc1:recv_frame() assert.is_nil(wc1.fatal) assert(frame, err) assert.equal("pong", typ) assert(wc2:send_ping(cjson.encode(payload))) wc2:recv_frame() assert.is_not_nil(wc2.fatal) wc1:close() wc2:close() wc1 = open_socket(uri, auth_key) assert(wc1:send_ping(cjson.encode(payload))) local frame, typ, err = wc1:recv_frame() assert.is_nil(wc1.fatal) assert(frame, err) assert.equal("pong", typ) wc1:close() end) it("send 429 error code under HTTPS", function() local payload = { message = "give me a pong" } local uri = "wss://" .. helpers.get_proxy_ip(true) .. ":" .. helpers.get_proxy_port(true) .. "/up-ws" local wc1 = open_socket(uri, auth_key) local wc2 = open_socket(uri, auth_key) assert(wc1:send_ping(cjson.encode(payload))) local frame, typ, err = wc1:recv_frame() assert.is_nil(wc1.fatal) assert(frame, err) assert.equal("pong", typ) assert(wc2:send_ping(cjson.encode(payload))) wc2:recv_frame() assert.is_not_nil(wc2.fatal) wc1:close() wc2:close() end) end) end)
object_tangible_quest_legacy_valarian_pallet4_datapad = object_tangible_quest_shared_legacy_valarian_pallet4_datapad:new { } ObjectTemplates:addTemplate(object_tangible_quest_legacy_valarian_pallet4_datapad, "object/tangible/quest/legacy_valarian_pallet4_datapad.iff")
mobs:register_mob("dmobs:badger", { type = "animal", passive = false, reach = 1, damage = 2, attack_type = "dogfight", hp_min = 12, hp_max = 22, armor = 130, collisionbox = {-0.3, -0.15, -0.3, 0.3, 0.4, 0.3}, visual = "mesh", mesh = "badger.b3d", textures = { {"dmobs_badger.png"}, }, blood_texture = "mobs_blood.png", visual_size = {x=2, y=2}, makes_footstep_sound = true, walk_velocity = 0.7, run_velocity = 1, jump = true, drops = { {name = "mobs:meat_raw", chance = 1, min = 1, max = 1}, }, water_damage = 0, lava_damage = 2, fire_damage = 2, light_damage = 0, fall_damage = 1, fall_speed = -8, fear_height = 4, follow = {"mobs:meat_raw"}, view_range = 14, animation = { speed_normal = 12, speed_run = 18, walk_start = 34, walk_end = 58, stand_start = 1, stand_end = 30, run_start = 34, run_end = 58, punch_start = 60, punch_end = 80, }, on_rightclick = function(self, clicker) if mobs:feed_tame(self, clicker, 8, true, true) then return end mobs:capture_mob(self, clicker, 0, 5, 50, false, nil) end, }) mobs:register_egg("dmobs:badger", "Badger", "default_obsidian.png", 1)
function table.clone(org) return {unpack(org)} end function Event () local state = { listeners = {} } local api = { debug = false } local function listen (fn) if api.debug then DebugPrint('Adding listener') end local handler = { fn = fn, removed = false } table.insert(state.listeners, handler) local function unlisten () for index = 1,#state.listeners do if state.listeners[index] == handler then table.remove(state.listeners, index) handler.removed = true return end end end return unlisten end local function broadcast ( ... ) if api.debug then DebugPrint('Triggering ' .. #state.listeners .. ' listener') end if #state.listeners == 0 then return end local handlers = table.clone(state.listeners) local data = {...} local errors = {} for index = 1,#handlers do local handler = handlers[index] if handler and not handler.removed then local status, err = pcall(function () handler.fn(unpack(data)) end) if err then print(err) table.insert(errors, err) end end end for index = 1,#errors do -- this will throw and not print any of the others, but whatever error(errors[index]) end end api.broadcast = broadcast api.listen = listen return api end
SellOrnateItems = {} SellOrnateItems.name = "SellOrnateItems" function SellOrnateItems:Initialize() EVENT_MANAGER:RegisterForEvent(self.name, EVENT_OPEN_STORE, self.OnVendorOpen) EVENT_MANAGER:RegisterForEvent(self.name, EVENT_CLOSE_STORE, self.OnVendorClose) end function SellOrnateItems.OnAddOnLoaded(event, addonName) if addonName == SellOrnateItems.name then SellOrnateItems:Initialize() SellOrnateItemsIndicator:SetHidden(true) end end function SellOrnateItems.OnVendorOpen(event) SellOrnateItemsIndicator:SetHidden(false) end function SellOrnateItems.OnVendorClose(event) SellOrnateItemsIndicator:SetHidden(true) end function SellOrnateItems.SellTrash() local slotId = 0 local bagsize = GetBagSize(1) local totalAmount = 0 local itemCount = 0 local goldIcon = ZO_Currency_GetPlatformFormattedGoldIcon() for slotId = 0,bagsize do if GetItemTrait(1,slotId)==ITEM_TRAIT_TYPE_ARMOR_ORNATE or GetItemTrait(1,slotId)==ITEM_TRAIT_TYPE_WEAPON_ORNATE or GetString("SI_ITEMTRAITTYPE",GetItemTrait(1,slotId))=="Ornate" then SellInventoryItem(1,slotId,1) local value = GetItemSellValueWithBonuses(1,slotId) totalAmount = totalAmount + value itemCount = itemCount + 1 d("Sold: " .. GetItemLink(1,slotId,1) .. " for " .. value .. goldIcon) end end d("Sold " .. itemCount .. " items for a total of " .. totalAmount .. goldIcon) end EVENT_MANAGER:RegisterForEvent(SellOrnateItems.name, EVENT_ADD_ON_LOADED, SellOrnateItems.OnAddOnLoaded)
---@meta ---@class cc.ShuffleTiles :cc.TiledGrid3DAction local ShuffleTiles={ } cc.ShuffleTiles=ShuffleTiles ---* brief Initializes the action with grid size, random seed and duration.<br> ---* param duration Specify the duration of the ShuffleTiles action. It's a value in seconds.<br> ---* param gridSize Specify the size of the grid.<br> ---* param seed Specify the random seed.<br> ---* return If the Initialization success, return true; otherwise, return false. ---@param duration float ---@param gridSize size_table ---@param seed unsigned_int ---@return boolean function ShuffleTiles:initWithDuration (duration,gridSize,seed) end ---* ---@param pos size_table ---@return size_table function ShuffleTiles:getDelta (pos) end ---* brief Create the action with grid size, random seed and duration.<br> ---* param duration Specify the duration of the ShuffleTiles action. It's a value in seconds.<br> ---* param gridSize Specify the size of the grid.<br> ---* param seed Specify the random seed.<br> ---* return If the creation success, return a pointer of ShuffleTiles action; otherwise, return nil. ---@param duration float ---@param gridSize size_table ---@param seed unsigned_int ---@return self function ShuffleTiles:create (duration,gridSize,seed) end ---* ---@param target cc.Node ---@return self function ShuffleTiles:startWithTarget (target) end ---* ---@return self function ShuffleTiles:clone () end ---* ---@param time float ---@return self function ShuffleTiles:update (time) end ---* ---@return self function ShuffleTiles:ShuffleTiles () end
-- // Libraries local Library = loadstring(game:HttpGet("https://raw.githubusercontent.com/wally-rblx/uwuware-ui/main/main.lua"))() local EspLibrary = loadstring(game:HttpGet("https://kiriot22.com/releases/ESP.lua"))() -- // Destroy excess GUIS for _, v in ipairs(game.CoreGui:GetChildren()) do if v.Name == "ScreenGui" then v:Destroy() end end -- // Services local players = game:GetService("Players") local runService = game:GetService("RunService") -- // Variables local localPlayer = players.LocalPlayer local playerChar = localPlayer.Character or localPlayer.Character:Wait() -- // UI Components local window = Library:CreateWindow("Floppa Hub - SD") local mainFolder = window:AddFolder("Main") do mainFolder:AddToggle( { text = "No Rocket Cooldown", flag = "rocketCool", callback = function() local m = require(game:GetService("ReplicatedStorage").Shared.Data.WeaponConstants) for k, v in pairs(m) do if string.find(k, "RELOAD_TIME") and type(v) == "function" then print "Ass" local upval = debug.getupvalues(v) for a, val in pairs(upval) do print(a, val) debug.setupvalue(v, 3, Library.flags.rocketCool and 0.00001 or 6) end end end end } ) mainFolder:AddToggle( { text = "Super Lunge", flag = "superLunge", callback = function() local m = require(game:GetService("StarterPlayer").StarterPlayerScripts.ToolBehaviors.Sword) local upval = debug.getupvalues(m.lunge) for valIdx, val in pairs(upval) do print("INDEX: ", valIdx, "| VALUE: ", val) end debug.setupvalue(m.lunge, 2, Library.flags.superLunge and 0.00001 or 2) end } ) end Library:Init()
-- add your own keymappings here local M = {} M.config = function() lvim.keys.normal_mode["<C-s>"] = ":w<cr>" -- unmap a default keymapping -- lvim.keys.normal_mode["<C-Up>"] = false -- edit a default keymapping -- lvim.keys.normal_mode["<C-q>"] = ":q<cr>" -- or this style... lvim.keys.normal_mode = { -- Page down/up -- ["[d"] = "<PageUp>", -- ["]d"] = "<PageDown>", -- gwap (as opposed to gqap) reflows and restores cursor position ["<M-q>"] = "gwap", -- Navigate buffers ["<Tab>"] = ":bnext<CR>", ["<S-Tab>"] = ":bprevious<CR>", } -- Change Telescope navigation to use j and k for navigation and n and p for history in both input and normal mode. -- we use protected-mode (pcall) just in case the plugin wasn't loaded yet. -- local _, actions = pcall(require, "telescope.actions") -- lvim.builtin.telescope.defaults.mappings = { -- -- for input mode -- i = { -- ["<C-j>"] = actions.move_selection_next, -- ["<C-k>"] = actions.move_selection_previous, -- ["<C-n>"] = actions.cycle_history_next, -- ["<C-p>"] = actions.cycle_history_prev, -- }, -- -- for normal mode -- n = { -- ["<C-j>"] = actions.move_selection_next, -- ["<C-k>"] = actions.move_selection_previous, -- }, -- } -- Use which-key to add extra bindings with the leader-key prefix -- lvim.builtin.which_key.mappings["P"] = { "<cmd>Telescope projects<CR>", "Projects" } -- lvim.builtin.which_key.mappings["t"] = { -- name = "+Trouble", -- r = { "<cmd>Trouble lsp_references<cr>", "References" }, -- f = { "<cmd>Trouble lsp_definitions<cr>", "Definitions" }, -- d = { "<cmd>Trouble document_diagnostics<cr>", "Diagnostics" }, -- q = { "<cmd>Trouble quickfix<cr>", "QuickFix" }, -- l = { "<cmd>Trouble loclist<cr>", "LocationList" }, -- w = { "<cmd>Trouble workspace_diagnostics<cr>", "Wordspace Diagnostics" }, -- } end return M
GLib.Resources.ResourceState = GLib.Enum ( { Available = 1, -- Available locally (may have been received from the server) Unknown = 2, -- Not available locally, may be in cache, request needs to be sent to server Requested = 3, -- Requested from server, waiting for response Unavailable = 4, -- Server does not have the resource Receiving = 5 -- Server is sending the resource to us } )
----------------------------------- -- Area: Attohwa Chasm -- NPC: Cradle_of_Rebirth ----------------------------------- local ID = require("scripts/zones/Attohwa_Chasm/IDs") require("scripts/globals/settings") require("scripts/globals/keyitems") ----------------------------------- function onTrade(player, npc, trade) -- Trade Flaxen Pouch if (trade:hasItemQty(1777, 1) and trade:getItemCount() == 1) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, 1778) -- Parradamo Stones else player:tradeComplete() player:addItem(1778) player:messageSpecial(ID.text.ITEM_OBTAINED, 1778) -- Parradamo Stones end end end function onTrigger(player, npc) if (player:hasKeyItem(tpz.ki.MIMEO_JEWEL) == true) then player:delKeyItem(tpz.ki.MIMEO_JEWEL) player:messageSpecial(ID.text.KEYITEM_LOST, tpz.ki.MIMEO_JEWEL) player:addKeyItem(tpz.ki.MIMEO_FEATHER) player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.MIMEO_FEATHER) player:addKeyItem(tpz.ki.SECOND_MIMEO_FEATHER) player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.SECOND_MIMEO_FEATHER) player:addKeyItem(tpz.ki.THIRD_MIMEO_FEATHER) player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.THIRD_MIMEO_FEATHER) else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
SCONFIG = L2TConfig.GetConfig(); SCONFIG_FILE = GetDir() .. '\\scripts\\giranToDion.l2b'; L2TConfig.SaveConfig(SCONFIG_FILE); moveDistance = 30; TargetNpc("Кларисса", 30080); MoveTo(83378, 147935, -3406, moveDistance); Talk(); ClickAndWait("teleport_request", "Teleport"); ClickAndWait("teleport_3547261648_2_57_1209030033_3", "1010006"); WaitForTeleport(); MoveTo(15477, 142875, -2702, moveDistance); Target("djoo1"); MoveTo(15474, 142931, -2701, moveDistance); MoveTo(15518, 143041, -2702, moveDistance); MoveTo(15480, 143024, -2699, moveDistance); L2TConfig.LoadConfig(SCONFIG_FILE);
OBJECT.Name = "Bridge" OBJECT.Creator = "Robin Wellner" OBJECT.Version = 0.0 OBJECT.Resources = { texture = "snakeface/longblock" } OBJECT.TextureScale = { x = 1 , y = 1} OBJECT.Static = false OBJECT.Polygon = { {-1.4, -.4, -1.4, .4, 1.4, .4, 1.4, -.4} } function OBJECT:collision(a) end
--------------------------------------------- -- Arrow Deluge -- Description: Delivers a threefold ranged attack to targets in an area of effect. -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: Unknown --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target, mob, skill) if mob:getMainJob() == tpz.job.RNG then return 0 else return 1 end end function onMobWeaponSkill(target, mob, skill) local numhits = 1 local accmod = 1 local dmgmod = 2 local info = MobPhysicalMove(mob, target, skill, numhits, accmod, dmgmod, TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg, mob, skill, target, tpz.attackType.RANGED, tpz.damageType.PIERCING, MOBPARAM_3_SHADOW) target:takeDamage(dmg, mob, tpz.attackType.RANGED, tpz.damageType.PIERCING) return dmg end
-------------------------------- -- @module TiledGrid3D -- @extend GridBase -- @parent_module cc -------------------------------- -- overload function: create(size_table) -- -- overload function: create(size_table, cc.Texture2D, bool) -- -- @function [parent=#TiledGrid3D] create -- @param self -- @param #size_table size -- @param #cc.Texture2D texture2d -- @param #bool bool -- @return TiledGrid3D#TiledGrid3D ret (retunr value: cc.TiledGrid3D) -------------------------------- -- @function [parent=#TiledGrid3D] calculateVertexPoints -- @param self -------------------------------- -- @function [parent=#TiledGrid3D] blit -- @param self -------------------------------- -- @function [parent=#TiledGrid3D] reuse -- @param self -------------------------------- -- @function [parent=#TiledGrid3D] TiledGrid3D -- @param self return nil
--[[-------------------------------------------------------------------]]--[[ Copyright wiltOS Technologies LLC, 2020 Contact: www.wiltostech.com ----------------------------------------]]-- wOS = wOS or {} wOS.ForcePowers:RegisterNewPower({ name = "Saut De Force", icon = "L", image = "wos/forceicons/leap.png", cooldown = 2, manualaim = false, description = "Sautez plus haut et plus loin grâce à la Force.", action = function( self ) if ( self:GetForce() < 10 || !self.Owner:IsOnGround() ) then return end self:SetForce( self:GetForce() - 10 ) self:SetNextAttack( 0.5 ) self.Owner:SetVelocity( self.Owner:GetAimVector() * 512 + Vector( 0, 0, 512 ) ) self:PlayWeaponSound( "lightsaber/force_leap.wav" ) // Trigger the jump animation, yay self:CallOnClient( "ForceJumpAnim", "" ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Charge", icon = "CH", distance = 600, image = "wos/forceicons/charge.png", target = 1, cooldown = 0, manualaim = false, description = "Foncez sur votre ennemis.", action = function( self ) local ent = self:SelectTargets( 1, 600 )[ 1 ] if !IsValid( ent ) then self:SetNextAttack( 0.2 ) return end if ( self:GetForce() < 20 ) then self:SetNextAttack( 0.2 ) return end local newpos = ( ent:GetPos() - self.Owner:GetPos() ) newpos = newpos / newpos:Length() self.Owner:SetLocalVelocity( newpos*700 + Vector( 0, 0, 300 ) ) self:SetForce( self:GetForce() - 20 ) self:PlayWeaponSound( "lightsaber/force_leap.wav" ) self.Owner:SetSequenceOverride( "phalanx_a_s2_t1", 5 ) self:SetNextAttack( 1 ) self.AerialLand = true return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Absorption De Force", icon = "A", image = "wos/forceicons/eshell.png", cooldown = 0, description = "Maintenez Click Droit pour vous protéger.", action = function( self ) if ( self:GetForce() < 1 ) then return end self:SetForce( self:GetForce() - 0.1 ) self.Owner:SetNW2Float( "wOS.ForceAnim", CurTime() + 0.6 ) self:SetNextAttack( 0.3 ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Lancée De Sabre", icon = "T", image = "wos/forceicons/throw.png", cooldown = 0, manualaim = false, description = "Envoie votre sabre laser qui reviendra vers vous.", action = function(self) if self:GetForce() < 20 then return end self:SetForce( self:GetForce() - 20 ) self:SetEnabled(false) self:SetBladeLength(0) self:SetNextAttack( 1 ) self:GetOwner():DrawWorldModel(false) local ent = ents.Create("ent_lightsaber_thrown") ent:SetModel(self:GetWorldModel()) ent:Spawn() ent.CustomSettings = table.Copy( self.CustomSettings ) ent:SetBladeLength(self:GetMaxLength()) ent:SetMaxLength(self:GetMaxLength()) ent:SetBladeWidth( self:GetBladeWidth() ) ent:SetCrystalColor(self:GetCrystalColor()) ent:SetInnerColor( self:GetInnerColor() ) ent:SetDarkInner( self:GetDarkInner() ) ent:SetWorldModel( self:GetWorldModel() ) ent.SaberThrowDamage = self.SaberThrowDamage local pos = self:GetSaberPosAng() ent:SetPos(pos) pos = pos + self.Owner:GetAimVector() * 750 ent:SetEndPos(pos) ent:SetOwner(self.Owner) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Soin De Force", icon = "H", image = "wos/forceicons/heal.png", cooldown = 0, target = 1, manualaim = false, description = "Soigne votre cible.", action = function( self ) if ( self:GetForce() < 10 ) then return end local foundents = 0 for k, v in pairs( self:SelectTargets( 1 ) ) do if ( !IsValid( v ) ) then continue end foundents = foundents + 1 local ed = EffectData() ed:SetOrigin( self:GetSaberPosAng() ) ed:SetEntity( v ) util.Effect( "rb655_force_heal", ed, true, true ) v:SetHealth( math.Clamp( v:Health() + 25, 0, v:GetMaxHealth() ) ) end if ( foundents > 0 ) then self:SetForce( self:GetForce() - 3 ) local tbl = wOS.ALCS.Config.Skills.ExperienceTable[ self.Owner:GetUserGroup() ] if not tbl then tbl = wOS.ALCS.Config.Skills.ExperienceTable[ "Default" ].XPPerHeal else tbl = wOS.ALCS.Config.Skills.ExperienceTable[ self.Owner:GetUserGroup() ].XPPerHeal end self.Owner:AddSkillXP( tbl ) end self.Owner:SetNW2Float( "wOS.ForceAnim", CurTime() + 0.5 ) self:SetNextAttack( 0.25 ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Soin De Groupe", icon = "GH", image = "wos/forceicons/group_heal.png", cooldown = 0, manualaim = false, description = "Soigne les personnes autour de vous et vous-même.", action = function( self ) if ( self:GetForce() < 75 ) then return end local players = 0 for _, ply in pairs( ents.FindInSphere( self.Owner:GetPos(), 200 ) ) do if not IsValid( ply ) then continue end if not ply:IsPlayer() then continue end if not ply:Alive() then continue end if players >= 8 then break end ply:SetHealth( math.Clamp( ply:Health() + 500, 0, ply:GetMaxHealth() ) ) local ed = EffectData() ed:SetOrigin( self:GetSaberPosAng() ) ed:SetEntity( ply ) util.Effect( "rb655_force_heal", ed, true, true ) players = players + 1 end self.Owner:SetNW2Float( "wOS.ForceAnim", CurTime() + 0.6 ) self:SetForce( self:GetForce() - 75 ) local tbl = wOS.ALCS.Config.Skills.ExperienceTable[ self.Owner:GetUserGroup() ] if not tbl then tbl = wOS.ALCS.Config.Skills.ExperienceTable[ "Default" ].XPPerHeal else tbl = wOS.ALCS.Config.Skills.ExperienceTable[ self.Owner:GetUserGroup() ].XPPerHeal end self.Owner:AddSkillXP( tbl ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Invisibilité", icon = "C", image = "wos/forceicons/cloak.png", cooldown = 0, description = "Vous rend invisible pendant 15 secondes.", action = function( self ) if ( self:GetForce() < 50 || !self.Owner:IsOnGround() ) then return end if self:GetCloaking() then return end self:SetForce( self:GetForce() - 50 ) self:SetNextAttack( 0.7 ) self:PlayWeaponSound( "lightsaber/force_leap.wav" ) self.CloakTime = CurTime() + 15 self.Owner:SetNoTarget( true ) local stean = self.Owner:SteamID64() local ply = self.Owner if timer.Exists( "ALCS_CLOAK_" .. stean ) then timer.Destroy( "ALCS_CLOAK_" .. stean ) end timer.Create( "ALCS_CLOAK_" .. stean, 0.5, 20, function() if not IsValid( ply ) then timer.Destroy( "ALCS_CLOAK_" .. stean ) end if not IsValid( self ) or not ply:Alive() or self.CloakTime < CurTime() then timer.Destroy( "ALCS_CLOAK_" .. stean ) ply:SetNoTarget( false ) end ply:SetNoTarget( ply:GetActiveWeapon() == self ) end ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Réflexion de Force", icon = "FR", image = "wos/forceicons/reflect.png", cooldown = 0, description = "Renvoie toutes les attaques de votre adversaire", action = function( self ) if ( self:GetForce() < 50 || !self.Owner:IsOnGround() ) then return end if self.Owner:GetNW2Float( "ReflectTime", 0 ) >= CurTime() then return end self:SetForce( self:GetForce() - 50 ) self:SetNextAttack( 0.7 ) self:PlayWeaponSound( "lightsaber/force_leap.wav" ) self.Owner:SetNW2Float( "ReflectTime", CurTime() + 2 ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Rage", icon = "RA", image = "wos/forceicons/icefuse/adrenaline.png", cooldown = 0, description = "Augmente vos dégats en libérant votre rage", action = function( self ) if ( self:GetForce() < 50 || !self.Owner:IsOnGround() ) then return end if self.Owner:GetNW2Float( "RageTime", 0 ) >= CurTime() then return end self:SetForce( self:GetForce() - 50 ) self:SetNextAttack( 0.7 ) self:PlayWeaponSound( "lightsaber/force_leap.wav" ) self.Owner:SetNW2Float( "RageTime", CurTime() + 10 ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Frappe De l'Ombre", icon = "SS", distance = 30, image = "wos/forceicons/cripple.png", cooldown = 0, target = 1, manualaim = false, description = "Assène un coup puissant en visant les points vitaux de l'ennemis tout en étant invisible", action = function( self ) if !self:GetCloaking() then return end local ent = self:SelectTargets( 1, 30 )[ 1 ] if !IsValid( ent ) then self:SetNextAttack( 0.2 ) return end if ( self:GetForce() < 50 ) then self:SetNextAttack( 0.2 ) return end self.Owner:SetSequenceOverride("b_c3_t2", 1) self:SetForce( self:GetForce() - 50 ) self.Owner:EmitSound( "lightsaber/saber_hit_laser" .. math.random( 1, 4 ) .. ".wav" ) self.Owner:AnimResetGestureSlot( GESTURE_SLOT_CUSTOM ) self.Owner:SetAnimation( PLAYER_ATTACK1 ) ent:TakeDamage( 500, self.Owner, self ) self.CloakTime = CurTime() + 0.5 self:SetNextAttack( 0.7 ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Attraction De Force", icon = "PL", target = 1, description = "Ramène la cible vers vous", image = "wos/forceicons/pull.png", cooldown = 0, manualaim = false, action = function( self ) if ( self:GetForce() < 20 ) then return end local ent = self:SelectTargets( 1 )[ 1 ] if not IsValid( ent ) then return end self:PlayWeaponSound( "lightsaber/force_repulse.wav" ) local newpos = ( self.Owner:GetPos() - ent:GetPos() ) newpos = newpos / newpos:Length() ent:SetVelocity( newpos*700 + Vector( 0, 0, 300 ) ) self:SetForce( self:GetForce() - 20 ) self.Owner:SetNW2Float( "wOS.ForceAnim", CurTime() + 0.3 ) self:SetNextAttack( 1.5 ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Poussée De Force", icon = "PH", target = 1, distance = 150, description = "Pousse l'ennemis avec la Force", image = "wos/forceicons/push.png", cooldown = 0, manualaim = false, action = function( self ) if ( self:GetForce() < 20 ) then return end local ent = self:SelectTargets( 1 )[ 1 ] if not IsValid( ent ) then return end self:PlayWeaponSound( "lightsaber/force_repulse.wav" ) local newpos = ( self.Owner:GetPos() - ent:GetPos() ) newpos = newpos / newpos:Length() ent:SetVelocity( newpos*-700 + Vector( 0, 0, 300 ) ) self:SetForce( self:GetForce() - 20 ) self.Owner:SetNW2Float( "wOS.ForceAnim", CurTime() + 0.3 ) self:SetNextAttack( 1.5 ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Frappe D'Éclair", icon = "LS", distance = 600, image = "wos/forceicons/lightningstrike.png", cooldown = 0, target = 1, manualaim = false, description = "Une charge d'éclair concentrée puissante", action = function( self ) local ent = self:SelectTargets( 1, 600 )[ 1 ] if !IsValid( ent ) then self:SetNextAttack( 0.2 ) return end if ( self:GetForce() < 20 ) then self:SetNextAttack( 0.2 ) return end self:SetForce( self:GetForce() - 20 ) local ed = EffectData() ed:SetOrigin( self:GetSaberPosAng() ) ed:SetEntity( ent ) util.Effect( "rb655_force_lighting", ed, true, true ) local dmg = DamageInfo() dmg:SetAttacker( self.Owner || self ) dmg:SetInflictor( self.Owner || self ) dmg:SetDamage( 150 ) ent:TakeDamageInfo( dmg ) self.Owner:EmitSound( Sound( "npc/strider/fire.wav" ) ) self.Owner:EmitSound( Sound( "ambient/atmosphere/thunder1.wav" ) ) if ( !self.SoundLightning ) then self.SoundLightning = CreateSound( self.Owner, "lightsaber/force_lightning" .. math.random( 1, 2 ) .. ".wav" ) self.SoundLightning:Play() else self.SoundLightning:Play() end local bullet = {} bullet.Num = 1 bullet.Src = self.Owner:GetPos() + Vector( 0, 0, 10 ) bullet.Dir = ( ent:GetPos() - ( self.Owner:GetPos() + Vector( 0, 0, 10 ) ) ) bullet.Spread = 0 bullet.Tracer = 1 bullet.Force = 0 bullet.Damage = 0 bullet.AmmoType = "Pistol" bullet.Entity = self.Owner bullet.TracerName = "thor_thunder" self:SetNextAttack( 2 ) self.Owner:FireBullets( bullet ) timer.Create( "test" .. self:EntIndex(), 0.2, 1, function() if ( self.SoundLightning ) then self.SoundLightning:Stop() self.SoundLightning = nil end end ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Invisibilté avancé", icon = "AC", image = "wos/forceicons/advanced_cloak.png", cooldown = 0, manualaim = false, description = "Shrowd yourself with the force for 25 seconds", action = function( self ) if ( self:GetForce() < 50 || !self.Owner:IsOnGround() ) then return end if self:GetCloaking() then return end self:SetForce( self:GetForce() - 50 ) self:SetNextAttack( 0.7 ) self:PlayWeaponSound( "lightsaber/force_leap.wav" ) self.CloakTime = CurTime() + 45 self.Owner:SetNoTarget( true ) local stean = self.Owner:SteamID64() local ply = self.Owner if timer.Exists( "ALCS_CLOAK_" .. stean ) then timer.Destroy( "ALCS_CLOAK_" .. stean ) end timer.Create( "ALCS_CLOAK_" .. stean, 0.5, 50, function() if not IsValid( ply ) then timer.Destroy( "ALCS_CLOAK_" .. stean ) end if not IsValid( self ) or not ply:Alive() or self.CloakTime < CurTime() then timer.Destroy( "ALCS_CLOAK_" .. stean ) ply:SetNoTarget( false ) end ply:SetNoTarget( ply:GetActiveWeapon() == self ) end ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Éclair De Force", icon = "L", target = 1, image = "wos/forceicons/lightning.png", cooldown = 0, manualaim = false, description = "Torture les personnes et monstres à volonté.", action = function( self ) if ( self:GetForce() < 1 ) then return end local foundents = 0 for id, ent in pairs( self:SelectTargets( 1 ) ) do if ( !IsValid( ent ) ) then continue end foundents = foundents + 1 local ed = EffectData() ed:SetOrigin( self:GetSaberPosAng() ) ed:SetEntity( ent ) util.Effect( "rb655_force_lighting", ed, true, true ) local dmg = DamageInfo() dmg:SetAttacker( self.Owner || self ) dmg:SetInflictor( self.Owner || self ) dmg:SetDamage( 8 ) local wep = ent:GetActiveWeapon() if IsValid( wep ) and wep.IsLightsaber and wep:GetBlocking() then ent:EmitSound( "lightsaber/saber_hit_laser" .. math.random( 1, 4 ) .. ".wav" ) if wOS.ALCS.Config.EnableStamina then wep:AddStamina( -5 ) else wep:SetForce( wep:GetForce() - 1 ) end ent:SetSequenceOverride( "h_block", 0.5 ) else if ent:IsNPC() then dmg:SetDamage( 1.6 ) end ent:TakeDamageInfo( dmg ) end end if ( foundents > 0 ) then self:SetForce( self:GetForce() - foundents ) if ( !self.SoundLightning ) then self.SoundLightning = CreateSound( self.Owner, "lightsaber/force_lightning" .. math.random( 1, 2 ) .. ".wav" ) self.SoundLightning:Play() else self.SoundLightning:Play() end timer.Create( "test" .. self:EntIndex(), 0.2, 1, function() if ( self.SoundLightning ) then self.SoundLightning:Stop() self.SoundLightning = nil end end ) end self:SetNextAttack( 0.1 ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Combustion De Force", icon = "C", target = 1, description = "Enflamme les choses devant vous.", image = "wos/forceicons/combust.png", cooldown = 0, manualaim = false, action = function( self ) local ent = self:SelectTargets( 1 )[ 1 ] if ( !IsValid( ent ) or ent:IsOnFire() ) then self:SetNextAttack( 0.2 ) return end local time = math.Clamp( 512 / self.Owner:GetPos():Distance( ent:GetPos() ), 1, 16 ) local neededForce = math.ceil( math.Clamp( time * 2, 10, 32 ) ) if ( self:GetForce() < neededForce ) then self:SetNextAttack( 0.2 ) return end ent:Ignite( time, 0 ) self:SetForce( self:GetForce() - neededForce ) self:SetNextAttack( 1 ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Répulsion De Force", icon = "R", image = "wos/forceicons/repulse.png", description = "Maintenir pour une meilleur distance/dégats. Pousse tout ce qu'il y a autour de vous.", think = function( self ) if ( self:GetNextSecondaryFire() > CurTime() ) then return end if ( self:GetForce() < 1 ) then return end if ( !self.Owner:KeyDown( IN_ATTACK2 ) && !self.Owner:KeyReleased( IN_ATTACK2 ) ) then return end if ( !self._ForceRepulse && self:GetForce() < 16 ) then return end if ( !self.Owner:KeyReleased( IN_ATTACK2 ) ) then if ( !self._ForceRepulse ) then self:SetForce( self:GetForce() - 16 ) self._ForceRepulse = 1 end if ( !self.NextForceEffect or self.NextForceEffect < CurTime() ) then local ed = EffectData() ed:SetOrigin( self.Owner:GetPos() + Vector( 0, 0, 36 ) ) ed:SetRadius( 128 * self._ForceRepulse ) util.Effect( "rb655_force_repulse_in", ed, true, true ) self.NextForceEffect = CurTime() + math.Clamp( self._ForceRepulse / 20, 0.1, 0.5 ) end self._ForceRepulse = self._ForceRepulse + 0.025 self:SetForce( self:GetForce() - 0.5 ) if ( self:GetForce() > 0.99 ) then return end else if ( !self._ForceRepulse ) then return end end local maxdist = 128 * self._ForceRepulse for i, e in pairs( ents.FindInSphere( self.Owner:GetPos(), maxdist ) ) do if ( e == self.Owner ) then continue end local dist = self.Owner:GetPos():Distance( e:GetPos() ) local mul = ( maxdist - dist ) / 256 local v = ( self.Owner:GetPos() - e:GetPos() ):GetNormalized() v.z = 0 if ( e:IsNPC() && util.IsValidRagdoll( e:GetModel() or "" ) ) then local dmg = DamageInfo() dmg:SetDamagePosition( e:GetPos() + e:OBBCenter() ) dmg:SetDamage( 48 * mul ) dmg:SetDamageType( DMG_GENERIC ) if ( ( 1 - dist / maxdist ) > 0.8 ) then dmg:SetDamageType( DMG_DISSOLVE ) dmg:SetDamage( e:Health() * 3 ) end dmg:SetDamageForce( -v * math.min( mul * 40000, 80000 ) ) dmg:SetInflictor( self.Owner ) dmg:SetAttacker( self.Owner ) e:TakeDamageInfo( dmg ) if ( e:IsOnGround() ) then e:SetVelocity( v * mul * -2048 + Vector( 0, 0, 64 ) ) elseif ( !e:IsOnGround() ) then e:SetVelocity( v * mul * -1024 + Vector( 0, 0, 64 ) ) end elseif ( e:IsPlayer() && e:IsOnGround() ) then e:SetVelocity( v * mul * -2048 + Vector( 0, 0, 64 ) ) elseif ( e:IsPlayer() && !e:IsOnGround() ) then e:SetVelocity( v * mul * -384 + Vector( 0, 0, 64 ) ) elseif ( e:GetPhysicsObjectCount() > 0 ) then for i = 0, e:GetPhysicsObjectCount() - 1 do e:GetPhysicsObjectNum( i ):ApplyForceCenter( v * mul * -512 * math.min( e:GetPhysicsObject():GetMass(), 256 ) + Vector( 0, 0, 64 ) ) end end end local ed = EffectData() ed:SetOrigin( self.Owner:GetPos() + Vector( 0, 0, 36 ) ) ed:SetRadius( maxdist ) util.Effect( "rb655_force_repulse_out", ed, true, true ) self._ForceRepulse = nil self:SetNextAttack( 1 ) self:PlayWeaponSound( "lightsaber/force_repulse.wav" ) end }) wOS.ForcePowers:RegisterNewPower({ name = "Tempête De Force", icon = "STR", image = "wos/forceicons/storm.png", cooldown = 0, description = "Se charge pendant 2 secondes. Libère une tempête de Force sur vos ennemis.", action = function( self ) if ( self:GetForce() < 100 ) then self:SetNextAttack( 0.2 ) return end if self:GetAttackDelay() >= CurTime() then return end self:SetForce( self:GetForce() - 100 ) self.Owner:EmitSound( Sound( "npc/strider/charging.wav" ) ) self:SetAttackDelay( CurTime() + 2 ) local tr = util.TraceLine( util.GetPlayerTrace( self.Owner ) ) local pos = tr.HitPos + Vector( 0, 0, 600 ) local pi = math.pi local bullet = {} bullet.Num = 1 bullet.Spread = 0 bullet.Tracer = 1 bullet.Force = 0 bullet.Damage = 500 bullet.AmmoType = "Pistol" bullet.Entity = self.Owner bullet.TracerName = "thor_storm" timer.Simple( 2, function() if not IsValid( self.Owner ) then return end self.Owner:EmitSound( Sound( "ambient/atmosphere/thunder1.wav" ) ) bullet.Src = pos bullet.Dir = Vector( 0, 0, -1 ) self.Owner:EmitSound( Sound( "npc/strider/fire.wav" ) ) self.Owner:FireBullets( bullet ) timer.Simple( 0.1, function() if not IsValid( self.Owner ) then return end bullet.Src = pos + Vector( 65*math.sin( pi*2/5 ), 65*math.cos( pi*2/5 ), 0 ) bullet.Dir = Vector( 0, 0, -1 ) self.Owner:EmitSound( Sound( "npc/strider/fire.wav" ) ) self.Owner:FireBullets( bullet ) end ) timer.Simple( 0.2, function() if not IsValid( self.Owner ) then return end bullet.Src = pos + Vector( 65*math.sin( pi*4/5 ), 65*math.cos( pi*4/5 ), 0 ) bullet.Dir = Vector( 0, 0, -1 ) self.Owner:EmitSound( Sound( "npc/strider/fire.wav" ) ) self.Owner:FireBullets( bullet ) end ) timer.Simple( 0.3, function() if not IsValid( self.Owner ) then return end bullet.Src = pos + Vector( 65*math.sin( pi*6/5 ), 65*math.cos( pi*6/5 ), 0 ) bullet.Dir = Vector( 0, 0, -1 ) self.Owner:EmitSound( Sound( "npc/strider/fire.wav" ) ) self.Owner:FireBullets( bullet ) end ) timer.Simple( 0.4, function() if not IsValid( self.Owner ) then return end bullet.Src = pos + Vector( 65*math.sin( pi*8/5 ), 65*math.cos( pi*8/5 ), 0 ) bullet.Dir = Vector( 0, 0, -1 ) self.Owner:EmitSound( Sound( "npc/strider/fire.wav" ) ) self.Owner:FireBullets( bullet ) end ) timer.Simple( 0.5, function() if not IsValid( self.Owner ) then return end bullet.Src = pos + Vector( 65*math.sin( 2*pi ), 65*math.cos( 2*pi ), 0 ) bullet.Dir = Vector( 0, 0, -1 ) self.Owner:EmitSound( Sound( "npc/strider/fire.wav" ) ) self.Owner:FireBullets( bullet ) end ) end ) return true end }) wOS.ForcePowers:RegisterNewPower({ name = "Méditation", icon = "M", image = "wos/forceicons/meditate.png", description = "Relaxez-vous pour vous soigner et afin de déployer une grande puissance.", think = function( self ) if self.MeditateCooldown and self.MeditateCooldown >= CurTime() then return end if ( self.Owner:KeyDown( IN_ATTACK2 ) ) and !self:GetEnabled() and self.Owner:OnGround() then self._ForceMeditating = true else self._ForceMeditating = false end if self._ForceMeditating then self:SetMeditateMode( 1 ) if not self._NextMeditateHeal then self._NextMeditateHeal = 0 end if self._NextMeditateHeal < CurTime() then self.Owner:SetHealth( math.min( self.Owner:Health() + ( self.Owner:GetMaxHealth()*0.01 ), self.Owner:GetMaxHealth() ) ) if #self.DevestatorList > 0 then self:SetDevEnergy( self:GetDevEnergy() + self.DevCharge ) end local tbl = wOS.ALCS.Config.Skills.ExperienceTable[ self.Owner:GetUserGroup() ] if not tbl then tbl = wOS.ALCS.Config.Skills.ExperienceTable[ "Default" ].Meditation else tbl = wOS.ALCS.Config.Skills.ExperienceTable[ self.Owner:GetUserGroup() ].Meditation end self.Owner:AddSkillXP( tbl ) self._NextMeditateHeal = CurTime() + 3 end self.Owner:SetLocalVelocity(Vector(0, 0, 0)) self.Owner:SetMoveType(MOVETYPE_NONE) else self:SetMeditateMode( 0 ) if self:GetMoveType() != MOVETYPE_WALK and self.Owner:GetNW2Float( "wOS.DevestatorTime", 0 ) < CurTime() then self.Owner:SetMoveType(MOVETYPE_WALK) end end if self.Owner:KeyReleased( IN_ATTACK2 ) then self.MeditateCooldown = CurTime() + 3 end end }) wOS.ForcePowers:RegisterNewPower({ name = "Canalisation", icon = "HT", image = "wos/forceicons/channel_hatred.png", description = "Concentrez votre haine pour vous soigner et emmagasinez là afin de déployer une grande puissance", think = function( self ) if self.ChannelCooldown and self.ChannelCooldown >= CurTime() then return end if ( self.Owner:KeyDown( IN_ATTACK2 ) ) and !self:GetEnabled() and self.Owner:OnGround() then self._ForceChanneling = true else self._ForceChanneling = false end if self.Owner:KeyReleased( IN_ATTACK2 ) then self.ChannelCooldown = CurTime() + 3 end if self._ForceChanneling then if not self._NextChannelHeal then self._NextChannelHeal = 0 end self:SetMeditateMode( 2 ) if self._NextChannelHeal < CurTime() then self.Owner:SetHealth( math.min( self.Owner:Health() + ( self.Owner:GetMaxHealth()*0.01 ), self.Owner:GetMaxHealth() ) ) if #self.DevestatorList > 0 then self:SetDevEnergy( self:GetDevEnergy() + self.DevCharge ) end local tbl = wOS.ALCS.Config.Skills.ExperienceTable[ self.Owner:GetUserGroup() ] if not tbl then tbl = wOS.ALCS.Config.Skills.ExperienceTable[ "Default" ].Meditation else tbl = wOS.ALCS.Config.Skills.ExperienceTable[ self.Owner:GetUserGroup() ].Meditation end self.Owner:AddSkillXP( tbl ) self._NextChannelHeal = CurTime() + 3 end self.Owner:SetLocalVelocity(Vector(0, 0, 0)) self.Owner:SetMoveType(MOVETYPE_NONE) if ( !self.SoundChanneling ) then self.SoundChanneling = CreateSound( self.Owner, "ambient/levels/citadel/field_loop1.wav" ) self.SoundChanneling:Play() else self.SoundChanneling:Play() end timer.Create( "test" .. self:EntIndex(), 0.2, 1, function() if ( self.SoundChanneling ) then self.SoundChanneling:Stop() self.SoundChanneling = nil end end ) else self:SetMeditateMode( 0 ) if self:GetMoveType() != MOVETYPE_WALK and self.Owner:GetNW2Float( "wOS.DevestatorTime", 0 ) < CurTime() then self.Owner:SetMoveType(MOVETYPE_WALK) end end if self.Owner:KeyReleased( IN_ATTACK2 ) then self.ChannelCooldown = CurTime() + 3 end end })
--[[ BLACK TEA ICON LIBRARY FOR NUTSCRIPT 1.1 The MIT License (MIT) Copyright (c) 2017, Kyu Yeon Lee(Black Tea Za rebel1324) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and thispermission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. TL;DR: https://tldrlegal.com/license/mit-license OK - Commercial Use Modify Distribute Sublicense Private Use NOT OK - Hold Liable MUST - Include Copyright Include License ]]-- --[[ Default Tables. ]]-- ikon = ikon or {} ikon.cache = ikon.cache or {} ikon.requestList = ikon.requestList or {} ikon.dev = false ikon.maxSize = 8 -- 8x8 (512^2) is max icon size. IKON_BUSY = 1 IKON_PROCESSING = 0 IKON_SOMETHINGWRONG = -1 local schemaName = schemaName or (Schema and Schema.folder) --[[ Initialize hooks and RT Screens. returns nothing ]]-- function ikon:init() if (self.dev) then hook.Add("HUDPaint", "ikon_dev2", ikon.showResult) else hook.Remove("HUDPaint", "ikon_dev2") end --[[ Being good at gmod is knowing all of stinky hacks - Black Tea (2017) ]]-- ikon.haloAdd = ikon.haloAdd or halo.Add function halo.Add(...) if (ikon.rendering != true) then ikon.haloAdd(...) end end ikon.haloRender = ikon.haloRender or halo.Render function halo.Render(...) if (ikon.rendering != true) then ikon.haloRender(...) end end file.CreateDir("helix/icons") file.CreateDir("helix/icons/" .. schemaName) end --[[ IKON Library Essential Material/Texture Declare ]]-- local TEXTURE_FLAGS_CLAMP_S = 0x0004 local TEXTURE_FLAGS_CLAMP_T = 0x0008 ikon.max = ikon.maxSize * 64 ikon.RT = GetRenderTargetEx("ixIconRendered", ikon.max, ikon.max, RT_SIZE_NO_CHANGE, MATERIAL_RT_DEPTH_SHARED, bit.bor(TEXTURE_FLAGS_CLAMP_S, TEXTURE_FLAGS_CLAMP_T), CREATERENDERTARGETFLAGS_UNFILTERABLE_OK, IMAGE_FORMAT_RGBA8888 ) local tex_effect = GetRenderTarget("ixIconRenderedOutline", ikon.max, ikon.max) local mat_outline = CreateMaterial("ixIconRenderedTemp", "UnlitGeneric", { ["$basetexture"] = tex_effect:GetName(), ["$translucent"] = 1 }) local lightPositions = { BOX_TOP = Color(255, 255, 255), BOX_FRONT = Color(255, 255, 255), } function ikon:renderHook() local entity = ikon.renderEntity if (halo.RenderedEntity() == entity) then return end local w, h = ikon.curWidth * 64, ikon.curHeight * 64 local x, y = 0, 0 local tab if (ikon.info) then tab = { origin = ikon.info.pos, angles = ikon.info.ang, fov = ikon.info.fov, outline = ikon.info.outline, outCol = ikon.info.outlineColor } if (!tab.origin and !tab.angles and !tab.fov) then table.Merge(tab, PositionSpawnIcon(entity, entity:GetPos(), true)) end else tab = PositionSpawnIcon(entity, entity:GetPos(), true) end -- Taking MDave's Tip xpcall(function() render.OverrideAlphaWriteEnable(true, true) -- some playermodel eyeballs will not render without this render.SetWriteDepthToDestAlpha(false) render.OverrideBlend(true, BLEND_ONE, BLEND_ONE, BLENDFUNC_ADD, BLEND_ONE, BLEND_ONE, BLENDFUNC_ADD) render.SuppressEngineLighting(true) render.Clear(0, 0, 0, 0, true, true) render.SetLightingOrigin(vector_origin) render.ResetModelLighting(200 / 255, 200 / 255, 200 / 255) render.SetColorModulation(1, 1, 1) for i = 0, 6 do local col = lightPositions[i] if (col) then render.SetModelLighting(i, col.r / 255, col.g / 255, col.b / 255) end end if (tab.outline) then ix.util.ResetStencilValues() render.SetStencilEnable(true) render.SetStencilWriteMask(137) -- yeah random number to avoid confliction render.SetStencilCompareFunction(STENCILCOMPARISONFUNCTION_ALWAYS) render.SetStencilPassOperation(STENCILOPERATION_REPLACE) render.SetStencilFailOperation(STENCILOPERATION_REPLACE) end --[[ Add more effects on the Models! ]]-- if (ikon.info and ikon.info.drawHook) then ikon.info.drawHook(entity) end cam.Start3D(tab.origin, tab.angles, tab.fov, 0, 0, w, h) render.SetBlend(1) entity:DrawModel() cam.End3D() if (tab.outline) then render.PushRenderTarget(tex_effect) render.Clear(0, 0, 0, 0) render.ClearDepth() cam.Start2D() cam.Start3D(tab.origin, tab.angles, tab.fov, 0, 0, w, h) render.SetBlend(0) entity:DrawModel() render.SetStencilWriteMask(138) -- could you please? render.SetStencilTestMask(1) render.SetStencilReferenceValue(1) render.SetStencilCompareFunction(STENCILCOMPARISONFUNCTION_EQUAL) render.SetStencilPassOperation(STENCILOPERATION_KEEP) render.SetStencilFailOperation(STENCILOPERATION_KEEP) cam.Start2D() surface.SetDrawColor(tab.outCol or color_white) surface.DrawRect(0, 0, ScrW(), ScrH()) cam.End2D() cam.End3D() cam.End2D() render.PopRenderTarget() render.SetBlend(1) render.SetStencilCompareFunction(STENCILCOMPARISONFUNCTION_NOTEQUAL) --[[ Thanks for Noiwex NxServ.eu ]]-- cam.Start2D() surface.SetMaterial(mat_outline) surface.DrawTexturedRectUV(-2, 0, w, h, 0, 0, w / ikon.max, h / ikon.max) surface.DrawTexturedRectUV(2, 0, w, h, 0, 0, w / ikon.max, h / ikon.max) surface.DrawTexturedRectUV(0, 2, w, h, 0, 0, w / ikon.max, h / ikon.max) surface.DrawTexturedRectUV(0, -2, w, h, 0, 0, w / ikon.max, h / ikon.max) cam.End2D() render.SetStencilEnable(false) end render.SuppressEngineLighting(false) render.SetWriteDepthToDestAlpha(true) render.OverrideAlphaWriteEnable(false) end, function(message) print(message) end) end function ikon:showResult() local x, y = ScrW() / 2, ScrH() / 2 local w, h = ikon.curWidth * 64, ikon.curHeight * 64 surface.SetDrawColor(255, 255, 255, 255) surface.DrawOutlinedRect(x, 0, w, h) surface.SetMaterial(mat_outline) surface.DrawTexturedRect(x, 0, w, h) end --[[ Renders the Icon with given arguments. returns nothing ]]-- function ikon:renderIcon(name, w, h, mdl, material, camInfo, updateCache) if (#ikon.requestList > 0) then return IKON_BUSY end if (ikon.requestList[name]) then return IKON_PROCESSING end if (!w or !h or !mdl) then return IKON_SOMETHINGWRONG end local capturedIcon ikon.curWidth = w or 1 ikon.curHeight = h or 1 ikon.renderModel = mdl ikon.renderMaterial = material or "" if (camInfo) then ikon.info = camInfo end local w, h = ikon.curWidth * 64, ikon.curHeight * 64 local sw, sh = ScrW(), ScrH() if (ikon.renderModel) then if (!IsValid(ikon.renderEntity)) then ikon.renderEntity = ClientsideModel(ikon.renderModel, RENDERGROUP_BOTH) ikon.renderEntity:SetNoDraw(true) end end ikon.renderEntity:SetModel(ikon.renderModel) ikon.renderEntity:SetMaterial(ikon.renderMaterial) local bone = ikon.renderEntity:LookupBone("ValveBiped.Bip01_Head1") if (bone) then ikon.renderEntity:SetEyeTarget(ikon.renderEntity:GetBonePosition(bone) + ikon.renderEntity:GetForward() * 32) end local oldRT = render.GetRenderTarget() render.PushRenderTarget(ikon.RT) ikon.rendering = true ikon:renderHook() ikon.rendering = nil capturedIcon = render.Capture({ format = "png", alpha = true, x = 0, y = 0, w = w, h = h }) file.Write("helix/icons/" .. schemaName .. "/" .. name .. ".png", capturedIcon) ikon.info = nil render.PopRenderTarget() if (updateCache) then local materialID = tostring(os.time()) file.Write(materialID .. ".png", capturedIcon) timer.Simple(0, function() local material = Material("../data/".. materialID ..".png") ikon.cache[name] = material file.Delete(materialID .. ".png") end) end ikon.requestList[name] = nil return true end --[[ Gets rendered icon with given unique name. returns IMaterial ]]-- function ikon:GetIcon(name) if (ikon.cache[name]) then return ikon.cache[name] -- yeah return cache end if (file.Exists("helix/icons/" .. schemaName .. "/" .. name .. ".png", "DATA")) then ikon.cache[name] = Material("../data/helix/icons/" .. schemaName .. "/".. name ..".png") return ikon.cache[name] -- yeah return cache else return false -- retryd end end concommand.Add("ix_flushicon", function() local root = "helix/icons/" .. schemaName for _, v in pairs(file.Find(root .. "/*.png", "DATA")) do file.Delete(root .. "/" .. v) end ikon.cache = {} end) hook.Add("InitializedSchema", "updatePath", function() schemaName = Schema.folder ikon:init() end) if (schemaName) then ikon:init() end
package.path = package.path .. ";data/scripts/lib/?.lua" package.path = package.path .. ";data/scripts/systems/?.lua" include("basesystem") include("stringutility") include("randomext") include("utility") include("callable") local Azimuth = include("azimuthlib-basic") if not Azimuth then return end local Log, config -- optimization so that energy requirement doesn't have to be read every frame FixedEnergyRequirement = true --data local seed, rarity, permanent local isScanning = false local scanningProgress = 0 local playerList local foundPlayers = {} local additionalEnergyUsage = 0 local myRandom = Random(Seed(appTimeMs())) local origProductionRate = 0 --UI local uiInitialized = false local window local nameList = {} local coordList = {} local labelcontent = {} local scanButton local progressBar local oldLabelList = {} local fakeUpdateCounter = 0 local old_initialize = initialize function initialize(seed, rarity, permanent_in) old_initialize(seed, rarity, permanent_in) -- load config local configOptions = { _version = {default = "1.2", comment = "Config version. Don't touch"}, LogLevel = {default = 2, min = 0, max = 4, format = "floor", comment = "0 - Disable, 1 - Errors, 2 - Warnings, 3 - Info, 4 - Debug."} } if onClient() then configOptions["UIRows"] = {default = 15, min = 1, max = 100, format = "floor", comment = "Amount of UI rows for displaying players."} else configOptions["GeneratedEnergyDebuff"] = {default = 0.5, min = 0, max = 1, comment = "Reduce energy generation while scanning. 1 to disable."} configOptions["ShieldDurabilityDebuff"] = {default = 0.5, min = 0, max = 1, comment = "Reduce shield current durability when scanning starts. 1 to disable."} configOptions["HyperspaceCooldownDebuff"] = {default = 50, min = 0, format = "floor", comment = "Apply hyperspace cooldown when scanning starts. 0 to disable."} configOptions["ScanningTime"] = {default = 25, min = 1, max = 100, comment = "How long in seconds scanning will take."} configOptions["PVPZoneRange"] = {default = -1, min = -1, comment = "System only detects players in PVP area. Here you can specify PVP area radius from center of galaxy. -1 means that system can detect players anywhere."} configOptions["UpgradeWeight"] = {default = 0.5, min = 0, max = 1000, comment = "Relative chance of getting this upgrade from 0.0 to 1000."} end local isModified config, isModified = Azimuth.loadConfig("PVPScanner", configOptions) if isModified then Azimuth.saveConfig("PVPScanner", config, configOptions) end Log = Azimuth.logs("PVPScanner", config.LogLevel) -- If scanner was started and then the game was closed or sector was unloaded, we'll need to remove energy production debuff if onServer() then restoreProductionRate() end end function onInstalled(pSeed, pRarity, pPermanent) seed, rarity, permanent = pSeed, pRarity, pPermanent if onServer() then -- When user get moved in other sector while scanning, search MUST be stopped Entity():registerCallback("onJump", "stopScanning") else -- Just update the button tooltip if scanButton then scanButton.tooltip = string.format("Scan up to %i sectors away."%_t, getPlayerScannerRange(seed, rarity, permanent)) end end end function onUninstalled(seed, rarity, permanent) if onServer() and isScanning then restoreProductionRate() end end function interactionPossible(playerIndex, option) return Player(playerIndex).craft.index == Entity().index end -- create all required UI elements for the client side function initUI() -- UI should be created immediately, we can update button tooltip later local res = getResolution() local size = vec2(800, 600) local menu = ScriptUI() window = menu:createWindow(Rect(res * 0.5 - size * 0.5, res * 0.5 + size * 0.5)) menu:registerWindow(window, "Scan for players"%_t) window.caption = "Player Scanner"%_t window.showCloseButton = 1 window.moveable = 1 local size = window.size local scanButtonSize = 200 local y = 20 local buttonRect = Rect(size.x / 2 - scanButtonSize / 2 - 15, y, size.x / 2 + scanButtonSize / 2 - 15, y + 35) scanButton = window:createButton(buttonRect, "Start Scanning"%_t, "onStartScanning") if seed then scanButton.tooltip = string.format("Scan up to %i sectors away."%_t, getPlayerScannerRange(seed, rarity, permanent)) end y = y + 45 local rect = Rect(size.x / 2 - scanButtonSize - 15, size.y - 20 - 25, size.x / 2 + scanButtonSize - 15, size.y - 20) progressBar = window:createNumbersBar(rect) progressBar:setRange(0, 1) -- Receive ScanningTime later from server uiInitialized = true -- Create player rows local nameLabelSizeX = 400 local coordLabelSize = 150 local oldnameLabel, nameLabel, coordLabel for i = 1, config.UIRows do oldnameLabel = window:createLabel(vec2(10, y+1), "", 15) oldnameLabel.color = ColorARGB(0.9, 0.1, 0.5, 0.1) oldnameLabel.size = vec2(nameLabelSizeX, 25) oldnameLabel.wordBreak = false nameLabel = window:createLabel(vec2(10, y), "", 15) nameLabel.color = ColorARGB(1.0, 0.1, 0.8, 0.1) nameLabel.size = vec2(nameLabelSizeX, 25) nameLabel.caption = "" nameLabel.wordBreak = false coordLabel = window:createLabel(vec2(nameLabelSizeX + 10 + 20, y), "", 15) coordLabel.tooltip = nil coordLabel.mouseDownFunction = "" coordLabel.size = vec2(coordLabelSize, 25) coordLabel.mouseDownFunction = "onCoordClicked" oldLabelList[#oldLabelList+1] = oldnameLabel nameList[#nameList+1] = nameLabel coordList[#coordList+1] = coordLabel y = y + 35 end end function getName(seed, rarity) return "Player Scanner"%_t end function getIcon(seed, rarity) return "data/textures/icons/aggressive.png" end function getEnergy(seed, rarity, permanent) math.randomseed(seed) local scannerRange = getPlayerScannerRange(seed, rarity, permanent) local energy = scannerRange * 1e8 + scannerRange * 1e6 * (math.random() + 0.5) return energy * 4.5 ^ rarity.value + additionalEnergyUsage end function getPrice(seed, rarity) math.randomseed(seed) local scannerRange = getPlayerScannerRange(seed, rarity, false) local price = scannerRange * 1e4 + scannerRange * 1e4 * (math.random() + 0.5) return price * 2.5 ^ rarity.value end function getPlayerBonusScannerRange(seed, rarity, permanent) if not permanent then return 0 end math.randomseed(seed) local range = math.floor((3 * rarity.value + 2 + math.random() * 3) / 2) if range < 0 then range = 0 end return range end function getPlayerScannerRange(seed, rarity, permanent) math.randomseed(seed) local range = 3 * rarity.value + 3 + math.floor(math.random() * 2.5 + 0.5) if range <= 0 then range = 1 end return range + getPlayerBonusScannerRange(seed, rarity, permanent) end function getTooltipLines(seed, rarity, permanent) local texts = {} local bonuses = {} table.insert(texts, {ltext = "Player scanning range"%_t, rtext = getPlayerScannerRange(seed, rarity, permanent), icon = "data/textures/icons/rss.png", boosted = permanent}) table.insert(bonuses, {ltext = "Player scanning range"%_t, rtext = "+"..getPlayerBonusScannerRange(seed, rarity, true), icon = "data/textures/icons/rss.png"}) return texts, bonuses end function getDescriptionLines(seed, rarity, permanent) return { {ltext = "Adds a scanner for Players."%_t, rtext = "", icon = ""} } end -- Reduce update rate. We don't want to kill server performance if onClient() then function getUpdateInterval() return 0.25 end else -- onServer function getUpdateInterval() return 1 end end -- Moving name and coordinates 'decoding' to the serverside, otherwise it's super easy to cheat function updateServer(timestep) if not isScanning then return end -- scan lasts longer when there is not enough energy local energySystem = EnergySystem() local step = timestep if energySystem.consumableEnergy == 0 then -- multiplier value depending on energy: 0.05 - 1 local multiplier = math.max(1 - ((energySystem.requiredEnergy - energySystem.productionRate) / (origProductionRate * 0.5)), 0.05) multiplier = math.min(multiplier, 1) step = timestep * multiplier end scanningProgress = scanningProgress + step if scanningProgress >= config.ScanningTime then -- stop scanning stopScanning() scanningProgress = config.ScanningTime end local percProgress = scanningProgress / config.ScanningTime local foundIndex, dX, dY if playerList then for i, playerData in ipairs(playerList) do if playerList[i].foundIndex then foundIndex = playerList[i].foundIndex foundPlayers[foundIndex].name = getRandomName(playerData.name, foundPlayers[foundIndex].name, percProgress) dX, dY = getRandomCoord(playerData.x, playerData.y, foundPlayers[foundIndex].x, foundPlayers[foundIndex].y, percProgress) foundPlayers[foundIndex].x = dX foundPlayers[foundIndex].y = dY foundPlayers[foundIndex].correct = (dX == playerData.x and dY == playerData.y) foundPlayers[foundIndex].correctName = foundPlayers[foundIndex].name == playerData.name Log.Debug("updateServer - decode: %s (%i:%i)", foundPlayers[foundIndex].name, dX, dY) elseif findPlayer(i, percProgress) then foundPlayers[#foundPlayers+1] = {} playerList[i].foundIndex = #foundPlayers foundIndex = playerList[i].foundIndex foundPlayers[foundIndex].name = getRandomName(playerData.name, nil, percProgress) dX, dY = getRandomCoord(playerData.x, playerData.y, nil, nil, percProgress) foundPlayers[foundIndex].x = dX foundPlayers[foundIndex].y = dY foundPlayers[foundIndex].correct = (dX == playerData.x and dY == playerData.y) foundPlayers[foundIndex].correctName = foundPlayers[foundIndex].name == playerData.name Player(playerData.index):sendChatMessage("", 2, "Another ship located your position!"%_t) Log.Debug("updateServer - register: %s (%i:%i)", foundPlayers[foundIndex].name, dX, dY) end end end if percProgress >= 1 then -- notify ship pilots on finish for _, playerId in pairs({Entity():getPilotIndices()}) do invokeClientFunction(Player(playerId), "receivePlayersInRange", foundPlayers, scanningProgress, config.ScanningTime, origProductionRate) end end end -- Moving name and coordinates 'decoding' to the serverside, otherwise it's super easy to cheat function updateClient(timestep) if Player().craft.index ~= Entity().index then return end if not isScanning then return end -- request decoded data if fakeUpdateCounter == 0 then invokeServerFunction("getPlayersInRange") else -- perform fake updates between real ones to make 'decoding' look smoother fakeUpdate(timestep) end fakeUpdateCounter = fakeUpdateCounter + timestep if fakeUpdateCounter >= 1 then fakeUpdateCounter = 0 end end function fakeUpdate(timestep) local energySystem = EnergySystem() local step = timestep if energySystem.consumableEnergy == 0 then -- multiplier value depending on energy: 0.05 - 1 local multiplier = math.max(1 - ((energySystem.requiredEnergy - energySystem.productionRate) / (origProductionRate * 0.5)), 0.05) multiplier = math.min(multiplier, 1) step = timestep * multiplier end scanningProgress = scanningProgress + step local percProgress = scanningProgress / config.ScanningTime Log.Debug("Fake update") -- update UI progressBar:clear() progressBar:setRange(0, config.ScanningTime) progressBar:addEntry(scanningProgress, string.format("Progress: %i%%"%_t, round(percProgress * 100, 2)), ColorARGB(0.9, 1 - percProgress, percProgress, 0.1)) if foundPlayers then local oldnameLabel, nameLabel, coordLabel, pseudoName, playerName, pseudoX, pseudoY, dX, dY for i, playerData in ipairs(foundPlayers) do local coordIndex = coordList[i].index oldnameLabel = oldLabelList[i] nameLabel = nameList[i] coordLabel = coordList[i] if playerData.correctName then playerName = playerData.name oldnameLabel.caption = "" else playerName = getRandomName(playerData.name, nil, 0.7 + percProgress / 5) oldnameLabel.caption = playerData.name end nameLabel.caption = playerData.name if playerData.correct then -- no need to make everything complicated if RNG found the coordinates already dX, dY = playerData.x, playerData.y coordLabel.color = ColorRGB(0.3, 0.9, 0.1) else dX, dY = getRandomCoord(playerData.x, playerData.y, nil, nil, 0.7 + percProgress / 5) coordLabel.color = ColorRGB(1.0, 1.0, 1.0) end coordLabel.caption = "("..dX..":"..dY..")" coordLabel.tooltip = string.format("Click to show %s on Galaxy Map"%_t, playerName) if labelcontent[coordIndex] then labelcontent[coordIndex].x = dX labelcontent[coordIndex].y = dY end oldnameLabel.visible = true nameLabel.visible = true coordLabel.visible = true end -- hide other rows for i = #foundPlayers+1, config.UIRows do oldLabelList[i].visible = false nameList[i].visible = false coordList[i].visible = false end end end function findPlayer(i, percProgress) return myRandom:getFloat(0.0, 1.0)-0.7 > (0.5-percProgress) end function getRandomCoord(pX, pY, lastX, lastY, percProgress) lastX = lastX or myRandom:getInt(-500,500) lastY = lastY or myRandom:getInt(-500,500) local x, y if percProgress > 0.2 then if pX ~= lastX then local dist = math.min(50, math.sqrt(pX^2 - lastX^2)) dist = dist * (1 - percProgress) x = myRandom:getInt(pX - dist, pX + dist) else x = pX end if pY ~= lastY then local dist = math.min(50, math.sqrt(pY^2-lastY^2)) dist = dist * (1 - percProgress) y = myRandom:getInt(pY - dist, pY + dist) else y = pY end else x,y = myRandom:getInt(-500,500), myRandom:getInt(-500,500) end return x, y end function getRandomName(name, lastName, percProgress) if percProgress >= 1.0 then return name end lastName = lastName or "" local newName = "" for i=1, 25 do if percProgress > 0.2 then local nameChar = name:byte(i) or 32 -- " " local lastNameChar = lastName:byte(i) or myRandom:getInt(48,57) if lastNameChar ~= nameChar then if percProgress + myRandom:getFloat(0.0, 0.4) >= 1 then newName = newName..string.char(nameChar) else local char = myRandom:getInt(48,57) newName = newName..string.char(char) end else newName = newName..string.char(nameChar) end end end return newName end function restoreProductionRate() local entity = Entity() local scannerDebuffKey = entity:getValue("pvpScannerDebuff") if scannerDebuffKey then removeBonus(scannerDebuffKey) entity:setValue("pvpScannerDebuff") -- remove value end end function startScanning() Log.Debug("startScanning") if isScanning then return end if onServer() then local player = Player(callingPlayer) local entity = Entity() if player.craft.index ~= entity.index then return end -- Apply debuffs -- Modifying productionRate directly is a bad idea. Let's use multiplier. We still need origProductionRate for calculations local energySystem = EnergySystem() origProductionRate = energySystem.productionRate if config.GeneratedEnergyDebuff < 1 then local scannerDebuffKey = addMultiplier(StatsBonuses.GeneratedEnergy, config.GeneratedEnergyDebuff) entity:setValue("pvpScannerDebuff", scannerDebuffKey) end -- Apply debuffs immediately local entity = Entity() if entity.shieldDurability and config.ShieldDurabilityDebuff < 1 then local damage = entity.shieldDurability * config.ShieldDurabilityDebuff entity:damageShield(damage, entity.translationf, player.craftIndex) end if config.HyperspaceCooldownDebuff > 0 then entity.hyperspaceCooldown = math.max(entity.hyperspaceCooldown, config.HyperspaceCooldownDebuff) end -- find players scanningProgress = 0 foundPlayers = {} playerList = {} local onlineplayers = {Server():getOnlinePlayers()} local range = getPlayerScannerRange(seed, rarity, permanent) local playerposX, playerposY = Sector():getCoordinates() local pX, pY, dist, distToCore for _, player in pairs(onlineplayers) do if player then pX, pY = player:getSectorCoordinates() if not (pX == playerposX and pY == playerposY) then -- Exclude players in current sector dist = math.sqrt((playerposX - pX)^2 + (playerposY - pY)^2) distToCore = length(vec2(pX, pY)) -- Show only players in the module range if dist <= range and (config.PVPZoneRange < 0 or distToCore <= config.PVPZoneRange) then playerList[#playerList+1] = {index = player.index, name = player.name, x = pX, y = pY} end end end end broadcastInvokeClientFunction("onStartScanning", nil, true) -- sync UI end myRandom = Random(Seed(appTimeMs())) isScanning = true fakeUpdateCounter = 0 end callable(nil, "startScanning") function stopScanning(broadcast) Log.Debug("stopScanning") if not isScanning then return end if onServer() then -- Never trust client if not callingPlayer or Player(callingPlayer).craft.index == Entity().index then callingPlayer = nil restoreProductionRate() broadcastInvokeClientFunction("onStopScanning", nil, true) -- sync UI end end isScanning = false end callable(nil, "stopScanning") function onStartScanning(button, isInvoked) Log.Debug("onStartScanning") -- This function may be executed when already scanning. This should be skipped. if not isScanning then if scanButton then scanButton.onPressedFunction = "onStopScanning" scanButton.caption = "Stop Scanning"%_t progressBar:clear() end scanningProgress = 0 foundPlayers = {} startScanning() if not isInvoked then invokeServerFunction("startScanning") end -- Clear old data labelcontent = {} end end function onStopScanning(button, isInvoked) Log.Debug("onStopScanning") if scanButton then scanButton.onPressedFunction = "onStartScanning" scanButton.caption = "Start Scanning"%_t end stopScanning() if not isInvoked then invokeServerFunction("stopScanning") end end function getPlayersInRange() -- Now this function will be called every second by client and will send 'decoded' data if not isScanning then return end local player = Player(callingPlayer) if player.craft.index ~= Entity().index then return end invokeClientFunction(player, "receivePlayersInRange", foundPlayers, scanningProgress, config.ScanningTime, origProductionRate) end callable(nil, "getPlayersInRange") -- Now we're using this function to process 'decoded' data every second function receivePlayersInRange(decodedPlayers, scanProgress, scanTime, origProduction) foundPlayers = decodedPlayers scanningProgress = scanProgress config.ScanningTime = scanTime origProductionRate = origProduction -- update UI local percProgress = scanningProgress / config.ScanningTime progressBar:clear() progressBar:setRange(0, config.ScanningTime) progressBar:addEntry(scanningProgress, string.format("Progress: %i%%"%_t, round(percProgress * 100, 2)), ColorARGB(0.9, 1 - percProgress, percProgress, 0.1)) Log.Debug("Real update") if foundPlayers then local oldnameLabel, nameLabel, coordLabel for i, playerData in ipairs(foundPlayers) do local coordIndex = coordList[i].index oldnameLabel = oldLabelList[i] nameLabel = nameList[i] coordLabel = coordList[i] if percProgress < 1 and labelcontent[coordIndex] then oldnameLabel.caption = labelcontent[coordIndex].name end if percProgress >= 1 or playerData.correctName then oldnameLabel.caption = "" end nameLabel.caption = playerData.name coordLabel.caption = "("..playerData.x..":"..playerData.y..")" coordLabel.tooltip = string.format("Click to show %s on Galaxy Map"%_t, playerData.name) coordLabel.color = playerData.correct and ColorRGB(0.3, 0.9, 0.1) or ColorRGB(1.0, 1.0, 1.0) labelcontent[coordIndex] = {x = playerData.x, y = playerData.y, name = playerData.name, correct = playerData.correct, playerData.index} oldnameLabel.visible = true nameLabel.visible = true coordLabel.visible = true end -- hide other rows for i = #foundPlayers+1, config.UIRows do oldLabelList[i].visible = false nameList[i].visible = false coordList[i].visible = false end end end function onCoordClicked(labelIndex) local x, y = labelcontent[labelIndex].x, labelcontent[labelIndex].y GalaxyMap():show(x, y) end
-- torch reimplementation of deepRotator: https://github.com/jimeiyang/deepRotator.git require 'torch' require 'nn' require 'cunn' --require 'cudnn' require 'nngraph' require 'optim' require 'image' model_utils = require 'utils.model_utils' optim_utils = require 'utils.adam_v2' opt = lapp[[ --save_every (default 40) --print_every (default 1) --data_root (default 'data') --data_id_path (default 'data/shapenetcore_ids') --data_view_path (default 'data/shapenetcore_viewdata') --dataset (default 'dataset_rotatorRNN_base') --gpu (default 0) --nz (default 512) --na (default 3) --nview (default 24) --nThreads (default 4) --niter (default 160) --display (default 1) --checkpoint_dir (default 'models/') --lambda (default 10) --kstep (default 1) --batch_size (default 32) --adam (default 1) --arch_name (default 'arch_rotatorRNN') --weight_decay (default 0.001) --exp_list (default 'singleclass') --load_size (default 64) ]] opt.ntrain = math.huge for k,v in pairs(opt) do opt[k] = tonumber(os.getenv(k)) or os.getenv(k) or opt[k] end print(opt) if opt.display == 0 then opt.display = false end if opt.gpu > 0 then ok, cunn = pcall(require, 'cunn') ok2, cutorch = pcall(require, 'cutorch') cutorch.setDevice(opt.gpu) end opt.manualSeed = torch.random(1, 10000) -- fix seed print("Random Seed: " .. opt.manualSeed) torch.manualSeed(opt.manualSeed) torch.setnumthreads(1) torch.setdefaulttensortype('torch.FloatTensor') -- create data loader local TrainLoader = require 'utils/data.lua' local ValLoader = require 'utils/data_val.lua' local data = TrainLoader.new(opt.nThreads, opt.dataset, opt) local data_val = ValLoader.new(opt.nThreads, opt.dataset, opt) print("dataset: " .. opt.dataset, "train size: ", data:size(), "val size: ", data_val:size()) ---------------------------------------------------------------- local function weights_init(m) local name = torch.type(m) if name:find('Convolution') and name:find('Spatial') then local nin = m.nInputPlane*m.kH*m.kW m.weight:uniform(-0.08, 0.08):mul(math.sqrt(1/nin)) m.bias:fill(0) elseif name:find('Convolution') and name:find('Volumetric') then local nin = m.nInputPlane*m.kT*m.kH*m.kW m.weight:uniform(-0.08, 0.08):mul(math.sqrt(1/nin)) m.bias:fill(0) elseif name:find('Linear') then local nin = m.weight:size(2) m.weight:uniform(-0.08, 0.08):mul(math.sqrt(1/nin)) m.bias:fill(0) elseif name:find('BatchNormalization') then if m.weight then m.weight:normal(1.0, 0.02) end if m.bias then m.bias:fill(0) end end end opt.model_name = string.format('%s_%s_nv%d_adam%d_bs%d_nz%d_wd%g_lbg%g_ks%d', opt.arch_name, opt.exp_list, opt.nview, opt.adam, opt.batch_size, opt.nz, opt.weight_decay, opt.lambda, opt.kstep) -- initialize parameters init_models = dofile('scripts/' .. opt.arch_name .. '.lua') encoder, actor, mixer, decoder_msk, decoder_im = init_models.create(opt) encoder:apply(weights_init) actor:apply(weights_init) mixer:apply(weights_init) decoder_msk:apply(weights_init) decoder_im:apply(weights_init) opt.model_path = opt.checkpoint_dir .. opt.model_name if not paths.dirp(opt.model_path) then paths.mkdir(opt.model_path) end prev_iter = 0 -- load model from previous iterations for i = opt.niter, 1, -opt.save_every do print(opt.model_path .. string.format('/net-epoch-%d.t7', i)) if paths.filep(opt.model_path .. string.format('/net-epoch-%d.t7', i)) then prev_iter = i loader = torch.load(opt.model_path .. string.format('/net-epoch-%d.t7', i)) state = torch.load(opt.model_path .. '/state.t7') print(string.format('resuming from epoch %d', i)) break end end -- build nngraph if prev_iter > 0 then encoder = loader.encoder actor = loader.actor mixer = loader.mixer decoder_msk = loader.decoder_msk decoder_im = loader.decoder_im end -- criterion local criterion_im = nn.MSECriterion() criterion_im.sizeAverage = false local criterion_msk = nn.MSECriterion() criterion_msk.sizeAverage = false -- hyperparams function getAdamParams(opt) config = {} if opt.adam == 1 then config.learningRate = 0.0001 config.epsilon = 1e-8 config.beta1 = 0.9 config.beta2 = 0.999 config.weightDecay = opt.weight_decay end return config end config = getAdamParams(opt) print(config) ------------------------------------------------- local batch_im_in = torch.Tensor(opt.batch_size, 3, opt.load_size, opt.load_size) local batch_rot = torch.Tensor(opt.batch_size, opt.na):zero() local batch_outputs = {} for k = 1, opt.kstep do batch_outputs[2*k-1] = torch.Tensor(opt.batch_size, 3, opt.load_size, opt.load_size) batch_outputs[2*k] = torch.Tensor(opt.batch_size, 1, opt.load_size, opt.load_size) end local preds = {} for k = 1, opt.kstep do preds[2*k-1] = torch.Tensor(opt.batch_size, 3, opt.load_size, opt.load_size) preds[2*k] = torch.Tensor(opt.batch_size, 1, opt.load_size, opt.load_size) end local errIM, errMSK local epoch_tm = torch.Timer() local tm = torch.Timer() local data_tm = torch.Timer() ------------------------------------------------ if opt.gpu > 0 then batch_im_in = batch_im_in:cuda() batch_rot = batch_rot:cuda() for k = 1, opt.kstep do batch_outputs[2*k-1] = batch_outputs[2*k-1]:cuda() batch_outputs[2*k] = batch_outputs[2*k]:cuda() end encoder:cuda() actor:cuda() mixer:cuda() decoder_msk:cuda() decoder_im:cuda() criterion_im:cuda() criterion_msk:cuda() end local inputs = {nn.Identity()(), nn.Identity()()} local h_enc_id, h_enc_rot = encoder(inputs[1]):split(2) local outputs = {} local h_dec_rot = actor({h_enc_rot, inputs[2]}) local h_mix = mixer({h_enc_id, h_dec_rot}) local h_dec_msk = decoder_msk(h_mix) local h_dec_im = decoder_im(h_mix) table.insert(outputs, h_dec_im) table.insert(outputs, h_dec_msk) rotatorRNN = nn.gModule(inputs, outputs) params, grads = rotatorRNN:getParameters() local opfunc = function(x) collectgarbage() if x ~= params then params:copy(x) end grads:zero() -- train data_tm:reset(); data_tm:resume() cur_im_in, cur_outputs, cur_rot, _ = data:getBatch() data_tm:stop() batch_im_in:copy(cur_im_in:mul(2):add(-1)) for k = 1, opt.kstep do batch_outputs[k*2-1]:copy(cur_outputs[k*2-1]:mul(2):add(-1)) batch_outputs[k*2]:copy(cur_outputs[k*2]) end batch_rot:copy(cur_rot) local f = rotatorRNN:forward({batch_im_in, batch_rot}) errIM = 0 errMSK = 0 local df_dw = {} for k = 1, opt.kstep do -- fast forward (actor, mixer, decoder) errIM = errIM + criterion_im:forward(f[2*k-1], batch_outputs[2*k-1]) / (8 * opt.batch_size) errMSK = errMSK + criterion_msk:forward(f[2*k], batch_outputs[2*k]) / (2 * opt.batch_size) local df_dIM = criterion_im:backward(f[2*k-1], batch_outputs[2*k-1]):mul(opt.lambda):div(8 * opt.batch_size) local df_dMSK = criterion_msk:backward(f[2*k], batch_outputs[2*k]):div(2 * opt.batch_size) df_dw[2*k-1] = df_dIM:clone() df_dw[2*k] = df_dMSK:clone() end rotatorRNN:backward({batch_im_in, batch_rot}, df_dw) local err = errIM * opt.lambda + errMSK return err, grads end ------------------------------------------------- local feedforward = function(x) collectgarbage() if x ~= params then params:copy(x) end grads:zero() -- val data_tm:reset(); data_tm:resume() cur_im_in, cur_outputs, cur_rot, _ = data_val:getBatch() data_tm:stop() batch_im_in:copy(cur_im_in:mul(2):add(-1)) for k = 1, opt.kstep do batch_outputs[k*2-1]:copy(cur_outputs[k*2-1]:mul(2):add(-1)) batch_outputs[k*2]:copy(cur_outputs[k*2]) end batch_rot:copy(cur_rot) local f = rotatorRNN:forward({batch_im_in, batch_rot}) errIM = 0 errMSK = 0 for k = 1, opt.kstep do errIM = errIM + criterion_im:forward(f[2*k-1], batch_outputs[2*k-1]) / (8 * opt.batch_size) errMSK = errMSK + criterion_msk:forward(f[2*k], batch_outputs[2*k]) / (2 * opt.batch_size) preds[2*k-1] = f[2*k-1]:float():clone() preds[2*k] = f[2*k]:float():clone() end local err = errIM * opt.lambda + errMSK return err end -------------------------------------------------- -- train & val for epoch = prev_iter + 1, opt.niter do epoch_tm:reset() local counter = 0 -- train rotatorRNN:training() for i = 1, math.min(data:size() * opt.nview / 2 , opt.ntrain), opt.batch_size do tm:reset() optim_utils.adam_v2(opfunc, params, config, state) counter = counter + 1 print(string.format('Epoch: [%d][%8d / %8d]\t Time: %.3f DataTime: %.3f ' .. ' Err_Im: %.4f , Err_Msk: %.4f', epoch, ((i-1) / opt.batch_size), math.floor(math.min(data:size() * opt.nview / 2, opt.ntrain) / opt.batch_size), tm:time().real, data_tm:time().real, errIM and errIM or -1, errMSK and errMSK or -1)) end -- val rotatorRNN:evaluate() for i = 1, opt.batch_size do tm:reset() local err = feedforward(params) end -- plot local to_plot = {} for i = 1, 32 do for k = 1, opt.kstep do local res = batch_im_in[i]:float():clone() res = torch.squeeze(res) res:add(1):mul(0.5) to_plot[#to_plot+1] = res:clone() local res = preds[2*k][i]:float() res = torch.squeeze(res) res = res:repeatTensor(3, 1, 1) res:mul(-1):add(1) to_plot[#to_plot+1] = res:clone() local res = preds[2*k-1][i]:float() res = torch.squeeze(res) res:add(1):mul(0.5) to_plot[#to_plot+1] = res:clone() local res = batch_outputs[2*k-1][i]:float():clone() res = torch.squeeze(res) res:add(1):mul(0.5) to_plot[#to_plot+1] = res:clone() end end local formatted = image.toDisplayTensor({input=to_plot, nrow = 16}) formatted = formatted:double() formatted:mul(255) formatted = formatted:byte() image.save(opt.model_path .. string.format('/sample-%03d.jpg', epoch), formatted) if epoch % opt.save_every == 0 then torch.save((opt.model_path .. string.format('/net-epoch-%d.t7', epoch)), {encoder = encoder, actor = actor, mixer = mixer, decoder_msk = decoder_msk, decoder_im = decoder_im}) torch.save((opt.model_path .. '/state.t7'), state) end end
local local0 = 0.4 local local1 = 2.4 - local0 local local2 = 20.6 - local0 local local3 = 4 - local0 local local4 = 20.6 - local0 local local5 = 2.3 - local0 local local6 = 4.6 - local0 function OnIf_210010(arg0, arg1, arg2) if arg2 == 0 then EyeCollector210010_ActAfter_RealTime(arg0, arg1) end return end function EyeCollector210010Battle_Activate(arg0, arg1) local local0 = {} local local1 = {} local local2 = {} Common_Clear_Param(local0, local1, local2) local local3 = arg0:GetDist(TARGET_ENE_0) local local4 = arg0:GetRandam_Int(1, 100) local local5 = arg0:GetExcelParam(AI_EXCEL_THINK_PARAM_TYPE__thinkAttr_doAdmirer) if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 120) then local0[20] = 100 elseif not arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 90) then if local3 <= 3.2 then local0[3] = 100 local0[20] = 100 else local0[20] = 100 end elseif 8 <= local3 then local0[1] = 0 local0[2] = 30 local0[3] = 0 local0[4] = 0 local0[5] = 30 local0[10] = 0 local0[11] = 30 elseif 5 <= local3 then local0[1] = 0 local0[2] = 50 local0[3] = 0 local0[4] = 0 local0[5] = 0 local0[10] = 0 local0[11] = 50 elseif 3.2 <= local3 then local0[1] = 0 local0[2] = 25 local0[3] = 25 local0[4] = 0 local0[5] = 0 local0[10] = 0 local0[11] = 50 elseif 2.4 <= local3 then local0[1] = 0 local0[2] = 30 local0[3] = 40 local0[4] = 0 local0[5] = 0 local0[10] = 30 local0[11] = 0 else local0[1] = 50 local0[2] = 0 local0[3] = 30 local0[4] = 0 local0[5] = 0 local0[10] = 30 local0[11] = 0 end if 0.1 <= arg0:GetDistY(TARGET_ENE_0) then local0[10] = 0 local0[11] = 0 end local1[1] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act01) local1[2] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act02) local1[3] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act03) local1[4] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act04) local1[5] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act05) local1[10] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act10) local1[11] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act11) local1[15] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act15) local1[20] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act20) local1[30] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act30) local1[31] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act31) local1[32] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act32) local1[33] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act33) local1[34] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act34) local1[35] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act35) local1[36] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act36) local1[37] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act37) local1[38] = REGIST_FUNC(arg0, arg1, EyeCollector210010_Act38) Common_Battle_Activate(arg0, arg1, local0, local1, REGIST_FUNC(arg0, arg1, EyeCollector210010_ActAfter_AdjustSpace), local2) return end local0 = local1 function EyeCollector210010_Act01(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = UPVAL0 local local2 = 9999 local local3 = 0 if arg0:GetRandam_Int(1, 100) <= 50 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, UPVAL0, 0, -1) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, AttDist0, 0, 120) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, AttDist1_8, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3008, TARGET_ENE_0, AttDist8, 0) end GetWellSpace_Odds = 70 return GetWellSpace_Odds end local0 = local2 function EyeCollector210010_Act02(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL0 local local3 = 9999 local local4 = 0 arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3002, TARGET_ENE_0, UPVAL0, 0, 120) GetWellSpace_Odds = 70 return GetWellSpace_Odds end local0 = local3 function EyeCollector210010_Act03(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL0 local local3 = 9999 local local4 = 0 arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, UPVAL0, 0, 120) GetWellSpace_Odds = 70 return GetWellSpace_Odds end local0 = local4 function EyeCollector210010_Act04(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL0 local local3 = 9999 local local4 = 0 arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3004, TARGET_ENE_0, UPVAL0, 0, 0) GetWellSpace_Odds = 70 return GetWellSpace_Odds end local0 = local4 function EyeCollector210010_Act05(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL0 local local3 = 9999 local local4 = 0 local local5 = UPVAL0 local local6 = arg0:GetRandam_Int(0, 1) local local7 = arg0:GetRandam_Float(2, 3) if local1 <= 60 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local7, TARGET_ENE_0, local6, arg0:GetRandam_Int(120, 120), true, true, -1) elseif local1 <= 75 then arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, arg0:GetRandam_Float(2, 3.5), TARGET_ENE_0, 6, TARGET_ENE_0, true, -1) elseif local1 <= 90 then arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, 1, TARGET_ENE_0, 10, TARGET_ENE_0, true, -1) arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local7, TARGET_ENE_0, local6, arg0:GetRandam_Int(120, 120), true, true, -1) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local5 function EyeCollector210010_Act10(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, 0, 0, 5) end arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, UPVAL0, 0, 0) GetWellSpace_Odds = 70 return GetWellSpace_Odds end local0 = local6 function EyeCollector210010_Act11(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, 0, 0, 5) end arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3006, TARGET_ENE_0, UPVAL0, 0, 0) GetWellSpace_Odds = 70 return GetWellSpace_Odds end function EyeCollector210010_Act15(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = arg0:GetDist(TARGET_ENE_0) if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 10, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 0) elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 180) then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 10, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 0) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end function EyeCollector210010_Act20(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_Turn, 2.5, TARGET_ENE_0, 30, 0, 0) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local1 local0 = 0 - local0 function EyeCollector210010_Act30(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, UPVAL0 + 1, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 2.3 - local0 local0 = 0 - local0 function EyeCollector210010_Act31(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3001, TARGET_ENE_0, UPVAL0 + 1, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local2 local0 = 0 - local0 function EyeCollector210010_Act32(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3002, TARGET_ENE_0, UPVAL0 + 1, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local3 local0 = 0 - local0 function EyeCollector210010_Act33(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3003, TARGET_ENE_0, UPVAL0 + 1, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local4 local0 = 0 - local0 function EyeCollector210010_Act34(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3004, TARGET_ENE_0, UPVAL0 + 1, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local5 local0 = 0 - local0 function EyeCollector210010_Act35(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, UPVAL0 + 1, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local6 local0 = 0 - local0 function EyeCollector210010_Act36(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL1 Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 10, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3006, TARGET_ENE_0, UPVAL0 + 1, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function EyeCollector210010_Act37(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = Att3007_Dist_min Approach_Act(arg0, arg1, Att3007_Dist_max - 0.5, Att3007_Dist_max + 10, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, Att3007_Dist_max + 1, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function EyeCollector210010_Act38(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = Att3008_Dist_min Approach_Act(arg0, arg1, Att3008_Dist_max, Att3008_Dist_max + 10, 0, 2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3008, TARGET_ENE_0, Att3008_Dist_max + 1, 0, -1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function EyeCollector210010_ActAfter_RealTime(arg0, arg1) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Int(1, 100) local local3 = arg0:GetRandam_Int(0, 1) local local4 = arg0:GetRandam_Float(2, 3.5) local local5 = arg0:GetRandam_Float(2, 3) local local6 = 0 if local0 <= 3 then if local1 <= 60 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 2, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(120, 120), true, true, -1) end elseif local0 <= 8 then if local1 <= 60 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 2, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(120, 120), true, true, -1) end elseif local0 <= 30 then if local1 <= 50 then arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 3, TARGET_SELF, true, -1) else arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 3, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(120, 120), true, true, -1) end end return end function EyeCollector210010_ActAfter_AdjustSpace(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_If, 10, 0) return end function EyeCollector210010Battle_Update(arg0, arg1) return GOAL_RESULT_Continue end function EyeCollector210010Battle_Terminate(arg0, arg1) return end function EyeCollector210010Battle_Interupt(arg0, arg1) if arg0:IsLadderAct(TARGET_SELF) then return false else local local0 = arg0:GetRandam_Int(1, 100) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Int(1, 100) local local3 = arg0:GetDist(TARGET_ENE_0) return false end end return
-- Gkyl ------------------------------------------------------------------------ local Plasma = require("App.PlasmaOnCartGrid").VlasovMaxwell local Constants = require "Lib.Constants" --contains universal constants taken from NIST's website -- ****************************** -- INPUT PARAMETERS -- ****************************** -- normalization parameters, working in SI units epsilon0 = Constants.EPSILON0 -- permittivity of free space mu0 = Constants.MU0 -- pemiability of free space lightSpeed = Constants.SPEED_OF_LIGHT -- speed of light unitCharge = Constants.ELEMENTARY_CHARGE elcMass = Constants.ELECTRON_MASS -- electron mass elcCharge = -1.0 * unitCharge -- electron charge ionMass = Constants.PROTON_MASS -- assuming proton mass ionCharge = 1.0 * unitCharge -- assuming proton charge eVJ = 1.0 * unitCharge -- 1 eV in Joules -- input quantities TeeV = 1000 -- Te in eV TieV = 1000 -- Ti in eV M0 = 0.35 -- Mach number at scale L0. u0 = M*cs ne = 2.30235e+28 -- electron density k0 = 822500.0 -- inverse of the length-scale L0 lnLambda = 10 -- Coulomb logarithm -- Noise generation parameters BNoiseAmpl = 10.0 -- Amplitude of B noise (in Tesla) nmodes = 4 -- Number of modes (mode 1 has a wave length comparable to the box) -- Forcing related quantities (Here only ions are forced) forcefactor = 3.0 -- Forcing is set to be Force = forceFactor * u * m / tstreamIon, -- (note that due to normalization m is not in the forcing function) -- We assume that the ions loose their momentum on the ion streaming time scale -- derived quantities Te = eVJ*TeeV -- Te in Joules Ti = eVJ*TieV -- Ti in Joules vte = math.sqrt(2*Te / elcMass) -- electron thermal speed vti = math.sqrt(2*Ti / ionMass) -- ion thermal speed cs = math.sqrt(Te / ionMass) -- proxy for sound speed u0 = cs*M0 -- flow velocity size at scale L0 tauei = 47.2488 * math.sqrt(elcMass)*(Te)^(3/2)*epsilon0^2/(ne*unitCharge^4*lnLambda) -- e-i collision time nuei = 1.0* 1.0/tauei -- collision frequency is inverse of collision time nuee = 1.0* 2.0*nuei -- estimating electron-electron collision time from electron-ion collision time sigma = 1.96928 * ne * unitCharge^2 * tauei / elcMass -- Spitzer conductivity eta = 1/(sigma*mu0) -- Magnetic diffusivity nuii = 1.0* ne*unitCharge^4*lnLambda/(4*math.pi*epsilon0^2*ionMass^2*vti^3) -- i-i collision frequency nuie = 1.0* nuei*elcMass/ionMass -- estimating ion-electron collision frequency from ion-electron collision frequency nu = 1.80477*Ti/(nuii*ionMass) -- kinematic viscosity Re = u0 / (nu*k0) -- Reynolds number at scale L0 Rm = u0 / (eta*k0) -- Magnetic Reynolds number at scale L0 L0 = 1/k0 -- System size tstreamIon = L0/vti -- Thermal ion streaming time across simulation domain tLightCrossing = L0/lightSpeed -- Light crossing time for simulation domain tEnd = 3.0 * tstreamIon -- end of simulation time (now: fraction of the ion thermal streaming time) rLe = - vte / (elcCharge * BNoiseAmpl / elcMass) -- thermal electron Larmor radius at B noise amplitude rLi = - vti / (ionCharge * BNoiseAmpl / ionMass) -- thermal ion Larmor radius at B noise amplitude -- domain size and simulation time LX = 1*L0 LY = 1*L0 LZ = 1*L0 -- Printing some information print("Te in eV") print(TeeV) print("Mach number") print(M0) print("Electron density") print(ne) print("System size") print(L0) print("Sound speed") print(cs) print("e-i collision time") print(tauei) print("Reynolds number") print(Re) print("Magnetic Reynolds number") print(Rm) print("Thermal ion crossing time") print(tstreamIon) print("Light crossing time") print(tLightCrossing) print("Noise B amplitude") print(BNoiseAmpl) print("ELectron Larmor radius") print(rLe) -- ****************************** -- FUNCTIONS -- ****************************** -- Maxwellian in 3 velocity dimensions (assumes temperature in Joules) local function maxwellian3D(n, vx, vy, vz, ux, uy, uz, mass, temp) local v2 = (vx - ux)^2 + (vy - uy)^2 + (vz - uz)^2 return n*(mass/(2*math.pi*temp))^(3/2)*math.exp(-mass*v2/(2*temp)) end -- Noise generator local function noiseGenerator(BNoiseAmpl,nmodes,x,y,z) local Pi = math.pi local _2pi = 2.0 * math.pi local sin = math.sin local cos = math.cos local sqrt = math.sqrt local Bx = 0.0 local By = 0.0 local Bz = 0.0 local Jx = 0.0 local Jy = 0.0 local Jz = 0.0 local B_xy = 0.0 local B_xz = 0.0 local B_yx = 0.0 local B_yz = 0.0 local B_zx = 0.0 local B_zz = 0.0 local phase_xy = 0.0 local phase_xz = 0.0 local phase_yx = 0.0 local phase_yz = 0.0 local phase_zx = 0.0 local phase_zz = 0.0 local seed = 120387 for i = 1, nmodes do seed = seed + 1 math.randomseed(seed) B_xy = math.random() B_xz = math.random() B_yx = math.random() B_yz = math.random() B_zx = math.random() B_zy = math.random() phase_xy = math.random() phase_xz = math.random() phase_yx = math.random() phase_yz = math.random() phase_zx = math.random() phase_zy = math.random() Bx = Bx + B_xy*cos(_2pi*i*(y/LY+phase_xy)) + B_xz*cos(_2pi*i*(z/LZ+phase_xz)) By = By + B_yx*cos(_2pi*i*(x/LX+phase_yx)) + B_yz*cos(_2pi*i*(z/LZ+phase_yz)) Bz = Bz + B_zx*cos(_2pi*i*(x/LX+phase_zx)) + B_zy*cos(_2pi*i*(y/LY+phase_zy)) Jx = Jx + i*( B_yz*sin( _2pi*i*(z/LZ+phase_yz) )/LZ - B_zy*sin( _2pi*i*(y/LY+phase_zy) )/LY ) Jy = Jy - i*( B_xz*sin( _2pi*i*(z/LZ+phase_xz) )/LZ + B_zx*sin( _2pi*i*(x/LX+phase_zx) )/LX ) Jz = Jz + i*( B_xy*sin( _2pi*i*(y/LY+phase_xy) )/LY - B_yx*sin( _2pi*i*(x/LX+phase_yx) )/LX ) end Bx = Bx * BNoiseAmpl By = By * BNoiseAmpl Bz = Bz * BNoiseAmpl Jx = Jx * BNoiseAmpl * _2pi/mu0 Jy = Jy * BNoiseAmpl * _2pi/mu0 Jz = Jz * BNoiseAmpl * _2pi/mu0 return Bx, By, Bz, Jx, Jy, Jz end -- Generates Roberts flow 1 on cubic domain, flow speed is called u0 local function robertsFlow(x,y,z) -- Assumes that LX=LY=LZ and the flow speed u0 are defined local Pi = math.pi local _2pi = 2.0 * math.pi local sin = math.sin local cos = math.cos local uRx, uRy, uRz = 0.0, 0.0, 0.0 uRx = u0 * ( cos(_2pi*y/LY) - cos(_2pi*z/LZ) ) uRy = u0 * sin(_2pi*z/LZ) uRz = u0 * sin(_2pi*y/LY) return uRx, uRy, uRz end -- ****************************** -- VLASOV APP -- ****************************** vlasovApp = Plasma.App { logToFile = true, tEnd = tEnd, -- end time suggestedDt = tLightCrossing/(10*5), -- suggested time step (here: some fraction of the light crossing time across cell) nFrame = 200, -- number of output frames lower = {0.0, 0.0, 0.0}, -- configuration space lower left upper = {LX, LY, LZ}, -- configuration space upper right cells = {10, 10, 10}, -- configuration space cells basis = "serendipity", -- one of "serendipity" or "maximal-order" polyOrder = 1, -- polynomial order timeStepper = "rk3", -- one of "rk2" or "rk3" -- restartFrameEvery = 0.1, -- not using restart frames for the dime being -- decomposition for configuration space decompCuts = {2, 2, 2}, -- cuts in each configuration direction useShared = true, -- if to use shared memory periodicDirs ={1, 2, 3}, -- electrons elc = Plasma.Species { nDistFuncFrame = 10, charge = elcCharge, mass = elcMass, -- velocity space grid lower = {-3.0*vte, -3.0*vte, -3.0*vte}, upper = {3.0*vte, 3.0*vte, 3.0*vte}, cells = {10, 10, 10}, decompCuts = {1, 1, 1}, -- do not change, no parallelization in velocity space currently -- initial conditions init = function (t, xn) local x, y, z, vx, vy, vz = xn[1], xn[2], xn[3], xn[4], xn[5], xn[6] local ux, uy, uz = 0.0, 0.0, 0.0 local Bx, By, Bz, Jx, Jy, Jz = noiseGenerator(BNoiseAmpl,nmodes,x,y,z) local uRx, uRy, uRz = robertsFlow(x,y,z) ux = Jx/(elcCharge*ne) + uRx -- uR assumes singly charged ions to cancel current uy = Jy/(elcCharge*ne) + uRy uz = Jz/(elcCharge*ne) + uRz local fv = maxwellian3D(ne, vx, vy, vz, ux, uy, uz, elcMass, Te) return fv end, evolve = true, -- evolve species? -- write out density, flow, total energy, and heat flux moments diagnosticMoments = { "M0", "M1i", "M2" }, -- Collisions. -- coll = Plasma.LBOCollisions { -- collideWith = { "elc", "ion", }, -- frequencies = { nuee, nuei, }, -- Optional arguments: -- crossOption = "Greene", -- Or crossOption="HeavyIons". -- betaGreene = 1.0, -- }, }, -- protons ion = Plasma.Species { nDistFuncFrame = 10, charge = ionCharge, mass = ionMass, -- velocity space grid lower = {-3.0*vti, -3.0*vti, -3.0*vti}, upper = {3.0*vti, 3.0*vti, 3.0*vti}, cells = {10, 10, 10}, decompCuts = {1, 1, 1}, -- do not change, no parallelization in velocity space currently -- initial conditions init = function (t, xn) local x, y, z, vx, vy, vz = xn[1], xn[2], xn[3], xn[4], xn[5], xn[6] local ux, uy, uz = 0.0, 0.0, 0.0 local uRx, uRy, uRz = robertsFlow(x,y,z) ux = uRx uy = uRy uz = uRz local fv = maxwellian3D(ne, vx, vy, vz, ux, uy, uz, ionMass, Ti) return fv end, -- Forcing (set to be proportional to the Roberts flow.) vlasovExtForceFunc = function(t, xn) x, y, z = xn[1], xn[2], xn[3] local ux, uy, uz = 0.0, 0.0, 0.0 local uRx, uRy, uRz = robertsFlow(x,y,z) force_x = forcefactor*uRx / tstreamIon force_y = forcefactor*uRy / tstreamIon force_z = forcefactor*uRz / tstreamIon return force_x, force_y, force_z end, evolve = true, -- evolve species? -- write out density, flow, total energy, and heat flux moments diagnosticMoments = { "M0", "M1i", "M2" }, -- Collisions. -- coll = Plasma.LBOCollisions { -- collideWith = { "ion", "elc", }, -- frequencies = { nuii, nuie, }, -- Optional arguments: --crossOption = "Greene", -- Or crossOption="HeavyIons". --betaGreene = 1.0, -- }, }, -- field solver field = Plasma.Field { epsilon0 = epsilon0, mu0 = mu0, init = function (t, xn) local x, y, z = xn[1], xn[2], xn[3] local Bx, By, Bz, Jx, Jy, Jz = noiseGenerator(BNoiseAmpl,nmodes,x,y,z) local Ex, Ey, Ez = 0.0, 0.0, 0.0 return Ex, Ey, Ez, Bx, By, Bz end, evolve = true, -- evolve field? }, -- ****************************** -- EXECUTING VLASOV APP -- ****************************** } -- run application vlasovApp:run()
-- This is the background for a single row inside ScreenMiniMenuContext -- which, so far in Simply Love, is only used for the faux-overlay menu -- that pops up when editing local profiles. -- -- The Quad is wrapped in an ActorFrame so that we can apply zoomto() -- via OnCommand without having the engine say that the OnCommand for -- the Frame is already defined in Metrics.ini -- -- It is unclear why I once thought defining the height of a row in this menu -- to be 1/20 of the screen's height was a good idea, but it works, so I -- guess I'll just leave it alone for now... return Def.ActorFrame{ Def.Quad { OnCommand=function(self) self:zoomto(200,_screen.h*0.05) end } }
local theme_config_default= { AutoSetStyle= true, LongFail= false, ComboOnRolls= false, FancyUIBG= false, TimingDisplay= false, GameplayFooter= false, Use12HourClock= false, } theme_config= create_lua_config{ name= "theme_config", file= "theme_config.lua", default= theme_config_default, } theme_config:load()
require("import") -- the import fn import("smart_pointer_rename") -- import lib into global spr=smart_pointer_rename --alias -- catching undefined variables local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) foo = spr.Foo() assert(foo:ftest1(1) == 1) assert(foo:ftest2(1,2) == 2) bar = spr.Bar(foo) assert(bar:test() == 3) assert(bar:ftest1(1) == 1) assert(bar:ftest2(1,2) == 2)
if CLIENT then return end DATA_BIT = "DATA_BIT" DATA_BOOL = DATA_BIT DATA_BYTE = "DATA_BYTE" DATA_8BITS = DATA_BYTE DATA_1BYTE = DATA_BYTE DATA_DOUBLE = "DATA_DOUBLE" DATA_64BITSDOUBLE = DATA_DOUBLE DATA_8BYTESDOUBLE = DATA_DOUBLE DATA_FLOAT = "DATA_FLOAT" DATA_32BITSFLOAT = DATA_FLOAT DATA_4BYTESFLOAT = DATA_FLOAT DATA_LINE = "DATA_LINE" DATA_LONG = "DATA_LONG" DATA_32BITS = DATA_LONG DATA_4BYTES = DATA_LONG DATA_SHORT = "DATA_SHORT" DATA_16BITS = DATA_SHORT DATA_2BYTES = DATA_SHORT DATA_ULONG = "DATA_ULONG" DATA_U31BITS = DATA_ULONG DATA_U4BYTES = DATA_ULONG DATA_USHORT = "DATA_USHORT" DATA_U16BITS = DATA_USHORT DATA_U2BYTES = DATA_USHORT DATA_STRING = "DATA_STRING" DATA_NEXTZERO = DATA_STRING local actions = { DATA_BIT = function(file) return file:ReadByte() end, DATA_BYTE = function(file) return file:ReadByte() end, DATA_DOUBLE = function(file) return file:ReadDouble() end, DATA_FLOAT = function(file) return file:ReadFloat() end, DATA_LONG = function(file) return file:ReadLong() end, DATA_SHORT = function(file) return file:ReadShort() end, DATA_ULONG = function(file) return file:ReadULong() end, DATA_USHORT = function(file) return file:ReadUShort() end, DATA_STRING = function(file) local byteTable = {} while (true) do local byte = file:ReadByte() if byte == 0 then return table.concat(byteTable) end local char = string.char(byte) table.insert(byteTable, char) end end } local specialActions = { DATA_LENSTRING = function(file, count) return file:Read(count) end, DATA_SKIP = function(file, count) file:Skip(count) end } local function handleAction(action, file) local _action = actions[action] if _action then return _action(file) else for k, v in pairs(specialActions) do if string.StartWith(action, k) then _action = k break end end if (_action) then local numStr = string.Right(action, action:len() - _action:len()) local num = tostring(numStr) return specialActions[_action](file, num) end end Error(string.format("Action : %s isn't implemented", action)) end function parseFile(path, struct) local outTbl = {} assert(file.Exists(path, "GAME"), string.format("File [%s] doesn't exist", path)) assert(istable(struct), "struct isn't a table") local gma = file.Open(path, "rb", "GAME") if not gma then return nil end for k, v in pairs(struct) do local key, value = next(v) outTbl[key] = handleAction(value, gma) end return outTbl end local fileStruct = { -- i had to do this ugly shit to conserv the order {HEADER = "DATA_LENSTRING4"}, {Version = DATA_BYTE}, {SteamID_Unused = "DATA_SKIP8"}, {TimeStamp = DATA_64BITSDOUBLE}, {Junk = "DATA_SKIP1"}, {Title = DATA_STRING}, {Description = DATA_STRING}, {Author_string = DATA_STRING}, {Addon_version = DATA_4BYTES}, } local tbl = parseFile("data/test.gma", fileStruct) PrintTable(tbl)
local tremove = table.remove function ezlib.log.print(tbl, indent) local freturn = 1 if not indent then indent = 0 freturn = 0 end local toprint = --[["\n" .. string.rep(" ", indent) .. ]]"{\r\n" indent = indent + 1 if type(tbl) == "table" then for k,v in pairs(tbl) do toprint = toprint .. string.rep(" ", indent) if (type(k) == "number") then toprint = toprint .. "[" .. k .. "] = " elseif (type(k) == "string") then toprint = toprint .. k .. " = " end if (type(v) == "number") then toprint = toprint .. v .. ",\r\n" elseif (type(v) == "string") then toprint = toprint .. '"' .. v .. '",\r\n' elseif (type(v) == "table") then local counter = 0 for _,_ in pairs(v) do counter = counter + 1 end if counter == 0 then toprint = toprint .. "{ },\r\n" else toprint = toprint .. ezlib.log.print(v, indent) .. ",\r\n" end else toprint = toprint .. "" .. tostring(v) .. ",\r\n" end end toprint = toprint .. string.rep(" ", indent - 1) .. "}" if freturn == 0 then log(toprint) else return toprint end else if freturn == 0 then log(tbl) else return tbl end end end function ezlib.tbl.remove(list1, list2) local print = "ezlib.tbl.remove\n---------------------------------------------------------------------------------------------\n" if list1 ~= nil then if list2 ~= nil then local list3 = {} for _, ing in pairs(list1) do list3[#list3+1] = ing end local z = 0 for x, ing in pairs(list1) do if type(list2) == "table" then for _,ing2 in pairs(list2) do if ing == ing2 then tremove(list3, (x - z)) z = z + 1 break end end else if list1[x] == list2 then tremove(list1, x) end end end if type(list2) ~= "string" then print = print .. " Removed ".. (#list1 - #list3) .. " items.\n" else print = print .. " Removed string ".. list2 .. ".\n" end if ezlib.debug_self then log(print .. " \n---------------------------------------------------------------------------------------------") end return list3 else if ezlib.debug_self then print = print .. " list2 is empty." log(print .. "\n---------------------------------------------------------------------------------------------") end return list1 end else if ezlib.debug_self then print = print .. " list1 is empty. Returning: nil" log(print .. "\n---------------------------------------------------------------------------------------------") end return nil end end function ezlib.tbl.add(list1, list2, list3, list4, list5) local list = {} local print = "ezlib.tbl.add\n---------------------------------------------------------------------------------------------\n" if type(list1) == "table" then for _,ing in pairs(list1) do list[#list+1] = ing end print = print .. " Table_1 added as table\n" elseif type(list1) == "string" then list[#list+1] = list1 print = print .. " Table_1 added as string\n" end if type(list2) == "table" then for _,ing in pairs(list2) do list[#list+1] = ing end print = print .. " Table_2 added as table\n" elseif type(list2) == "string" then list[#list+1] = list2 print = print .. " Table_2 added as string\n" end if type(list3) == "table" then for _,ing in pairs(list3) do list[#list+1] = ing end print = print .. " Table_3 added as table\n" elseif type(list3) == "string" then list[#list+1] = list3 print = print .. " Table_3 added as string\n" end if type(list4) == "table" then for _,ing in pairs(list4) do list[#list+1] = ing end print = print .. " Table_4 added as table\n" elseif type(list4) == "string" then list[#list+1] = list4 print = print .. " Table_4 added as string\n" end if type(list5) == "table" then for _,ing in pairs(list5) do list[#list+1] = ing end print = print .. " Table_5 added as table\n" elseif type(list5) == "string" then list[#list+1] = list5 print = print .. " Table_5 added as string\n" end if ezlib.debug_self then log(print .. "---------------------------------------------------------------------------------------------") end return list end function ezlib.string.add(string1, string2, string3, string4, string5) local string = "" local print = "ezlib.string.add\n---------------------------------------------------------------------------------------------\n" if type(string1) == "string" then string = string .. string1 end if type(string2) == "string" then string = string .. string2 end if type(string3) == "string" then string = string .. string3 end if type(string4) == "string" then string = string .. string4 end if type(string5) == "string" then string = string .. string5 end if ezlib.debug_self then print = print .. " Returning: " .. string log(print .. "\n---------------------------------------------------------------------------------------------") end return string end function ezlib.remove(ftype, value) local entites = data.raw[ftype] if entites and entites[value] then local entity = entites[value] if not entity.icon and not entity.icons then log(entity.icon) entity.icon = "__core__/graphics/slot-icon-blueprint.png" log(" [Warning] " .. ftype .. " with name " .. value .. " has no icon adding...") entity.localised_description = "Icon not found" end if not entity.icon_size then entity.icon_size = 32 log(" [Warning] " .. ftype .. " with name " .. value .. " has no icon_size adding...") end end end
local banks = { ["Bank1"] = { ["x"]=152.04, ["y"]=-1040.77, ["z"]= 29.37, ["robbing"] = false, ["robbingvault"] = false, ["lastRobbed"] = 1, ["rob"] = {}, ["started"] = false }, ["Bank2"] = { ["x"]=-1212.980, ["y"]=-330.841, ["z"]= 37.787, ["robbing"] = false, ["robbingvault"] = false, ["lastRobbed"] = 1, ["rob"] = {}, ["started"] = false }, ["Bank3"] = { ["x"]=-2962.582, ["y"]=482.627, ["z"]= 15.703, ["robbing"] = false, ["robbingvault"] = false, ["lastRobbed"] = 1, ["rob"] = {}, ["started"] = false }, ["Bank4"] = { ["x"]=314.187, ["y"]=-278.621, ["z"]= 54.170, ["robbing"] = false, ["robbingvault"] = false, ["lastRobbed"] = 1, ["rob"] = {}, ["started"] = false }, ["Bank5"] = { ["x"]=-351.534, ["y"]=-49.529, ["z"]= 49.042, ["robbing"] = false, ["robbingvault"] = false, ["lastRobbed"] = 1, ["rob"] = {}, ["started"] = false }, ["Bank6"] = { ["x"]=1176.04, ["y"]=2706.339, ["z"]= 37.15, ["robbing"] = false, ["robbingvault"] = false, ["lastRobbed"] = 1, ["rob"] = {}, ["started"] = false }, } RegisterServerEvent("rob:doorOpen") AddEventHandler("rob:doorOpen", function(bankId,robbing) local src = source local bank = "Bank"..bankId if robbing == "robbingvault" then local bankRob = banks[bank] bankRob["started"] = false bankRob["robbing"] = true bankRob["robbingvault"] = true TriggerClientEvent('robbery:openDoor',-1,"square") TriggerClientEvent('robbery:scanbank',src, bankId, banks) end if robbing == "robbing" then end end) RegisterServerEvent("robbery:checkSearch") AddEventHandler("robbery:checkSearch", function(nearbank, inputType) local src = source TriggerClientEvent('robbery:giveleitem', source, nearbank, inputType) local bank = "Bank"..nearbank local bankRob = banks[bank] table.insert(bankRob.rob, inputType) TriggerClientEvent("robbery:scanbank",src,nearbank,banks) end) RegisterServerEvent("request:BankUpdate") AddEventHandler("request:BankUpdate", function() local src = source local timers = {1,2,3,4,5,6} TriggerClientEvent('robbery:timers',src, timers) banks["started"] = true for i=1,6 do local bankRob = banks['Bank'..i] bankRob["started"] = true end Citizen.Wait(1000) TriggerClientEvent('updateBanksNow',src, banks) end) RegisterServerEvent("robbery:decrypt") AddEventHandler("robbery:decrypt", function() local src = source TriggerClientEvent('send:email', src) end) RegisterServerEvent('robbery:shutdown') AddEventHandler('robbery:shutdown', function(bankID) TriggerClientEvent('robbery:shutdownBank',-1,bankID,true) local bankSecured = banks[bank] bankSecured["started"] = false TriggerClientEvent("robbery:closeDoor", -1, "square") end)
local Util = require("Util/Util") local WikiText = require("Pages/World_of_Warcraft_API/WikiText") Util:MakeDir("cache_lua") local m = {} local ignoredTags = { DEPRECATED = true, UI = true, Lua = true, } function m:ParseWikitext(wikitext) local api_names, tag_data = {}, {} for s1, name in string.gmatch(wikitext, "\n:(.-)%[API (.-)|") do table.insert(api_names, name) -- allow finding duplicates local tag = s1:match("<small>''(.-)''</small>") if tag then tag_data[name] = tag end end return api_names, tag_data end function m:GetGlobalApi() local global_api = Util:DownloadAndRun( "cache_lua/GlobalAPI.lua", "https://raw.githubusercontent.com/Ketho/BlizzardInterfaceResources/mainline/Resources/GlobalAPI.lua" ) return Util:ToMap(global_api[1]) end function m:FindDuplicates(wowpedia) print("-- duplicates") local t = {} for _, v in pairs(wowpedia) do if t[v] then print(v) else t[v] = true end end end function m:HasIgnoredTag(str) local tags = Util:strsplit(str, ", ") for _, tag in pairs(tags) do if ignoredTags[tag] then return true end end end function m:FindMissing(wowpedia, wowpedia_tags, global_api) local map = Util:ToMap(wowpedia) print("\n-- to add") for _, k in pairs(Util:SortTable(global_api)) do if not map[k] then print(k) end end print("\n-- to remove") table.sort(wowpedia) for _, k in pairs(wowpedia) do local hasIgnoredTag = wowpedia_tags[k] and self:HasIgnoredTag(wowpedia_tags[k]) if not global_api[k] and not hasIgnoredTag then print(k) end end end local function main() WikiText:SaveExport() local text = WikiText:GetWikitext(true) local api, tags = m:ParseWikitext(text) m:FindDuplicates(api) local global_api = m:GetGlobalApi() m:FindMissing(api, tags, global_api) end main() print("done")
--[[ 3p8_collector_rock Uses: Collects 3p8_rock_s Todo: perhaps make this be apart of a vehicle (or crane or something) in the future. ]] AddCSLuaFile() ENT.Base = "3p8_collector" ENT.HeldObject = "3p8_rock_s" ENT.ItemName = "Collector: Rocks" ENT.ItemModel = "models/props_c17/oildrum001.mdl" ENT.MaxCount = 5 ENT.Health = 100
<td>{{ ( "&nbsp;&nbsp;&nbsp;" ):rep( depth ) }}<a class="rare{{ weapon.rarity }}{{ weapon.create and " create" or "" }}" href="{{ U( ( "weapons/%s/%s" ):format( class.short, urlFromName( weapon.name ) ) ) }}">{{ T( weapon.name ) }}</a></td> <td>{{ weapon.attack }}</td> <td>{{ weapon.reload }}</td> <td>{{ weapon.drift }}</td> <td>{{ weapon.recoil }}</td> <td{% if weapon.affinity ~= 0 then printf( [[ class="%s"]], weapon.affinity > 0 and "pos" or "neg" ) end %}>{{ weapon.affinity }}%</td> <td{{ weapon.slots == 0 and [[ class="none">-]] or ">" .. ( "O" ):rep( weapon.slots ) }}</td>
--Uk-P.U.N.K.アメイジング・ドラゴン --Scripted by mallu11 function c100417008.initial_effect(c) --synchro summon aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1) c:EnableReviveLimit() --tohand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(100417008,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET) e1:SetCountLimit(1,100417008) e1:SetCondition(c100417008.thcon) e1:SetTarget(c100417008.thtg) e1:SetOperation(c100417008.thop) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(100417008,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1,100417008) e2:SetTarget(c100417008.sptg) e2:SetOperation(c100417008.spop) c:RegisterEffect(e2) end function c100417008.thcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsSummonType(SUMMON_TYPE_SYNCHRO) end function c100417008.thfilter(c) return (c:IsFaceup() or c:IsLocation(LOCATION_GRAVE)) and c:IsRace(RACE_PSYCHO) and c:IsLevel(3) end function c100417008.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and chkc:IsAbleToHand() end if chk==0 then return Duel.IsExistingMatchingCard(c100417008.thfilter,tp,LOCATION_MZONE+LOCATION_GRAVE,0,1,nil) and Duel.IsExistingTarget(Card.IsAbleToHand,tp,0,LOCATION_ONFIELD,1,nil) end local g=Duel.GetMatchingGroup(c100417008.thfilter,tp,LOCATION_MZONE+LOCATION_GRAVE,0,nil) local ct=g:GetClassCount(Card.GetCode) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND) local sg=Duel.SelectTarget(tp,Card.IsAbleToHand,tp,0,LOCATION_ONFIELD,1,ct,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,sg,sg:GetCount(),0,0) end function c100417008.thop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) end end function c100417008.spfilter(c,e,tp) return not c:IsCode(100417008) and c:IsSetCard(0x26f) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c100417008.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c100417008.spfilter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c100417008.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c100417008.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c100417008.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
engine_name = 'memtx' iterations = 100000 math.randomseed(1) delete_replace_update(engine_name, iterations) math.randomseed(2) delete_replace_update(engine_name, iterations) math.randomseed(3) delete_replace_update(engine_name, iterations) math.randomseed(4) delete_replace_update(engine_name, iterations) math.randomseed(5) delete_replace_update(engine_name, iterations)
#!/usr/bin/env lua local ui = require "tek.ui" ui.Application:new { AuthorStyles = [[ .huge { width: free; height: free; font: ui-huge; } ]], Children = { ui.Window:new { Title = "Groups Demo", HideOnEscape = true, Children = { ui.ScrollGroup:new { Legend = "Virtual Group", HSliderMode = "on", VSliderMode = "on", Child = ui.Canvas:new { AutoPosition = true, MaxWidth = 500, MaxHeight = 500, CanvasWidth = 500, CanvasHeight = 500, Child = ui.Group:new { Columns = 2, Children = { ui.Button:new { Text = "Foo", Class = "huge" }, ui.Button:new { Text = "Bar", Class = "huge" }, ui.Button:new { Text = "Baz", Class = "huge" }, ui.ScrollGroup:new { Legend = "Virtual Group", Width = 500, Height = 500, MinWidth = 0, MinHeight = 0, HSliderMode = "on", VSliderMode = "on", Child = ui.Canvas:new { AutoPosition = true, CanvasWidth = 500, CanvasHeight = 500, Child = ui.Group:new { Columns = 2, Children = { ui.Button:new { Text = "Red", Class = "huge" }, ui.Button:new { Text = "Green", Class = "huge" }, ui.Button:new { Text = "Blue", Class = "huge" }, ui.ScrollGroup:new { Legend = "Virtual Group", Width = 500, Height = 500, MinWidth = 0, MinHeight = 0, HSliderMode = "on", VSliderMode = "on", Child = ui.Canvas:new { AutoPosition = true, CanvasWidth = 500, CanvasHeight = 500, Child = ui.Group:new { Columns = 2, Children = { ui.Button:new { Text = "One", Class = "huge" }, ui.Button:new { Text = "Two", Class = "huge" }, ui.Button:new { Text = "Three", Class = "huge" }, ui.Button:new { Text = "Four", Class = "huge" }, } } } } } } } } } } } } } } } }:run()
local Commands = {} Commands.util = {} Commands.util.dontUse = {} function Commands.become_god(self) if self.util.allowedToUse() == false then return end if game.player.character == nil then return end local inventories = { defines.inventory.character_main, defines.inventory.character_guns, defines.inventory.character_ammo, defines.inventory.character_armor, defines.inventory.character_tools, defines.inventory.character_vehicle, defines.inventory.character_trash } local playerCharacter = game.player.character game.player.character = nil for _, inv in pairs(inventories) do self.util.transferInventory(playerCharacter, game.player, inv) end playerCharacter.destroy() end function Commands.become_mortal(self) local position = self.player.position if self.player.character == nil then game.player.create_character() self.player.teleport(position) end end function Commands.cli_ext(self) local availableCommands = "The following commands are added by "..mod_info.print_name.."\r" for _, v in pairs(self.util.getCommands()) do availableCommands = availableCommands .. " /" .. v end self.player.print(availableCommands); end function Commands.destroy_selected(self) if self.util.allowedToUse() == false then return end if self.player.selected ~= nil then self.player.selected.destroy() end end function Commands.empty_all_pipes(self) if self.util.allowedToUse() == false then return end local surface = self.player.surface local deleted=0 for key, entity in pairs(surface.find_entities_filtered({force=self.player.force})) do if string.find(entity.name, "pipe") or string.find(entity.name, "pump") or string.find(entity.name, "tank") then for i=1,#entity.fluidbox do deleted = deleted + 1 entity.fluidbox[i] = nil; end end end self.player.print("Fluids removed from "..deleted .." entities") end function Commands.finish_current_tech(self) if self.util.allowedToUse() == false then return end if self.player.force.current_research ~= nil then self.player.force.current_research.researched = true end end function Commands.freeze(self) if self.util.allowedToUse() == false then return end self.player.surface.freeze_daytime = self.util.switchBool(self.player.surface.freeze_daytime, "Freezing") end function Commands.generate_ore_patch(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": ore name. Example usage '/generate_ore_patch iron ore'" if not self.util.correctParameterCount(1, parameterCountMessage) then return end local ore_name = self.util.join(self.parameters, "-") if (game.item_prototypes[ore_name] == nil) then game.print(ore_name.." was not found as a resource") return end local surface=self.player.surface local ore=nil local size=math.random(10, 20) local density=math.random(7, 20) for y=-size, size do for x=-size, size do a=(size+1-math.abs(x))*10 b=(size+1-math.abs(y))*10 if a<=b then ore=math.random(a*density-a*(density-8), a*density+a*(density-8)) end if b<a then ore=math.random(b*density-b*(density-8), b*density+b*(density-8)) end surface.create_entity({name=ore_name, amount=ore, position={self.player.position.x+x, self.player.position.y+y}}) end end end function Commands.generate_oil_patch (self) if self.util.allowedToUse() == false then return end local ore_name = "crude-oil" if self.parameterCount > 0 then local ore_name = self.util.join(self.parameters, "-") end if (game.entity_prototypes[ore_name] == nil) then game.print(ore_name.." was not found as a resource") return end local surface=self.player.surface local position=nil for i=1,9 do position=game.player.surface.find_non_colliding_position("crude-oil", self.player.position, 0, i/2+1.5) if position then surface.create_entity({name=ore_name, amount=5000, position=position}) end end end function Commands.give_stack(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": item name. Example usage '/give_stack iron plate'" if not self.util.correctParameterCount(1, parameterCountMessage) then return end local name = self.util.join(self.parameters, "-") if game.item_prototypes[name] ~= nil then local stack = game.item_prototypes[name].stack_size self.player.insert({ name = name, count = stack }) end end function Commands.kill_enemies(self) if self.util.allowedToUse() == false then return end for key, entity in pairs(self.player.surface.find_entities_filtered({ force = "enemy" })) do entity.destroy() end end function Commands.lock_all_tech(self) if self.util.allowedToUse() == false then return end for _, tech in pairs(self.player.force.technologies) do tech.researched = false self.player.force.set_saved_technology_progress(tech, 0) end end function Commands.lock_tech(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": nameOfResearch. Example usage '/lock_tech automation'" if not self.util.correctParameterCount(1, parameterCountMessage) then return end local techName = self.util.join(self.parameters, "-") if self.player.force.current_research ~= nil then if self.player.force.current_research.name == techName then self.player.force.current_research = nil end end self.player.print("Searching technology with the name: '" .. techName .. "' ") for _, tech in pairs(self.player.force.technologies) do if tech.name == techName then self.player.print("Technology with the name: '" .. techName .. "' found") selectedTech = tech elseif tech.prerequisites[techName] ~= nil then self.util.lockDependingTechs(tech) end end if selectedTech == nil then self.player.print("Technology with the name: '" .. techName .. "' was not found") return end selectedTech.researched = false self.player.force.set_saved_technology_progress(selectedTech, 0) end function Commands.map_cancel_reveal(self) self.player.force.cancel_charting(self.player.surface) end function Commands.map_rechart(self) if self.util.allowedToUse() == false then return end self.player.force.rechart() end function Commands.map_reveal(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": distance. Example usage '/map_reveal 32'" if not self.util.correctParameterCount(1, parameterCountMessage) then return end local left_top, right_bottom = self.player.position, self.player.position left_top.x = left_top.x - self.parameters[1] left_top.y = left_top.y - self.parameters[1] right_bottom.x = right_bottom.x + self.parameters[1] right_bottom.y = right_bottom.y + self.parameters[1] self.player.force.chart(self.player.surface, {left_top, right_bottom}) end function Commands.pickup_dropped_items(self) if self.util.allowedToUse() == false then return end local radius = 32 if self.parameterCount > 0 then radius = self.parameters[1] end local groundEntities = self.player.surface.find_entities_filtered({ area = { { self.player.position.x - radius, self.player.position.y - radius }, { self.player.position.x + radius, self.player.position.y + radius } }, name = "item-on-ground" }) for _, entity in pairs(groundEntities) do entity.to_be_looted = true entity.teleport({ self.player.position.x, self.player.position.y }) end end function Commands.position(self) local color = self.player.color color.a = 0.5 self.player.print(self.player.name .. ": (" .. self.player.position.x .. ", " .. self.player.position.y .. ")", color) end function Commands.position_to_global_chat(self) local color = self.player.color color.a = 0.5 game.print(self.player.name .. ": (" .. game.player.position.x .. ", " .. game.player.position.y .. ")", color) end function Commands.position_to_player(self) local parameterCountMessage = ": playerName, Example usage: /position_to_player " .. self.player.name if not self.util.correctParameterCount(1, parameterCountMessage) then return end local destinationPlayer = self.util.getPlayerIndexFromName(self.parameters[1]) if destinationPlayer == nil then return else destinationPlayer = game.players[destinationPlayer] end local color = self.player.color color.a = 0.5 destinationPlayer.print(self.player.name .. ": (" .. game.player.position.x .. ", " .. game.player.position.y .. ")", color) end function Commands.save(self) if self.parameterCount > 0 then local savename = self.util.join(self.parameters, " ") game.print("saving as: " .. savename) game.server_save(savename) else game.print("saving") game.auto_save(); end end function Commands.set_crafting_speed(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": speed. Example usage '/set_crafting_speed 2'" if not self.util.correctParameterCount(1, parameterCountMessage) then return end local player = self.player if self.parameters[2] ~= nil then local destinationPlayer = self.util.getPlayerIndexFromName(self.parameters[2]) player = game.players[destinationPlayer] end player.character_crafting_speed_modifier = self.parameters[1] end function Commands.set_mining_speed(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": speed. Example usage '/set_mining_speed 2'" if not self.util.correctParameterCount(1, parameterCountMessage) then return end local player = self.player if self.parameters[2] ~= nil then local destinationPlayer = self.util.getPlayerIndexFromName(self.parameters[2]) player = game.players[destinationPlayer] end player.character_mining_speed_modifier = self.parameters[1] end function Commands.set_running_speed(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": speed. Example usage '/set_running_speed 2'" if not self.util.correctParameterCount(1, parameterCountMessage) then return end local player = self.player if self.parameters[2] ~= nil then local destinationPlayer = self.util.getPlayerIndexFromName(self.parameters[2]) player = game.players[destinationPlayer] end player.character_running_speed_modifier = self.parameters[1] end function Commands.speed(self) if self.util.allowedToUse() == false then return end if self.util.correctParameterCount(1) == false then return end local speed = tonumber(self.parameters[1]) if speed < 1 then self.player.print("Game can not run slower than 1% speed") speed = 1 elseif speed > 10000 then self.player.print("Game should not go faster then 10.000% speed. It can severly harm the performance of the game after that") speed = 10000 end speed = speed / 100 game.speed = speed end function Commands.teleport_to(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": x and y. Example usage '/teleport_to 0 0'" if not self.util.correctParameterCount(2, parameterCountMessage) then return end if tonumber(self.parameters[1]) ~= nil and tonumber(self.parameters[2]) ~= nil then self.player.teleport(self.util.makeValidTeleportLocation({ x = tonumber(self.parameters[1]), y = tonumber(self.parameters[2]) })) end end function Commands.teleport_to_player(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": player_name. Example usage '/teleport_to_player "..self.player.name.."'" if not self.util.correctParameterCount(1, parameterCountMessage) then return end local destinationPlayer = self.util.getPlayerIndexFromName(self.parameters[1]) if destinationPlayer == nil then return else destinationPlayer = game.players[destinationPlayer] end local destinationPosition = destinationPlayer.position self.player.teleport(self.util.makeValidTeleportLocation(destinationPosition)) end --function Commands.teleport_us(self) -- if self.util.allowedToUse() == false then return end -- local parameterCountMessage = ": x, y, player_name,[player_name]. Example usage '/teleport_us 0, 0, jelmergu'" -- if not self.util.correctParameterCount(3, parameterCountMessage) then -- return -- end -- -- local destinationPosition, destinationPlayer = {x= tonumber(self.parameters[1]), y=tonumber(self.parameters[2])} -- self.player.teleport(self.util.makeValidTeleportLocation(destinationPosition)) -- for i = 3, self.parameterCount do -- local destinationPlayer = self.util.getPlayerIndexFromName(self.parameters[i]) -- if destinationPlayer ~= nil then -- destinationPlayer = game.players[destinationPlayer] -- game.players[destinationPlayers].teleport(self.util.makeValidTeleportLocation(destinationPosition)) -- destinationPlayer = nil -- end -- end --end function Commands.teleport_to_me(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": player_name. Example usage '/teleport_to_player "..self.player.name.."'" if not self.util.correctParameterCount(1, parameterCountMessage) then return end local sourcePlayer = self.util.getPlayerIndexFromName(self.parameters[1]) if sourcePlayer == nil then return else sourcePlayer = game.players[sourcePlayer] end local destinationPosition = self.player.position sourcePlayer.teleport(self.util.makeValidTeleportLocation(destinationPosition)) end function Commands.toggle_cheat(self) if self.util.allowedToUse() == false then return end self.player.cheat_mode = self.util.switchBool(self.player.cheat_mode, "Cheat mode is now") end function Commands.toggle_expansion(self) if self.util.allowedToUse() == false then return end game.map_settings.enemy_expansion.enabled = self.util.switchBool(game.map_settings.enemy_expansion.enabled, "Enemy expansion is now") end function Commands.toggle_friendly_fire(self) if self.util.allowedToUse() == false then return end self.player.force.friendly_fire = self.util.switchBool(self.player.force.friendly_fire, "Friendly fire is now") end function Commands.toggle_night(self) if self.util.allowedToUse() == false then return end self.player.surface.always_day = self.util.switchBool(self.player.surface.always_day, "Turning always_day") end function Commands.toggle_peace(self) if self.util.allowedToUse() == false then return end self.player.surface.peaceful_mode = self.util.switchBool(self.player.surface.peaceful_mode, "Peace is now") end function Commands.unlock_all_tech(self) if self.util.allowedToUse() == false then return end self.player.force.research_all_technologies() end function Commands.unlock_tech(self) if self.util.allowedToUse() == false then return end local parameterCountMessage = ": nameOfResearch. Example usage '/unlock_tech automation'" if not self.util.correctParameterCount(1, parameterCountMessage) then return end local techName = self.util.join(self.parameters, "-") self.player.print("Searching technology with the name: '" .. techName .. "' ") for _, tech in pairs(self.player.force.technologies) do if tech.name == techName then self.player.print("Technology with the name: '" .. techName .. "' found") selectedTech = tech end end if selectedTech == nil then self.player.print("Technology with the name: '" .. techName .. "' was not found") return end self.util.unlockDependingTechs(selectedTech) end function Commands.zoom(self) if not self.util.correctParameterCount(1) then return end local zoom = tonumber(self.parameters[1]) if zoom < 4 then self.player.print("zoom command is capped at 4, the game has a big potential to freeze with a zoom level that is smaller than that") zoom = 4 elseif zoom > 1000 then self.player.print("zoom command is capped at 1000, a level greater than that will be unable to completely display the player character") zoom = 1000 end zoom = zoom / 100 self.player.zoom = zoom end -- Util functions -- Check if allowed to use a command function Commands.util.allowedToUse() if (settings.startup["cli-ext-adminOnly"] == false or Commands.admin == true) then return true end game.print(Commands.player.name .. " tried to use " .. Commands.calledCommand .. " but was not allowed", Commands.player.color) return false end -- The entry point of every command. function Commands.util.command(event) Commands.player = game.get_player(event.player_index) Commands.parameters = Commands.util.explode(event.parameter, " ") Commands.parameterCount = 0 Commands.admin = Commands.player.admin for _, __ in pairs(Commands.parameters) do Commands.parameterCount = Commands.parameterCount + 1 end Commands.calledCommand = event.name if in_table(Commands, Commands.calledCommand) then Commands[Commands.calledCommand](Commands) end end -- Check if the parameter count is the same or more as count. If not display a message function Commands.util.correctParameterCount(count, message) if message == nil then message = "" end if Commands.parameterCount >= count then return true end local argumentsText = count == 1 and " argument" or " arguments" Commands.player.print(Commands.calledCommand .. " requires " .. count .. argumentsText .. message) return false end -- Convert a string to a table, splitting the string at the delimiter function Commands.util.explode(s, delimiter) if type(s) ~= "string" then return {} end result = {}; for match in (s .. delimiter):gmatch("(.-)" .. delimiter) do table.insert(result, match); end return result; end -- Get all of the commands available function Commands.util.getCommands() local returnTable = {} for k, _ in pairs(Commands) do if in_table(Commands.util.dontUse, k) == false and type(_) == "function" then table.insert(returnTable, k) end end return returnTable end -- Find a player by name and return its index or nil if the player was not found function Commands.util.getPlayerIndexFromName(name) if name == nil then Commands.player.print("Something went wrong. Please contact the writer of "..mod_info.print_name) end for k, v in pairs(game.players) do if v.name == name then return k end end Commands.player.print("Player '" .. name .. "' not found. Make sure that the name is typed correctly(case sensitive)") return nil end -- Get the help message of a command Commands.util.help = require "help" -- Join the elements of a table with the glue function Commands.util.join(t, glue) local string = "" for _, v in pairs(t) do if string ~= "" then string = string .. glue .. v else string = string .. v end end return string end -- Lock the techs that depend on the given tech function Commands.util.lockDependingTechs(tech) if Commands.player.force.current_research ~= nil then if Commands.player.force.current_research.name == tech.name then Commands.player.force.current_research = nil end end for _, t in pairs(Commands.player.force.technologies) do if t.prerequisites[tech.name] ~= nil then Commands.util.lockDependingTechs(t) end end tech.researched = false Commands.player.force.set_saved_technology_progress(tech, 0) end -- Check the teleport target location for collisions function Commands.util.makeValidTeleportLocation(position) if Commands.player.surface.can_place_entity({ name = "character", position = position }) then return position else if Commands.player.surface.can_place_entity({ name = "character", position = { position.x - 1, position.y } }) then return { position.x - 2, position.y } -- left side of position elseif Commands.player.surface.can_place_entity({ name = "character", position = { position.x + 1, position.y } }) then return { position.x + 1, position.y } -- above position elseif Commands.player.surface.can_place_entity({ name = "character", position = { position.x - 1, position.y + 1 } }) then return { position.x - 1, position.y + 1 } -- above position elseif Commands.player.surface.can_place_entity({ name = "character", position = { position.x - 1, position.y - 1 } }) then return { position.x - 1, position.y - 1 } -- below position else return { position.x, position.y } -- same space as position end end end -- Change true to false and false to true, and display a message to the player if specified function Commands.util.switchBool(value, message) if value == true then value = false if message ~= nil then Commands.player.print(message .. " off") end else value = true if message ~= nil then Commands.player.print(message .. " on") end end return value end -- Unlock the techs that the given tech depends on function Commands.util.unlockDependingTechs(tech) for _, t in pairs(tech.prerequisites) do Commands.util.unlockDependingTechs(t) end tech.researched = true end -- Transfer all items from one inventory to the other function Commands.util.transferInventory(origin, destination, inventory) if origin.get_inventory(inventory) == nil then return end for i, v in pairs(origin.get_inventory(inventory).get_contents()) do destination.insert({ name = i, count = v }) origin.remove_item({ name = i, count = v }) end end return Commands
----------------------------------- -- Area: Bastok Mines -- NPC: Ranpi-Pappi -- Type: Standard NPC -- !pos -4.535 -1.044 49.881 234 -- -- Auto-Script: Requires Verification (Verified by Brando) ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:startEvent(77); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
-- 9.2.5.43971 KethoWowpedia.dbc.toy = { [1] = {1973, 0, 0}, [4] = {32566, 0, 2}, [5] = {33223, 0, 2}, [7] = {38578, 0, 2}, [9] = {34480, 0, 6}, [12] = {67097, 0, 7}, [16] = {68806, 0, 2}, [17] = {70161, 0, 2}, [18] = {70722, 0, 6}, [19] = {72161, 0, 7}, [20] = {72231, 2, 0}, [21] = {86568, 0, 0}, [22] = {86571, 0, 0}, [23] = {72221, 2, 0}, [24] = {86575, 0, 0}, [25] = {72225, 2, 0}, [29] = {21540, 0, 1}, [30] = {33079, 2, 7}, [33] = {64651, 0, 3}, [34] = {43499, 0, 2}, [99] = {32782, 0, 0}, [100] = {34499, 0, 2}, [101] = {37254, 0, 0}, [102] = {38301, 0, 7}, [103] = {44430, 0, 5}, [109] = {46709, 0, 6}, [110] = {49703, 0, 7}, [111] = {49704, 2, 7}, [112] = {52201, 0, 1}, [114] = {52253, 0, 1}, [116] = {64358, 0, 3}, [117] = {64361, 0, 3}, [118] = {64373, 0, 3}, [119] = {64383, 0, 3}, [120] = {64456, 0, 3}, [121] = {64481, 0, 3}, [122] = {64482, 0, 3}, [123] = {64646, 0, 3}, [124] = {64881, 0, 3}, [125] = {66888, 4, 2}, [126] = {69895, 0, 2}, [127] = {72159, 0, 7}, [128] = {79769, 0, 7}, [129] = {86581, 0, 0}, [131] = {72224, 2, 0}, [132] = {86586, 0, 0}, [133] = {86588, 0, 0}, [134] = {86589, 0, 0}, [135] = {72229, 2, 0}, [136] = {72227, 2, 0}, [137] = {86593, 0, 0}, [139] = {86596, 0, 5}, [140] = {87528, 0, 5}, [142] = {90175, 4, 2}, [143] = {90883, 0, 6}, [144] = {90888, 0, 6}, [145] = {90899, 0, 6}, [147] = {72220, 2, 0}, [148] = {72226, 2, 0}, [151] = {98132, 0, 5}, [152] = {98136, 0, 0}, [153] = {72230, 2, 2}, [154] = {103685, 4, 2}, [155] = {104262, 0, 0}, [156] = {104302, 0, 0}, [157] = {104309, 0, 0}, [158] = {104318, 0, 6}, [159] = {104323, 0, 2}, [160] = {104324, 0, 2}, [161] = {72233, 2, 0}, [162] = {104331, 0, 0}, [164] = {105898, 0, 6}, [165] = {104294, 0, 0}, [168] = {54653, 2, 6}, [169] = {90000, 0, 6}, [170] = {90427, 0, 2}, [180] = {54651, 2, 6}, [181] = {72223, 2, 1}, [182] = {89999, 0, 6}, [183] = {54343, 0, 2}, [184] = {54438, 0, 2}, [185] = {54437, 0, 2}, [186] = {44606, 0, 2}, [187] = {45057, 0, 2}, [188] = {69776, 0, 3}, [189] = {46843, 0, 2}, [190] = {90067, 0, 0}, [191] = {97921, 0, 2}, [192] = {34686, 0, 6}, [193] = {33927, 0, 6}, [194] = {89222, 4, 2}, [195] = {37710, 0, 6}, [196] = {23767, 0, 3}, [197] = {88589, 0, 1}, [198] = {45021, 0, 2}, [199] = {36863, 0, 0}, [200] = {45020, 0, 2}, [201] = {88801, 0, 2}, [202] = {45063, 0, 2}, [203] = {69227, 0, 7}, [204] = {88802, 0, 2}, [205] = {44719, 0, 2}, [206] = {95589, 4, 1}, [207] = {95590, 4, 1}, [208] = {45019, 0, 2}, [209] = {40895, 0, 3}, [210] = {33219, 0, 2}, [211] = {88417, 0, 1}, [212] = {69777, 0, 3}, [213] = {88385, 0, 1}, [214] = {32542, 0, 2}, [215] = {54212, 0, 7}, [216] = {88587, 2, 1}, [217] = {45018, 0, 2}, [218] = {88579, 0, 1}, [219] = {88580, 0, 1}, [220] = {88566, 0, 0}, [221] = {88531, 0, 1}, [222] = {71259, 0, 1}, [223] = {63269, 0, 0}, [224] = {101571, 0, 6}, [225] = {70159, 0, 2}, [226] = {46780, 0, 2}, [227] = {35275, 0, 0}, [228] = {45014, 0, 2}, [229] = {89869, 4, 2}, [230] = {30690, 0, 1}, [231] = {108739, 0, 0}, [232] = {88370, 0, 1}, [233] = {71628, 0, 7}, [234] = {45015, 0, 2}, [235] = {97942, 0, 2}, [236] = {88387, 0, 1}, [237] = {45017, 0, 2}, [238] = {88381, 0, 1}, [239] = {17716, 0, 3}, [240] = {91904, 0, 2}, [241] = {45011, 0, 2}, [242] = {80822, 0, 1}, [243] = {50471, 0, 6}, [244] = {45013, 0, 2}, [245] = {64997, 4, 2}, [246] = {63141, 4, 2}, [247] = {88584, 0, 1}, [248] = {88377, 0, 1}, [249] = {45016, 0, 2}, [250] = {45984, 0, 0}, [251] = {69775, 0, 3}, [252] = {69215, 0, 7}, [253] = {35227, 0, 2}, [254] = {97919, 0, 2}, [255] = {17712, 0, 6}, [256] = {18660, 0, 3}, [257] = {36862, 0, 0}, [258] = {98552, 0, 2}, [264] = {116139, 0, 6}, [265] = {116067, 0, 6}, [269] = {71137, 0, 6}, [270] = {116125, 0, 0}, [271] = {113570, 0, 0}, [272] = {111476, 0, 0}, [273] = {116115, 0, 6}, [275] = {75042, 0, 6}, [278] = {118191, 2, 0}, [279] = {113096, 0, 2}, [280] = {109183, 0, 3}, [281] = {112324, 0, 7}, [282] = {118427, 0, 0}, [283] = {53057, 0, 1}, [285] = {119144, 0, 1}, [286] = {119432, 0, 0}, [287] = {119178, 0, 0}, [289] = {108743, 0, 0}, [290] = {110586, 2, 0}, [293] = {115468, 4, 2}, [294] = {115503, 0, 1}, [295] = {117550, 0, 0}, [296] = {117569, 0, 0}, [297] = {117573, 0, 0}, [298] = {118221, 0, 0}, [299] = {118244, 0, 0}, [301] = {119145, 0, 1}, [302] = {119160, 4, 2}, [303] = {72222, 2, -1}, [304] = {72228, 2, 0}, [305] = {119182, 4, 2}, [306] = {119215, 0, 5}, [307] = {119217, 0, 0}, [308] = {119218, 0, 0}, [309] = {119219, 0, 0}, [310] = {119220, 2, -1}, [311] = {119221, 2, -1}, [312] = {119421, 4, 2}, [319] = {109739, 0, 0}, [320] = {116122, 0, 0}, [322] = {119212, 0, 2}, [324] = {119210, 0, 2}, [325] = {118222, 0, 0}, [327] = {120276, 0, 0}, [328] = {108735, 0, 0}, [329] = {113670, 0, 0}, [330] = {113631, 0, 0}, [331] = {113375, 0, 0}, [332] = {118716, 0, 0}, [333] = {114227, 0, 0}, [334] = {116651, 0, 6}, [335] = {116758, 0, 6}, [336] = {116763, 0, 6}, [337] = {116400, 0, 6}, [338] = {118937, 0, 0}, [339] = {118938, 0, 0}, [340] = {119003, 0, 0}, [341] = {119039, 0, 0}, [342] = {119083, 0, 0}, [343] = {72232, 2, -1}, [344] = {116440, 0, 2}, [345] = {116435, 0, 6}, [346] = {116757, 0, 6}, [347] = {116689, 0, 6}, [348] = {116690, 0, 6}, [349] = {116691, 0, 6}, [350] = {116692, 0, 6}, [351] = {119134, 0, 1}, [352] = {120857, 2, 0}, [357] = {119092, 0, 0}, [359] = {89205, 2, 5}, [360] = {108745, 0, 3}, [361] = {122293, 0, 5}, [365] = {122304, 0, 0}, [366] = {122283, 6, -1}, [367] = {116456, 0, 6}, [368] = {122129, 0, 5}, [369] = {122126, 0, 5}, [371] = {122120, 0, 5}, [372] = {122122, 0, 5}, [373] = {122123, 0, 5}, [374] = {122674, 0, 1}, [375] = {122700, 0, 5}, [376] = {119163, 0, 0}, [377] = {82467, 0, 1}, [378] = {13379, 0, 0}, [379] = {123851, 0, 0}, [381] = {122119, 0, 5}, [383] = {116856, 0, 6}, [384] = {116888, 0, 6}, [385] = {116889, 0, 6}, [386] = {116890, 0, 6}, [387] = {116891, 0, 6}, [388] = {126931, 0, 2}, [389] = {127670, 0, 0}, [390] = {127668, 0, 0}, [391] = {119001, 0, 1}, [392] = {127695, 0, 2}, [393] = {127696, 0, 2}, [394] = {127707, 0, 2}, [395] = {127766, 0, 0}, [396] = {127394, 0, -1}, [398] = {127859, 0, 0}, [399] = {127864, 0, 2}, [400] = {127659, 0, 0}, [401] = {127652, 0, 0}, [402] = {127666, 0, 0}, [403] = {128310, 0, 0}, [404] = {69896, 0, 6}, [405] = {128328, 0, 4}, [406] = {122121, 0, 5}, [408] = {128471, 4, 2}, [409] = {128462, 4, 2}, [410] = {128536, 0, 3}, [411] = {97994, 0, 2}, [412] = {108635, 0, 6}, [413] = {108634, 0, 0}, [415] = {108633, 0, 0}, [416] = {108632, 0, 6}, [417] = {108631, 0, 0}, [418] = {86573, 0, 0}, [420] = {128776, 0, 6}, [421] = {128794, 0, 6}, [422] = {128807, 0, 6}, [425] = {122117, 0, 0}, [428] = {127709, 0, 0}, [429] = {92738, 0, -1}, [431] = {129926, 0, -1}, [432] = {129938, 0, -1}, [433] = {129952, 0, -1}, [434] = {129956, 0, 3}, [435] = {129057, 0, 2}, [436] = {129929, 0, 2}, [437] = {130199, 4, 2}, [438] = {130194, 2, -1}, [439] = {130147, 0, 0}, [440] = {129055, 0, 0}, [441] = {129093, 0, 1}, [442] = {86565, 0, -1}, [443] = {129111, 2, -1}, [444] = {133511, 0, 2}, [445] = {133542, 0, -1}, [446] = {131812, 4, 2}, [447] = {131811, 0, -1}, [448] = {93672, 2, -1}, [449] = {119093, 0, 0}, [451] = {86590, 0, 0}, [452] = {86582, 0, 0}, [453] = {134024, 0, 0}, [454] = {86583, 0, 0}, [455] = {64488, 0, 3}, [456] = {134023, 0, 0}, [457] = {86578, 0, 0}, [458] = {113540, 0, 0}, [459] = {116120, 0, 0}, [460] = {118935, 0, -1}, [461] = {128223, 0, -1}, [462] = {86594, 0, 0}, [463] = {88375, 0, 1}, [464] = {89614, 0, 3}, [465] = {43824, 0, 5}, [466] = {115506, 0, 0}, [467] = {102467, 0, 2}, [468] = {86584, 0, 0}, [469] = {113543, 0, -1}, [470] = {104329, 0, 0}, [471] = {54452, 2, -1}, [472] = {134020, 0, 2}, [473] = {60854, 2, 3}, [474] = {87214, 2, 3}, [475] = {111821, 2, 3}, [476] = {40768, 2, 3}, [477] = {48933, 2, 3}, [478] = {87215, 2, 3}, [479] = {112059, 2, 3}, [480] = {18986, 2, 3}, [481] = {30544, 2, 3}, [482] = {18984, 2, 3}, [483] = {30542, 2, 3}, [484] = {40727, 2, 3}, [485] = {85973, 2, 0}, [486] = {85500, 6, 2}, [487] = {134019, 0, 0}, [488] = {134022, 0, 0}, [489] = {134021, 0, 1}, [490] = {133997, 0, -1}, [491] = {133998, 0, 1}, [492] = {122298, 0, 2}, [493] = {113542, 0, 0}, [494] = {118224, 0, 0}, [495] = {116113, 0, 0}, [496] = {119180, 0, 0}, [497] = {95567, 0, 1}, [498] = {95568, 0, 1}, [499] = {127655, 0, 0}, [500] = {127669, 0, 0}, [501] = {134007, 0, 2}, [502] = {134004, 0, 2}, [503] = {130169, 0, 0}, [504] = {130157, 4, 2}, [505] = {130158, 4, 2}, [506] = {130171, 0, 0}, [507] = {130170, 4, 2}, [508] = {130191, 4, 2}, [509] = {130232, 4, 2}, [510] = {130214, 0, 0}, [511] = {130249, 2, 0}, [512] = {129045, 2, 0}, [513] = {129165, 0, 0}, [514] = {37460, 0, -1}, [515] = {44820, 0, -1}, [516] = {89139, 0, 0}, [520] = {131724, 0, 1}, [521] = {136849, 2, -1}, [522] = {136846, 2, -1}, [525] = {136927, 2, -1}, [526] = {136855, 2, -1}, [527] = {136928, 2, -1}, [528] = {136934, 2, -1}, [529] = {136935, 2, -1}, [530] = {136937, 2, -1}, [531] = {129211, 0, 3}, [532] = {137294, 2, -1}, [533] = {129958, 0, 3}, [534] = {129960, 0, 3}, [535] = {129961, 0, 3}, [536] = {137663, 0, -1}, [537] = {138202, 0, 2}, [538] = {138415, 0, 6}, [539] = {138490, 2, -1}, [540] = {138876, 0, 1}, [541] = {138873, 0, 1}, [542] = {115472, 4, 2}, [543] = {129279, 4, 2}, [544] = {129149, 4, 2}, [545] = {139337, 0, 6}, [546] = {128636, 0, 6}, [547] = {130254, 0, 3}, [548] = {138900, 0, 2}, [549] = {139773, 0, 0}, [550] = {139587, 0, -1}, [551] = {140160, 0, -1}, [552] = {140231, 0, 2}, [553] = {140309, 0, 2}, [554] = {140363, 0, 0}, [557] = {131814, 4, 2}, [558] = {134831, 0, 0}, [559] = {140325, 4, 2}, [560] = {140324, 4, 2}, [561] = {132518, 0, 3}, [562] = {130151, 0, 2}, [563] = {140632, 2, 0}, [564] = {140336, 0, 2}, [565] = {138878, 0, 1}, [566] = {129113, 0, 0}, [567] = {140779, 2, -1}, [568] = {140780, 0, -1}, [569] = {130251, 0, 3}, [570] = {122681, 0, 0}, [571] = {130209, 0, 1}, [572] = {119211, 2, 0}, [573] = {109167, 0, 3}, [574] = {140786, 0, -1}, [575] = {141297, 0, -1}, [576] = {141300, 2, -1}, [577] = {141298, 0, -1}, [578] = {141301, 0, -1}, [579] = {141306, 0, -1}, [580] = {141299, 0, -1}, [581] = {141296, 0, -1}, [582] = {141331, 2, 0}, [584] = {131933, 0, 1}, [585] = {131900, 0, 0}, [586] = {141649, 0, 6}, [587] = {141879, 0, 1}, [588] = {140314, 0, 0}, [589] = {142265, 0, 0}, [590] = {142341, 0, 6}, [593] = {142497, 0, 1}, [594] = {142496, 0, 1}, [595] = {142495, 0, 1}, [596] = {142494, 0, 1}, [597] = {142528, 0, 0}, [598] = {142529, 0, 0}, [599] = {142530, 0, 0}, [600] = {142531, 4, -1}, [601] = {142532, 4, -1}, [602] = {142536, 0, 1}, [603] = {143545, 2, -1}, [604] = {143544, 0, 0}, [605] = {143543, 2, 6}, [606] = {141862, 0, 2}, [607] = {129965, 0, 2}, [608] = {143534, 2, -1}, [609] = {142542, 2, 6}, [610] = {143662, 0, 0}, [611] = {130102, 0, -1}, [612] = {143727, 0, 1}, [613] = {143660, 0, 5}, [614] = {143827, 0, 6}, [615] = {143828, 0, 6}, [616] = {143829, 0, 6}, [618] = {144339, 0, 6}, [619] = {144393, 0, 2}, [621] = {147308, 0, 2}, [622] = {147312, 0, 2}, [623] = {147310, 0, 2}, [624] = {147307, 0, 2}, [625] = {147311, 0, 2}, [626] = {147309, 0, 2}, [627] = {147537, 0, 2}, [628] = {147832, 0, 2}, [629] = {147838, 0, -1}, [630] = {147843, 0, 0}, [631] = {147867, 0, 0}, [632] = {147708, 4, 2}, [633] = {144072, 0, 2}, [634] = {142452, 0, 2}, [639] = {150547, 2, 6}, [640] = {151016, 0, 2}, [641] = {151271, 0, 6}, [642] = {151270, 0, 6}, [643] = {151344, 0, 6}, [644] = {151343, 0, 6}, [645] = {151265, 0, 0}, [646] = {151184, 0, 2}, [647] = {150743, 0, -1}, [651] = {150746, 0, -1}, [652] = {134026, 0, 5}, [653] = {134031, 0, 5}, [654] = {134032, 0, 5}, [655] = {134034, 0, 5}, [656] = {150744, 0, -1}, [657] = {150745, 0, -1}, [658] = {151877, 2, 0}, [659] = {152556, 0, 2}, [660] = {152574, 0, 2}, [661] = {151349, 0, 6}, [662] = {151348, 0, 6}, [663] = {129367, 0, 2}, [664] = {152982, 2, 0}, [665] = {153004, 2, 0}, [666] = {153039, 4, -1}, [667] = {153124, 0, 0}, [668] = {153126, 0, 0}, [669] = {153180, 0, 0}, [670] = {153179, 0, 0}, [671] = {153181, 0, 0}, [672] = {153182, 0, 0}, [673] = {153183, 0, 0}, [674] = {153193, 0, 0}, [675] = {153204, 0, 2}, [676] = {151652, 2, 3}, [677] = {153253, 0, -1}, [678] = {153194, 0, 0}, [679] = {153293, 0, 0}, [680] = {156649, 0, 6}, [681] = {156833, 0, 5}, [682] = {156871, 0, 1}, [683] = {158149, 0, 6}, [684] = {160740, 0, 3}, [685] = {160751, 0, 3}, [686] = {161342, 2, -1}, [787] = {162539, 0, 2}, [788] = {159749, 0, 2}, [789] = {162643, 0, 6}, [790] = {162642, 0, 6}, [791] = {162973, 0, 6}, [792] = {163045, 0, 6}, [793] = {163211, 4, 2}, [795] = {163210, 4, 2}, [796] = {163206, 2, 2}, [797] = {163201, 4, 2}, [798] = {163200, 4, 2}, [799] = {159753, 4, 2}, [800] = {163565, 2, 2}, [801] = {163566, 2, 2}, [802] = {163603, 2, 0}, [803] = {163607, 0, 1}, [804] = {163697, 0, 5}, [805] = {163713, 0, -1}, [806] = {163735, 0, -1}, [807] = {163736, 0, -1}, [808] = {163738, 0, -1}, [809] = {163741, 0, -1}, [810] = {163744, 0, -1}, [811] = {163745, 0, -1}, [812] = {163750, 0, -1}, [813] = {163775, 0, -1}, [814] = {163742, 0, 0}, [815] = {163740, 0, 0}, [816] = {163704, 0, -1}, [817] = {163705, 0, -1}, [819] = {163795, 0, 0}, [820] = {163828, 0, 0}, [821] = {163829, 0, 0}, [822] = {163924, 0, 0}, [823] = {163987, 2, 7}, [824] = {163986, 2, 7}, [827] = {160509, 0, 1}, [828] = {164375, 0, 0}, [829] = {164374, 0, 0}, [832] = {164373, 0, 0}, [834] = {163463, 4, 2}, [890] = {164310, 0, 5}, [891] = {164983, 0, 6}, [892] = {165021, 4, 6}, [893] = {165671, 0, 6}, [894] = {165672, 0, 6}, [895] = {165673, 0, 6}, [896] = {165674, 0, 6}, [897] = {165675, 0, 6}, [898] = {165676, 0, 6}, [899] = {165791, 0, 1}, [900] = {166308, 0, 0}, [901] = {166247, 0, 5}, [902] = {166461, 0, 2}, [903] = {166662, 0, 2}, [904] = {166663, 0, 2}, [905] = {166678, 0, 1}, [906] = {166544, 0, 1}, [907] = {166701, 0, -1}, [908] = {166702, 0, -1}, [909] = {166703, 0, -1}, [910] = {166704, 0, -1}, [911] = {166744, 0, 2}, [912] = {166743, 0, 2}, [913] = {166778, 2, 9}, [914] = {166777, 2, 9}, [916] = {165669, 0, -1}, [917] = {165670, 0, -1}, [918] = {165802, 0, -1}, [919] = {166746, 0, -1}, [920] = {166747, 0, -1}, [921] = {166784, 0, 0}, [922] = {166785, 0, 0}, [923] = {166787, 0, 0}, [924] = {166788, 0, -1}, [925] = {166790, 0, 0}, [926] = {166779, 0, 9}, [927] = {166880, 0, 0}, [928] = {166808, 0, 0}, [929] = {166851, 2, 0}, [930] = {166877, 0, 0}, [931] = {166879, 0, 0}, [940] = {167931, 0, 0}, [941] = {168012, 0, 2}, [942] = {168014, 0, 2}, [943] = {168123, 0, -1}, [944] = {168016, 0, 5}, [945] = {115501, 0, -1}, [946] = {116396, 0, -1}, [947] = {115505, 0, -1}, [948] = {168807, 2, 3}, [949] = {168808, 2, 3}, [950] = {168824, 0, 0}, [953] = {168836, 2, -1}, [955] = {168907, 0, -1}, [956] = {169275, 0, 2}, [957] = {169276, 0, 2}, [958] = {169278, 0, 2}, [959] = {169277, 0, 2}, [960] = {169297, 0, -1}, [961] = {169298, 0, -1}, [964] = {169347, 0, 0}, [965] = {169768, 0, 1}, [966] = {169796, 0, 1}, [967] = {169865, 0, 0}, [968] = {170155, 2, 1}, [969] = {170154, 2, 1}, [970] = {170187, 0, 0}, [971] = {170380, 0, 2}, [972] = {170204, 0, 2}, [973] = {170198, 0, 0}, [974] = {170203, 0, 0}, [975] = {170199, 0, 0}, [976] = {170196, 0, 0}, [977] = {168667, 2, 3}, [978] = {170476, 0, 0}, [979] = {170469, 4, -1}, [980] = {169108, 4, 2}, [981] = {172179, 0, 7}, [982] = {172223, 0, 6}, [983] = {172222, 0, 6}, [984] = {172219, 0, 6}, [985] = {173727, 2, -1}, [986] = {173951, 0, -1}, [992] = {173984, 0, 0}, [993] = {174445, 2, 0}, [994] = {174830, 0, 5}, [995] = {174871, 0, 5}, [996] = {174873, 0, 0}, [997] = {174874, 0, 0}, [998] = {169303, 0, 0}, [999] = {174920, 0, -1}, [1000] = {174928, 0, -1}, [1001] = {174926, 0, -1}, [1002] = {174924, 0, -1}, [1003] = {174921, 0, -1}, [1005] = {174995, 4, 2}, [1006] = {175140, 0, -1}, [1007] = {175063, 0, 1}, [1062] = {178530, 0, 6}, [1063] = {177951, 0, 1}, [1064] = {172924, 2, 3}, [1065] = {181794, 0, 0}, [1066] = {181825, 0, 0}, [1068] = {182729, 0, 0}, [1069] = {182732, 0, 0}, [1070] = {182773, 0, -1}, [1071] = {182694, 0, 0}, [1072] = {182696, 0, 0}, [1073] = {182695, 0, 5}, [1074] = {183847, 0, 1}, [1075] = {183856, 0, 1}, [1076] = {183900, 4, 2}, [1078] = {180993, 0, 0}, [1079] = {182780, 0, 0}, [1080] = {183876, 0, -1}, [1081] = {180947, 0, -1}, [1082] = {180873, 0, 0}, [1083] = {179393, 0, 0}, [1084] = {182890, 4, 2}, [1085] = {183903, 0, 5}, [1086] = {183989, 0, 2}, [1087] = {183986, 0, 0}, [1088] = {184075, 0, 0}, [1089] = {184218, 4, 2}, [1090] = {184223, 0, 5}, [1091] = {184292, 0, 0}, [1092] = {184312, 0, 0}, [1093] = {183716, 0, 2}, [1094] = {184318, 0, 0}, [1095] = {180290, 0, 2}, [1096] = {184353, 0, 2}, [1097] = {183988, 0, 0}, [1098] = {184449, 0, 5}, [1099] = {184447, 0, 0}, [1100] = {184476, 0, 0}, [1101] = {184508, 0, 5}, [1102] = {183810, 2, 0}, [1103] = {184495, 0, 0}, [1104] = {184396, 0, -1}, [1105] = {184487, 0, -1}, [1106] = {184489, 0, -1}, [1107] = {184490, 0, -1}, [1108] = {184410, 4, -1}, [1109] = {184404, 0, -1}, [1110] = {184415, 0, -1}, [1111] = {184418, 0, -1}, [1112] = {184413, 0, -1}, [1113] = {184435, 0, -1}, [1114] = {186501, 2, -1}, [1115] = {186686, 0, 3}, [1116] = {186702, 0, 3}, [1117] = {186973, 0, -1}, [1118] = {186985, 0, -1}, [1119] = {186974, 0, -1}, [1120] = {187075, 0, -1}, [1121] = {187176, 0, 0}, [1122] = {187184, 0, -1}, [1123] = {187185, 0, 0}, [1124] = {187416, 0, 0}, [1125] = {187417, 0, 0}, [1126] = {187113, 0, 0}, [1127] = {187159, 0, 1}, [1128] = {187154, 0, 1}, [1129] = {187155, 0, 1}, [1130] = {187140, 0, 1}, [1131] = {187344, 0, 0}, [1132] = {187339, 0, 0}, [1133] = {187174, 0, 0}, [1134] = {187051, 0, 0}, [1135] = {187139, 0, 0}, [1136] = {187419, 0, -1}, [1137] = {187420, 0, 0}, [1138] = {183901, 0, 0}, [1139] = {187422, 2, -1}, [1145] = {187512, 0, -1}, [1146] = {187591, 0, -1}, [1147] = {187705, 0, 0}, [1148] = {187834, 2, -1}, [1149] = {187840, 0, -1}, [1150] = {187793, 0, 5}, [1151] = {187861, 2, -1}, [1152] = {187869, 0, -1}, [1153] = {187875, 0, -1}, [1154] = {187895, 0, -1}, [1155] = {187896, 0, -1}, [1156] = {187897, 0, -1}, [1157] = {187898, 0, -1}, [1158] = {187899, 0, -1}, [1159] = {187900, 0, -1}, [1161] = {187913, 0, -1}, [1162] = {187957, 2, -1}, [1163] = {187958, 2, -1}, [1164] = {187959, 2, -1}, [1165] = {187860, 0, 5}, [1166] = {188680, 0, 2}, [1167] = {188694, 0, 2}, [1168] = {188695, 0, 2}, [1169] = {188698, 0, 2}, [1170] = {188699, 0, -1}, [1171] = {188701, 0, -1}, [1173] = {188952, 0, 5}, [1174] = {190177, 0, -1}, [1175] = {190196, 2, -1}, [1176] = {190237, 4, 2}, [1177] = {190238, 0, 0}, [1178] = {190333, 0, -1}, [1179] = {190457, 0, 0}, [1180] = {190734, 0, -1}, [1181] = {190754, 0, -1}, [1182] = {190853, 0, 0}, [1183] = {190926, 0, 0}, [1184] = {187689, 0, 5}, [1186] = {191937, 2, -1}, [1187] = {191925, 2, -1}, [1188] = {192099, 0, -1}, [1189] = {192485, 2, -1}, }
-------------------------------------------------------------------------------- -- Function......... : easeInOutBack -- Author........... : -- Description...... : -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function Tweener.easeInOutBack ( t, b, c, d, s ) -------------------------------------------------------------------------------- if (s==nil) then s = 1.70158; end t=t/d/2 if (t < 1) then s = s * 1.525 return c/2*(t*t*((s+1)*t - s)) + b; end t=t-2 s = s * 1.525 return c/2*(t*t*((s+1)*t + s) + 2) + b; -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
Dummy = Entity:extend("Dummy", { collider = nil, tpos = vec2(), tppos = vec2(), axis = vec2(), jump = false, crouch = false, controlmode = nil }) function Dummy:init(data) Base.init(self, data) self.collider = CircleCollider{ radius = 32 } self:setControlMode("Previous") end collision = nil function Dummy:update(tl) if self.controlmode == "Current" then self.pos = self.pos + self.axis * 100 * tl elseif self.controlmode == "Previous" then self.ppos = self.ppos + self.axis * 100 * tl end self.vel = self.pos - self.ppos self:updateCollider(tl) local brush = debugState.brushes[1] --bounds_self = self.collider:getCastBounds() --bounds_other = brush:getCastBounds() --bounds_check = self.collider:checkCastBounds(brush) collision = self.collider:cast(brush) if collision then if collision.t >= 0 then self.tppos = collision.self_pos self.tpos = self.tppos + collision.tangent * (self.vel * collision.tangent) * collision.r else collision = nil end end self:updateCollider(tl) return false end function Dummy:draw() lg.push("all") lg.translate(self.ppos:split()) stache.setColor("white", 0.8) lg.line(0, 0, self.vel:split()) lg.push() lg.translate((self.vel.normal * self.collider.radius):split()) lg.line(0, 0, self.vel:split()) lg.pop() lg.push() lg.translate((-self.vel.normal * self.collider.radius):split()) lg.line(0, 0, self.vel:split()) lg.pop() lg.pop() stache.debugCircle(self.ppos, self.collider.radius, "red", 1) stache.debugCircle(self.pos, self.collider.radius, "green", 1) if collision then stache.debugCircle(self.tppos, self.collider.radius, "red", 0.5) stache.debugCircle(self.tpos, self.collider.radius, "green", 0.5) stache.debugTangent(self.tppos, collision.tangent * 100, "white", 0.5) end if bounds_check then local alpha = bounds_check and 0.4 or 0.2 stache.debugBounds(bounds_self, "white", alpha) stache.debugBounds(bounds_other, "white", alpha) end end function Dummy:setControlMode(mode) stache.checkArg("mode", mode, "string", "Dummy:setControlMode") if mode ~= "Current" and mode ~= "Previous" then stache.formatError("Dummy:setControlMode() called with a 'mode' argument that does not correspond to a valid control mode: %q", mode) end self.controlmode = mode end function Dummy:toggleControlMode() if self.controlmode == "Current" then self:setControlMode("Previous") elseif self.controlmode == "Previous" then self:setControlMode("Current") end end function Dummy:updateCollider(tl) self.collider:update(tl, self.pos, self.ppos) end
-- The Computer Language Shootout -- http://shootout.alioth.debian.org/ -- contributed by Mike Pall local gmatch, gsub, write = string.gmatch, string.gsub, io.write local seq = io.read("*a") local ilen = #seq seq = gsub(seq, ">.-\n", "") seq = gsub(seq, "\n", "") local clen = #seq local variants = { "agggtaaa", "tttaccct", "[cgt]gggtaaa", "tttaccc[acg]", "a[act]ggtaaa", "tttacc[agt]t", "ag[act]gtaaa", "tttac[agt]ct", "agg[act]taaa", "ttta[agt]cct", "aggg[acg]aaa", "ttt[cgt]ccct", "agggt[cgt]aa", "tt[acg]accct", "agggta[cgt]a", "t[acg]taccct", "agggtaa[cgt]", "[acg]ttaccct", } local count, prev = 0 for i,pattern in ipairs(variants) do for _ in gmatch(seq, pattern) do count = count + 1 end if prev then write(prev, "|", pattern, " ", count, "\n") count = 0 prev = nil else prev = pattern end end local subst = { B = "(c|g|t)", D = "(a|g|t)", H = "(a|c|t)", K = "(g|t)", M = "(a|c)", N = "(a|c|g|t)", R = "(a|g)", S = "(c|g)", V = "(a|c|g)", W = "(a|t)", Y = "(c|t)", } -- Dumbing down forced by "the rules": for k,v in pairs(subst) do seq = gsub(seq, k, v) end -- Otherwise you're better off with: seq = gsub(seq, "[BDHKMNRSVWY]", subst) write("\n", ilen, "\n", clen, "\n", #seq, "\n")
#!/usr/bin/env luajit local ldb = require("lua-db") local lfb = require("lua-fb") print("creating db") local db = ldb.new(100,100) print("Got drawbuffer", db) print("opening framebuffer") local fb = lfb.new(arg[1] or "/dev/fb0") print("Got framebuffer", fb) print("getting varinfo") local vinfo = fb:get_varinfo() print("Framebuffer resolution ->", vinfo.xres .. "x" .. vinfo.yres) print("getting fixinfo") local finfo = fb:get_fixinfo() print("clearing drawbuffer") db:clear(0xFF,0x00,0xFF,0xFF) print("drawing to framebuffer from drawbuffer") fb:draw_from_drawbuffer(db, 0,0)
--[[------------------------------------------------------ mdns.Registration ----------------- This class registers a service name for a give service type and calls a callback when the service is announced. (this is an implementation of the ZeroConf or Bonjour registration). --]]------------------------------------------------------ require 'mdns.core' local lib = mdns.Registration_core mdns.Registration = lib local private = {} local function dummy() -- noop end local ctx = mdns.Context() --- We should provide a socket to inform when registration is over (callback). -- This socket could be the default zmq.REQ socket used to by lk.Service ? local new = lib.new function lib.new(service_type, name, port, txt, func) if not func then if type(txt) == 'function' then func = txt txt = nil end end txt = private.buildTXT(txt) local self = new(ctx, service_type, name, port, txt) self.callback = func or dummy self.txt = txt self.thread = lk.Thread(function() while true do sched:waitRead(self:fd()) self:callback(self:getService()) end end) ctx:addRegistration(self) return self end function lib:kill() if self.thread then self.thread:kill() self.thread = nil end end --=============================================== PRIVATE local INVALID_KEY_CHARS = '[^a-zA-Z]' --- Build a TXT record from a Lua table. function private.buildTXT(dict) if not dict then return '' elseif type(dict) ~= 'table' then error('txt field is not a table') end local txt = '' for key, value in pairs(dict) do if type(value) == 'number' then value = string.format('%i', value) end if type(key) == 'string' and type(value) == 'string' then if string.match(key, INVALID_KEY_CHARS) then error(string.format("Invalid key '%s' in TXT record (contains invalid characters).", key)) end if string.len(key) + string.len(value) > 254 then error(string.format("Invalid value '%s' in TXT record (value + key is too long).", value)) end txt = txt .. string.char(string.len(key) + 1 + string.len(value)) .. key .. '=' .. value end end if string.len(txt) > 400 then error(string.format("TXT record size is too big (%i bytes)", string.len(txt))) end return txt end
----------------------------- -- INIT ----------------------------- --get the addon namespace local addon, ns = ... local cfg = ns.cfg ----------------------------- -- CHARSPECIFIC REWRITES ----------------------------- local playername, _ = UnitName("player") local _, playerclass = UnitClass("player") if playername == "Zörk" then cfg.bars.stancebar.enable = false cfg.bars.bar2.mouseover.enable = false cfg.bars.bar3.mouseover.enable = false cfg.bars.bar4.mouseover.fadeOut.alpha = 0 cfg.bars.bags.mouseover.fadeOut.alpha = 0 cfg.bars.micromenu.mouseover.fadeOut.alpha = 0 end if playername == "Lishi" then cfg.bars.bar1.uselayout2x6 = true cfg.bars.bar2.uselayout2x6 = true cfg.bars.bar4.mouseover.enable = false cfg.bars.bar5.mouseover.enable = false end
-- -- This file describes 'cursor action' regions, rectangular regions -- in floating workspace mode where some action will be taken if you -- drag a window around. They can be used to implement behavior like -- "drag window to edge to resize to fixed size", trigger migration -- to a specific screen and so on. -- local cactions = {}; -- this example, if uncommented, would exec the overview tool if the -- cursor in its non-drag state is moved to the top left corner. These -- are always invisible. -- -- table.insert(cactions, { -- region = {0.0, 0.0, 0.001, 0.001}, -- on_over = function() -- dispatch_symbol("!tools/overview/ws_tile") -- end --}); -- this example, if uncommented, would trigger a window center -- if dropped to the left edge of the user area, with a preview on -- how that would look. It's slightly more complicated as it needs -- to create / manage the "center- preview". -- table.insert(cactions, { -- region = {0.0, 0.0, 0.05, 1.0}, -- visible = true, -- on_drag_over = function(ctx, wnd, vid) -- local nsrf = color_surface(wnd.width, wnd.height, 0, 255, 0); -- blend_image(nsrf, 0.5, gconfig_get("transition")); -- order_image(nsrf, 65532); -- move_image(nsrf, -- 0.5 * (wnd.wm.width - wnd.width), 0.5 * ( wnd.wm.height - wnd.height)); -- ctx.temp_vid = nsrf; -- image_mask_set(nsrf, MASK_UNPICKABLE); -- blend_image(vid, 0.7, gconfig_get("transition")); -- end, -- on_drag_out = function(ctx, wnd, vid) -- if (valid_vid(ctx.temp_vid)) then -- expire_image(ctx.temp_vid, 10); -- blend_image(ctx.temp_vid, 0.0, 10); -- ctx.temp_vid = nil; -- end -- end, -- on_drop = function(ctx, wnd) -- if (valid_vid(ctx.temp_vid)) then -- expire_image(ctx.temp_vid, 10); -- blend_image(ctx.temp_vid, 0.0, 10); -- ctx.temp_vid = nil; -- end -- if (wnd.move) then -- wnd:move(0.5*(wnd.wm.width - wnd.width), -- 0.5*(wnd.wm.height - wnd.height), false, true); -- end -- end --}); return cactions;
function isClient() return getLocalPlayer and true end
local t = require( "taptest" ) local frombase2 = require( "frombase2" ) -- reads data from a bitfields string t( frombase2( "01000001010000110100010001000011" ), "ACDC" ) -- read data with o instead of 0 t( frombase2( "o1ooooo1o1oooo11" ), "AC" ) t( frombase2( "OioooooiOiooooii" ), "AC" ) -- allows to ignore characters in a bitfield string t( frombase2( "o1ooooo1 o1oooo11", " " ), "AC" ) -- handles wrong characters without a crash local res, err = frombase2( "o1oo*ooo1*o1oo*oo11" ) t( res, nil ) t( err, "unexpected character at position 5: '*'" ) t()
local ToolkitCI = script:FindFirstAncestor("ToolkitCI") local Roact = require(ToolkitCI.vendor.Roact) local RoactRodux = require(ToolkitCI.vendor.RoactRodux) local Flipper = require(ToolkitCI.vendor.Flipper) local RoactFlipper = require(ToolkitCI.vendor.RoactFlipper) local HoverColorImageButton = require(script.Parent.Components.HoverColorImageButton) local PagesTree = require(script.Parent.Parent.PagesTree) local e = Roact.createElement local Sidebar = Roact.Component:extend("Sidebar") local function getPages(props) local contents = {} if props.category.subcategory ~= "" then for pageName, _module in pairs(PagesTree[props.category.category][props.category.subcategory]) do contents[pageName] = e("TextButton", { BackgroundColor3 = Color3.fromRGB(84,84,84), TextColor3 = Color3.fromRGB(255,255,255), Font = Enum.Font.SourceSansBold, TextSize = 27, Text = pageName, [Roact.Event.Activated] = function() props.setCategory({ page = pageName, }) props.sidebarMotor:setGoal(Flipper.Spring.new(0, { frequency = 3, dampingRatio = 1 })) end }, { UICorner = e("UICorner", { CornerRadius = UDim.new(0.3,0), }) }) end end contents["UIGridLayout"] = e("UIGridLayout", { CellPadding = UDim2.new(0,5,0,5), CellSize = UDim2.new(1,0,0,30), SortOrder = Enum.SortOrder.LayoutOrder, }) return e("Frame", { AnchorPoint = Vector2.new(0.5,0), BackgroundTransparency = 1, Position = props.Position, Size = UDim2.fromOffset(190,360), }, contents) end local function getCategories(props) local contents = {} local layoutOrder = 1 for categoryName, categoryTable in pairs(PagesTree) do contents[categoryName .. " Title"] = e("Frame", { BackgroundTransparency = 1, Size = UDim2.new(1,0,0,25), LayoutOrder = layoutOrder, }, { Title = e("TextLabel", { BackgroundTransparency = 1, Size = UDim2.new(1,0,0,20), TextXAlignment = Enum.TextXAlignment.Left, TextColor3 = Color3.fromRGB(213,213,213), Font = Enum.Font.SourceSansBold, TextSize = 17, Text = categoryName, }, { UIPadding = e("UIPadding", { PaddingLeft = UDim.new(0,7), }) }), Line = e("Frame", { Position = UDim2.fromOffset(5,21), Size = UDim2.new(0.5,0,0,2), BackgroundColor3 = Color3.fromRGB(213,213,213), BorderSizePixel = 0, }), }) -- Subcategory buttons local subcategoryContents = {} for subcategoryName, _ in pairs(categoryTable) do subcategoryContents[subcategoryName] = e("TextButton", { BackgroundColor3 = Color3.fromRGB(84,84,84), TextColor3 = Color3.fromRGB(255,255,255), Font = Enum.Font.SourceSans, TextSize = 27, Text = subcategoryName, [Roact.Event.Activated] = function() props.setCategory({ category = categoryName, subcategory = subcategoryName, page = "", }) props.setSidebarPage("pages") end, }, { UICorner = e("UICorner", { CornerRadius = UDim.new(0.3,0), }) }) end subcategoryContents["UIGridLayout"] = e("UIGridLayout", { CellPadding = UDim2.new(0,5,0,5), CellSize = UDim2.new(1,0,0,30), SortOrder = Enum.SortOrder.LayoutOrder, }) contents[categoryName] = e("Frame", { BackgroundTransparency = 1, Size = UDim2.new(1,0,0,0), AutomaticSize = Enum.AutomaticSize.Y, LayoutOrder = layoutOrder + 1, }, subcategoryContents) layoutOrder += 2 end contents["UIListLayout"] = e("UIListLayout", { Padding = UDim.new(0,3), SortOrder = Enum.SortOrder.LayoutOrder, }) return e("Frame", { AnchorPoint = Vector2.new(0.5,0), BackgroundTransparency = 1, Position = props.Position, Size = UDim2.fromOffset(190,360), }, contents) end function Sidebar:init() -- 0 for hidden, 1 for shown sidebar self.sidebarMotor = Flipper.SingleMotor.new(1) self.sidebarBinding = RoactFlipper.getBinding(self.sidebarMotor) end function Sidebar:render() return e("Frame", { BackgroundColor3 = Color3.fromRGB(53,53,53), BorderSizePixel = 0, Size = UDim2.new(0,215,1,0), Position = self.sidebarBinding:map(function(alpha) return UDim2.new(0,-175,0,0):Lerp(UDim2.new(0,0,0,0), alpha) end), ZIndex = 1000, }, { Title = e("TextLabel", { BackgroundTransparency = 1, Size = UDim2.fromOffset(170,40), TextColor3 = Color3.fromRGB(213,213,213), Font = Enum.Font.SourceSans, Position = self.sidebarBinding:map(function(alpha) return UDim2.new(0,-35,0,0):Lerp(UDim2.new(0,0,0,0), alpha) end), TextSize = 18, Text = "Crystal Isles dev toolkit", }), ShowHide = e(HoverColorImageButton, { BackgroundTransparency = 1, Position = UDim2.new(1,-30,0,6), Size = UDim2.fromOffset(22,30), Rotation = 90, Image = "rbxassetid://6873094251", onActivated = function() self.sidebarMotor:setGoal(Flipper.Spring.new(self.sidebarBinding:getValue() == 0 and 1 or 0, { frequency = 3, dampingRatio = 1 })) end, }), BackArrow = self.props.sidebarPage ~= "subcategory" and e(HoverColorImageButton, { BackgroundTransparency = 1, Position = self.sidebarBinding:map(function(alpha) return UDim2.new(1,-90,0,9):Lerp(UDim2.new(1,-55,0,9), alpha) end), Size = UDim2.fromOffset(24,22), Image = "rbxassetid://6994815425", onActivated = function() self.props.setSidebarPage("subcategory") end, }), MainList = self.props.sidebarPage == "subcategory" and e(getCategories, { Position = self.sidebarBinding:map(function(alpha) return UDim2.new(0,0,0,45):Lerp(UDim2.new(0.5,0,0,45), alpha) end), sidebarPage = self.props.sidebarPage, category = self.props.category, setSidebarPage = self.props.setSidebarPage, setCategory = self.props.setCategory, }), Pages = self.props.sidebarPage == "pages" and e(getPages, { Position = self.sidebarBinding:map(function(alpha) return UDim2.new(0,0,0,45):Lerp(UDim2.new(0.5,0,0,45), alpha) end), sidebarMotor = self.sidebarMotor, sidebarPage = self.props.sidebarPage, category = self.props.category, setSidebarPage = self.props.setSidebarPage, setCategory = self.props.setCategory, }), Shadow = e("Frame", { Position = UDim2.fromScale(1,0), Size = UDim2.new(0,10,1,0), BackgroundColor3 = Color3.fromRGB(38,38,38), BorderSizePixel = 0, }, { UIGradient = e("UIGradient", { Transparency = NumberSequence.new({ NumberSequenceKeypoint.new(0,0), NumberSequenceKeypoint.new(1,1), }) }) }) }) end return RoactRodux.connect(function(state) return { sidebarPage = state.sidebarPage, category = state.category, } end, function(dispatch) return { setSidebarPage = function(newPage) dispatch({ type = "SetSidebarPage", sidebarPage = newPage, }) end, setCategory = function(newCategory) dispatch({ type = "SetCategory", newCategory = newCategory, }) end, goBack = function() dispatch({ type = "RemoveLastCategory", }) dispatch({ type = "SetSidebarPage", sidebarPage = "subcategory", }) end, } end)(Sidebar)
local pretty = require("pl.pretty") local widget = require("widget") local scrollBar = {} scrollBar.__index = scrollBar function scrollBar.new(widget) local self = {} setmetatable(self, scrollBar) scrollBar.init(self, widget) return self end function scrollBar.calculateHandle(self) local handleHeight = self.widget.height * self.widget.height / self.widget:getContentRect().height handleHeight = math.max(handleHeight, self.minHandle) handleHeight = math.min(self.bar.height, handleHeight) self.handle.width=self.width; self.handle.height=handleHeight; end function scrollBar.init(self, widget, callBack) self.widget = widget self.callBack = callBack self.width = 10 self.pos = 0 self.bar = {x=self.widget.x + self.widget.width - self.width, y=self.widget.y, width=self.width, height=self.widget.height} self.minHandle = self.width self.handle = {x=self.widget.x + self.widget.width - self.width, y=self.widget.y, width=self.width, height=handleHeight} self:calculateHandle() self.diffX = 0 self.diffY = 0 self.dragging = false return self end function scrollBar.draw(self) self:calculateHandle() --love.graphics.setColor(self.color.fill) --love.graphics.rectangle("fill", self.x, self.y, self.width, self.height, self.radius.x, self.radius.y) local currentColor = self.widget:getColor() love.graphics.setColor(currentColor.stroke) love.graphics.rectangle("line", self.widget.x + self.widget.width - self.width, self.widget.y, self.width, self.widget.height, self.widget.radius.x, self.widget.radius.y) love.graphics.setColor(currentColor.fill) love.graphics.rectangle("fill", self.widget.x + self.widget.width - self.width, self.widget.y, self.width, self.widget.height, self.widget.radius.x, self.widget.radius.y) love.graphics.setColor(currentColor.stroke) love.graphics.rectangle("fill", self.handle.x, self.handle.y, self.handle.width, self.handle.height, self.widget.radius.x, self.widget.radius.y) end function scrollBar.hit(self, x, y) return x >= self.handle.x and x < self.handle.x + self.handle.width and y >= self.handle.y and y < self.handle.y + self.handle.height end function scrollBar.mousePressed(self, handled, x, y, button, isTouch) if self:hit(x,y) then --self.color = self.colors.pressed self.dragging = true self.diffX = x - self.handle.x self.diffY = y - self.handle.y return true end end function scrollBar.mouseReleased(self, handled, x, y, button, isTouch) if self:hit(x,y) and self.pressed then self.focused = true self.open = not self.open --self.color = self.colors.focused return true else self.focused = false --self.color = self.colors.released self.open = false end self.dragging = false end function scrollBar.update(self, dt) if self.dragging then --self.handle.x = love.mouse.getX() - self.diffX self.handle.y = love.mouse.getY() - self.diffY self.handle.y = math.max(self.handle.y, self.bar.y) self.handle.y = math.min(self.handle.y, self.bar.y+self.bar.height-self.handle.height) local contentPos = self.widget:getContentRect() local posPercent = 0 if self.bar.height ~= self.handle.height then posPercent = (self.handle.y - self.bar.y) / (self.bar.height - self.handle.height) end local ypos = self.widget.y if(contentPos.height > self.widget.height) then yPos = self.widget.y - (contentPos.height - self.widget.height) * posPercent end self.widget:setContentPosition({x=contentPos.x, y=yPos}) end end function scrollBar.wheelMoved(self, x, y) end return scrollBar
--------------------------------------------------------------------------- --- tmux hotkeys for awful.hotkeys_widget -- -- @author nahsi [email protected] -- @copyright 2017 nahsi -- @submodule awful.hotkeys_popup --------------------------------------------------------------------------- local hotkeys_popup = require("awful.hotkeys_popup.widget") local tmux = {} --- Add rules to match tmux session. -- -- For example: -- -- tmux.add_rules_for_terminal({ rule = { name = { "tmux" }}}) -- -- will show tmux hotkeys for any window that has 'tmux' in its title. -- If no rules are provided then tmux hotkeys will be shown always! -- @function add_rules_for_terminal -- @see awful.rules.rules -- @tparam table rule Rules to match a window containing a tmux session. function tmux.add_rules_for_terminal(rule) for group_name, group_data in pairs({ ["tmux: sessions"] = rule, ["tmux: windows"] = rule, ["tmux: panes"] = rule, ["tmux: misc"] = rule, }) do hotkeys_popup.add_group_rules(group_name, group_data) end end local tmux_keys = { ["tmux: sessions"] = {{ modifiers = {}, keys = { s = "show all sessions", ['$'] = "rename the current session", ['('] = "move to previous session", [')'] = "move to next session", d = "detach from current session" } }}, ["tmux: windows"] = {{ modifiers = {}, keys = { c = "create window", f = "find window", [','] = "rename current window", --['&'] = "close current window", p = "previous window", n = "next window", ['0...9'] = "select window by number" } }}, ["tmux: panes"] = {{ modifiers = {}, keys = { [';'] = "toggle last active pane", ['%'] = "split pane vertically", ['"'] = "split pane horizontally", ['{'] = "move the current pane left", ['}'] = "move the current pane right", ['q 0...9'] = "select pane by number", o = "toggle between panes", z = "toggle pane zoom", ['space'] = "toggle between layouts", ['!'] = "convert pane into a window", x = "close current pane" } }}, ["tmux: misc"] = {{ modifiers = {}, keys = { [':'] = "enter command mode", ['?'] = "list shortcuts", t = "show clock" } }} } hotkeys_popup.add_hotkeys(tmux_keys) return tmux -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
-- Alternate movement bindings using the number keys, for numpad usage over telnet. if BindMovementToNumKeys then Keybindings["8"] = COMMAND_WALKNORTH Keybindings["9"] = COMMAND_WALKNE Keybindings["6"] = COMMAND_WALKEAST Keybindings["3"] = COMMAND_WALKSE Keybindings["2"] = COMMAND_WALKSOUTH Keybindings["1"] = COMMAND_WALKSW Keybindings["4"] = COMMAND_WALKWEST Keybindings["7"] = COMMAND_WALKNW Keybindings["5"] = COMMAND_WAIT end -- List of keys to set up as quickkeys. local QuickKeys = {} if BindQuickKeysTo == 'num-keys' then QuickKeys = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' } elseif BindQuickKeysTo == 'f-keys' then QuickKeys = { 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F11', 'F12' } end -- List of weapons to bind to those keys. local QuickKeyWeapons = { 'chainsaw', 'knife', 'pistol', 'shotgun', 'ashotgun', 'dshotgun', 'chaingun', 'bazooka', 'plasma', 'bfg9000' } -- Given a weapon name, return a QuickKey function for it. local function MakeQuickKey(weapon) return function() command.quick_weapon(weapon) end end ---- Begin QuickKey category support. ---- -- QuickKey weapon categories. Each key cycles through the corresponding category. local QuickKeyCategories = { { name = 'melee weapons'; 'knife', 'chainsaw', 'ubutcher', 'usubtle', 'umjoll', 'spear', 'uscythe' }; { name = 'pistols'; 'pistol', 'ucpistol', 'ublaster', 'utrigun', 'uberetta', 'ujackal' }; { name = 'shotguns'; 'shotgun', 'dshotgun', 'ashotgun', 'udshotgun', 'uashotgun', 'upshotgun', 'usjack', 'ufshotgun' }; { name = 'rapid-fire weapons'; 'chaingun', 'uminigun', 'plasma', 'unplasma', 'ulaser', 'umega' }; { name = 'explosive weapons'; 'bazooka', 'umbazooka', 'unapalm', 'urbazooka' }; { name = 'BFGs'; 'bfg9000', 'unbfg9000', 'ubfg10k' }; { name = 'exotic weapons'; 'utristar', 'utrans', 'urailgun', 'uacid', 'unullpointer' }; } -- Get the last complete log message. Seeks backwards in the log until it either -- runs out of logging or finds an empty line. local function GetLastFullMessage() local n,msg = 0,'' repeat msg = ui.msg_history(n) .. msg n = n+1 until ui.msg_history(n) == nil or not ui.msg_history(n):match('%S') return msg end -- Attempt to equip a weapon and read the log to figure out if we succeeded or not. -- Also attempts to clean up the log after itself on success. local function TryEquip(weapon) ui.msg_clear() command.quick_weapon(weapon) local msg = GetLastFullMessage() local success_msg = msg:match("You prepare the .-[.!] ") or msg:match("You already have the .-[.!] ") or msg:match("You swap your weapons.-[.!] ") if not success_msg then return false end if msg ~= success_msg then -- This means that there were additional messages appended to the equip message, -- almost certainly "there is a %s lying here". Due to a bug in DoomRL, this -- will get appended twice, once now and once when we return from the key handler. -- So, we get rid of it here so it only appears once. ui.msg_clear() ui.msg(success_msg) end return true end -- QuickKey function builder for categories. Some ugly hacks in here (repeatedly -- clearing the log, reading the log messages to figure out what happened) -- because command.quick_weapon() doesn't return a value indicating whether -- we successfully equipped a thing the way command.use_item does. local current_category local function MakeQuickKeyForCategory(category) local index = 1 local max = #category local function inc() index = index % #category + 1; return index end return function() -- Player probably already has category[index] equipped. -- Skip to the next weapon. if current_category == category then inc() end -- Search for the first weapon in this category that the player has. local start = index repeat if TryEquip(category[index]) then current_category = category return end -- Proceed to the next weapon. Stop if we've looped all the way around -- to the weapon we started with. until inc() == start -- We ran out of weapons to try. Clear any lingering "you don't have the" messages. ui.msg_clear() ui.msg("You don't have any "..category.name..".") end end if QuickKeysUseCategories then MakeQuickKey = MakeQuickKeyForCategory QuickKeyWeapons = QuickKeyCategories end for i,key in ipairs(QuickKeys) do if QuickKeyWeapons[i] then Keybindings[key] = MakeQuickKey(QuickKeyWeapons[i]) end end
local utils = require "kong.tools.utils" local cache = require "kong.tools.database_cache" local crypto = require "kong.plugins.basic-auth.crypto" local singletons = require "kong.singletons" local constants = require "kong.constants" local responses = require "kong.tools.responses" local ngx_set_header = ngx.req.set_header local ngx_get_headers = ngx.req.get_headers local realm = 'Basic realm="'.._KONG._NAME..'"' local _M = {} -- Fast lookup for credential retrieval depending on the type of the authentication -- -- All methods must respect: -- -- @param request ngx request object -- @param {table} conf Plugin config -- @return {string} public_key -- @return {string} private_key local function retrieve_credentials(request, header_name, conf) local username, password local authorization_header = request.get_headers()[header_name] if authorization_header then local iterator, iter_err = ngx.re.gmatch(authorization_header, "\\s*[Bb]asic\\s*(.+)") if not iterator then ngx.log(ngx.ERR, iter_err) return end local m, err = iterator() if err then ngx.log(ngx.ERR, err) return end if m and next(m) then local decoded_basic = ngx.decode_base64(m[1]) if decoded_basic then local basic_parts = utils.split(decoded_basic, ":") username = basic_parts[1] password = basic_parts[2] end end end if conf.hide_credentials then request.clear_header(header_name) end return username, password end --- Validate a credential in the Authorization header against one fetched from the database. -- @param credential The retrieved credential from the username passed in the request -- @param given_password The password as given in the Authorization header -- @return Success of authentication local function validate_credentials(credential, given_password) local digest, err = crypto.encrypt({consumer_id = credential.consumer_id, password = given_password}) if err then ngx.log(ngx.ERR, "[basic-auth] "..err) end return credential.password == digest end local function load_credential_into_memory(username) local credentials, err = singletons.dao.basicauth_credentials:find_all {username = username} if err then return nil, err end return credentials[1] end local function load_credential_from_db(username) if not username then return end local credential, err = cache.get_or_set(cache.basicauth_credential_key(username), nil, load_credential_into_memory, username) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end return credential end local function load_consumer_into_memory(consumer_id, anonymous) local result, err = singletons.dao.consumers:find { id = consumer_id } if not result then if anonymous and not err then err = 'anonymous consumer "'..consumer_id..'" not found' end return nil, err end return result end local function set_consumer(consumer, credential) ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id) ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id) ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username) ngx.ctx.authenticated_consumer = consumer if credential then ngx_set_header(constants.HEADERS.CREDENTIAL_USERNAME, credential.username) ngx.ctx.authenticated_credential = credential ngx_set_header(constants.HEADERS.ANONYMOUS, nil) -- in case of auth plugins concatenation else ngx_set_header(constants.HEADERS.ANONYMOUS, true) end end local function do_authentication(conf) -- If both headers are missing, return 401 local headers = ngx_get_headers() if not (headers["authorization"] or headers["proxy-authorization"]) then ngx.header["WWW-Authenticate"] = realm return false, {status = 401} end local credential local given_username, given_password = retrieve_credentials(ngx.req, "proxy-authorization", conf) if given_username then credential = load_credential_from_db(given_username) end -- Try with the authorization header if not credential then given_username, given_password = retrieve_credentials(ngx.req, "authorization", conf) credential = load_credential_from_db(given_username) end if not credential or not validate_credentials(credential, given_password) then return false, {status = 403, message = "Invalid authentication credentials"} end -- Retrieve consumer local consumer, err = cache.get_or_set(cache.consumer_key(credential.consumer_id), nil, load_consumer_into_memory, credential.consumer_id, false) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end set_consumer(consumer, credential) return true end function _M.execute(conf) if ngx.ctx.authenticated_credential and conf.anonymous ~= "" then -- we're already authenticated, and we're configured for using anonymous, -- hence we're in a logical OR between auth methods and we're already done. return end local ok, err = do_authentication(conf) if not ok then if conf.anonymous ~= "" then -- get anonymous user local consumer, err = cache.get_or_set(cache.consumer_key(conf.anonymous), nil, load_consumer_into_memory, conf.anonymous, true) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end set_consumer(consumer, nil) else return responses.send(err.status, err.message) end end end return _M
require "Object" require "AppContext" require "NSDictionary" class(NotificationObserver, Object); function NotificationObserver:create() self = self:get(runtime::invokeClassMethod("LINotificationObserver", "create:", AppContext.current())); NotificationObserverEventProxyTable[self:id()] = self; return self; end function NotificationObserver:dealloc() NotificationObserverEventProxyTable[self:id()] = nil; super:dealloc(); end function NotificationObserver:observe(notificationName) self.notificationName = notificationName; runtime::invokeMethod(self:id(), "setNotificationName:func:", self.notificationName, "NotificationObserver_notification"); end function NotificationObserver:cancel() runtime::invokeMethod(self:id(), "setNotificationName:func:", "", ""); end -- event function NotificationObserver:didReceive(object, userInfo)--[[event]] end -- event proxy NotificationObserverEventProxyTable = {}; function NotificationObserver_notification(noId, objectId, userInfoId) local no = NotificationObserverEventProxyTable[noId]; if no then local object = nil; if string.len(objectId) ~= 0 then object = Object:get(objectId); end local userInfo = nil; if string.len(userInfoId) then userInfo = NSDictionary:get(userInfoId); end no:didReceive(object, userInfo); end end
local API_NPC = require(script:GetCustomProperty("API_NPC")) local API_DS = require(script:GetCustomProperty("APIDifficultySystem")) local API_D = require(script:GetCustomProperty("APIDamage")) local API_RE = require(script:GetCustomProperty("APIReliableEvents")) local RANGE = 0.0 -- This spell doesn't care where the player target is local COOLDOWN = 17.0 local MAX_OFFSET = 700.0 local INNER_RADIUS = 250.0 local OUTER_RADIUS = 1200.0 local DAMAGE = 55.0 local DELAY = 2.5 local targets = {} function GetPriority(npc, taskHistory) if API_DS.GetDifficultyLevel() > 1 then return 1.0 else return 0.0 end end function OnTaskStart(npc, threatTable) function GetRandomGroundedPointInCircle(center, radius) for i = 1, 5 do local t = 2 * math.pi * math.random() local u = math.random() + math.random() local r = radius * (1.0 - math.abs(u - 1.0)) local p = center + r * Vector3.New(math.cos(t), math.sin(t), 0.0) local rayStart = p + Vector3.UP * 800.0 local rayEnd = p - Vector3.UP * 800.0 local hitResult = World.Raycast(rayStart, rayEnd, {ignorePlayers = true}) if hitResult then return hitResult:GetImpactPosition() end end end local anchorPosition = API_NPC.GetRandomCharacterInThreatTable(threatTable):GetWorldPosition() local target = GetRandomGroundedPointInCircle(anchorPosition, MAX_OFFSET) if not target then target = anchorPosition end API_NPC.LookAtTargetWithoutPitch(npc, target) targets[npc] = target return 1.5 end function OnTaskEnd(npc, interrupted) if not interrupted then API_RE.BroadcastToAllPlayers("SMR", npc, targets[npc]) local target = targets[npc] Task.Spawn(function() Task.Wait(DELAY) for _, player in pairs(Game.FindPlayersInSphere(target, OUTER_RADIUS, {ignoreDead = true})) do local distance = (player:GetWorldPosition() - target).size if distance > INNER_RADIUS then API_D.ApplyDamage(npc, player, DAMAGE, API_D.TAG_AOE) end end end) end targets[npc] = nil end API_NPC.RegisterTaskServer("swampmystic_ring", RANGE, COOLDOWN, GetPriority, OnTaskStart, OnTaskEnd)
-- Copyright (C) 2016 Libo Huang (huangnauh), UPYUN Inc. local _M = {} -- for lua-resty-checkups _M.global = { checkup_timer_interval = 5, checkup_timer_overtime = 60, default_heartbeat_enable = false, shd_config_timer_interval = 1, shd_config_prefix = "shd_v1", } _M.consul = { config_key_prefix = "config/test/", config_positive_ttl = 10, config_negative_ttl = 5, config_cache_enable = true, cluster = { { servers = { { host = "10.0.5.108", port = 8500 }, }, }, }, } -- for lua-resty-load _M.load_init = { module_name = "resty.consul.load" } return _M
--Example2.lua -- --Simple example of using IAP Badger to purchase an IAP for buying coins. --------------------------------- -- -- IAP Badger initialisation -- --------------------------------- --Load IAP Badger local iap = require("iap_badger") --Progress spinner local spinner=nil --Text object indicating how many coins the user is currently holding local coinText=nil --Forward declaration local buyCoins10=nil --Create the catalogue local catalogue = { --Information about the product on the app stores products = { --buy50coins is the product identifier. --Always use this identifier to talk to IAP Badger about the purchase. buy50coins = { --A list of product names or identifiers specific to apple's App Store or Google Play. productNames = { apple="buy50coins", google="50_coins", amazon="COINSx50"}, --The product type productType = "consumable", --This function is called when a purchase is complete. onPurchase=function() iap.addToInventory("coins", 50) end, --The function is called when a refund is made onRefund=function() iap.removeFromInventory("coins", 50) end, }, --buy100coins is the product identifier. --Always use this identifier to talk to IAP Badger about the purchase. buy100coins = { --A list of product names or identifiers specific to apple's App Store or Google Play. productNames = { apple="buy100coins", google="100_coins", amazon="COINSx100"}, --The product type productType = "consumable", --This function is called when a purchase is complete. onPurchase=function() iap.addToInventory("coins", 100) end, --The function is called when a refund is made onRefund=function() iap.removeFromInventory("coins", 100) end, }, }, --Information about how to handle the inventory item inventoryItems = { coins = { productType="consumable" } } } --Called when a purchase fails local function failedListener() --If the spinner is on screen, remove it if (spinner) then spinner:removeSelf() spinner=nil end end local iapOptions = { --The catalogue generated above catalogue=catalogue, --The filename in which to save the inventory filename="example2.txt", --Salt for the hashing algorithm salt = "something tr1cky to gue55!", --Listeners for failed and cancelled transactions will just remove the spinner from the screen failedListener=failedListener, cancelledListener=failedListener, --Once the product has been purchased, it will remain in the inventory. Uncomment the following line --to test the purchase functions again in future. --doNotLoadInventory=true, debugMode=true, } --Initialise IAP badger iap.init(iapOptions) local function purchaseListener(product) --Remove the spinner spinner:removeSelf() spinner=nil --Any changes to the value in 'coins' in the inventory has been taken care of. --Update the text object to reflect how many coins are now in the user's inventory coinText.text = iap.getInventoryValue("coins") .. " coins" --Save the inventory change iap.saveInventory() --Tell user their purchase was successful native.showAlert("Info", "Your purchase was successful", {"Okay"}) end --Purchase function buyCoins=function(event) --Place a progress spinner on screen and tell the user the app is contating the store local spinnerBackground = display.newRect(160,240,360,600) spinnerBackground:setFillColor(1,1,1,0.75) --Spinner consumes all taps so the user cannot tap the purchase button twice spinnerBackground:addEventListener("tap", function() return true end) local spinnerText = display.newText("Contacting " .. iap.getStoreName() .. "...", 160,180, native.systemFont, 18) spinnerText:setFillColor(0,0,0) --Add a little spinning rectangle local spinnerRect = display.newRect(160,260,35,35) spinnerRect:setFillColor(0.25,0.25,0.25) transition.to(spinnerRect, { time=4000, rotation=360, iterations=999999, transition=easing.inOutQuad}) --Create a group and add all these objects to it spinner=display.newGroup() spinner:insert(spinnerBackground) spinner:insert(spinnerText) spinner:insert(spinnerRect) --Tell IAP to initiate a purchase - the product name will be stored in target.product iap.purchase(event.target.product, purchaseListener) end --------------------------------- -- -- Main game code -- --------------------------------- --Remove status bar display.setStatusBar( display.HiddenStatusBar ) --Background local background = display.newRect(160,240,360,600) background:setFillColor({type="gradient", color1={ 0,0,0 }, color2={ 0,0,0.4 }, direction="down"}) --Draw "buy 50 coins" button --Create button background local buy50Background = display.newRect(240, 400, 150, 50) buy50Background.stroke = { 0.5, 0.5, 0.5 } buy50Background.strokeWidth = 2 --Create "buy IAP" text object local buy50Text = display.newText("Buy 50 coins", buy50Background.x, buy50Background.y, native.systemFont, 18) buy50Text:setFillColor(0,0,0) --Store the name of the product this button relates to buy50Background.product="buy50coins" --Create tap listener buy50Background:addEventListener("tap", buyCoins) --Draw "buy 100 coins" button --Create button background local buy100Background = display.newRect(80, 400, 150, 50) buy100Background.stroke = { 0.5, 0.5, 0.5 } buy100Background.strokeWidth = 2 --Create "buy IAP" text object local buy100Text = display.newText("Buy 100 coins", buy100Background.x, buy100Background.y, native.systemFont, 18) buy100Text:setFillColor(0,0,0) --Store the name of the product this button relates to buy100Background.product="buy100coins" --Create tap listener buy100Background:addEventListener("tap", buyCoins) --Text indicating how many coins the player currently holds --Get how many coins are currently being held by the player local coinsHeld = iap.getInventoryValue("coins") --If no coins are held in the inventory, nil will be returned - this equates to no coins if (not coinsHeld) then coinsHeld=0 end coinText = display.newText(coinsHeld .. " coins", 160, 20, native.systemFont, 18) coinText:setFillColor(1,1,0)
UPGRADE = 1 // upgrade sprites or levels data if UPGRADE lua ;ALLPASS function fileList(path) return io.popen("dir \""..path.."\" /a /b", "r"):lines() end function save(data) local file,err = io.open("sprites/storage.asm",'w') if file then file:write(tostring(data)) file:close() else print("error:", err) -- not so hard? end end -- .PBM to asm local path = "sprites/bmp/" local data = "" --// read path for names for fileName in io.popen("dir \""..path.."\" /a /b", "r"):lines() do local lines = {} local file = assert(io.open(path..fileName, "rb")) --// read lines from file.pbm 'PBM' format for line in io.lines(path..fileName) do --// [1] format --// [2] width --// [3] height --// [4] sprite data lines[#lines + 1] = line end --// reformat name for asm label uppercaseName = string.upper(fileName) dotUnderscore = string.gsub(string.upper(fileName),"%.", "_") local strData = "" for c in (lines[4] or ''):gmatch'.' do strData = strData..c:byte().."," end data = data..dotUnderscore..':\tdb '..string.sub(strData, 1, #strData-1).."\n" file:close() end save(data) -- Tiled to asm local mapsPath = "maps/" for levelName in fileList(mapsPath) do local file = assert(io.open(mapsPath..levelName, "r")) local t = file:read("*a") print(t) file:close() end endlua endif
--[[ desc: Combo, A module of combo buff. author: Musoucrow since: 2019-1-15 ]]-- local _Base = require("actor.buff.base") ---@class Actor.Buff.Combo : Actor.Buff ---@field protected _skill Actor.Skill local _Combo = require("core.class")(_Base) function _Combo:Ctor(entity, data) _Base.Ctor(self, entity, data) self._skill = data.skill self._skill:Reset() end function _Combo:Exit() if (_Base.Exit(self)) then self._skill:CoolDown() end end return _Combo
--[[ © CloudSixteen.com http://crowlite.com/license --]] Crow.nest:IncludeFile("sh_enum.lua"); Crow.nest:IncludeFile("sv_hooks.lua"); Crow.nest:IncludeFile("cl_hooks.lua"); CrowBall.build = "Alpha"; function CrowBall:CreateTeams() team.SetUp(self._TEAM_BLUE, "Blue Team", Color(0, 100, 255, 255), true); team.SetUp(self._TEAM_RED, "Red Team", Color(255, 0, 0, 255), true); team.SetSpawnPoint(self._TEAM_BLUE, {"info_player_blue"}); team.SetSpawnPoint(self._TEAM_RED, {"info_player_red"}); end; function CrowBall:PlayerNoClip(player, desired) if (!player:IsAdmin() and desired == true) then return false; end; end; function CrowBall:GetOtherTeam(teamIndex) local result = self._TEAM_BLUE; if (teamIndex == result) then result = self._TEAM_RED; end; return result; end; function CrowBall:OnInitialize() --[[ Add The Simple Rounds --]] CrowRounds:AddRound(1, "Time Attack", true, nil, nil, "Get the most amount of kills before the timer runs out to win!"); --[[ Temporary Options --]] self._DEBUG = false; self._MINIMUM_PLAYERS = 2; self._BALL_NUMBER = 9; self._SPAWN_IMMUNITY = 3; self._RESPAWN_TIMER = 1; self._ELIMINATION_LIVES = 1; self._COMBO_TIME = 3; if (!team.Valid(self._TEAM_BLUE) or team.GetName(self._TEAM_BLUE) != "Blue Team") then self:CreateTeams(); end; if (SERVER) then util.AddNetworkString("CrowBallChangeTeam"); if (#_player.GetAll() >= self._MINIMUM_PLAYERS) then CrowRounds:HandleStart(); else self:AutoAssignTeams(); self:ResetGame(); end; end; end; function CrowBall:OnUnloaded() if (SERVER) then game.CleanUpMap(); for k, v in pairs(_player.GetAll()) do local color = v:GetColor(); v:SetColor(color.r, color.g, color.b, 255); v:SetTeam(TEAM_UNASSIGNED); end; CrowRounds:StopRound(); end; end;
local pairs = pairs local require = require local setmetatable = setmetatable local setup = require 'kit'.setup local _M = {} function _M.init(config) for modname, modconfig in pairs(config) do local module = require(modname) setup(module, modconfig) _M[modname] = module end end return setmetatable(_M, { __call = setup })