content
stringlengths
5
1.05M
headToolbarLayout= { name="headToolbarLayout",type=0,typeName="View",time=0,x=0,y=0,width=1280,height=720,visible=1,nodeAlign=kAlignTopLeft,fillParentWidth=1,fillParentHeight=1, { name="per_info_bg",type=0,typeName="Image",time=107172465,x=0,y=0,width=1246,height=64,nodeAlign=kAlignBottom,visible=1,fillParentWidth=0,fillParentHeight=0,file="games/common/head/ornament_per_info_bg.png" } } return headToolbarLayout;
--local Model = require( 'models/base' ) local MuutForum = class( 'MuutForum' ) --, Model ) MuutForum.static.key = '[]' MuutForum.static.secret = '[]' function MuutForum.sso( personid, name, email, is_admin ) local is_admin = is_admin or false local results = { key = MuutForum.static.key, timestamp = ngx.time() } results.fields = { user = { id = personid, displayname = name, email = email, is_admin = is_admin } } results.message = ngx.encode_base64( cjson.encode( results.fields ) ) local str = require ('resty.string') results.signature = str.to_hex( ngx.sha1_bin( MuutForum.static.secret..' '..results.message..' '..results.timestamp ) ) return results end return MuutForum
ITEM.name = "SSP-99 suit" ITEM.model ="models/kek1ch/ecolog_outfit_orange.mdl" ITEM.newModel ="models/nasca/stalker/male_ssp_eco.mdl" ITEM.description= "An SSP-99 suit, used by ecologists." ITEM.longdesc = "A SSP-99 Scientific Research suit specially designed for the Zone conditions. It is used by scientific expeditions and the eco-stalkers who cooperate with them. It has an integrated air-filtering and air-conditioning system. It is heat and electricity resistant, provides good protection from radiation and biological anomalies. It is resistant to chemically aggressive environments. It is not designed for combat, so it provides neither bullet, nor splinter protection." ITEM.width = 2 ITEM.height = 3 ITEM.price = 120000 ITEM.busflag = "dev" ITEM.br = 0.15 ITEM.fbr = 1 ITEM.ar = 0.80 ITEM.far = 6 ITEM.isHelmet = true ITEM.isGasmask = true ITEM.radProt = 0.8 ITEM.repairCost = ITEM.price/100*1 ITEM.overlayPath = "vgui/overlays/hud_sci" ITEM.ballisticlevels = {"l","ll-a","ll-a","l","l"} ITEM.img = ix.util.GetMaterial("vgui/hud/ssp99.png") ITEM.noBusiness = true ITEM.weight = 7.900 ITEM.miscslots = 3 ITEM.newSkin = 0 ITEM.bodygroup = {0} ITEM.bodygroupsub = {0}
require 'cunn' -- example of extracting descriptors on GPU N = 76 -- the number of patches to match patches = torch.rand(N,1,64,64):cuda() -- load the network net = torch.load'../networks/siam2stream/siam2stream_liberty_nn.t7':cuda() print(net) -- to extract the descriptors we need a branch of the first parallel module net = net:get(1):get(1) print(net) -- in place mean subtraction local p = patches:view(N,1,64*64) p:add(-p:mean(3):expandAs(p)) -- get the output descriptors output = net:forward(patches) -- print the size of the output tensor print(#output) -- OR if there is a lot of patches to extract descriptors -- it is better to split them to smaller batches batch_size = 128 -- preallocate the output tensor, here we know the dimensionality of descriptor descriptors = torch.CudaTensor(N,512) descriptors_split = descriptors:split(batch_size) for i,v in ipairs(patches:split(batch_size)) do descriptors_split[i]:copy(net:forward(v)) end
local alpha = require("alpha") local dashboard = require("alpha.themes.dashboard") -- Set header dashboard.section.header.val = { " ", " ███╗ ██╗███████╗ ██████╗ ██╗ ██╗██╗███╗ ███╗ ", " ████╗ ██║██╔════╝██╔═══██╗██║ ██║██║████╗ ████║ ", " ██╔██╗ ██║█████╗ ██║ ██║██║ ██║██║██╔████╔██║ ", " ██║╚██╗██║██╔══╝ ██║ ██║╚██╗ ██╔╝██║██║╚██╔╝██║ ", " ██║ ╚████║███████╗╚██████╔╝ ╚████╔╝ ██║██║ ╚═╝ ██║ ", " ╚═╝ ╚═══╝╚══════╝ ╚═════╝ ╚═══╝ ╚═╝╚═╝ ╚═╝ ", " ", } -- Set menu dashboard.section.buttons.val = { dashboard.button( "Leader f f", " > Find file", ":Leaderf file --popup<CR>"), dashboard.button( "Leader f r", " > Recent files" , ":Leaderf mru --popup<CR>"), dashboard.button( "Leader f g", " > Project grep" , ":Leaderf rg --popup<CR>"), dashboard.button( "e", " > New file" , ":enew <CR>"), dashboard.button( "q", " > Quit NVIM", ":qa<CR>"), } local fortune = require("alpha.fortune") dashboard.section.footer.val = fortune() alpha.setup(dashboard.opts) -- Send config to alpha alpha.setup(dashboard.opts)
RuneSystem = CreateModule("RuneSystem", GAME_PHASE_GAME) local spawnTicket = {}; function RuneSystem:Init() self.gameManager = GetGameManager() self.gameManager:RegisterVariable("Rune_Spawn_Interval", 120) self.gameManager:RegisterVariable("First_Rune_Spawn_Time", 25) self.RuneSpawners = GameManagerRequestBus.Broadcast.GetEntitiesHavingTag(Crc32("Rune_Spawner")) self:SpawnFirstRune() end function RuneSystem:SpawnFirstRune() for i = 1, #self.RuneSpawners do spawnTicket[i] = SpawnerComponentRequestBus.Event.Spawn(self.RuneSpawners[i]) end self.timer = CreateInterval(partial(self.SpawnRunes, self), self.gameManager:GetValue("Rune_Spawn_Interval")) end function RuneSystem:SpawnRunes() self.Runes = GameManagerRequestBus.Broadcast.GetEntitiesHavingTag(Crc32("rune")) self:RemoveAllRunes(self.Runes) for i = 1, #self.RuneSpawners do spawnTicket[i] = SpawnerComponentRequestBus.Event.Spawn(self.RuneSpawners[i]) end end function RuneSystem:RemoveAllRunes(runes) for i = 1, #runes do GameEntityContextRequestBus.Broadcast.DestroyGameEntity(runes[i]); end end
outputFiles = { NormvolumeCumulative={ --experimental data filename="Collecteddata/data_7_cities.csv", selected_columns=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14], }
-- rIngameModelViewer -- zork 2011 --------------------------------------------------------------------- -- DO NOT TOUCH ANYTHING HERE --------------------------------------------------------------------- local cfg = { size = 200, page = 1, num = 0, rows = 0, cols = 0, backdrop = { bgFile = "", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = false, tileSize = 0, edgeSize = 16, insets = { left = 0, right = 0, top = 0, bottom = 0, }, }, } --sounds local snd_swap = "INTERFACESOUND_LOSTTARGETUNIT" local snd_select = "igMainMenuOption" local snd_close = "igMainMenuLogout"; local models = {} ----------------------------- -- FUNCTIONS ----------------------------- --round some stuff local function rIMV_roundNumber(n) return floor((n)*10)/10 end local function calcPageForDisplayID(displayid) local n = math.ceil(displayid/cfg.num) return n end local function calcFirstDisplayIdOfPage() local n = ((cfg.page*cfg.num)+1)-cfg.num return n end --change portraitZoom func local function rIMV_changeModelPortraitZoom(self, delta) local maxzoom = 1 local minzoom = -0.5 self.zoomLevel = self.zoomLevel + delta*0.15 if (self.zoomLevel > maxzoom) then self.zoomLevel = maxzoom end if (minzoom > self.zoomLevel) then self.zoomLevel = minzoom end self.zoomLeve = rIMV_roundNumber(self.zoomLevel) self:SetPortraitZoom(self.zoomLevel) end --change camDistanceScale func local function rIMV_changeModelDistanceScale(self, delta) local maxscale = 10 local minscale = 0.1 self.scaleLevel = self.scaleLevel + delta*0.15 if (self.scaleLevel > maxscale) then self.scaleLevel = maxscale end if (minscale > self.scaleLevel) then self.scaleLevel = minscale end self.scaleLevel = rIMV_roundNumber(self.scaleLevel) self:SetCamDistanceScale(self.scaleLevel) end --move model left right func local function rIMV_moveModelLeftRight(self, delta) local max = 10 local min = -10 self.posX = self.posX + delta*0.15 if (self.posX > max) then self.posX = max end if (min > self.posX) then self.posX = min end self.posX = rIMV_roundNumber(self.posX) self:SetPosition(0,self.posX,self.posY) end --move model top bottom func local function rIMV_moveModelTopBottom(self, delta) local max = 10 local min = -10 self.posY = self.posY + delta*0.15 if (self.posY > max) then self.posY = max end if (min > self.posY) then self.posY = min end self.posY = rIMV_roundNumber(self.posY) self:SetPosition(0,self.posX,self.posY) end --model rotation func local function rIMV_rotateModel(self,button) local rotationIncrement = 0.2 if button == "LeftButton" then self.rotation = self.rotation - rotationIncrement else self.rotation = self.rotation + rotationIncrement end self.rotation = rIMV_roundNumber(self.rotation) self:SetRotation(self.rotation) end --tooltip for model func local function rIMV_showModelTooltip(self,theatre) GameTooltip:SetOwner(self, "ANCHOR_CURSOR") --GameTooltip:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -90, 90) if not theatre then GameTooltip:AddLine("Model View", 0, 1, 0.5, 1, 1, 1) else GameTooltip:AddLine("Theatre View", 0, 1, 0.5, 1, 1, 1) end GameTooltip:AddLine(" ") GameTooltip:AddDoubleLine("DisplayID", self.id, 1, 1, 1, 1, 1, 1) GameTooltip:AddDoubleLine("SetCamDistanceScale", self.scaleLevel, 1, 1, 1, 1, 1, 1) GameTooltip:AddDoubleLine("SetPortraitZoom", self.zoomLevel, 1, 1, 1, 1, 1, 1) GameTooltip:AddDoubleLine("SetPosition", "(0,"..self.posX..","..self.posY..")", 1, 1, 1, 1, 1, 1) GameTooltip:AddDoubleLine("SetRotation", self.rotation, 1, 1, 1, 1, 1, 1) GameTooltip:AddDoubleLine("GetModel", self.model, 1, 1, 1, 1, 1, 1) GameTooltip:AddLine(" ") if not theatre then GameTooltip:AddLine("Click on the model to open the theatre view!") end GameTooltip:AddLine("Hold SHIFT and click any mousebutton to reset all model values") GameTooltip:AddLine("Hold ALT and click model with left mousebutton to turn it LEFT") GameTooltip:AddLine("Hold ALT and click model with right mousebutton to turn it RIGHT") GameTooltip:AddLine("Use MouseWheel to change SetCamDistanceScale") GameTooltip:AddLine("Hold ALT+SHIFT and use MouseWheel to change SetPortraitZoom") GameTooltip:AddLine("Hold ALT and use MouseWheel to move model in y-Axis") GameTooltip:AddLine("Hold SHIFT and use MouseWheel to move model in x-Axis") if theatre then GameTooltip:AddLine(" ") GameTooltip:AddLine("Click on the black area to get back!", 1, 0, 1, 1, 1, 1) end GameTooltip:Show() end --tooltip for icon func local function rIMV_showIconTooltip(self) GameTooltip:SetOwner(self, "ANCHOR_CURSOR") --GameTooltip:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -90, 90) GameTooltip:AddLine("rIngameModelViewer", 0, 1, 0.5, 1, 1, 1) GameTooltip:AddLine("Click the icon to open the model viewer.", 1, 1, 1, 1, 1, 1) GameTooltip:AddLine("Hold ALT and any mousebutton to move the icon.", 1, 1, 1, 1, 1, 1) GameTooltip:Show() end --tooltip for theatre func local function rIMV_showTheatreTooltip(self) GameTooltip:SetOwner(self, "ANCHOR_CURSOR") --GameTooltip:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -90, 90) GameTooltip:AddLine("Close Theatre View", 0, 1, 0.5, 1, 1, 1) GameTooltip:AddLine("Click here to close the theatre view!") GameTooltip:Show() end --color tooltip func local function rIMV_showColorTooltip(self) GameTooltip:SetOwner(self, "ANCHOR_CURSOR") --GameTooltip:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -90, 90) GameTooltip:AddLine("Color Select", 0, 1, 0.5, 1, 1, 1) GameTooltip:AddLine("Cick here to change model background color to: "..self.color) GameTooltip:Show() end --set some default values to work with local function rIMV_setModelValues(self) self.scaleLevel = 1 self.zoomLevel = 0 self.posX = 0 self.posY = 0 self.rotation = 0 self:SetPortraitZoom(self.zoomLevel) self:SetCamDistanceScale(self.scaleLevel) self:SetPosition(0,self.posX,self.posY) self:SetRotation(self.rotation) end --bring the model to life and set the displayID local function rIMV_setModel(self,id) self:ClearModel() local defaultmodel = "interface\\buttons\\talktomequestionmark.m2" self:SetModel(defaultmodel) --in case setdisplayinfo fails self:SetDisplayInfo(id) local model = self:GetModel() if model == defaultmodel then self.model = "" self:EnableMouse(false) else self.model = model self:EnableMouse(true) end self.id = id self.p:SetText(id) end --move model into position func and adjust some values based on model size local function rIMV_adjustModelPosition(self,row,col) self:SetSize(cfg.size,cfg.size) self:SetPoint("TOPLEFT",cfg.size*row,cfg.size*col*(-1)) local fs = cfg.size*10/100 if fs < 8 then fs = 8 end self.p:SetFont("Fonts\\FRIZQT__.ttf", fs, "THINOUTLINE") self:Show() end --create a new model func local function rIMV_createModel(b,id) local m = CreateFrame("PlayerModel", nil,b) m:EnableMouse(true) m:SetScript("OnMouseDown", function(s,bu,...) if IsShiftKeyDown() then rIMV_setModelValues(s) PlaySound(snd_select) elseif IsAltKeyDown() then rIMV_rotateModel(s,bu) PlaySound(snd_select) else PlaySound("UChatScrollButton") b.theatre:Show() b.theatre:EnableMouse(true) rIMV_setModelValues(b.theatre.m) b.theatre.m:ClearModel() b.theatre.m:SetDisplayInfo(s.id) b.theatre.m.model = b.theatre.m:GetModel() b.theatre.m.id = s.id b.theatre.m.p:SetText(s.id) b.theatre.ag1:Play() end end) m:SetScript("OnMouseWheel", function(s,d,...) if IsShiftKeyDown() and IsAltKeyDown() then rIMV_changeModelPortraitZoom(s,d) elseif IsAltKeyDown() then rIMV_moveModelTopBottom(s,d) elseif IsShiftKeyDown() then rIMV_moveModelLeftRight(s,d) else rIMV_changeModelDistanceScale(s,d) end end) m:SetScript("OnEnter", function(s) rIMV_showModelTooltip(s) end) m:SetScript("OnLeave", function(s) GameTooltip:Hide() end) local d = m:CreateTexture(nil, "BACKGROUND",nil,-8) d:SetTexture(0,0,0,0.2) d:SetAllPoints(m) m.d = d local t = m:CreateTexture(nil, "BACKGROUND",nil,-7) t:SetTexture(1,1,1,0.5) t:SetPoint("TOPLEFT", m, "TOPLEFT", 2, -2) t:SetPoint("BOTTOMRIGHT", m, "BOTTOMRIGHT", -2, 2) m.t = t local p = m:CreateFontString(nil, "BACKGROUND") p:SetPoint("TOP", 0, -2) p:SetAlpha(.5) m.p = p return m end --change models on page swap local function rIMV_changeModelViewerPage(pageid) cfg.page = pageid local displayid = 1 + ((cfg.page-1)*cfg.num) local id = 1 for i=1, cfg.num do if models[id] then rIMV_setModelValues(models[id]) rIMV_setModel(models[id],displayid) end displayid = displayid+1 id=id+1 end end --hide all the models local function rIMV_hideAllModels() local id = 1 --hide all models first until we are sure which models need to be shown at all for i=1, cfg.num do if models[id] and models[id]:IsShown() then models[id]:ClearAllPoints() models[id]:Hide() end id=id+1 end end --create all the models local function rIMV_createAllModels(b) --cleanup first, make sure all models get hidden first rIMV_hideAllModels() --calc the new page values local w = floor(b:GetWidth()) local h = floor(b:GetHeight())-70 --remove 70px for the bottom bar cfg.rows = floor(h/cfg.size) cfg.cols = floor(w/cfg.size) cfg.num = cfg.rows*cfg.cols local displayid = 1 + ((cfg.page-1)*cfg.num) local id = 1 for i=1, cfg.rows do for k=1, cfg.cols do --if the model does not exist yet create it, otherwise reset it if not models[id] then --make sure rIMV_createModel is only used when needed models[id] = rIMV_createModel(b,displayid) --print("[IMV DEBUG] Creating model: "..id) --debugging, only new numbers should be printed end rIMV_adjustModelPosition(models[id],k-1,i-1) rIMV_setModelValues(models[id]) rIMV_setModel(models[id],displayid) displayid = displayid+1 id=id+1 end end end --create menu buttons func local function rIMV_createMenu(b) local l1,l2,l3,l4,l5,t,p,e,d,e2 p = b:CreateFontString(nil, "BACKGROUND") p:SetFont("Fonts\\FRIZQT__.ttf", 20, "THINOUTLINE") p:SetPoint("BOTTOMLEFT", 10, 15) p:SetText("rIngameModelViewer 1.5") p:SetTextColor(0,1,0.5) --editbox pageid e = CreateFrame("EditBox", nil,b) e:SetSize(80,30) e:SetPoint("BOTTOM",47.5,10) d = e:CreateTexture(nil, "BACKGROUND",nil,-8) d:SetTexture(0,0,0,0.2) d:SetAllPoints(e) t = e:CreateTexture(nil, "BACKGROUND",nil,-7) t:SetTexture(1,1,1,0.5) t:SetPoint("TOPLEFT", e, "TOPLEFT", 2, -2) t:SetPoint("BOTTOMRIGHT", e, "BOTTOMRIGHT", -2, 2) e:SetFont("Fonts\\FRIZQT__.ttf", 14, "THINOUTLINE") e:SetText(cfg.page) e:SetJustifyH("CENTER") p = e:CreateFontString(nil, "BACKGROUND") p:SetFont("Fonts\\FRIZQT__.ttf", 14, "THINOUTLINE") p:SetPoint("BOTTOM", e, "TOP", 0, 10) p:SetText("PAGE") --e:EnableMouse(true) e:SetScript("OnEnterPressed", function(s,v,...) PlaySound(snd_swap) local n = floor(s:GetNumber()) if n < 1 then n = 1 end s:SetText(n) if n ~= cfg.page then rIMV_changeModelViewerPage(n) e2:SetText(calcFirstDisplayIdOfPage()) end end) --editbox displayid e2 = CreateFrame("EditBox", nil,b) e2:SetSize(80,30) e2:SetPoint("RIGHT",e,"LEFT",-15,0) d = e2:CreateTexture(nil, "BACKGROUND",nil,-8) d:SetTexture(0,0,0,0.2) d:SetAllPoints(e2) t = e2:CreateTexture(nil, "BACKGROUND",nil,-7) t:SetTexture(1,1,1,0.5) t:SetPoint("TOPLEFT", e2, "TOPLEFT", 2, -2) t:SetPoint("BOTTOMRIGHT", e2, "BOTTOMRIGHT", -2, 2) e2:SetFont("Fonts\\FRIZQT__.ttf", 14, "THINOUTLINE") e2:SetText(cfg.page) e2:SetJustifyH("CENTER") p = e2:CreateFontString(nil, "BACKGROUND") p:SetFont("Fonts\\FRIZQT__.ttf", 14, "THINOUTLINE") p:SetPoint("BOTTOM", e2, "TOP", 0, 10) p:SetText("DISPLAYID") --e:EnableMouse(true) e2:SetScript("OnEnterPressed", function(s,v,...) PlaySound(snd_swap) local n = floor(s:GetNumber()) if n < 1 then n = 1 end s:SetText(n) local n2 = calcPageForDisplayID(n) if n2 ~= cfg.page then e:SetText(n2) rIMV_changeModelViewerPage(n2) end end) --prev page button l1 = CreateFrame("FRAME", nil,b) l1:SetSize(80,30) l1:SetPoint("RIGHT",e2,"LEFT",-15,0) t = l1:CreateTexture(nil, "BACKGROUND",nil,-8) t:SetTexture(0.2,0.2,0.2,0.5) t:SetAllPoints(l1) l1.t = t p = l1:CreateFontString(nil, "BACKGROUND") p:SetFont("Fonts\\FRIZQT__.ttf", 14, "THINOUTLINE") p:SetPoint("CENTER", 0, 0) p:SetText("< PAGE") l1:EnableMouse(true) l1:SetScript("OnMouseDown", function(...) if cfg.page-1 >= 1 then PlaySound(snd_swap) e:SetText(cfg.page-1) rIMV_changeModelViewerPage(cfg.page-1) e2:SetText(calcFirstDisplayIdOfPage()) end end) --next page button l2 = CreateFrame("FRAME", nil,b) l2:SetSize(80,30) l2:SetPoint("LEFT",e,"RIGHT",15,0) t = l2:CreateTexture(nil, "BACKGROUND",nil,-8) t:SetTexture(0.2,0.2,0.2,0.5) t:SetAllPoints(l2) l2.t = t p = l2:CreateFontString(nil, "BACKGROUND") p:SetFont("Fonts\\FRIZQT__.ttf", 14, "THINOUTLINE") p:SetPoint("CENTER", 0, 0) p:SetText("PAGE >") l2:EnableMouse(true) l2:SetScript("OnMouseDown", function(...) PlaySound(snd_swap) e:SetText(cfg.page+1) rIMV_changeModelViewerPage(cfg.page+1) e2:SetText(calcFirstDisplayIdOfPage()) end) --close button l3 = CreateFrame("FRAME", nil,b) l3:SetSize(80,30) l3:SetPoint("BOTTOMRIGHT",-10,10) t = l3:CreateTexture(nil, "BACKGROUND",nil,-8) t:SetTexture(0.2,0.2,0.2,0.5) t:SetAllPoints(l3) l3.t = t p = l3:CreateFontString(nil, "BACKGROUND") p:SetFont("Fonts\\FRIZQT__.ttf", 14, "THINOUTLINE") p:SetPoint("CENTER", 0, 0) p:SetText("</CLOSE>") l3:EnableMouse(true) l3:SetScript("OnMouseDown", function() b:EnableMouse(false) PlaySoundFile("Sound\\Creature\\BabyMurloc\\BabyMurlocB.wav") b.ag2:Play() end) --size + button l4 = CreateFrame("FRAME", nil,b) l4:SetSize(80,30) l4:SetPoint("LEFT",l2,"RIGHT",15,0) t = l4:CreateTexture(nil, "BACKGROUND",nil,-8) t:SetTexture(0.2,0.2,0.2,0.5) t:SetAllPoints(l4) l4.t = t p = l4:CreateFontString(nil, "BACKGROUND") p:SetFont("Fonts\\FRIZQT__.ttf", 14, "THINOUTLINE") p:SetPoint("CENTER", 0, 0) p:SetText("SIZE ++") l4:EnableMouse(true) l4:SetScript("OnMouseDown", function() PlaySound(snd_swap) cfg.size = cfg.size+20 if cfg.size > 300 then cfg.size = 300 else rIMV_createAllModels(b) e2:SetText(calcFirstDisplayIdOfPage()) end end) --size - button l5 = CreateFrame("FRAME", nil,b) l5:SetSize(80,30) l5:SetPoint("RIGHT",l1,"LEFT",-15,0) t = l5:CreateTexture(nil, "BACKGROUND",nil,-8) t:SetTexture(0.2,0.2,0.2,0.5) t:SetAllPoints(l5) l5.t = t p = l5:CreateFontString(nil, "BACKGROUND") p:SetFont("Fonts\\FRIZQT__.ttf", 14, "THINOUTLINE") p:SetPoint("CENTER", 0, 0) p:SetText("SIZE --") l5:EnableMouse(true) l5:SetScript("OnMouseDown", function() PlaySound(snd_swap) cfg.size = cfg.size-20 if cfg.size < 60 then cfg.size = 60 else rIMV_createAllModels(b) e2:SetText(calcFirstDisplayIdOfPage()) end end) l1:SetScript("OnEnter", function(s) s.t:SetTexture(0.2,0.2,0.2,0.8) end) l1:SetScript("OnLeave", function(s) s.t:SetTexture(0.2,0.2,0.2,0.5) end) l2:SetScript("OnEnter", function(s) s.t:SetTexture(0.2,0.2,0.2,0.8) end) l2:SetScript("OnLeave", function(s) s.t:SetTexture(0.2,0.2,0.2,0.5) end) l3:SetScript("OnEnter", function(s) s.t:SetTexture(0.2,0.2,0.2,0.8) end) l3:SetScript("OnLeave", function(s) s.t:SetTexture(0.2,0.2,0.2,0.5) end) l4:SetScript("OnEnter", function(s) s.t:SetTexture(0.2,0.2,0.2,0.8) end) l4:SetScript("OnLeave", function(s) s.t:SetTexture(0.2,0.2,0.2,0.5) end) l5:SetScript("OnEnter", function(s) s.t:SetTexture(0.2,0.2,0.2,0.8) end) l5:SetScript("OnLeave", function(s) s.t:SetTexture(0.2,0.2,0.2,0.5) end) end --create fullscreen background frame func local function rIMV_createHolderFrame() local b = CreateFrame("Frame","rIMV_HolderFrame",UIParent) b:SetFrameStrata("FULLSCREEN") b:SetAllPoints(UIParent) --b:SetPoint("CENTER",0,0) --b:SetSize(500,400) --b:SetBackdrop(cfg.backdrop) --b:SetBackdropBorderColor(0.4,0.3,0.3,1) local t = b:CreateTexture(nil, "BACKGROUND",nil,-8) --t:SetTexture(1,0.95,0.65,1) t:SetAllPoints(b) t:SetTexture("Interface\\AddOns\\rIngameModelViewer\\leinwand",true,true) t:SetVertTile(true) t:SetHorizTile(true) b.t = t b:EnableMouse(false) b:SetAlpha(0) local ag1, ag2, a1, a2 --fade in anim ag1 = b:CreateAnimationGroup() a1 = ag1:CreateAnimation("Alpha") a1:SetDuration(0.8) a1:SetSmoothing("IN") a1:SetChange(1) b.ag1 = ag1 b.ag1.a1 = a1 --fade out anim ag2 = b:CreateAnimationGroup() a2 = ag2:CreateAnimation("Alpha") a2:SetDuration(0.8) a2:SetSmoothing("OUT") a2:SetChange(-1) b.ag2 = ag2 b.ag2.a2 = a2 b.ag1:SetScript("OnFinished", function(ag) b:SetAlpha(1) end) b.ag2:SetScript("OnFinished", function(ag) b:SetAlpha(0) b:Hide() end) --b:SetScript("OnMouseDown", function(s,bu,...) --s.ag2:Play() --end) return b end --create layer that persists above the models for a special view local function rIMV_createTheatreFrame(f) local b = CreateFrame("Frame","rIMV_TheatreFrame",f) b:SetFrameStrata("FULLSCREEN_DIALOG") b:SetAllPoints(f) --b:SetPoint("CENTER",0,0) --b:SetSize(500,400) --b:SetBackdrop(cfg.backdrop) --b:SetBackdropBorderColor(0.4,0.3,0.3,1) local t = b:CreateTexture(nil, "BACKGROUND",nil,-8) t:SetTexture(0,0,0,0.9) t:SetAllPoints(b) t:SetVertTile(true) t:SetHorizTile(true) b.t = t b:EnableMouse(false) b:SetAlpha(0) local ag1, ag2, a1, a2 --fade in anim ag1 = b:CreateAnimationGroup() a1 = ag1:CreateAnimation("Alpha") a1:SetDuration(1) a1:SetSmoothing("OUT") a1:SetChange(1) b.ag1 = ag1 b.ag1.a1 = a1 --fade out anim ag2 = b:CreateAnimationGroup() a2 = ag2:CreateAnimation("Alpha") a2:SetDuration(1) a2:SetSmoothing("IN") a2:SetChange(-1) b.ag2 = ag2 b.ag2.a2 = a2 b.ag1:SetScript("OnFinished", function(ag) local s = ag:GetParent() s:SetAlpha(1) end) b.ag2:SetScript("OnFinished", function(ag) local s = ag:GetParent() s:SetAlpha(0) s:EnableMouse(false) s:Hide() end) b:SetScript("OnMouseDown", function(s,bu,...) PlaySound("UChatScrollButton") s.ag2:Play() end) local m = CreateFrame("PlayerModel", nil,b) m:EnableMouse(true) m:SetScript("OnMouseDown", function(s,bu,...) PlaySound(snd_select) if IsShiftKeyDown() then rIMV_setModelValues(s) elseif IsAltKeyDown() then rIMV_rotateModel(s,bu) else rIMV_rotateModel(s,bu) end end) m:SetScript("OnMouseWheel", function(s,d,...) if IsShiftKeyDown() and IsAltKeyDown() then rIMV_changeModelPortraitZoom(s,d) elseif IsAltKeyDown() then rIMV_moveModelTopBottom(s,d) elseif IsShiftKeyDown() then rIMV_moveModelLeftRight(s,d) else rIMV_changeModelDistanceScale(s,d) end end) b:SetScript("OnEnter", function(s) rIMV_showTheatreTooltip(s) end) b:SetScript("OnLeave", function(s) GameTooltip:Hide() end) m:SetScript("OnEnter", function(s) rIMV_showModelTooltip(s,"theatre") end) m:SetScript("OnLeave", function(s) GameTooltip:Hide() end) local d = m:CreateTexture(nil, "BACKGROUND",nil,-8) d:SetTexture(0,0,0,0.5) d:SetPoint("TOPLEFT", m, "TOPLEFT", -5, 5) d:SetPoint("BOTTOMRIGHT", m, "BOTTOMRIGHT", 5, -5) m.d = d local t = m:CreateTexture(nil, "BACKGROUND",nil,-7) t:SetTexture(1,1,1,0.9) t:SetAllPoints(m) m.t = t local p = m:CreateFontString(nil, "BACKGROUND") p:SetPoint("TOP", 0, -2) p:SetAlpha(.5) m.p = p local colorselect1 = CreateFrame("Frame","rIMV_ColorSelectWhite",b) local colorselect2 = CreateFrame("Frame","rIMV_ColorSelectGrey",b) local colorselect3 = CreateFrame("Frame","rIMV_ColorSelectMagenta",b) colorselect1:SetSize(50,50) colorselect1:SetPoint("TOPLEFT", m, "TOPRIGHT", 10, 0) colorselect1:EnableMouse(true) colorselect1.color = "White" colorselect1:SetScript("OnEnter", function(s) rIMV_showColorTooltip(s) end) colorselect1:SetScript("OnLeave", function(s) GameTooltip:Hide() end) colorselect1.t = colorselect1:CreateTexture(nil, "BACKGROUND",nil,-8) colorselect1.t:SetTexture(1,1,1,1) colorselect1.t:SetAllPoints(colorselect1) colorselect1:SetScript("OnMouseDown", function() PlaySound(snd_swap) m.t:SetTexture(1,1,1,0.9) end) colorselect1:SetHitRectInsets(-10, -10, -10, -5); colorselect2:SetSize(50,50) colorselect2:SetPoint("TOP", colorselect1, "BOTTOM", 0, -10) colorselect2:EnableMouse(true) colorselect2.color = "Grey" colorselect2:SetScript("OnEnter", function(s) rIMV_showColorTooltip(s) end) colorselect2:SetScript("OnLeave", function(s) GameTooltip:Hide() end) colorselect2.t = colorselect2:CreateTexture(nil, "BACKGROUND",nil,-8) colorselect2.t:SetTexture(0.2,0.2,0.2,1) colorselect2.t:SetAllPoints(colorselect2) colorselect2:SetScript("OnMouseDown", function() PlaySound(snd_swap) m.t:SetTexture(0.2,0.2,0.2,0.9) end) colorselect2:SetHitRectInsets(-10, -10, -5, -5); colorselect3:SetSize(50,50) colorselect3:SetPoint("TOP", colorselect2, "BOTTOM", 0, -10) colorselect3:EnableMouse(true) colorselect3.color = "Magenta" colorselect3:SetScript("OnEnter", function(s) rIMV_showColorTooltip(s) end) colorselect3:SetScript("OnLeave", function(s) GameTooltip:Hide() end) colorselect3.t = colorselect3:CreateTexture(nil, "BACKGROUND",nil,-8) colorselect3.t:SetTexture(1,0,1,1) colorselect3.t:SetAllPoints(colorselect3) colorselect3:SetScript("OnMouseDown", function() PlaySound(snd_swap) m.t:SetTexture(1,0,1,0.9) end) colorselect3:SetHitRectInsets(-10, -10, -5, -10); m.scaleLevel = 1 m.zoomLevel = 0 m.posX = 0 m.posY = 0 m.rotation = 0 m:SetPortraitZoom(m.zoomLevel) m:SetCamDistanceScale(m.scaleLevel) m:SetPosition(0,m.posX,m.posY) m:SetRotation(m.rotation) local size = floor(b:GetHeight())-40 m:SetSize(size,size) m:SetPoint("CENTER",0,0) m.p:SetFont("Fonts\\FRIZQT__.ttf", 30, "THINOUTLINE") m:Show() b.m = m f.theatre = b end --create icon func local function rIMV_createIcon(b) local i = CreateFrame("Frame","rIMV_Icon",UIParent) i:SetSize(128,128) i:SetPoint("CENTER",0,0) local t = i:CreateTexture(nil, "BACKGROUND",nil,-8) t:SetTexture("Interface\\AddOns\\rIngameModelViewer\\murloc") t:SetAllPoints(i) i.t = t local hover = i:CreateTexture(nil, "BACKGROUND",nil,-6) hover:SetTexture("Interface\\AddOns\\rIngameModelViewer\\murloc_hover") hover:SetAllPoints(i) hover:SetBlendMode("ADD") hover:SetVertexColor(0,1,0.5,0.1) i.hover = hover i.hover:Hide() i:SetMovable(true) i:SetUserPlaced(true) i:EnableMouse(true) i:RegisterForDrag("LeftButton","RightButton") i:SetScript("OnDragStart", function(s) if IsAltKeyDown() then s:StartMoving() end end) i:SetScript("OnDragStop", function(s) s:StopMovingOrSizing() end) i:SetScript("OnMouseDown", function() if not IsAltKeyDown() then b:Show() PlaySoundFile("Sound\\Creature\\BabyMurloc\\BabyMurlocA.wav") rIMV_createAllModels(b) b:EnableMouse(true) b.ag1:Play() end end) i:SetScript("OnEnter", function(s) s.hover:Show() PlaySound("igCreatureAggroSelect") rIMV_showIconTooltip(s) end) i:SetScript("OnLeave", function(s) s.hover:Hide() PlaySound("INTERFACESOUND_LOSTTARGETUNIT") GameTooltip:Hide() end) end ----------------------------- -- LOADUP ----------------------------- --rIMV_init func local function rIMV_init() local b = rIMV_createHolderFrame() rIMV_createTheatreFrame(b) rIMV_createIcon(b) rIMV_createMenu(b) b:Hide() b.theatre:Hide() end --call rIMV_init()
local lambda = require "lambda" local t = require "testhelper" -- lambda-like syntax t( 1, lambda"x|x+1"( 0 ) ) -- multiple arguments t( 4, lambda"x,y|x+y"( 1, 3 ) ) -- additional statement, only the last expression is returned t( 3, lambda"x| x=x+1; x+1"( 1 ) ) -- default args are a,b,c,d,e,f,...( vararg ) t( 1, lambda"a+1"( 0 ) ) -- Memo local m = lambda'a+1' t( m, lambda'a+1' ) t.test_embedded_example() t()
return function() local liter = require(game:GetService('ReplicatedStorage').liter) it('should return the successor and then nil', function() local iter = liter.successors(1, function(number) local new = number * 10 return new <= 10_000 and new or nil end) expect(iter:after()).to.equal(1) expect(iter:after()).to.equal(10) expect(iter:after()).to.equal(100) expect(iter:after()).to.equal(1_000) expect(iter:after()).to.equal(10_000) expect(iter:after()).never.to.be.ok() end) end
--- Recipe class -- @classmod Recipe local Recipe = { _class = "Recipe" } setmetatable(Recipe, {__index = require("stdlib/data/data")}) local Item = require("stdlib/data/item") function Recipe:_get(recipe) return self:get(recipe, "recipe") end Recipe:set_caller(Recipe._get) -- Returns a formated ingredient or prodcut table local function format(ingredient, result_count) --[[ Ingredient table {"name", amount} -- Assumes a type of "item" { type :: string: "item" or "fluid". name :: string: Prototype name of the required item or fluid. amount :: uint: Amount of the item. minimum_temperature :: uint (optional): The minimum fluid temperature required. Has no effect if type is '"item"'. maximum_temperature :: uint (optional): The maximum fluid temperature allowed. Has no effect if type is '"item"'. } Product table { type :: string: "item" or "fluid". name :: string: Prototype name of the result. amount :: float (optional): If not specified, amount_min, amount_max and probability must all be specified. temperature :: uint (optional): The fluid temperature of this product. Has no effect if type is '"item"'. amount_min :: uint (optional): amount_max :: uint (optional): probability :: double (optional): A value in range [0, 1]. } --]] local object if type(ingredient) == "table" then if ingredient.valid and ingredient:valid() then return ingredient elseif ingredient.name then if Item(ingredient.name, ingredient.type):valid() then object = table.deepcopy(ingredient) if not object.amount and not (object.amount_min and object.amount_max and object.probability) then error("Result table requires amount or probabilities") end end elseif #ingredient > 0 then -- Can only be item types not fluid local item = Item(ingredient[1]) if item:valid() and item.type ~= "fluid" then object = { type = "item", name = ingredient[1], amount = ingredient[2] or 1 } end end elseif type(ingredient) == "string" then -- Our shortcut so we need to check it local item = Item(ingredient) if item:valid() then object = { type = item.type == "fluid" and "fluid" or "item", name = ingredient, amount = result_count or 1 } end end return object end -- get items for dificulties local function get_difficulties(normal, expensive) return format(normal), format((expensive == true and table.deepcopy(normal)) or expensive) end --- Remove an ingredient from an ingredients table -- @tparam table ingredients -- @tparam string name Name of the ingredient to remove local function remove_ingredient(ingredients, name) name = name.name -- TODO: Fix this?? for i, ingredient in pairs(ingredients) do if ingredient[1] == name or ingredient.name == name then ingredients[i] = nil return true end end end --- Replace an ingredient -- @tparam table ingredients Ingredients table -- @tparam string find ingredient to replace -- @tparam concepts.ingredient replace -- @tparam boolean replace_name_only Don't replace amounts local function replace_ingredient(ingredients, find, replace, replace_name_only) for i, ingredient in pairs(ingredients) do if ingredient[1] == find or ingredient.name == find then if replace_name_only then local amount = ingredient[2] or ingredient.amount replace.amount = amount end ingredients[i] = replace return true end end end --- Add an ingredient to a recipe -- @tparam string|Concepts.ingredient normal -- @tparam[opt] string|Concepts.ingredient|boolean expensive -- @treturn Recipe function Recipe:add_ingredient(normal, expensive) if self:valid() then normal, expensive = get_difficulties(normal, expensive) if self.normal then if normal then self.normal.ingredients[#self.normal.ingredients + 1] = normal end if expensive then self.expensive.ingredients[#self.expensive.ingredients + 1] = expensive end elseif normal then self.ingredients[#self.ingredients + 1] = normal end end return self end --- Remove one ingredient completely -- @tparam string normal -- @tparam string|boolean expensive expensive recipe to remove, or if true remove normal recipe from both -- @treturn Recipe function Recipe:remove_ingredient(normal, expensive) if self:valid() then normal, expensive = get_difficulties(normal, expensive) if self.normal then if normal then remove_ingredient(self.normal.ingredients, normal) end if expensive then remove_ingredient(self.expensive.ingredients, expensive) end elseif normal then remove_ingredient(self.ingredients, normal) end end return self end --- Replace one ingredient with another. -- @tparam string replace -- @tparam string|ingredient normal -- @tparam[opt] string|ingredient|boolean expensive function Recipe:replace_ingredient(replace, normal, expensive) self.fail_if_missing(replace, "Missing recipe to replace") if self:valid() then local n_string = type(normal) == "string" local e_string = type(expensive == true and normal or expensive) == "string" normal, expensive = get_difficulties(normal, expensive) if self.normal then if normal then replace_ingredient(self.normal.ingredients, replace, normal, n_string) end if expensive then replace_ingredient(self.expensive.ingredients, replace, expensive, e_string) end elseif normal then replace_ingredient(self.ingredients, replace, normal, n_string) end end return self end --- Converts a recipe to the difficulty recipe format -- @tparam[opt] number expensive_energy crafting energy_required for the expensive recipe -- @treturn self function Recipe:make_difficult(expensive_energy) if self:valid("recipe") and not self.normal then --convert all ingredients local normal, expensive = {}, {} for _, ingredient in ipairs(self.ingredients) do local this = format(ingredient) normal[#normal + 1] = this expensive[#expensive + 1] = table.deepcopy(this) end local r_normal, r_expensive = {}, {} for _, ingredient in ipairs(self.results or {self.result}) do local this = format(ingredient) r_normal[#r_normal + 1] = this r_expensive[#r_expensive + 1] = table.deepcopy(this) end self.normal = { enabled = self.enabled, energy_required = self.energy_required, ingredients = normal, results = r_normal, main_product = self.main_product } self.expensive = { enabled = self.enabled, energy_required = expensive_energy or self.energy_required, ingredients = expensive, results = r_expensive, main_product = self.main_product } self.ingredients = nil self.result = nil self.results = nil self.result_count = nil self.energy_required = nil self.enabled = nil self.main_product = nil end return self end --- Change the recipe category -- @tparam string category_name Crafting category -- @tparam[opt] boolean make_new Create the category if it doesn't exist -- @treturn self function Recipe:change_category(category_name, make_new) if self:valid() then local Category = require("stdlib/data/category") self.category = (Category(category_name, "recipe-category", make_new):valid() and category_name) or self.category end return self end --- Add to technology as a recipe unlock -- @tparam string tech_name Name of the technology to add the unlock too -- @treturn self function Recipe:add_unlock(tech_name) if self:valid() then local Tech = require("stdlib/data/technology") Tech.add_effect(self, tech_name) end return self end --- Remove the recipe unlock from the technology -- @tparam string tech_name Name of the technology to remove the unlock from -- @treturn self function Recipe:remove_unlock(tech_name) if self:valid("recipe") then local Tech = require("stdlib/data/technology") Tech.remove_effect(self, tech_name, "unlock-recipe") end return self end --- Set the enabled status of the recipe -- @tparam boolean enabled Enable or disable the recipe -- @treturn self function Recipe:set_enabled(enabled) if self:valid() then if self.normal then self.normal.enabled = enabled self.expensive.enabled = enabled else self.enabled = enabled end end return self end --- Convert result type to results type -- @treturn self function Recipe:convert_results() if self:valid("recipe") then if self.normal then if self.normal.result then self.normal.results = { format(self.normal.result, self.normal.result_count or 1) } self.normal.result = nil self.normal.result_count = nil end if self.expensive.result then self.expensive.results = { format(self.expensive.result, self.expensive.result_count or 1) } self.expensive.result = nil self.expensive.result_count = nil end elseif self.result then self.results = { format(self.result, self.result_count or 1) } self.result = nil self.result_count = nil end end return self end --- Set the main product of the recipe. -- @tparam string|boolean main_product if boolean then use normal/expensive recipes passed as main product -- @tparam[opt] Concepts.Product|string normal recipe -- @tparam[opt] Concempts.Product|string expensive recipe -- @treturn self function Recipe:set_main_product(main_product, normal, expensive) if self:valid("recipe") then normal, expensive = get_difficulties(normal, expensive) local normal_main, expensive_main if main_product then if type(main_product) == "string" and Item(main_product):valid() then normal_main = normal and main_product expensive_main = expensive and main_product elseif type(main_product) == "boolean" then normal_main = normal and Item(normal.name):valid() and normal.name expensive_main = expensive and Item(expensive.name):valid() and expensive.name end if self.normal then self.normal.main_product = normal_main self.expensive.main_product = expensive_main else self.main_product = normal_main end end end return self end --- Remove the main product of the recipe. -- @tparam[opt=false] boolean for_normal -- @tparam[opt=false] boolean for_expensive function Recipe:remove_main_product(for_normal, for_expensive) if self:valid("recipe") then if self.normal then if for_normal or (for_normal == nil and for_expensive == nil) then self.normal.main_product = nil end if for_expensive or (for_normal == nil and for_expensive == nil) then self.expensive.main_product = nil end elseif for_normal or (for_normal == nil and for_expensive == nil) then self.main_product = nil end end return self end --- Add a new product to results, converts if needed -- @tparam string|Concepts.product normal -- @tparam[opt] string|Concepts.product|boolean expensive -- @tparam[opt] string main_product function Recipe:add_result(normal, expensive, main_product) if self:valid() then normal, expensive = get_difficulties(normal, expensive) self:convert_results() self:set_main_product(main_product, normal, expensive) -- if self.normal then -- if normal then -- end -- if expensive then -- end -- elseif normal then -- end end return self end --- Remove a product from results, converts if needed -- @tparam[opt] string|Concepts.product normal -- @tparam[opt] string|Concepts.product|boolean expensive -- @tparam[opt] string main_product new main_product to use function Recipe:remove_result(normal, expensive, main_product) if self:valid() then normal, expensive = get_difficulties(normal, expensive) self:convert_results() self:set_main_product(main_product, normal, expensive) -- if self.normal then -- if normal then -- end -- if expensive then -- end -- elseif normal then -- end end return self end --- Remove a product from results, converts if needed -- @tparam string|Concepts.product result_name -- @tparam[opt] string|Concepts.product normal -- @tparam[opt] string|Concepts.product|boolean expensive -- @tparam[opt] string main_product function Recipe:replace_result(result_name, normal, expensive, main_product) if self:valid() and normal or expensive then result_name = format(result_name) if result_name then normal, expensive = get_difficulties(normal, expensive) self:convert_results() self:remove_result(result_name, expensive and result_name) self:set_main_product(main_product, normal, expensive) -- if self.normal then -- if normal then -- end -- if expensive then -- end -- elseif normal then -- end end end return self end Recipe._mt = { type = "recipe", __index = Recipe, __call = Recipe._get, __tostring = Recipe.tostring } return Recipe
local ffi = require "ffi" local bit = require "bit" local bnot = bit.bnot local band = bit.band local bor = bit.bor local lshift = bit.lshift local rshift = bit.rshift -- Contains the protypes for the vchi functions. require "vcos" require "vchi_cfg" require "vchi_common" require "connection" require "vchi_mh" VCHI_BULK_ROUND_UP = function(x) return band((x+VCHI_BULK_ALIGN-1), bnot(VCHI_BULK_ALIGN-1)) end VCHI_BULK_ROUND_DOWN = function(x) return band(x, bnot(VCHI_BULK_ALIGN-1)) end VCHI_BULK_ALIGN_NBYTES = function(x) if VCHI_BULK_ALIGNED(x) > 0 then return 0 end return (VCHI_BULK_ALIGN - band(x, VCHI_BULK_ALIGN-1)) end if USE_VCHIQ_ARM then VCHI_BULK_ALIGNED = function(x) return 1 end else VCHI_BULK_ALIGNED = function(x) return (band(x, VCHI_BULK_ALIGN-1) == 0) end end ffi.cdef[[ typedef struct { uint32_t version; uint32_t version_min; } VCHI_VERSION_T; ]] VCHI_VERSION = function(v_) return ffi.new("VCHI_VERSION_T", v_, v_ ); end VCHI_VERSION_EX = function(v_,m_) return ffi.new("VCHI_VERSION_T", v_, m_); end ffi.cdef[[ typedef enum { VCHI_VEC_POINTER, VCHI_VEC_HANDLE, VCHI_VEC_LIST } VCHI_MSG_VECTOR_TYPE_T; typedef struct vchi_msg_vector_ex { VCHI_MSG_VECTOR_TYPE_T type; union { // a memory handle struct { VCHI_MEM_HANDLE_T handle; uint32_t offset; int32_t vec_len; } handle; // an ordinary data pointer struct { const void *vec_base; int32_t vec_len; } ptr; // a nested vector list struct { struct vchi_msg_vector_ex *vec; uint32_t vec_len; } list; } u; } VCHI_MSG_VECTOR_EX_T; ]] -- BUGBUG --[[ // Construct an entry in a msg vector for a pointer (p) of length (l) #define VCHI_VEC_POINTER(p,l) VCHI_VEC_POINTER, { { (VCHI_MEM_HANDLE_T)(p), (l) } } // Construct an entry in a msg vector for a message handle (h), starting at offset (o) of length (l) #define VCHI_VEC_HANDLE(h,o,l) VCHI_VEC_HANDLE, { { (h), (o), (l) } } --]] -- Macros to manipulate fourcc_t values MAKE_FOURCC = function(x) if type(x) == "string" then return (bor( lshift(string.byte(x,1), 24), lshift(string.byte(x,2), 16), lshift(string.byte(x,3), 8), string.byte(x,4) )) end return (bor( lshift(x[0], 24), lshift(x[1], 16), lshift(x[2], 8), x[3] )) end FOURCC_TO_CHAR = function(x) return ffi.new("char[4]", band(rshift(x, 24), 0xFF), band(rshift(x, 16), 0xFF), band(rshift(x, 8), 0xFF), band(x, 0xFF)); end ffi.cdef[[ // Opaque service information struct opaque_vchi_service_t; // Descriptor for a held message. Allocated by client, initialised by vchi_msg_hold, // vchi_msg_iter_hold or vchi_msg_iter_hold_next. Fields are for internal VCHI use only. typedef struct { struct opaque_vchi_service_t *service; void *message; } VCHI_HELD_MSG_T; // structure used to provide the information needed to open a server or a client typedef struct { VCHI_VERSION_T version; vcos_fourcc_t service_id; VCHI_CONNECTION_T *connection; uint32_t rx_fifo_size; uint32_t tx_fifo_size; VCHI_CALLBACK_T callback; void *callback_param; vcos_bool_t want_unaligned_bulk_rx; // client intends to receive bulk transfers of odd lengths or into unaligned buffers vcos_bool_t want_unaligned_bulk_tx; // client intends to transmit bulk transfers of odd lengths or out of unaligned buffers vcos_bool_t want_crc; // client wants to check CRCs on (bulk) transfers. Only needs to be set at 1 end - will do both directions. } SERVICE_CREATION_T; // Opaque handle for a VCHI instance typedef struct opaque_vchi_instance_handle_t *VCHI_INSTANCE_T; // Opaque handle for a server or client typedef struct opaque_vchi_service_handle_t *VCHI_SERVICE_HANDLE_T; // Service registration & startup typedef void (*VCHI_SERVICE_INIT)(VCHI_INSTANCE_T initialise_instance, VCHI_CONNECTION_T **connections, uint32_t num_connections); typedef struct service_info_tag { const char * const vll_filename; /* VLL to load to start this service. This is an empty string if VLL is "static" */ VCHI_SERVICE_INIT init; /* Service initialisation function */ void *vll_handle; /* VLL handle; NULL when unloaded or a "static VLL" in build */ } SERVICE_INFO_T; ]] --[[ ****************************************************************************** Global funcs - implementation is specific to which side you are on (local / remote) ***************************************************************************** --]] ffi.cdef[[ VCHI_CONNECTION_T * vchi_create_connection( const VCHI_CONNECTION_API_T * function_table, const VCHI_MESSAGE_DRIVER_T * low_level); // Routine used to initialise the vchi on both local + remote connections int32_t vchi_initialise( VCHI_INSTANCE_T *instance_handle ); int32_t vchi_exit( void ); int32_t vchi_connect( VCHI_CONNECTION_T **connections, const uint32_t num_connections, VCHI_INSTANCE_T instance_handle ); //When this is called, ensure that all services have no data pending. //Bulk transfers can remain 'queued' int32_t vchi_disconnect( VCHI_INSTANCE_T instance_handle ); // Global control over bulk CRC checking int32_t vchi_crc_control( VCHI_CONNECTION_T *connection, VCHI_CRC_CONTROL_T control ); // helper functions void * vchi_allocate_buffer(VCHI_SERVICE_HANDLE_T handle, uint32_t *length); void vchi_free_buffer(VCHI_SERVICE_HANDLE_T handle, void *address); uint32_t vchi_current_time(VCHI_INSTANCE_T instance_handle); ]] ffi.cdef[[ /****************************************************************************** Global service API *****************************************************************************/ // Routine to create a named service extern int32_t vchi_service_create( VCHI_INSTANCE_T instance_handle, SERVICE_CREATION_T *setup, VCHI_SERVICE_HANDLE_T *handle ); // Routine to destory a service extern int32_t vchi_service_destroy( const VCHI_SERVICE_HANDLE_T handle ); // Routine to open a named service extern int32_t vchi_service_open( VCHI_INSTANCE_T instance_handle, SERVICE_CREATION_T *setup, VCHI_SERVICE_HANDLE_T *handle); // Routine to close a named service extern int32_t vchi_service_close( const VCHI_SERVICE_HANDLE_T handle ); // Routine to increment ref count on a named service extern int32_t vchi_service_use( const VCHI_SERVICE_HANDLE_T handle ); // Routine to decrement ref count on a named service extern int32_t vchi_service_release( const VCHI_SERVICE_HANDLE_T handle ); // Routine to send a message accross a service extern int32_t vchi_msg_queue( VCHI_SERVICE_HANDLE_T handle, const void *data, uint32_t data_size, VCHI_FLAGS_T flags, void *msg_handle ); // scatter-gather (vector) and send message int32_t vchi_msg_queuev_ex( VCHI_SERVICE_HANDLE_T handle, VCHI_MSG_VECTOR_EX_T *vector, uint32_t count, VCHI_FLAGS_T flags, void *msg_handle ); // legacy scatter-gather (vector) and send message, only handles pointers int32_t vchi_msg_queuev( VCHI_SERVICE_HANDLE_T handle, VCHI_MSG_VECTOR_T *vector, uint32_t count, VCHI_FLAGS_T flags, void *msg_handle ); // Routine to receive a msg from a service // Dequeue is equivalent to hold, copy into client buffer, release extern int32_t vchi_msg_dequeue( VCHI_SERVICE_HANDLE_T handle, void *data, uint32_t max_data_size_to_read, uint32_t *actual_msg_size, VCHI_FLAGS_T flags ); // Routine to look at a message in place. // The message is not dequeued, so a subsequent call to peek or dequeue // will return the same message. extern int32_t vchi_msg_peek( VCHI_SERVICE_HANDLE_T handle, void **data, uint32_t *msg_size, VCHI_FLAGS_T flags ); // Routine to remove a message after it has been read in place with peek // The first message on the queue is dequeued. extern int32_t vchi_msg_remove( VCHI_SERVICE_HANDLE_T handle ); // Routine to look at a message in place. // The message is dequeued, so the caller is left holding it; the descriptor is // filled in and must be released when the user has finished with the message. extern int32_t vchi_msg_hold( VCHI_SERVICE_HANDLE_T handle, void **data, // } may be NULL, as info can be uint32_t *msg_size, // } obtained from HELD_MSG_T VCHI_FLAGS_T flags, VCHI_HELD_MSG_T *message_descriptor ); // Initialise an iterator to look through messages in place extern int32_t vchi_msg_look_ahead( VCHI_SERVICE_HANDLE_T handle, VCHI_MSG_ITER_T *iter, VCHI_FLAGS_T flags ); ]] ffi.cdef[[ /****************************************************************************** Global service support API - operations on held messages and message iterators *****************************************************************************/ // Routine to get the address of a held message void *vchi_held_msg_ptr( const VCHI_HELD_MSG_T *message ); // Routine to get the size of a held message int32_t vchi_held_msg_size( const VCHI_HELD_MSG_T *message ); // Routine to get the transmit timestamp as written into the header by the peer uint32_t vchi_held_msg_tx_timestamp( const VCHI_HELD_MSG_T *message ); // Routine to get the reception timestamp, written as we parsed the header uint32_t vchi_held_msg_rx_timestamp( const VCHI_HELD_MSG_T *message ); // Routine to release a held message after it has been processed int32_t vchi_held_msg_release( VCHI_HELD_MSG_T *message ); // Indicates whether the iterator has a next message. vcos_bool_t vchi_msg_iter_has_next( const VCHI_MSG_ITER_T *iter ); // Return the pointer and length for the next message and advance the iterator. int32_t vchi_msg_iter_next( VCHI_MSG_ITER_T *iter, void **data, uint32_t *msg_size ); // Remove the last message returned by vchi_msg_iter_next. // Can only be called once after each call to vchi_msg_iter_next. int32_t vchi_msg_iter_remove( VCHI_MSG_ITER_T *iter ); // Hold the last message returned by vchi_msg_iter_next. // Can only be called once after each call to vchi_msg_iter_next. int32_t vchi_msg_iter_hold( VCHI_MSG_ITER_T *iter, VCHI_HELD_MSG_T *message ); // Return information for the next message, and hold it, advancing the iterator. int32_t vchi_msg_iter_hold_next( VCHI_MSG_ITER_T *iter, void **data, // } may be NULL uint32_t *msg_size, // } VCHI_HELD_MSG_T *message ); ]] ffi.cdef[[ /****************************************************************************** Global bulk API *****************************************************************************/ // Routine to prepare interface for a transfer from the other side int32_t vchi_bulk_queue_receive( VCHI_SERVICE_HANDLE_T handle, void *data_dst, uint32_t data_size, VCHI_FLAGS_T flags, void *transfer_handle ); // Prepare interface for a transfer from the other side into relocatable memory. int32_t vchi_bulk_queue_receive_reloc( const VCHI_SERVICE_HANDLE_T handle, VCHI_MEM_HANDLE_T h_dst, uint32_t offset, uint32_t data_size, const VCHI_FLAGS_T flags, void * const bulk_handle ); // Routine to queue up data ready for transfer to the other (once they have signalled they are ready) int32_t vchi_bulk_queue_transmit( VCHI_SERVICE_HANDLE_T handle, const void *data_src, uint32_t data_size, VCHI_FLAGS_T flags, void *transfer_handle ); ]] ffi.cdef[[ /****************************************************************************** Configuration plumbing *****************************************************************************/ // function prototypes for the different mid layers (the state info gives the different physical connections) const VCHI_CONNECTION_API_T *single_get_func_table( void ); //extern const VCHI_CONNECTION_API_T *local_server_get_func_table( void ); //extern const VCHI_CONNECTION_API_T *local_client_get_func_table( void ); // declare all message drivers here const VCHI_MESSAGE_DRIVER_T *vchi_mphi_message_driver_func_table( void ); ]] ffi.cdef[[ int32_t vchi_bulk_queue_transmit_reloc( VCHI_SERVICE_HANDLE_T handle, VCHI_MEM_HANDLE_T h_src, uint32_t offset, uint32_t data_size, VCHI_FLAGS_T flags, void *transfer_handle ); ]] return { Lib = ffi.load("vchiq_arm"), }
print("Hello from Lua") print(" Arguments:", arg) freq_ghz = sim.config.get("perf_model/core/frequency") print(" core frequency = ", freq_ghz, "GHz") sim.hooks.register(sim.hooks.HOOK_ROI_BEGIN, function() sim.dvfs.set_frequency(0, 3.92) end) function roi_end() print("ROI end from Lua") time_fs = sim.stats.get("performance_model", 0, "elapsed_time") print(" cpu0 time", time_fs/1e6, "ns, ", time_fs*freq_ghz/1e6, "cycles") freq0_ghz = sim.dvfs.get_frequency(0) print(" core0 frequency = ", freq0_ghz, "GHz") freqG_ghz = sim.dvfs.get_frequency(sim.dvfs.GLOBAL) print(" global frequency = ", freqG_ghz, "GHz") end sim.hooks.register(sim.hooks.HOOK_ROI_END, roi_end) function dvfs_change(coreid) print("DVFS change from Lua") print(" core", coreid, "new freq", sim.dvfs.get_frequency(coreid), "GHz") end sim.hooks.register(sim.hooks.HOOK_CPUFREQ_CHANGE, dvfs_change)
-- LovePainter/Border --[[ TODO draw line type "double". ]]-- module("LovePainter.Border", package.seeall) require "Tools/Object" local Border = {} function Border.initialize(style,width,color) local obj = { width= width or 1, color=color or {love.graphics.getColor()}, style=style or 'solid', hidden=false, corner={type='curves', radius=0.15}, calculPoints=nil } return Ncr7.tObject.New._object(Border, obj) end function new(style,width,color) return Border.initialize(); end function Border:setVisible(visible) if(true == visible) then self.hidden = false else self.hidden = true end return self end function Border:setWidth(width) self.width=width return self end function Border:getWidth() return self.width end function Border:setColor(color) self.color = color return self end function Border:getColor() return self.color end function Border:setStyle(style) if(style == 'solid' or style == 'dotted' or style == 'dashed' or style == 'double' or style == 'ridge' or style == 'outset' ) then self.style = style else self.style = 'solid' end return self end function Border:getStyle() return self.style end function Border:setCornerRadius(ratio) self.corner.radius = ratio return self end function Border:setCornerType(type) self.corner.type = type return self end function Border:getCornerType() return self.corner.type end function Border:forceUpdate() self.calculPoints=nil return self end function Border:draw(points, angle) love.graphics.setLineJoin('bevel') love.graphics.setLineStyle('rough') love.graphics.setLineWidth(self.width) if(false==self.hidden) then if(self.style == 'solid' or self.style == 'dotted' or self.style == 'dashed' or self.style == 'double' or self.style == 'ridge' or self.style == 'outset' ) then if(nil ~= self:getCornerType()) then self:drawWithCorner(points, self:getCornerType()) else self:drawWithoutCorner(points) end end end end function Border:drawWithCorner(points, typeOfCorner) if('curves' == typeOfCorner) then if(self.calculPoints==nil) then self.calculPoints=self:generatePointsCornerCurves(points) end self:drawCornerCurves(self.calculPoints,true) end end function Border:drawCornerCurves(complex, drawlines) local i=0 local line={} local drawlines = drawlines or true if(drawlines) then for key,point in pairs(complex.lines) do if(i<4) then i=i+1 line[#line+1]=point end if(i>=4) then self:drawLine(line, self.style) i=0 line={} end end end local i=0 local curve={} for key,point in pairs(complex.curves) do if(i<6) then i=i+1 curve[#curve+1]=point end if(i>=6) then self:drawLine(love.math.newBezierCurve(curve):render(6), self.style) i=0 curve = {} end end end function Border:drawLine(line, style) if(self.style == 'solid') then love.graphics.line(line) elseif(self.style == 'double') then --love.graphics.line(line) local i=0 local tmp = {minX=nil, minY=nil, maxX=nil, maxY=nil, pos=Ncr7.mtPosition.new()} local polygon = Ncr7.mtPolygon.new(); for key,point in pairs(line) do if(i==0) then if(nil~=tmp.minX) then tmp.minX = math.min(tmp.minX,point) tmp.maxX = math.max(tmp.maxX,point) else tmp.minX = point tmp.maxX = point end tmp.pos:setX(point) i=i+1 elseif(i==1) then if(nil~=tmp.minY) then tmp.minY = math.min(tmp.minY,point) tmp.maxY = math.max(tmp.maxY,point) else tmp.minY = point tmp.maxY = point end tmp.pos:setY(point) polygon:addVerticeA(tmp.pos) i=0 tmp.pos=Ncr7.mtPosition.new() end end polygon:setCenter(Ncr7.mtPosition.new(((tmp.maxX-tmp.minX)/2)+tmp.minX,((tmp.maxY-tmp.minY)/2)+tmp.minY,0)) polygon:calculVerticesA2R():scale(0.9):calculVerticesR2A() local points = polygon:calculPoints(false) love.graphics.line(points.absolutes) --[[ for key,point in pairs(line) do if(i<4) then i=i+1 segment[#segment+1]=point end if(i>=4) then line[key-3]=line[key-3]+self.width+self.width line[key-2]=line[key-2]+self.width+self.width line[key-1]=line[key-1]+self.width+self.width line[key]=line[key]+self.width+self.width ------ if((segment[2]==segment[4] and 2>=math.abs(segment[1]-segment[3])) or (segment[1]==segment[3] and 2>=math.abs(segment[2]-segment[4]))) then else if(segment[1]==segment[3]) then line[key-3]=segment[1]+self.width+self.width line[key-1]=segment[3]+self.width+self.width elseif(segment[2]==segment[4]) then line[key-2]=segment[4]+self.width+self.width line[key]=segment[4]+self.width+self.width else line[key-3]=line[key-3]+self.width+self.width line[key-2]=line[key-2]+self.width+self.width line[key-1]=line[key-1]+self.width+self.width line[key]=line[key]+self.width+self.width end end ------ i=0 segment={} end end ]]-- --love.graphics.line(line) end end function Border:generatePointsCornerCurves(points) local result = {curves={},lines={}} local lines = {} local i=0; local copyRadius=0; local segment = {} -- l : longueur, min/max : pos ... local tmp = {l=nil,max=0,min=0,x1=0,y1=0,x2=0,y2=0} -- Search min tmp.l for key,point in pairs(points) do if(i<4) then i=i+1 segment[#segment+1]=point end if(i>=4) then -- axis x : if(segment[1]~=segment[3]) then if(tmp.l~=nil)then tmp.l = math.min(( math.max(segment[1],segment[3]) - math.min(segment[1],segment[3]) ) * self.corner.radius, tmp.l) else tmp.l = (math.max(segment[1],segment[3]) - math.min(segment[1],segment[3])) * self.corner.radius end end -- axis y : if(segment[2]~=segment[4]) then if(tmp.l~=nil)then tmp.l = math.min(( math.max(segment[2],segment[4]) - math.min(segment[2],segment[4]) ) * self.corner.radius, tmp.l) else tmp.l = (math.max(segment[2],segment[4]) - math.min(segment[2],segment[4])) * self.corner.radius end end i=2 segment={segment[3],segment[4]} end end local segment = {} local i=0; local newPoints = {} for key,point in pairs(points) do if(i<4) then i=i+1 segment[#segment+1]=point end if(i>=4) then -- axis x : if(segment[1]~=segment[3]) then tmp.max = math.max(segment[1],segment[3]) tmp.min = math.min(segment[1],segment[3]) if(tmp.max == segment[1]) then tmp.x1=tmp.max-tmp.l tmp.x2=tmp.min+tmp.l else tmp.x1=tmp.min+tmp.l tmp.x2=tmp.max-tmp.l end else tmp.x1=segment[1] tmp.x2=segment[3] end -- axis y : if(segment[2]~=segment[4]) then tmp.max = math.max(segment[2],segment[4]) tmp.min = math.min(segment[2],segment[4]) if(tmp.max == segment[2]) then tmp.y1=tmp.max-tmp.l tmp.y2=tmp.min+tmp.l else tmp.y1=tmp.min+tmp.l tmp.y2=tmp.max-tmp.l end else tmp.y1=segment[2] tmp.y2=segment[4] end newPoints[#newPoints+1]=tmp.x1 newPoints[#newPoints+1]=tmp.y1 newPoints[#newPoints+1]=tmp.x2 newPoints[#newPoints+1]=tmp.y2 lines[#lines+1]=newPoints[#newPoints-3] lines[#lines+1]=newPoints[#newPoints-2] lines[#lines+1]=newPoints[#newPoints-1] lines[#lines+1]=newPoints[#newPoints-0] newPoints[#newPoints+1]=segment[3] newPoints[#newPoints+1]=segment[4] i=2 segment={segment[3],segment[4]} end end local curves = {} for key,point in pairs(newPoints) do if(key>2) then curves[#curves+1]=point end end curves[#curves+1]=newPoints[1] curves[#curves+1]=newPoints[2] result.curves=curves result.lines=lines return result end
--[[ changes an attribute of an entity. Simple not requiring verification. This is not setup for sharding yet but does take mining fees (as supplied by the originator). KEYS[1] is originator pubKey (inserted automatically). Pays mining fees KEYS[2] is entity to update TODO: take in counter to make unique and prevent replay attacks, counter used in ordering in the block. Nonce cant be replayed, sequence we check within a few 10's of transactions and reject if too low (so can take out of order but only 'close' to most recent --> range is 20. height +- 20. TODO: data associated with update (eg description) to be stored with instruction but not in redis TODO: check data types on inbound NOTE: update does not apply to permissions (this is a separate instruction type) ARGV 1,2,3 are all standard for instructions: 1: mining/mined (if testing mining or processing mined block, instruction hash, blockHash if in a block or 'None' if in mining mode ARGV[1]: 'mining / mined' if 'mining' it is a balance check to confirm that the fees do not exhaust the balance. if 'mined' the attribute is updated ARGV[2] is instructionHash to check and remove from unprocessedpool if instruction passes ARGV[3] is blockHash to rollback state (this is the state of the chain immediately before applying this block), also used to store the processed instructions in a hash ARGV[4] is the attribute to update (can be created if not there) ARGV[5] is the updated value ARGV[6] is the previous value (for optimistic check that change is correct, can be null) ARGV[7] is incrementing counter to update state (will be rejected if state counter is greater than or equal to instruction counter) TODO - update NONCE value in the state ARGV[8] is evidence hash if evidence is provided ARGV[9] is link to evidence ARGV[10] is flag if the attribute is encrypted ARGV[11] is flag if the evidence is encrypted ARGV[12] is mining fee being paid (can be rejected if too low - up to agents) --]] -- name of instructionType local name = "changeConfiguration" -- Check if originator, entity on this chain: if redis.call("SISMEMBER", "entities", KEYS[1]) == 1 and redis.call("SISMEMBER", "entities", KEYS[2]) == 1 then -- Check permissions for originator to update entity if redis.call("HEXISTS", KEYS[2], "permissions." .. KEYS[1] .. ".all") ~= 1 and redis.call("HEXISTS", KEYS[2], "permissions." .. KEYS[1] .. ARGV[4]) ~= 1 then -- no permissions return {"0", "no permissions to update entity " .. KEYS[2] .. " for originator " .. KEYS[1]} end -- Check wallet exists: cant pay fees if wallet does not exist. if redis.call("HEXISTS", KEYS[1], "wallets.default.balance") ~= 1 then return {"0", "wallet does not exist to pay fees for originator " .. KEYS[1]} end -- Check if previous value is the same value we currently have (can be nil). Fail if not if redis.call("HEXISTS", KEYS[1], ARGV[4] GREG: here -- Check is counter is incremented above current state. Fail if not GREG: here -- check if we are mining the block or already mined if ARGV[1] == "mining" then -- we are mining so: copy the old attribute if not in the mining pool. Check if can decrement wallet by mining fees, decrement if possible, return 0 / 1 as failure / success to stop mining if redis.call("SMEMBER", "mining", KEYS[1]) == 0 then -- not yet copied into mining pool, copy balance = redis.call("HGET", KEYS[1], "wallets.default.balance") redis.call("SADD", "mining",KEYS[1]) redis.call("HSET", "mining." .. KEYS[1], "wallets.default.balance", balance) end if redis.call("HGET", "mining." .. KEYS[1], "wallets.default.balance") >= ARGV[10] then -- sufficient balance: decrement for this mining round redis.call("HINCRBY", "mining." .. KEYS[1], "wallets.default.balance", -ARGV[10]) return {"1", "in mining successfully processed " .. ARGV[2]} else -- insufficient balance. deny payment for this mining round return {"0", "insufficient balance to pay mining fees for instruction " .. ARGV[2]} end else -- TODO: check why using tonumber here but not higher and in payment_adv?? -- we are processing mined block so update and include transaction fees. -- Fail if insufficient funds (which will fail the whole block and require a rollback) if tonumber(redis.call("HGET", KEYS[1], "wallets.default.balance")) < tonumber(ARGV[10]) then return {"0", "insufficient balance for instruction " .. ARGV[2]} end end -- All checks passed, into write mode: -- update previous block state if not already stored (TODO: delete state from block n - 5 in python? or in more advanced LUA script, setup block n-1 in python, setup miner fees to rollback in python, etc) -- we have a hash for this and a set to reduce costs of the rollback if redis.call("SMEMBER", "BlockState." .. ARGV[3], KEYS[1]) == 0 then local payerState = redis.call("HGET", KEYS[1], "wallets.default.balance") redis.call("SADD", "BlockState." .. ARGV[3],KEYS[1]) redis.call("HSET", "PrevBlock." .. ARGV[3] .. "." .. KEYS[1], "wallets.default.balance", payerState) end -- TODO. GREG here: NOW CHECK JUST THIS ATTRIBUTE. regardless of if other payments done. COntinue here if redis.call("SMEMBER", "BlockState." .. ARGV[3], KEYS[3]) == 0 then local payeeState = redis.call("HGET", KEYS[3], ARGV[5]) redis.call("SADD", "BlockState." .. ARGV[3],KEYS[3]) redis.call("HSET", "PrevBlock." .. ARGV[3] .. "." .. KEYS[3], ARGV[5], payeeState) end -- change balances redis.call("HINCRBY", KEYS[2], ARGV[4], -ARGV[6]) redis.call("HINCRBY", KEYS[3], ARGV[5], ARGV[6]) -- pay miner fees redis.call("HINCRBY", KEYS[2], ARGV[4], -ARGV[7]) redis.call("HINCRBY", "circleFees", ARGV[3], ARGV[7]) -- delete the instruction from the pool -- Flag deleted from instruction processed set (we dont delete as may rollback block and want to restore the instruction to the pool, full delete only happens when blockheight above when instruction was issued gets to order 'n') redis.call("SADD", "instructionProcessedPool." .. ARGV[3], ARGV[2]) redis.call("SREM", "instructionUnprocessedPool", ARGV[2]) return {"1", "success"} else return {"0", "entity or entities unknown"} end
return { ["NameLimit"] = 7, ["HitCorrection"] = 1, ["InitItem"] = { 1001, 1002, 1003 }, ["InitMission"] = { "M101", "M102" } }
local a=20140920.13;local b="-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20140920.13 ]-"local OBJDEF={VERSION=a,AUTHOR_NOTE=b}local c={__tostring=function()return"JSON array"end}c.__index=c;local d={__tostring=function()return"JSON object"end}d.__index=d;function OBJDEF:newArray(e)return setmetatable(e or{},c)end;function OBJDEF:newObject(e)return setmetatable(e or{},d)end;local function f(g)if g<=127 then return string.char(g)elseif g<=2047 then local h=math.floor(g/0x40)local i=g-0x40*h;return string.char(0xC0+h,0x80+i)elseif g<=65535 then local h=math.floor(g/0x1000)local j=g-0x1000*h;local k=math.floor(j/0x40)local i=j-0x40*k;h=0xE0+h;k=0x80+k;i=0x80+i;if h==0xE0 and k<0xA0 or h==0xED and k>0x9F or h==0xF0 and k<0x90 or h==0xF4 and k>0x8F then return"?"else return string.char(h,k,i)end else local h=math.floor(g/0x40000)local j=g-0x40000*h;local l=math.floor(j/0x1000)j=j-0x1000*l;local m=math.floor(j/0x40)local i=j-0x40*m;return string.char(0xF0+h,0x80+l,0x80+m,0x80+i)end end;function OBJDEF:onDecodeError(n,o,p,q)if o then if p then n=string.format("%s at char %d of: %s",n,p,o)else n=string.format("%s: %s",n,o)end end;if q~=nil then n=n.." ("..OBJDEF:encode(q)..")"end;if self.assert then self.assert(false,n)else assert(false,n)end end;OBJDEF.onDecodeOfNilError=OBJDEF.onDecodeError;OBJDEF.onDecodeOfHTMLError=OBJDEF.onDecodeError;function OBJDEF:onEncodeError(n,q)if q~=nil then n=n.." ("..OBJDEF:encode(q)..")"end;if self.assert then self.assert(false,n)else assert(false,n)end end;local function r(self,o,s,q)local t=o:match('^-?[1-9]%d*',s)or o:match("^-?0",s)if not t then self:onDecodeError("expected number",o,s,q)end;local u=s+t:len()local v=o:match('^%.%d+',u)or""u=u+v:len()local w=o:match('^[eE][-+]?%d+',u)or""u=u+w:len()local x=t..v..w;local y=tonumber(x)if not y then self:onDecodeError("bad number",o,s,q)end;return y,u end;local function z(self,o,s,q)if o:sub(s,s)~='"'then self:onDecodeError("expected string's opening quote",o,s,q)end;local u=s+1;local A=o:len()local B=""while u<=A do local C=o:sub(u,u)if C=='"'then return B,u+1 end;if C~='\\'then B=B..C;u=u+1 elseif o:match('^\\b',u)then B=B.."\b"u=u+2 elseif o:match('^\\f',u)then B=B.."\f"u=u+2 elseif o:match('^\\n',u)then B=B.."\n"u=u+2 elseif o:match('^\\r',u)then B=B.."\r"u=u+2 elseif o:match('^\\t',u)then B=B.."\t"u=u+2 else local D=o:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])',u)if D then u=u+6;local g=tonumber(D,16)if g>=0xD800 and g<=0xDBFF then local E=o:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])',u)if E then u=u+6;g=0x2400+(g-0xD800)*0x400+tonumber(E,16)else end end;B=B..f(g)else B=B..o:match('^\\(.)',u)u=u+2 end end end;self:onDecodeError("unclosed string",o,s,q)end;local function F(o,s)local G,H=o:find("^[ \n\r\t]+",s)if H then return H+1 else return s end end;local I;local function J(self,o,s,q)if o:sub(s,s)~='{'then self:onDecodeError("expected '{'",o,s,q)end;local u=F(o,s+1)local B=self.strictTypes and self:newObject{}or{}if o:sub(u,u)=='}'then return B,u+1 end;local A=o:len()while u<=A do local K,L=z(self,o,u,q)u=F(o,L)if o:sub(u,u)~=':'then self:onDecodeError("expected colon",o,u,q)end;u=F(o,u+1)local M,L=I(self,o,u)B[K]=M;u=F(o,L)local C=o:sub(u,u)if C=='}'then return B,u+1 end;if o:sub(u,u)~=','then self:onDecodeError("expected comma or '}'",o,u,q)end;u=F(o,u+1)end;self:onDecodeError("unclosed '{'",o,s,q)end;local function N(self,o,s,q)if o:sub(s,s)~='['then self:onDecodeError("expected '['",o,s,q)end;local u=F(o,s+1)local B=self.strictTypes and self:newArray{}or{}if o:sub(u,u)==']'then return B,u+1 end;local O=1;local A=o:len()while u<=A do local P,L=I(self,o,u)B[O]=P;O=O+1;u=F(o,L)local C=o:sub(u,u)if C==']'then return B,u+1 end;if o:sub(u,u)~=','then self:onDecodeError("expected comma or '['",o,u,q)end;u=F(o,u+1)end;self:onDecodeError("unclosed '['",o,s,q)end;I=function(self,o,s,q)s=F(o,s)if s>o:len()then self:onDecodeError("unexpected end of string",o,nil,q)end;if o:find('^"',s)then return z(self,o,s,q)elseif o:find('^[-0123456789 ]',s)then return r(self,o,s,q)elseif o:find('^%{',s)then return J(self,o,s,q)elseif o:find('^%[',s)then return N(self,o,s,q)elseif o:find('^true',s)then return true,s+4 elseif o:find('^false',s)then return false,s+5 elseif o:find('^null',s)then return nil,s+4 else self:onDecodeError("can't parse JSON",o,s,q)end end;function OBJDEF:decode(o,q)if type(self)~='table'or self.__index~=OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format",nil,nil,q)end;if o==nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"),nil,nil,q)elseif type(o)~='string'then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s",type(o)),nil,nil,q)end;if o:match('^%s*$')then return nil end;if o:match('^%s*<')then self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"),o,nil,q)end;if o:sub(1,1):byte()==0 or o:len()>=2 and o:sub(2,2):byte()==0 then self:onDecodeError("JSON package groks only UTF-8, sorry",o,nil,q)end;local Q,R=pcall(I,self,o,1,q)if Q then return R else if self.assert then self.assert(false,R)else assert(false,R)end;return nil,R end end;local function S(C)if C=="\n"then return"\\n"elseif C=="\r"then return"\\r"elseif C=="\t"then return"\\t"elseif C=="\b"then return"\\b"elseif C=="\f"then return"\\f"elseif C=='"'then return'\\"'elseif C=='\\'then return'\\\\'else return string.format("\\u%04x",C:byte())end end;local T='['..'"'..'%\\'..'%z'..'\001'..'-'..'\031'..']'local function U(R)local V=R:gsub(T,S)return'"'..V..'"'end;local function W(self,X,q)local Y={}local Z={}local _=false;local a0;for K in pairs(X)do if type(K)=='string'then table.insert(Y,K)elseif type(K)=='number'then table.insert(Z,K)if K<=0 or K>=math.huge then _=true elseif not a0 or K>a0 then a0=K end else self:onEncodeError("can't encode table with a key of type "..type(K),q)end end;if#Y==0 and not _ then if#Z>0 then return nil,a0 elseif tostring(X)=="JSON array"then return nil elseif tostring(X)=="JSON object"then return{}else return nil end end;table.sort(Y)local a1;if#Z>0 then if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting",q)end;a1={}for K,P in pairs(X)do a1[K]=P end;table.sort(Z)for G,a2 in ipairs(Z)do local a3=tostring(a2)if a1[a3]==nil then table.insert(Y,a3)a1[a3]=X[a2]else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key "..a2 .." exists both as a string and a number.",q)end end end;return Y,nil,a1 end;local encode_value;function encode_value(self,R,a4,q,a5)if R==nil then return'null'elseif type(R)=='string'then return U(R)elseif type(R)=='number'then if R~=R then return"null"elseif R>=math.huge then return"1e+9999"elseif R<=-math.huge then return"-1e+9999"else return tostring(R)end elseif type(R)=='boolean'then return tostring(R)elseif type(R)~='table'then self:onEncodeError("can't convert "..type(R).." to JSON",q)else local X=R;if a4[X]then self:onEncodeError("table "..tostring(X).." is a child of itself",q)else a4[X]=true end;local a6;local a7,a0,a1=W(self,X,q)if a0 then local a8={}for u=1,a0 do table.insert(a8,encode_value(self,X[u],a4,q,a5))end;if a5 then a6="[ "..table.concat(a8,", ").." ]"else a6="["..table.concat(a8,",").."]"end elseif a7 then local a9=a1 or X;if a5 then local aa={}local ab=0;for G,K in ipairs(a7)do local ac=encode_value(self,tostring(K),a4,q,"")ab=math.max(ab,#ac)table.insert(aa,ac)end;local ad=a5 .." "local ae=a5 ..string.rep(" ",ab+2+4)local af="%s%"..string.format("%d",ab).."s: %s"local ag={}for u,K in ipairs(a7)do local ah=encode_value(self,a9[K],a4,q,ae)table.insert(ag,string.format(af,ad,aa[u],ah))end;a6="{\n"..table.concat(ag,",\n").."\n"..a5 .."}"else local ai={}for G,K in ipairs(a7)do local ah=encode_value(self,a9[K],a4,q,a5)local aj=encode_value(self,tostring(K),a4,q,a5)table.insert(ai,string.format("%s:%s",aj,ah))end;a6="{"..table.concat(ai,",").."}"end else a6="[]"end;a4[X]=false;return a6 end end;function OBJDEF:encode(R,q)if type(self)~='table'or self.__index~=OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format",q)end;return encode_value(self,R,{},q,nil)end;function OBJDEF:encode_pretty(R,q)if type(self)~='table'or self.__index~=OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format",q)end;return encode_value(self,R,{},q,"")end;function OBJDEF.__tostring()return"JSON encode/decode package"end;OBJDEF.__index=OBJDEF;function OBJDEF:new(ak)local new={}if ak then for K,P in pairs(ak)do new[K]=P end end;return setmetatable(new,OBJDEF)end;return OBJDEF:new()
#!/usr/bin/lua local url = require "socket.url"; for smtp_url in io.lines() do local parsed_url = url.parse(smtp_url); print("# "..smtp_url); for k, v in pairs(parsed_url) do print("# "..k.." = "..v) end print "" local protocol = parsed_url.scheme or "smtp"; local default_port = (protocol == "smtps" and 465) or 25; print("account default"); print(("host %s"):format(parsed_url.host)); print(("port %d"):format(parsed_url.port or default_port)); if parsed_url.params ~= "no-tls" then local verify_cert = parsed_url.params ~= "insecure"; print("tls on"); if verify_cert then print("tls_trust_file /etc/ssl/certs/ca-certificates.crt"); else print("tls_trust_file"); -- empty disables trust verification print("tls_certcheck off"); end if protocol == "smtps" then print("tls_starttls off"); end end if parsed_url.user then print("auth on"); print(("user %s"):format(parsed_url.user)); end if parsed_url.password then print(("password %s"):format(parsed_url.password)); end end
local BannerText = mainForm:GetChildChecked('Announce', false ) BannerText:SetVal('value', GTL('ACTIVATE A BANNER!')) BannerText:SetClassVal('class', 'LogColorOrange' ) local StartCheck = false function CheckBuff(params) if StartCheck then if IsBannerActive() then BannerText:Show(false) else BannerText:Show(true) end end end function onClientZoneChanged() StartCheck = false BannerText:Show(false) if cartographer.GetCurrentZoneInfo().sysZoneName:find('PvPArena') then StartCheck = true if IsBannerActive() then BannerText:Show(false) else BannerText:Show(true) end end end function IsBannerActive() local found = false local buffs = object.GetBuffs(avatar.GetId()) for _, buffid in pairs(buffs) do if userMods.FromWString(object.GetBuffInfo(buffid).name):find(GTL('Banner')) then found = true break end end return found end function Init() common.RegisterEventHandler( onClientZoneChanged, 'EVENT_AVATAR_CLIENT_ZONE_CHANGED') common.RegisterEventHandler( CheckBuff, 'EVENT_OBJECT_BUFFS_CHANGED',{objectId = avatar.GetId() }) onClientZoneChanged() end if (avatar.IsExist()) then Init() else common.RegisterEventHandler(Init, 'EVENT_AVATAR_CREATED') end
XYZUI = {} XYZUI.Config = {} XYZUI.Core = {} XYZUI.Elements = {} print("Loading XYZ UI 1") local path = "xyz_ui/" if SERVER then local files, folders = file.Find(path .. "*", "LUA") for _, folder in SortedPairs(folders, true) do print("Loading folder:", folder) for b, File in SortedPairs(file.Find(path .. folder .. "/*.lua", "LUA"), true) do print("Loading file:", File) AddCSLuaFile(path .. folder .. "/" .. File) end end end if CLIENT then local files, folders = file.Find(path .. "*", "LUA") for _, folder in SortedPairs(folders, true) do print("Loading folder:", folder) for b, File in SortedPairs(file.Find(path .. folder .. "/*.lua", "LUA"), true) do print("Loading file:", File) include(path .. folder .. "/" .. File) end end end print("Loaded XYZ UI")
local HttpService = game:GetService("HttpService") local HttpError = {} HttpError.__index = HttpError HttpError.__tostring = function(he) return HttpService:JSONEncode(he) end HttpError.ErrorCodes = { BadRequest = 400, Unauthorized = 401, Forbidden = 403, NotFound = 404, ServerError = 500, } function HttpError.new(targetUrl, errMsg, resBody, errCode, resTime) local h = { target = targetUrl, message = errMsg, responseBody = resBody, responseCode = errCode, responseTime = resTime } setmetatable(h, HttpError) return h end return HttpError
function ENT:SetupDataTables() self:NetworkVar( "Int", 0, "Freq" ) self:NetworkVar( "Int", 1, "Range" ) self:NetworkVar( "Bool", 0, "Sending" ) self:NetworkVar( "Bool", 1, "Online" ) self:NetworkVar( "Bool", 2, "Hearable" ) self:NetworkVar( "Bool", 3, "Radio" ) self:NetworkVar( "Entity", 0, "Speaker" ) end function ENT:CheckTalking() if !self.settings.trigger_at_talk then return end for k, v in next, self.connected_radios do if gspeak:radio_valid(Entity(v)) then local speaker = Entity(v):GetSpeaker() if gspeak:player_valid(speaker) then self:TriggerCom( speaker.talking ) end end end end function ENT:TriggerCom( trigger ) if trigger and !self.trigger_com then self.trigger_com = true self:EmitSound(self.settings.start_com) elseif !trigger and self.trigger_com then self.trigger_com = false self:EmitSound(self.settings.end_com) end end function ENT:RemoveRadio( radio_id ) for k, v in pairs(self.connected_radios) do if v == radio_id then self:RemoveID( radio_id, k ) return end end end function ENT:RemoveID( radio_id, id ) if gspeak.cl.TS.connected then tslib.delPos( radio_id, true, self:EntIndex() ) end self:TriggerCom( false ) table.remove(self.connected_radios, id) self:UpdateUI() end function ENT:AddRadio( radio_id ) if radio_id == self:EntIndex() then return end for k, v in pairs(self.connected_radios) do if v == radio_id then return end end if !self.settings.trigger_at_talk and self.trigger then self:TriggerCom( true ) end table.insert(self.connected_radios, radio_id) self:UpdateUI() end function ENT:Rescan(own_freq, own_online, own_sending) self.freq = own_freq self.online = own_online self.sending = own_sending local radio_id = self:EntIndex() for k, v in pairs( gspeak.cl.radios ) do if !gspeak:radio_valid(v) then table.remove(gspeak.cl.radios, k) continue end local v_id = v:EntIndex() local v_freq = v:GetFreq() if radio_id != v_id then if self.online and v:GetOnline() and self.freq == v_freq then if v:GetSending() then self:AddRadio(v_id) else self:RemoveRadio(v_id) end if self.sending then v:AddRadio(radio_id) else v:RemoveRadio(radio_id) end else self:RemoveRadio(v_id) v:RemoveRadio(radio_id) end end end end if SERVER then function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end end function ENT:checkTime(diff) local now = CurTime() self.last_try = self.last_try or 0 if self.last_try < now - diff then self.last_try = now return true end return false end function ENT:AddHearables( pos, volume ) for k, v in next, self.connected_radios do local remove_v = false if gspeak:radio_valid(Entity(v)) then local speaker = Entity(v):GetSpeaker() if gspeak:player_valid(speaker) and gspeak:player_alive(speaker) then local ts_id = gspeak:get_tsid(speaker) if gspeak.cl.TS.connected and speaker != LocalPlayer() and ts_id >= 0 then tslib.sendPos(ts_id, volume, v, pos.x, pos.y, pos.z, true, self:EntIndex()) end continue end end self:RemoveID( v, k ) end end
-- -*- coding:utf-8 -*- --- 数据库实例. -- 使用具体的技术(mysql 等)实现一个持久化数据库。 -- @classmod example_db -- @author:phenix3443@gmail.com local cjson = require("cjson.safe") local class = require("pl.class") local mysql_helper = require("database.mysql_helper") local M = class(mysql_helper) --- 示例程序. --查询数据库版本信息 function M:get_mysql_version() local stmt = string.format("select version() as version;") ngx.log(ngx.DEBUG, stmt) local res, err, errcode, sqlstate = self.db:query(stmt) if not res then ngx.log(ngx.ERR,string.format("%s:%s",errcode, err)) return end local resp = res[1].version ngx.log(ngx.DEBUG, "resp:", resp) return resp end -- 下面自行编写业务代码 ------------------------------------------------------- return M
-- add lua implementations of the intersection functions l1 = { a = vec3d(0,0,0), b = vec3d(100,0,100) } l2 = { a = vec3d(70,0,0), b = vec3d(0,0,100) } c1 = { c = vec3d(10,0,40), r = 50 } c2 = { c = vec3d(10,0,-40), r = 50 } function renderLine(l) drawLine(l.a.x, l.a.y, l.a.z, l.b.x, l.b.y, l.b.z) end function renderCircle(c) movePen(c.c.x + c.r * math.sin(0), 0, c.c.z + c.r * math.cos(0)) for i=0,math.pi * 2,math.pi * 0.05 do drawTo(c.c.x + c.r * math.sin(i), 0, c.c.z + c.r * math.cos(i)) end end function renderPoint(p) drawLine(p.x, p.y-20, p.z, p.x, p.y+20, p.z) end function render() renderLine(l1) renderLine(l2) renderCircle(c1) renderCircle(c2) local r = lineline(l1, l2) renderPoint(r.p1) r = linecircle(l1,c1) renderPoint(r.p1) r = circlecircle(c1,c2) renderPoint(r.p1) renderPoint(r.p2) --print(r.status) end clearTrace()
-- physics tests import('GlobalVars') import('PrintRecursive') import('Physics') local messages = { "Velocity X:", "Velocity Y:", "Position X:", "Position Y:", "Press ESC to go to main menu" } local objects = {} local dt = 0 local st = 0 local lastTime = 0 local testSelected = false local testNum = 0 local forceToApply = vec(0, 0) function addMessage(msg) messages[#messages + 1] = msg end function addObject(obj) if next(objects) ~= nil then objects[#objects + 1] = obj else objects = { obj } end end function init() local camera = { w = 800, h = 600 } graphics.set_camera(-camera.w / 2, -camera.h / 2, camera.w / 2, camera.h / 2) end function update() local newTime = mode_manager.time() dt = newTime - lastTime lastTime = newTime st = st + dt if #messages >= 7 and st > 0.1 then st = st % 0.1 if testNum == "1" then messages[1] = string.format("VELOCITY X: %f", objects[1].velocity.x) messages[2] = string.format("VELOCITY Y: %f", objects[1].velocity.y) else objects[1].force = objects[1].force + forceToApply messages[1] = string.format("FORCE X: %.2f", objects[1].force.x) messages[2] = string.format("FORCE Y: %.2f", objects[1].force.y) end messages[3] = string.format("POSITION X: %.2f", objects[1].position.x) messages[4] = string.format("POSITION Y: %.2f", objects[1].position.y) end Physics.UpdateSystem(dt, objects) end function render() graphics.begin_frame() if messages ~= nil then for i = 1, #messages do graphics.draw_text(messages[i], MAIN_FONT, "left", { x = -390, y = 320 - 40 * i }, 30) end end graphics.end_frame() end function key(k) if not testSelected then if k == "escape" then mode_manager.switch("Xsera/MainMenu") elseif k == "1" or k == "2" then testSelected = true testNum = k end return end if k == "escape" then mode_manager.switch("Xsera/MainMenu") elseif testNum == "1" then test1(k) elseif testNum == "2" then test2(k) end end function test1(k) print(k) if k == "1" then addMessage("Creating system without gravity.") Physics.NewSystem() elseif k == "2" then addMessage("Creating object of mass 1, velocity and position (0, 0).") addObject(Physics.NewObject()) elseif k == "3" then objects[1].velocity = objects[1].velocity + vec(0, .1) elseif k == "4" then objects[1].velocity = objects[1].velocity + vec(.1, 0) end end function test2(k) if k == "1" then addMessage("Creating system with Earth gravity straight down.") Physics.NewSystem(vec(0, -9.8)) elseif k == "2" then addMessage("Creating object of mass 10, velocity and position (0, 0).") addObject(Physics.NewObject(10, vec(0, 0), vec(0, 0))) elseif k == "3" then forceToApply = forceToApply + vec(0, .1) elseif k == "4" then forceToApply = forceToApply + vec(.1, 0) objects[1].force = objects[1].force + vec(.1, 0) end end
local meta = FindMetaTable("Entity") function meta:IsDestructible() return self:GetClass() == "prop_physics" end function meta:GetStable() return self:GetNWBool("Stable") end function meta:GetDamaged() return self:GetNWBool("Damaged") end function meta:GetRecoveryPerOnce() return self:GetMaxStrength() / 25 end function meta:GetMaxStrength() local phys = self:GetPhysicsObject() if IsValid(phys) then return phys:GetMass() * 2.25 end return 1 end
/sc --[[ solar ]] local stats = (game.player.selected or game.player.surface.find_entities_filtered{type="electric-pole",limit=1,position=game.player.position,radius=32}[1] or error("Script needs mouseover of electric pole.", 0)).electric_network_statistics local function printf(...) game.print(string.format(...)) end local function flow_count(name) return stats.get_flow_count{name=name, input=false, precision_index=defines.flow_precision_index.ten_minutes, count=true} end local function go(args) local accumulators, panels, turbines = flow_count("accumulator"), flow_count("solar-panel"), flow_count("steam-turbine") local solar_ratio = accumulators / panels local excess_accumulators = accumulators - math.ceil(panels * 21 / 25) printf("%d [img=item.accumulator] / %d [img=item.solar-panel] = %.4g (%+d accumulators vs. ideal ratio)", accumulators, panels, solar_ratio, excess_accumulators) local usable_panels = math.min(panels, math.floor(accumulators * 25 / 21)) local solarGW = usable_panels * 42 / 1000000 printf("%d usable panels = %.2f GW", usable_panels, solarGW) if turbines > 0 then local nuke_builds = turbines / args.nuke_bp_turbines local nukeGW = nuke_builds * args.nuke_bp_gw printf("%.4g nuke builds = %.2f GW", nuke_builds, nukeGW) if not args.goalGW then local total = 0 for i,_ in pairs(stats.input_counts) do if game.entity_prototypes[i].type ~= 'accumulator' then total = total + stats.get_flow_count{name=i, input=true, precision_index=defines.flow_precision_index.ten_minutes} end end args.goalGW = total * 60 / 1000000000 end local nukeGW_needed_for_goal = math.max(0, args.goalGW - solarGW) local needed_nukes = math.ceil(nukeGW_needed_for_goal / args.nuke_bp_gw) local lacking_nukes = needed_nukes - nuke_builds printf("... need %d nuke builds (%+.4g vs. current) for goal %.2f GW", needed_nukes, lacking_nukes, args.goalGW) end end go{nuke_bp_turbines=224, nuke_bp_gw=1.12, goalGW=nil}
require 'settings/autocmds' local api = vim.api local o = vim.o local g = vim.g api.nvim_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- Leader key configuation -- https://learnvimscriptthehardway.stevelosh.com/chapters/06.html g.mapleader = "\\" -- define leader key g.localmapleader = "," -- define local leader o.clipboard = "unnamedplus" -- allows neovim to access the system clipboard o.cursorline = true -- Highlight the screen line of the cursor. o.foldexpr = "nvim_treesitter#foldexpr()" o.foldlevelstart = 2 o.foldmethod = "expr" o.laststatus = 2 -- Display the status line always o.linespace = 0 -- Set line-spacing to minimum. o.mouse = "a" -- enable mouse o.number = true -- Line numbers o.relativenumber = true -- Line relative numbers o.showcmd = true -- Show (partial) command in status line. o.showmode = true -- Show current mode. o.splitbelow = true o.splitright = true -- Split configurations o.synmaxcol = 2048 -- Set a limit for syntax highlights o.termguicolors = true -- Enable true colors o.secure = true -- Prevent run autocmd not owned by you. o.fileencoding = "utf-8" -- the encoding written to a file o.undodir = os.getenv("NVIM_CACHE") .. "/undo" -- set an undo directory o.undofile = true o.wildmenu = true o.autoread = true o.exrc = true
local selected = turtle.getSelectedSlot() local ingredients = {} local result = turtle.getItemDetail(selected) for i=1, 16 do if i ~= selected then table.insert(ingredients, turtle.getItemDetail(i)) end end if result == nil or #ingredients == 0 then print("Please put the ingredients in the turtle inventory and the result in the selected slot.") return end local recipe = { recipe = ingredients, result = result } local recipes if fs.exists("recipes.json") then local file = fs.open("recipes.json", "r") recipes = textutils.unserialize(file.readAll()) file.close() else recipes = {} end table.insert(recipes, recipe) local file = fs.open("recipes.json", "w") file.write(textutils.serialize(recipes)) file.close() print("Successfully saved recipe!")
-- -- (C) 2016 Kriss@XIXs.com -- local coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,Gload,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require=coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require local wgrd =require("wetgenes.grd") local wpack=require("wetgenes.pack") local wzips=require("wetgenes.zips") --module local M={ modname=(...) } ; package.loaded[M.modname]=M function M.bake(oven,sprites) local gl=oven.gl local cake=oven.cake local canvas=cake.canvas local flat=canvas.flat sprites.load=function() local filename="lua/"..(M.modname):gsub("%.","/")..".glsl" gl.shader_sources( assert(wzips.readfile(filename),"file not found: "..filename) , filename ) return sprites end sprites.setup=function() sprites.load() return sprites end sprites.create=function(it,opts) it.screen=assert(it.system.components[opts.screen or "screen"]) -- find linked components by name it.tiles =assert(it.system.components[opts.tiles or "tiles" ]) it.opts=opts it.component="sprites" it.name=opts.name or it.component it.tile_hx=it.opts.tile_size and it.opts.tile_size[1] or it.tiles.tile_hx -- cache the tile size, or allow it to change per sprite component it.tile_hy=it.opts.tile_size and it.opts.tile_size[2] or it.tiles.tile_hy it.ax=it.opts.add and it.opts.add[1] or 0 it.ay=it.opts.add and it.opts.add[2] or 0 it.az=it.opts.add and it.opts.add[3] or 0 it.layer=opts.layer or 1 it.setup=function(opts) it.list={} end it.clean=function() end it.list_reset=function() it.list={} end it.list_add=function(v,idx) v.idx=(idx or v.idx or (#it.list+1) ) it.list[ v.idx ]=v v.hx=v.hx or v.h or it.tile_hx v.hy=v.hy or v.h or it.tile_hy v.tx=v.tx or ( ( (v.t or 0)%256 ) ) v.ty=v.ty or ( math.floor( (v.t or 0)/256 ) ) v.ox=v.ox or v.hx/2 v.oy=v.oy or v.hy/2 v.px=(v.px or 0) v.py=(v.py or 0) v.rz=(v.rz or 0) v.sx=v.sx or v.s or 1 v.sy=v.sy or v.s or 1 v.pz=v.pz or 0 if type(v.color)=="number" then v.color={ wpack.argb8_pmf4(v.color) } end -- an 0xff000000 style color v.r=v.color and ( v.color.r or v.color[1] ) or 1 v.g=v.color and ( v.color.g or v.color[2] ) or 1 v.b=v.color and ( v.color.b or v.color[3] ) or 1 v.a=v.color and ( v.color.a or v.color[4] ) or 1 end it.update=function() end it.draw=function() gl.Color(1,1,1,1) local dl={ color={1,1,1,1}} local batch={} for idx,v in pairs(it.list) do local bleed=v.bleed or 0 -- optional pixel bleed, set to 1 if you plan on rotating without glitch local ixw=(v.tx*it.tile_hx+v.hx-bleed)/(it.tiles.hx) local iyh=(v.ty*it.tile_hy+v.hy-bleed)/(it.tiles.hy) local ix= (v.tx*it.tile_hx+bleed )/(it.tiles.hx) local iy= (v.ty*it.tile_hy+bleed )/(it.tiles.hy) local ox=(v.ox-bleed)*(v.sx) local oy=(v.oy-bleed)*(v.sy) local hx=(v.hx-bleed*2)*(v.sx) local hy=(v.hy-bleed*2)*(v.sy) local s=-math.sin(math.pi*(v.rz)/180) local c= math.cos(math.pi*(v.rz)/180) local px=v.px local py=v.py if v.rz==0 then -- clamp only if no rotation, this fixes occasional pixel bleed problems px=math.floor(px+0.5) py=math.floor(py+0.5) end local v1={ px-c*(ox)-s*(oy), py+s*(ox)-c*(oy), v.pz , 1 } local v2={ px+c*(hx-ox)-s*(oy), py-s*(hx-ox)-c*(oy), v.pz , 1 } local v3={ px-c*(ox)+s*(hy-oy), py+s*(ox)+c*(hy-oy), v.pz , 1 } local v4={ px+c*(hx-ox)+s*(hy-oy), py-s*(hx-ox)+c*(hy-oy), v.pz , 1 } local t= { v1[1], v1[2], v1[3], ix, iy, v.r*dl.color[1],v.g*dl.color[2],v.b*dl.color[3],v.a*dl.color[4], v1[1], v1[2], v1[3], ix, iy, v.r*dl.color[1],v.g*dl.color[2],v.b*dl.color[3],v.a*dl.color[4], v2[1], v2[2], v2[3], ixw, iy, v.r*dl.color[1],v.g*dl.color[2],v.b*dl.color[3],v.a*dl.color[4], v3[1], v3[2], v3[3], ix, iyh, v.r*dl.color[1],v.g*dl.color[2],v.b*dl.color[3],v.a*dl.color[4], v4[1], v4[2], v4[3], ixw, iyh, v.r*dl.color[1],v.g*dl.color[2],v.b*dl.color[3],v.a*dl.color[4], v4[1], v4[2], v4[3], ixw, iyh, v.r*dl.color[1],v.g*dl.color[2],v.b*dl.color[3],v.a*dl.color[4], } local l=#batch for i,v in ipairs(t) do batch[ l+i ]=v end end flat.tristrip("rawuvrgba",batch,"fun_draw_sprites",function(p) gl.Uniform2f( p:uniform("projection_zxy"), it.screen.zx,it.screen.zy) gl.Uniform3f( p:uniform("modelview_add"), it.ax,it.ay,it.az) gl.ActiveTexture(gl.TEXTURE0) gl.Uniform1i( p:uniform("tex"), 0 ) gl.BindTexture( gl.TEXTURE_2D , it.tiles.bitmap_tex ) end) end return it end return sprites end
--====================================================================-- -- Lua Corovel Unit Tests -- -- Sample code is MIT licensed, the same license which covers Lua itself -- http://en.wikipedia.org/wiki/MIT_License -- Copyright (C) 2014-2015 David McCuskey. All Rights Reserved. --====================================================================-- print( '\n\n##############################################\n\n' ) --====================================================================-- --== Imports require 'tests.lunatest' --== setup test suites and run lunatest.suite( 'tests.lua_corovel_json' ) lunatest.suite( 'tests.lua_corovel_eventloop' ) lunatest.suite( 'tests.lua_corovel_timer' ) lunatest.run()
-- table-utils.lua: tests for small table utilities -- This file is a part of lua-nucleo library -- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license) dofile('lua-nucleo/strict.lua') dofile('lua-nucleo/import.lua') local make_suite = select(1, ...) assert(type(make_suite) == "function") local ensure, ensure_equals, ensure_tequals, ensure_fails_with_substring = import 'lua-nucleo/ensure.lua' { 'ensure', 'ensure_equals', 'ensure_tequals', 'ensure_fails_with_substring' } local empty_table, toverride_many, tappend_many, tkeys, tvalues, tkeysvalues, tflip, tiflip, tset, tiset, tiinsert_args, timap_inplace, timap_sliding, tiwalk, tiwalker, tequals, tiunique, tgenerate_n, taccumulate, tnormalize, tnormalize_inplace, table_utils_exports = import 'lua-nucleo/table-utils.lua' { 'empty_table', 'toverride_many', 'tappend_many', 'tkeys', 'tvalues', 'tkeysvalues', 'tflip', 'tiflip', 'tset', 'tiset', 'tiinsert_args', 'timap_inplace', 'timap_sliding', 'tiwalk', 'tiwalker', 'tequals', 'tiunique', 'tgenerate_n', 'taccumulate', 'tnormalize', 'tnormalize_inplace' } -------------------------------------------------------------------------------- local test = make_suite("table-utils", table_utils_exports) -------------------------------------------------------------------------------- test:test_for "empty_table" (function() ensure_equals("is table", type(empty_table), "table") ensure_equals("is empty", next(empty_table), nil) ensure_equals( "metatable is protected", getmetatable(empty_table), "empty_table" ) ensure_equals("allows read access", empty_table[42], nil) ensure_fails_with_substring( "disallows write access", function() empty_table[42] = true end, "attempted to change the empty table" ) ensure_equals("still empty", next(empty_table), nil) end) -------------------------------------------------------------------------------- test:group "toverride_many" -------------------------------------------------------------------------------- test "toverride_many-noargs-empty" (function() ensure_tequals("noargs-empty", toverride_many({ }), { }) end) test "toverride_many-noargs" (function() ensure_tequals("noargs", toverride_many({ 42 }), { 42 }) end) test "toverride_many-single" (function() ensure_tequals("single", toverride_many({ 3.14 }, { 42 }), { 42 }) end) test "toverride_many-empty-append" (function() ensure_tequals("single", toverride_many({ }, { 42 }), { 42 }) end) test "toverride_many-single-append" (function() ensure_tequals( "single append", toverride_many({ 2.71 }, { [2] = 42 }), { 2.71, 42 } ) end) test "toverride_many-returns-first-argument" (function() local t = { 2.71 } local r = toverride_many(t, { [2] = 42 }) ensure_tequals( "single append", r, { 2.71, 42 } ) ensure_equals("returned first argument", r, t) end) test "toverride_many-double-append" (function() ensure_tequals( "double append", toverride_many({ 2.71 }, { [2] = 42 }, { ["a"] = true }), { 2.71, 42, ["a"] = true } ) end) test "toverride_many-hole" (function() ensure_tequals( "hole stops", toverride_many({ 2.71 }, { [2] = 42 }, nil, { ["a"] = true }), { 2.71, 42 } ) end) test "toverride_many-on-self" (function() local v = { } local t = { v } ensure_tequals( "self-override is no-op", toverride_many(t, t, t, t, t), t ) ensure_equals("exactly the same", t[1], v) t[1] = nil ensure_equals("no extra data", next(t), nil) end) test "toverride_many-recursion" (function() local t = { } t[t] = t ensure_tequals( "recursion", toverride_many(t, t, { t }), t ) ensure_equals("old value is there", t[t], t) ensure_equals("and new one appeared", t[1] , t) t[t], t[1] = nil, nil ensure_equals("no extra data", next(t), nil) end) test "toverride_many-many" (function() local k = { } local t = { [1] = 42, ["a"] = k, [k] = false } local r = toverride_many( t, { }, { 1 }, t, { false, ["z"] = 2.71 }, { [k] = k, [1] = 2.71 }, t, nil, { 0 } ) ensure_equals("returns first argument", r, t) ensure_tequals( "many", r, { [1] = 2.71, ["a"] = k, [k] = k, ["z"] = 2.71 } ) end) -------------------------------------------------------------------------------- test:group "tappend_many" -------------------------------------------------------------------------------- test "tappend_many-noargs-empty" (function() ensure_tequals("noargs-empty", tappend_many({ }), { }) end) test "tappend_many-noargs" (function() ensure_tequals("noargs", tappend_many({ 42 }), { 42 }) end) test "tappend_many-single" (function() ensure_fails_with_substring( "single override fails", function() tappend_many({ 3.14 }, { 42 }) end, "attempted to override table key `1'" ) end) test "tappend_many-empty-append" (function() ensure_tequals("single", tappend_many({ }, { 42 }), { 42 }) end) test "tappend_many-single-append" (function() ensure_tequals( "single append", tappend_many({ 2.71 }, { [2] = 42 }), { 2.71, 42 } ) end) test "tappend_many-returns-first-argument" (function() local t = { 2.71 } local r = tappend_many(t, { [2] = 42 }) ensure_tequals( "single append", r, { 2.71, 42 } ) ensure_equals("returned first argument", r, t) end) test "tappend_many-double-append" (function() ensure_tequals( "double append", tappend_many({ 2.71 }, { [2] = 42 }, { ["a"] = true }), { 2.71, 42, ["a"] = true } ) end) test "tappend_many-hole" (function() ensure_tequals( "hole stops", tappend_many({ 2.71 }, { [2] = 42 }, nil, { 0 }), { 2.71, 42 } ) end) test "tappend_many-on-self" (function() local v = { } local t = { v } ensure_fails_with_substring( "self override fails", function() tappend_many(t, t) end, "attempted to override table key `1'" ) end) test "tappend_many-recursion" (function() local t = { } t[t] = t ensure_tequals( "recursion", tappend_many(t, { t }), t ) ensure_equals("old value is there", t[t], t) ensure_equals("and new one appeared", t[1] , t) t[t], t[1] = nil, nil ensure_equals("no extra data", next(t), nil) end) test "tappend_many-many" (function() local k = { } local t = { [1] = 42, ["a"] = k, [k] = false } local r = tappend_many( t, { }, { [2] = 1, ["z"] = 2.71 }, nil, t ) ensure_equals("returns first argument", r, t) ensure_tequals( "many", r, { [1] = 42, [2] = 1, ["a"] = k, [k] = false, ["z"] = 2.71 } ) end) -------------------------------------------------------------------------------- test:group "tkeys" -------------------------------------------------------------------------------- test "tkeys-empty" (function() ensure_tequals("empty", tkeys({ }), { }) end) test "tkeys-single" (function() ensure_tequals("simple", tkeys({ [1] = 42 }), { 1 }) end) test "tkeys-hole" (function() ensure_tequals("hole", tkeys({ [42] = 1 }), { 42 }) end) test "tkeys-hash" (function() ensure_tequals("hash", tkeys({ ["a"] = 42 }), { "a" }) end) test "tkeys-table" (function() local k = { } ensure_tequals("table", tkeys({ [k] = 42 }), { k }) end) test "tkeys-recursive" (function() local t = { } t[t] = t ensure_tequals("recursive", tkeys(t), { t }) end) test "tkeys-many" (function() -- NOTE: Can't use tequals() directly -- due to undetermined table traversal order. local k = { } local t = { [1] = 42, a = k, [k] = false } local keys = tkeys(t) -- Check needed in case there would be duplicate entries in the result. ensure_equals("three keys", #keys, 3) ensure_tequals("check key sets", tiset(keys), tiset { 1, "a", k }) end) -------------------------------------------------------------------------------- test:group "tvalues" -------------------------------------------------------------------------------- test "tvalues-empty" (function() ensure_tequals("empty", tvalues({ }), { }) end) test "tvalues-single" (function() ensure_tequals("simple", tvalues({ [1] = 42 }), { 42 }) end) test "tvalues-hole" (function() ensure_tequals("hole", tvalues({ [42] = 1 }), { 1 }) end) test "tvalues-hash" (function() ensure_tequals("hash", tvalues({ ["a"] = 42 }), { 42 }) end) test "tvalues-table" (function() local k = { } ensure_tequals("table", tvalues({ [42] = k }), { k }) end) test "tvalues-recursive" (function() local t = { } t[1] = t ensure_tequals("recursive", tvalues(t), { t }) end) test "tvalues-many" (function() -- NOTE: Can't use tequals() directly -- due to undetermined table traversal order. local k = { } local t = { [1] = 42, a = k, [k] = false } local values = tvalues(t) -- Check needed in case there would be duplicate entries in the result. ensure_equals("three values", #values, 3) ensure_tequals("check value sets", tiset(values), tiset { 42, k, false }) end) -------------------------------------------------------------------------------- test:group "tkeysvalues" -------------------------------------------------------------------------------- test "tkeysvalues-empty" (function() local keys, values = tkeysvalues({ }) ensure_tequals("keys empty", keys, { }) ensure_tequals("values empty", values, { }) end) test "tkeysvalues-single" (function() local keys, values = tkeysvalues({ [1] = 42 }) ensure_tequals("keys simple", keys, { 1 }) ensure_tequals("values simple", values, { 42 }) end) test "tkeysvalues-hole" (function() local keys, values = tkeysvalues({ [42] = 1 }) ensure_tequals("keys hole", keys, { 42 }) ensure_tequals("values hole", values, { 1 }) end) test "tkeysvalues-hash" (function() local keys, values = tkeysvalues({ ["a"] = 42 }) ensure_tequals("keys hash", keys, { "a" }) ensure_tequals("values hash", values, { 42 }) end) test "tkeysvalues-table" (function() local k = { } local keys, values = tkeysvalues({ [42] = k }) ensure_tequals("keys table", keys, { 42 }) ensure_tequals("values table", values, { k }) end) test "tkeysvalues-recursive" (function() local t = { } t[1] = t local keys, values = tkeysvalues(t) ensure_tequals("keys recursive", keys, { 1 }) ensure_tequals("values recursive", values, { t }) end) test "tkeysvalues-many" (function() -- NOTE: Can't use tequals() directly -- due to undetermined table traversal order. local k = { } local t = { [1] = 42, a = k, [k] = false } local keys, values = tkeysvalues(t) -- Check needed in case there would be duplicate entries in the result. ensure_equals("three keys", #keys, 3) ensure_equals("three values", #values, 3) ensure_tequals("check key sets", tiset(keys), tiset { 1, "a", k }) ensure_tequals("check value sets", tiset(values), tiset { 42, k, false }) end) -------------------------------------------------------------------------------- test:group "tflip" -------------------------------------------------------------------------------- test "tflip-empty" (function() ensure_tequals("empty", tflip({ }), { }) end) test "tflip-single" (function() ensure_tequals("simple", tflip({ [1] = 42 }), { [42] = 1 }) end) test "tflip-hole" (function() ensure_tequals("hole", tflip({ [42] = 1 }), { [1] = 42 }) end) test "tflip-hash" (function() ensure_tequals("hash", tflip({ ["a"] = 42 }), { [42] = "a" }) end) test "tflip-duplicate" (function() local t = tflip({ [1] = 42, [2] = 42 }) ensure( "duplicate", tequals(t, { [42] = 1 }) or tequals(t, { [42] = 2 }) ) end) test "tflip-duplicate-hash" (function() local t = tflip({ [1] = 42, ["a"] = 42 }) ensure( "duplicate hash", tequals(t, { [42] = 1 }) or tequals(t, { [42] = "a" }) ) end) test "tflip-table" (function() local k = { } ensure_tequals("table", tflip({ [k] = 42 }), { [42] = k }) end) test "tflip-recursive" (function() local t = { } t[1] = t ensure_tequals("recursive", tflip(t), { [t] = 1 }) end) test "tflip-many" (function() local k = { } local t = { [1] = 42, a = k, [k] = false } ensure_tequals( "many", tflip(t), { [42] = 1, [k] = "a", [false] = k } ) end) -------------------------------------------------------------------------------- test:group "tiflip" -------------------------------------------------------------------------------- test "tiflip-empty" (function() ensure_tequals("empty", tiflip({ }), { }) end) test "tiflip-single" (function() ensure_tequals("simple", tiflip({ [1] = 42 }), { [42] = 1 }) end) test "tiflip-hole" (function() ensure_tequals("hole ignored", tiflip({ [42] = 1 }), { }) end) test "tiflip-hash" (function() ensure_tequals("hash ignored", tiflip({ ["a"] = 42 }), { }) end) test "tiflip-duplicate" (function() ensure_tequals("duplicate", tiflip({ [1] = 42, [2] = 42 }), { [42] = 2 }) end) test "tiflip-duplicate-hash" (function() ensure_tequals( "duplicate hash ignored", tiflip({ [1] = 42, ["a"] = 42 }), { [42] = 1 } ) end) test "tiflip-recursive" (function() local t = { } t[1] = t ensure_tequals("recursive", tiflip(t), { [t] = 1 }) end) test "tiflip-many" (function() local k = { } local t = { [1] = 42, [2] = 42, a = k, [k] = 42 } ensure_tequals("many", tiflip(t), { [42] = 2 }) end) -------------------------------------------------------------------------------- test:group "tset" -------------------------------------------------------------------------------- test "tset-empty" (function() ensure_tequals("empty", tset({ }), { }) end) test "tset-single" (function() ensure_tequals("simple", tset({ [1] = 42 }), { [42] = true }) end) test "tset-hole" (function() ensure_tequals("hole", tset({ [42] = 1 }), { [1] = true }) end) test "tset-hash" (function() ensure_tequals("hash", tset({ ["a"] = 42 }), { [42] = true }) end) test "tset-duplicate" (function() ensure_tequals("duplicate", tset({ [1] = 42, [2] = 42 }), { [42] = true }) end) test "tset-duplicate-hash" (function() ensure_tequals( "duplicate hash", tset({ [1] = 42, ["a"] = 42 }), { [42] = true } ) end) test "tset-table" (function() local k = { } ensure_tequals("table", tset({ [k] = 42 }), { [42] = true }) end) test "tset-recursive" (function() local t = { } t[1] = t ensure_tequals("recursive", tset(t), { [t] = true }) end) test "tset-many" (function() local k = { } local t = { [1] = 42, a = k, [k] = false } ensure_tequals( "many", tset(t), { [42] = true, [k] = true, [false] = true } ) end) -------------------------------------------------------------------------------- test:group "tiset" -------------------------------------------------------------------------------- test "tiset-empty" (function() ensure_tequals("empty", tiset({ }), { }) end) test "tiset-single" (function() ensure_tequals("simple", tiset({ [1] = 42 }), { [42] = true }) end) test "tiset-hole" (function() ensure_tequals("hole ignored", tiset({ [42] = 1 }), { }) end) test "tiset-hash" (function() ensure_tequals("hash ignored", tiset({ ["a"] = 42 }), { }) end) test "tiset-duplicate" (function() ensure_tequals("duplicate", tiset({ [1] = 42, [2] = 42 }), { [42] = true }) end) test "tiset-duplicate-hash" (function() ensure_tequals( "duplicate hash", tiset({ [1] = 42, ["a"] = 42 }), { [42] = true } ) end) test "tiset-recursive" (function() local t = { } t[1] = t ensure_tequals("recursive", tiset(t), { [t] = true }) end) test "tiset-many" (function() local k = { } local t = { [1] = 42, [2] = 42, a = k, [k] = 42 } ensure_tequals("many", tiset(t), { [42] = true }) end) -------------------------------------------------------------------------------- test:group "tiinsert_args" -------------------------------------------------------------------------------- test "tiinsert_args-empty-noargs" (function() local t = { } local r = tiinsert_args(t) ensure_tequals("empty", r, { }) ensure_equals("returns first argument", r, t) end) test "tiinsert_args-empty-append" (function() local t = { } local r = tiinsert_args(t, 1, 2) ensure_tequals("append", r, { 1, 2 }) ensure_equals("returns first argument", r, t) end) test "tiinsert_args-non-empty-append" (function() local t = { 1 } local r = tiinsert_args(t, 2, 3) ensure_tequals("append", r, { 1, 2, 3 }) ensure_equals("returns first argument", r, t) end) test "tiinsert_args-nil-stops" (function() local t = { 1 } local r = tiinsert_args(t, 2, nil, 3) ensure_tequals("append", r, { 1, 2 }) ensure_equals("returns first argument", r, t) end) test "tiinsert_args-complex" (function() local t = { } t[1] = t t[t] = t local r = tiinsert_args(t, 1, t, t, nil, t) ensure_tequals("complex", r, { t, 1, t, t, [t] = t }) ensure_equals("returns first argument", r, t) end) -------------------------------------------------------------------------------- test:group "timap_inplace" -------------------------------------------------------------------------------- test "timap_inplace-empty-noargs" (function() local c = 0 local fn = function() c = c + 1 end local t = { } local r = timap_inplace(fn, t) ensure_equals("function not called", c, 0) ensure_equals("returned table", r, t) end) test "timap_inplace-empty-args" (function() local c = 0 local fn = function() c = c + 1 end local t = { } local r = timap_inplace(fn, t, 42) ensure_equals("function not called", c, 0) ensure_equals("returned table", r, t) end) test "timap_inplace-counter-noargs" (function() local c = 0 local fn = function(a, b) c = c + 1 ensure_equals("check a", a, c * 10) ensure_equals("check b", b, nil) return a + c end local t = { 10, 20, 30, ["a"] = 42 } local r = timap_inplace(fn, t) ensure_equals("function called", c, 3) ensure_equals("returned table", r, t) ensure_tequals("table changed", r, { 11, 22, 33, ["a"] = 42 }) end) test "timap_inplace-counter-args" (function() local k = { } local c = 0 local fn = function(a, b) c = c + 1 ensure_equals("check a", a, c * 10) ensure_equals("check b", b, k) return a + c end local t = { 10, 20, 30, ["a"] = 42 } local r = timap_inplace(fn, t, k) ensure_equals("function called", c, 3) ensure_equals("returned table", r, t) ensure_tequals("table changed", r, { 11, 22, 33, ["a"] = 42 }) end) -------------------------------------------------------------------------------- test:group "timap_sliding" -------------------------------------------------------------------------------- test "timap_sliding-empty-noargs" (function() local c = 0 local fn = function() c = c + 1 end local t = { } local r = timap_sliding(fn, t) ensure_equals("function not called", c, 0) ensure_tequals("result is empty", r, { }) ensure("returned new table", r ~= t) end) test "timap_sliding-empty-args" (function() local c = 0 local fn = function() c = c + 1 end local t = { } local r = timap_sliding(fn, t, 42) ensure_equals("function not called", c, 0) ensure_tequals("result is empty", r, { }) ensure("returned new table", r ~= t) end) test "timap_sliding-hash-noargs" (function() local c = 0 local fn = function() c = c + 1 end local t = { ["a"] = 1 } local r = timap_sliding(fn, t) ensure_equals("function not called", c, 0) ensure_tequals("result is empty", r, { }) ensure("returned new table", r ~= t) end) test "timap_sliding-hash-args" (function() local c = 0 local fn = function() c = c + 1 end local t = { ["a"] = 1 } local r = timap_sliding(fn, t, 42) ensure_equals("function not called", c, 0) ensure_tequals("result is empty", r, { }) ensure("returned new table", r ~= t) end) test "timap_sliding-counter-noargs" (function() local c = 0 local fn = function(a, b) c = c + 1 ensure_equals("check a", a, c * 10) ensure_equals("check b", b, nil) return a + c end local t = { 10, 20, 30, ["a"] = 42 } local r = timap_sliding(fn, t) ensure_equals("function called", c, 3) ensure_tequals("table changed", r, { 11, 22, 33 }) ensure("returned new table", r ~= t) end) test "timap_sliding-counter-args" (function() local k = { } local c = 0 local fn = function(a, b) c = c + 1 ensure_equals("check a", a, c * 10) ensure_equals("check b", b, k) return a + c end local t = { 10, 20, 30, ["a"] = 42 } local r = timap_sliding(fn, t, k) ensure_equals("function called", c, 3) ensure_tequals("table changed", r, { 11, 22, 33 }) ensure("returned new table", r ~= t) end) test "timap_sliding-counter-noargs-many" (function() local c = 0 local fn = function(a, b) c = c + 1 ensure_equals("check a", a, c * 10) ensure_equals("check b", b, nil) return a + c, a + c + 1 end local t = { 10, 20, 30, ["a"] = 42 } local r = timap_sliding(fn, t) ensure_equals("function called", c, 3) ensure_tequals("table changed", r, { 11, 12, 22, 23, 33, 34 }) ensure("returned new table", r ~= t) end) test "timap_sliding-counter-args-many" (function() local k = { } local c = 0 local fn = function(a, b) c = c + 1 ensure_equals("check a", a, c * 10) ensure_equals("check b", b, k) return a + c, a + c + 1 end local t = { 10, 20, 30, ["a"] = 42 } local r = timap_sliding(fn, t, k) ensure_equals("function called", c, 3) ensure_tequals("table changed", r, { 11, 12, 22, 23, 33, 34 }) ensure("returned new table", r ~= t) end) -------------------------------------------------------------------------------- test:group "tequals" -------------------------------------------------------------------------------- test "tequals-empty-eq" (function() ensure_equals("empty-eq", tequals({ }, { }), true) end) test "tequals-empty-neq" (function() ensure_equals("empty-neq-1", tequals({ }, { 1 }), false) ensure_equals("empty-neq-2", tequals({ 1 }, { }), false) end) test "tequals-empty-self" (function() local t = { } ensure_equals("empty-self", tequals(t, t), true) end) test "tequals-non-empty-eq" (function() ensure_equals("empty-eq", tequals({ 1 }, { 1 }), true) end) test "tequals-non-empty-neq" (function() ensure_equals("empty-neq-1", tequals({ 1 }, { 1, 2 }), false) ensure_equals("empty-neq-2", tequals({ 1, 2 }, { 1 }), false) ensure_equals("empty-neq-3", tequals({ 1, 2 }, { 3, 4 }), false) end) test "tequals-non-empty-self" (function() local t = { 1 } ensure_equals("non-empty-self", tequals(t, t), true) end) test "tequals-table-eq" (function() local t = { } ensure_equals("table-eq", tequals({ [t] = t }, { [t] = t }), true) end) test "tequals-table-neq" (function() local t1, t2 = { }, { } ensure_equals("table-neq", tequals({ [t1] = t1 }, { [t2] = t2 }), false) end) test "tequals-hole-eq" (function() ensure_equals("hole-eq", tequals({ [42] = 1 }, { [42] = 1 }), true) end) test "tequals-hole-neq" (function() ensure_equals("hole-neq", tequals({ [42] = 1 }, { [42] = 2 }), false) end) test "tequals-recursion-eq" (function() local lhs = { } lhs[lhs] = lhs local rhs = { } rhs[lhs] = lhs ensure_equals("recursion-eq", tequals(lhs, rhs), true) end) test "tequals-recursion-neq" (function() local lhs = { } lhs[lhs] = lhs local rhs = { } rhs[rhs] = rhs ensure_equals("reqursion-neq", tequals(lhs, rhs), false) end) test "tequals-recursion-self" (function() local t = { } t[t] = t ensure_equals("recursion-self", tequals(t, t), true) end) -------------------------------------------------------------------------------- test:group "tiwalk" -------------------------------------------------------------------------------- test "tiwalk-empty-noargs" (function() local c = 0 local fn = function() c = c + 1 end local t = { } local r = tiwalk(fn, t) ensure_equals("function not called", c, 0) ensure_equals("returned nil", r, nil) end) test "tiwalk-empty-args" (function() local c = 0 local fn = function() c = c + 1 end local t = { } local r = tiwalk(fn, t, 42) ensure_equals("function not called", c, 0) ensure_equals("returned nil", r, nil) end) test "tiwalk-counter-noargs" (function() local c = 0 local fn = function(a, b) c = c + 1 ensure_equals("check a", a, c * 10) ensure_equals("check b", b, nil) return a + c end local t = { 10, 20, 30, ["a"] = 42 } local r = tiwalk(fn, t) ensure_equals("function called", c, 3) ensure_equals("returned nil", r, nil) end) test "tiwalk-counter-args" (function() local k = { } local c = 0 local fn = function(a, b) c = c + 1 ensure_equals("check a", a, c * 10) ensure_equals("check b", b, k) return a + c end local t = { 10, 20, 30, ["a"] = 42 } local r = tiwalk(fn, t, k) ensure_equals("function called", c, 3) ensure_equals("returned nil", r, nil) end) -------------------------------------------------------------------------------- test:group "tiwalker" -------------------------------------------------------------------------------- test "tiwalker-empty-noargs" (function() local c = 0 local fn = function() c = c + 1 end local t = { } local r = tiwalker(fn)(t) ensure_equals("function not called", c, 0) ensure_equals("returned nil", r, nil) end) test "tiwalker-empty-args" (function() local c = 0 local fn = function() c = c + 1 end local t = { } local r = tiwalker(fn)(t, 42) ensure_equals("function not called", c, 0) ensure_equals("returned nil", r, nil) end) test "tiwalker-counter-noargs" (function() local c = 0 local fn = function(a, b) c = c + 1 ensure_equals("check a", a, c * 10) ensure_equals("check b", b, nil) return a + c end local t = { 10, 20, 30, ["a"] = 42 } local r = tiwalker(fn)(t) ensure_equals("function called", c, 3) ensure_equals("returned nil", r, nil) end) test "tiwalker-counter-args" (function() local k = { } local c = 0 local fn = function(a, b) c = c + 1 ensure_equals("check a", a, c * 10) ensure_equals("check b", b, nil) -- Arguments not passed through return a + c end local t = { 10, 20, 30, ["a"] = 42 } local r = tiwalker(fn)(t, k) ensure_equals("function called", c, 3) ensure_equals("returned nil", r, nil) end) -------------------------------------------------------------------------------- test:group "tiunique" -------------------------------------------------------------------------------- test "tiunique-empty" (function() ensure_tequals("empty", tiunique({ }), { }) end) test "tiunique-single" (function() ensure_tequals("simple", tiunique({ [1] = 42 }), { [1] = 42 }) end) test "tiunique-hole" (function() ensure_tequals("hole ignored", tiunique({ [42] = 1 }), { }) end) test "tiunique-hash" (function() ensure_tequals("hash ignored", tiunique({ ["a"] = 42 }), { }) end) test "tiunique-duplicate" (function() ensure_tequals("duplicate", tiunique({ [1] = 42, [2] = 42 }), { [1] = 42 }) end) test "tiunique-duplicate-hash" (function() ensure_tequals( "duplicate hash ignored", tiunique({ [1] = 42, ["a"] = 42 }), { [1] = 42 } ) end) test "tiunique-recursive" (function() local t = { } t[1] = t ensure_tequals("recursive", tiunique(t), t) end) test "tiunique-many" (function() local k = { } local t = { [1] = 42, [2] = 42, a = k, [k] = 42 } ensure_tequals("many", tiunique(t), { [1] = 42 }) end) -------------------------------------------------------------------------------- test:group "tgenerate_n" -------------------------------------------------------------------------------- test "tgenerate_n_0" (function() ensure_tequals("zero", tgenerate_n(0, function() return 42 end), { }) end) test "tgenerate_n_1" (function() ensure_tequals("one", tgenerate_n(1, function() return 42 end), { 42 }) end) test "tgenerate_n_multret" (function() ensure_tequals("one", tgenerate_n(1, function() return 42, 1 end), { 42 }) end) test "tgenerate_n_args" (function() ensure_tequals("args", tgenerate_n(1, function(a) return a end, 42), { 42 }) end) test "tgenerate_n_5" (function() ensure_tequals( "five", tgenerate_n(5, function() return 42 end), { 42, 42, 42, 42, 42 } ) end) test "tgenerate_n_nil" (function() ensure_tequals( "nil", tgenerate_n(5, function() return nil end), { nil, nil, nil, nil, nil } ) end) -------------------------------------------------------------------------------- test:group "taccumulate" -------------------------------------------------------------------------------- test "taccumulate-empty" (function() ensure_equals("empty default", taccumulate({}), 0) ensure_equals("empty 0", taccumulate({}, 0), 0) ensure_equals("empty 1", taccumulate({}, 1), 1) end) test "taccumulate-array" (function() ensure_equals("array", taccumulate({1, 2, 3}), 6) end) test "taccumulate-array-hole" (function() ensure_equals("array", taccumulate({1, 2, nil, nil, nil, 3}), 6) end) test "taccumulate-hash" (function() ensure_equals("hash", taccumulate({a = 1, b = 2, c = 3}), 6) end) test "taccumulate-mixed" (function() ensure_equals("mixed", taccumulate({ 3, -1, a = -1, b = 2, c = 3}), 6) end) -------------------------------------------------------------------------------- test:group "tnormalize" -------------------------------------------------------------------------------- test "tnormalize-empty" (function() local data = { } local expected_default, expected_sum = { }, { } local result_default = tnormalize(data) local result_sum = tnormalize(data, 30) ensure_tequals("empty default", result_default, expected_default) ensure("not inplace default", data ~= result_default) ensure_tequals("empty sum", result_sum, expected_sum) ensure("not inplace sum", data ~= result_sum) end) test "tnormalize-simple" (function() local data = { 3 } local expected_default, expected_sum = { 3 / 3 }, { 3 / 30 } local result_default = tnormalize(data) local result_sum = tnormalize(data, 30) ensure_tequals("empty default", result_default, expected_default) ensure("not inplace default", data ~= result_default) ensure_tequals("empty sum", result_sum, expected_sum) ensure("not inplace sum", data ~= result_sum) end) test "tnormalize-mixed" (function() local data = { a = 2, 3 } local expected_default, expected_sum = { a = 2 / 5, 3 / 5 }, { a = 2 / 30, 3 / 30 } local result_default = tnormalize(data) local result_sum = tnormalize(data, 30) ensure_tequals("empty default", result_default, expected_default) ensure("not inplace default", data ~= result_default) ensure_tequals("empty sum", result_sum, expected_sum) ensure("not inplace sum", data ~= result_sum) end) -------------------------------------------------------------------------------- test:group "tnormalize_inplace" -------------------------------------------------------------------------------- test "tnormalize_inplace-empty" (function() local data_default, data_sum = { }, { } local expected_default, expected_sum = { }, { } local result_default = tnormalize_inplace(data_default) local result_sum = tnormalize_inplace(data_sum, 30) ensure_tequals("empty default", result_default, expected_default) ensure("inplace default", data_default == result_default) ensure_tequals("empty sum", result_sum, expected_sum) ensure("inplace sum", data_sum == result_sum) end) test "tnormalize_inplace-simple" (function() local data_default, data_sum = { 3 }, { 3 } local expected_default, expected_sum = { 3 / 3 }, { 3 / 30 } local result_default = tnormalize_inplace(data_default) local result_sum = tnormalize_inplace(data_sum, 30) ensure_tequals("empty default", result_default, expected_default) ensure("inplace default", data_default == result_default) ensure_tequals("empty sum", result_sum, expected_sum) ensure("inplace sum", data_sum == result_sum) end) test "tnormalize_inplace-mixed" (function() local data_default, data_sum = { a = 2, 3 }, { a = 2, 3 } local expected_default, expected_sum = { a = 2 / 5, 3 / 5 }, { a = 2 / 30, 3 / 30 } local result_default = tnormalize_inplace(data_default) local result_sum = tnormalize_inplace(data_sum, 30) ensure_tequals("empty default", result_default, expected_default) ensure("inplace default", data_default == result_default) ensure_tequals("empty sum", result_sum, expected_sum) ensure("inplace sum", data_sum == result_sum) end) -------------------------------------------------------------------------------- assert(test:run())
return { name = "truemedian/lfs", version = "0.1.2", description = "A libuv equivalent for the popular lfs library", tags = { "lua", "lfs", "filesystem" }, license = "MIT", author = { name = "Nameless", email = "truemedian@gmail.com" }, homepage = "https://keplerproject.github.io/luafilesystem", dependencies = { }, files = { "**.lua", "!deps", "!test*" } }
function CRATE:__installed__() AddCSLuaFile(self.__path__..'lib/markdown.min.lua') if !Markdown then Markdown = include(self.__path__..(SERVER and 'lib/markdown.lua' or 'lib/markdown.min.lua')) end end
events = {} EventType = { NEW_JOB = 0, LOST_JOB = 1, NEW_JOB_LOCATION = 2, NEW_CHILD = 3, NEW_SCHOOL_LOCATION = 4, ZONING_RULE_CHANGE = 5, } function addHouseHoldEvent (day, type, householdId) event = ExternalEvent() event.day = day; event.householdId = householdId; event.type = type; if events[day] == nil then events[day] = {} end table.insert(events[day], event); end --function addDeveloperModelEvent(day, type, developerId) -- event = ExternalEvent(); -- event.day = day; -- event.developerId = developerId -- event.type = type; -- if events[day] == nil then -- events[day] = {} -- end -- table.insert(events[day], event); --end --addEvent(67, EventType.NEW_JOB, 1) --addEvent(67, EventType.NEW_JOB_LOCATION, 2) --addEvent(300, EventType.NEW_CHILD, 3) --addEvent(300, EventType.NEW_SCHOOL_LOCATION, 4) --addEvent(69, EventType.NEW_JOB, 51841) --addEvent(77, EventType.NEW_JOB_LOCATION, 51842) --addEvent(160, EventType.NEW_CHILD, 51848) --addEvent(200, EventType.NEW_SCHOOL_LOCATION, 51850) --[[ Gets all external events for given day. @param day to of the events. @return ExternalEvent list. ]] excluded={} function getExternalEvents (day) --if events[day] ~= nil then -- return events[day]; --end if day ~= 1 then for i= 1, 300 do local household = math.random(1,1146054) if excluded[household] == nil then addHouseHoldEvent(day, EventType.NEW_SCHOOL_LOCATION, household) excluded[household]={} end --addEvent(1, EventType.NEW_SCHOOL_LOCATION, i) end end --local developer = 2 -- addDeveloperModelEvent(day,EventType.ZONING_RULE_CHANGE,developer) return events[day] end
local parquet = require 'parquet' --local thrift_print_r = require 'thrift.print_r' local filename = 'model2-data-part-00002.parquet' --[[ KMeans model, trained and exported uncompressed with: $ docker run -it gettyimages/spark bin/spark-shell --conf spark.sql.parquet.compression.codec=uncompressed import org.apache.spark.mllib.linalg.Vector import org.apache.spark.mllib.linalg.Vectors import org.apache.spark.mllib.clustering.KMeans var v1 = Vectors.dense(Array[Double](1,2,3)) var v2 = Vectors.dense(Array[Double](5,6,7)) var data = sc.parallelize(Array(v1,v2)) var model = KMeans.train(data, k=1, maxIterations=1) model.save(sc, "model2") --]] describe(filename, function() it('readTestFile', function() local reader = parquet.ParquetReader.openFile('spec-fixtures/' .. filename) assert.equal(0, reader:getRowCount():toInt()) assert.is_not_nil(reader:getMetadata()) assert.is_not_nil(reader:getMetadata()['org.apache.spark.sql.parquet.row.metadata']) local schema = reader:getSchema() assert.equals(10, #schema.fieldList) assert.is_not_nil(schema.fields.id) assert.is_not_nil(schema.fields.point) do local c = schema.fields.id assert.equal('id', c.name) assert.equal('INT32', c.primitiveType) assert.equal(nil, c.originalType) assert.same({'id'}, c.path) assert.equal('REQUIRED', c.repetitionType) assert.equal('PLAIN', c.encoding) assert.equal('UNCOMPRESSED', c.compression) assert.equal(0, c.rLevelMax) assert.equal(0, c.dLevelMax) assert.equal(false, not not c.isNested) assert.equal(nil, c.fieldCount) end do local c = schema.fields.point assert.equal('point', c.name) assert.equal(nil, c.primitiveType) assert.equal(nil, c.originalType) assert.same({'point'}, c.path) assert.equal('OPTIONAL', c.repetitionType) assert.equal(nil, c.encoding) assert.equal(nil, c.compression) assert.equal(0, c.rLevelMax) assert.equal(1, c.dLevelMax) assert.equal(true, not not c.isNested) assert.equal(4, c.fieldCount) end do local cursor = reader:getCursor() local row = cursor:next() assert.is_nil(row) end reader:close() end) end)
bc.sidePanel.members.template = { member = { name = "Player", value = "SteamID", type = "options", options = { "Admin", "Member", "Remove" }, optionValues = { 0, 1, 2 }, default = 1, extra = "Set this player's role in the group", onChange = function( data ) local chan = bc.channels.get( "Group - " .. data.group.id ) if not chan then return end -- Shouldn't be able to edit this but u kno local oldGroup = data.group local newGroup = { name = oldGroup.name, id = oldGroup.id, members = {}, admins = {}, invites = oldGroup.invites } for k, v in pairs( data ) do if type( v ) ~= "number" then continue end if v <= 1 then table.insert( newGroup.members, k ) end if v == 0 then table.insert( newGroup.admins, k ) end end net.Start( "BC_updateGroup" ) net.WriteUInt( newGroup.id, 16 ) net.WriteString( util.TableToJSON( newGroup ) ) net.SendToServer() end, overrideWidth = 62, }, nonMember = { name = "Player", value = "SteamID", type = "button", text = "Invite", extra = "Invite this player to the group, limited to 1 invite per minute", onClick = function( data, self ) local group = data.group local id = self.value group.invites[id] = -1 net.Start( "BC_updateGroup" ) net.WriteUInt( group.id, 16 ) net.WriteString( util.TableToJSON( group ) ) net.SendToServer() end, overrideWidth = 62, }, leaveGroup = { name = "", value = "", type = "button", text = "Leave Group", extra = "Leave this group and close the channel", onClick = function( data, self ) net.Start( "BC_leaveGroup" ) net.WriteUInt( data.group.id, 16 ) net.SendToServer() end, overrideWidth = -1, }, deleteGroup = { name = "", value = "", type = "button", text = "Delete Group", extra = "Delete this group permanently", onClick = function( data, self ) net.Start( "BC_deleteGroup" ) net.WriteUInt( data.group.id, 16 ) net.SendToServer() end, overrideWidth = -1, requireConfirm = true, } }
object_intangible_saga_system_sage_intangible_holocron = object_intangible_saga_system_shared_sage_intangible_holocron:new { } ObjectTemplates:addTemplate(object_intangible_saga_system_sage_intangible_holocron, "object/intangible/saga_system/sage_intangible_holocron.iff")
local class = require("class") local common = require("common") local M = {} -- Lazy way to compare classes that is used generically. -- Would be more efficient to implement a __eq for each class. local function lazyEq(self, other) return common.tableEq(self, other) end -- Arithmetic expressions M.IntAexp = class(function (a, value) a.value = value end) function M.IntAexp:__tostring() return string.format("IntAexp(%d)", self.value) end function M.IntAexp:eval(env) return self.value end M.IntAexp.__eq = lazyEq M.VarAexp = class(function(v, name) v.name = name end) function M.VarAexp:__tostring() return string.format("VarAexp(%s)", self.name) end function M.VarAexp:eval(env) if env[self.name] ~= nil then return env[self.name] else return 0 end end M.VarAexp.__eq = lazyEq M.BinopAexp = class(function(b, op, left, right) b.op = op b.left = left b.right = right end) function M.BinopAexp:__tostring() return string.format("BinopAexp(%s, %s, %s)", self.op, self.left, self.right) end do local opToFunction = { ["+"] = function(left, right) return left + right end, ["-"] = function(left, right) return left - right end, ["*"] = function(left, right) return left * right end, ["/"] = function(left, right) return left / right end } function M.BinopAexp:eval(env) if opToFunction[self.op] ~= nil then local leftValue = self.left:eval(env) local rightValue = self.right:eval(env) return opToFunction[self.op](leftValue, rightValue) else error("Unknown operator: " .. self.op) end end end M.BinopAexp.__eq = lazyEq M.RelopBexp = class(function(r, op, left, right) r.op = op r.left = left r.right = right end) function M.RelopBexp:__tostring() return string.format("RelopBexp(%s, %s, %s)", self.op, self.left, self.right) end do local opToFunction = { ["<"] = function(left, right) return left < right end, ["<="] = function(left, right) return left <= right end, [">"] = function(left, right) return left > right end, [">="] = function(left, right) return left >= right end, ["="] = function(left, right) return left == right end, ["!="] = function(left, right) return left ~= right end } function M.RelopBexp:eval(env) if opToFunction[self.op] ~= nil then local leftValue = self.left:eval(env) local rightValue = self.right:eval(env) return opToFunction[self.op](leftValue, rightValue) else error("Unknown operator: " .. self.op) end end end M.RelopBexp.__eq = lazyEq M.AndBexp = class(function(r, left, right) r.left = left r.right = right end) function M.AndBexp:__tostring() return string.format("AndBexp(%s, %s)", self.left, self.right) end function M.AndBexp:eval(env) local leftValue = self.left:eval(env) local rightValue = self.right:eval(env) return leftValue and rightValue end M.AndBexp.__eq = lazyEq M.OrBexp = class(function(r, left, right) r.left = left r.right = right end) function M.OrBexp:__tostring() return string.format("OrBexp(%s, %s)", self.left, self.right) end function M.OrBexp:eval(env) local leftValue = self.left:eval(env) local rightValue = self.right:eval(env) return leftValue or rightValue end M.OrBexp.__eq = lazyEq M.NotBexp = class(function(bexp, exp) bexp.exp = exp end) function M.NotBexp:__tostring() return string.format("NotBexp(%s)", self.exp) end function M.NotBexp:eval(env) local value = self.exp:eval(env) return not value end M.NotBexp.__eq = lazyEq M.AssignStatement = class(function(stmt, name, aexp) stmt.name = name stmt.aexp = aexp end) function M.AssignStatement:__tostring() return string.format("AssignStatement(%s, %s)", self.name, self.aexp) end function M.AssignStatement:eval(env) local value = self.aexp:eval(env) env[self.name] = value end M.AssignStatement.__eq = lazyEq M.CompoundStatement = class(function(stmt, first, second) stmt.first = first stmt.second = second end) function M.CompoundStatement:__tostring() return string.format("CompoundStatement(%s, %s)", self.first, self.second) end function M.CompoundStatement:eval(env) self.first:eval(env) self.second:eval(env) end M.CompoundStatement.__eq = lazyEq M.IfStatement = class(function(stmt, condition, trueStmt, falseStmt) stmt.condition = condition stmt.trueStmt = trueStmt stmt.falseStmt = falseStmt end) function M.IfStatement:__tostring() return string.format( "IfStatement(%s, %s, %s)", self.condition, self.trueStmt, self.falseStmt ) end function M.IfStatement:eval(env) if self.condition:eval(env) then self.trueStmt:eval(env) elseif self.falseStmt ~= nil then self.falseStmt:eval(env) end end M.IfStatement.__eq = lazyEq M.WhileStatement = class(function(stmt, condition, body) stmt.condition = condition stmt.body = body end) function M.WhileStatement:__tostring() return string.format("WhileStatement(%s, %s)", self.condition, self.body) end function M.WhileStatement:eval(env) while self.condition:eval(env) do self.body:eval(env) end end M.WhileStatement.__eq = lazyEq return M
function love.draw() local x, y = love.mouse.getPosition() love.graphics.print("Hello World", x, y) end
local backupSpam = {} addEvent( "onPlayerPayfine", true ) addEventHandler( "onPlayerPayfine", root, function ( theMoney ) exports.AURpayments:takeMoney( source, theMoney,"DENpolice fine" ) exports.server:setPlayerWantedPoints( source, 0 ) exports.NGCdxmsg:createNewDxMessage(source,"You have paid $"..exports.server:convertNumber(theMoney).." fine bill!") end ) addEventHandler("onPlayerQuit",root,function() for k,v in pairs(getElementsByType("player")) do if exports.DENlaw:isLaw(v) == true then triggerClientEvent(v,"policeUnblip",v,source) end end end) addEvent("returnGovernmentData",true) addEventHandler("returnGovernmentData",root,function() local arrests = exports.DENstats:getPlayerAccountData(source,"arrests") local arrestpoints = exports.DENstats:getPlayerAccountData(source,"arrestpoints") local tazerassists = exports.DENstats:getPlayerAccountData(source,"tazerassists") local rt = exports.DENstats:getPlayerAccountData(source,"radioTurfsTakenAsCop") local at = exports.DENstats:getPlayerAccountData(source,"armoredtrucks") triggerClientEvent(source,"callBackGovernment",source,tazerassists,arrests,arrestpoints,rt,at) end) addEvent("onPlayerJailed",true) addEventHandler("onPlayerJailed",root,function() for k,v in pairs(getElementsByType("player")) do triggerClientEvent(v,"policeUnblip",v,source) end end) function payForJail(plr) local wantedPoints = getElementData ( plr, "wantedPoints" ) local jailTime = getElementData( plr, "jailTimeRemaining" ) local money = jailTime*100 if getElementData(plr,"isPlayerArrested") then exports.NGCdxmsg:createNewDxMessage("You can not use this function while arrested",plr,255,0,0) return false elseif getElementData(plr,"isPlayerAdminJailed") or exports.server:getPlayerWantedPoints(plr) < 10 then exports.NGCdxmsg:createNewDxMessage("You can not avoid an admin jail",plr,255,0,0) return false elseif getElementData(plr,"isPlayerJailed") then if getPlayerMoney(plr) < money then exports.NGCdxmsg:createNewDxMessage("You can not pay this fund right now!",plr,255,0,0) return end exports.AURpayments:takeMoney(plr, money,"DENpolice jailfine") exports.CSGadmin:removePlayerJailed( plr ) exports.NGCdxmsg:createNewDxMessage("You've paied fine and got released from the jail",plr,0,255,0) setElementData(plr,"isPlayerAdminJailed",false) end end addCommandHandler("payjailfine",payForJail)
 --[[ $project: Give Me Peace $copyright: © Copyright Michael Boyle. All Rights Reserved. ]]-- -- -- Setup localisation. -- function Peace_Localisation() -- wheres this client then? local client_area = GetLocale(); -- this is the default silent whisper sent to players who were blocked. -- English/US if(client_area == "enUS") then -- silent whisper sent to blocked players who send a message. MSG_BLOCKED1 = "Important: Your whisper was rejected and hidden from %s because you are not on %s's list of authorised friends. If you feel you should be on %s's list then please send an in-game mail."; -- France elseif(client_area == "frFR") then -- silent whisper sent to blocked players who send a message. MSG_BLOCKED1 = "Important: Your whisper was rejected and hidden from %s because you are not on %s's list of authorised friends. If you feel you should be on %s's list then please send an in-game mail."; -- German elseif(client_area == "deDE") then -- silent whisper sent to blocked players who send a message. MSG_BLOCKED1 = "Important: Your whisper was rejected and hidden from %s because you are not on %s's list of authorised friends. If you feel you should be on %s's list then please send an in-game mail."; -- Korean elseif(client_area == "koKR") then -- silent whisper sent to blocked players who send a message. MSG_BLOCKED1 = "Important: Your whisper was rejected and hidden from %s because you are not on %s's list of authorised friends. If you feel you should be on %s's list then please send an in-game mail."; -- Chinese (simplified) elseif(client_area == "zhCN") then -- silent whisper sent to blocked players who send a message. MSG_BLOCKED1 = "Important: Your whisper was rejected and hidden from %s because you are not on %s's list of authorised friends. If you feel you should be on %s's list then please send an in-game mail."; -- Chinese (traditional) elseif(client_area == "zhTW") then -- silent whisper sent to blocked players who send a message. MSG_BLOCKED1 = "Important: Your whisper was rejected and hidden from %s because you are not on %s's list of authorised friends. If you feel you should be on %s's list then please send an in-game mail."; -- Russian elseif(client_area == "ruRU") then -- silent whisper sent to blocked players who send a message. MSG_BLOCKED1 = "Important: Your whisper was rejected and hidden from %s because you are not on %s's list of authorised friends. If you feel you should be on %s's list then please send an in-game mail."; -- Spanish (Spain) elseif(client_area == "esES") then -- silent whisper sent to blocked players who send a message. MSG_BLOCKED1 = "Important: Your whisper was rejected and hidden from %s because you are not on %s's list of authorised friends. If you feel you should be on %s's list then please send an in-game mail."; -- Mexico elseif(client_area == "esMX") then -- silent whisper sent to blocked players who send a message. MSG_BLOCKED1 = "Important: Your whisper was rejected and hidden from %s because you are not on %s's list of authorised friends. If you feel you should be on %s's list then please send an in-game mail."; end; end;
-- -- The Roller, or Metal Former, takes various metals or plates and forms them into other shapes. -- local Directions = assert(foundation.com.Directions) local is_blank = assert(foundation.com.is_blank) local itemstack_is_blank = assert(foundation.com.itemstack_is_blank) local format_pretty_time = assert(foundation.com.format_pretty_time) local metaref_dec_float = assert(foundation.com.metaref_dec_float) local cluster_devices = assert(yatm.cluster.devices) local Energy = assert(yatm.energy) local ItemInterface = assert(yatm.items.ItemInterface) local rolling_registry = assert(yatm.rolling.rolling_registry) local fspec = assert(foundation.com.formspec.api) local function get_roller_formspec(pos, user) local spos = pos.x .. "," .. pos.y .. "," .. pos.z local node_inv_name = "nodemeta:" .. spos local cio = fspec.calc_inventory_offset return yatm.formspec_render_split_inv_panel(user, 8, 2, { bg = "machine" }, function (loc, rect) if loc == "main_body" then return fspec.list(node_inv_name, "roller_input", rect.x, rect.y, 1, 1) .. fspec.list(node_inv_name, "roller_processing", rect.x + cio(2), rect.y, 1, 1) .. fspec.list(node_inv_name, "roller_output", rect.x + cio(4), rect.y, 1, 1) elseif loc == "footer" then return fspec.list_ring(node_inv_name, "roller_input") .. fspec.list_ring("current_player", "main") .. fspec.list_ring(node_inv_name, "roller_output") .. fspec.list_ring("current_player", "main") end return "" end) end function roller_refresh_infotext(pos) local meta = minetest.get_meta(pos) local recipe_time = meta:get_float("recipe_time") local recipe_time_max = meta:get_float("recipe_time_max") local infotext = cluster_devices:get_node_infotext(pos) .. "\n" .. "Energy: " .. Energy.meta_to_infotext(meta, yatm.devices.ENERGY_BUFFER_KEY) .. "\n" .. "Time Remaining: " .. format_pretty_time(recipe_time) .. " / " .. format_pretty_time(recipe_time_max) meta:set_string("infotext", infotext) end local roller_yatm_network = { kind = "machine", groups = { machine_worker = 1, energy_consumer = 1, }, default_state = "off", states = { conflict = "yatm_machines:roller_error", error = "yatm_machines:roller_error", off = "yatm_machines:roller_off", on = "yatm_machines:roller_on", }, energy = { capacity = 4000, network_charge_bandwidth = 200, passive_lost = 0, startup_threshold = 100, } } function roller_yatm_network:work(ctx) local pos = ctx.pos local node = ctx.node local meta = ctx.meta local dtime = ctx.dtime local energy_consumed = 0 local inv = meta:get_inventory() do local processing_stack = inv:get_stack("roller_processing", 1) if itemstack_is_blank(processing_stack) then local input_stack = inv:get_stack("roller_input", 1) if not itemstack_is_blank(input_stack) then local recipe = RollerRegistry:get_roller_recipe(input_stack) if recipe then local consumed_stack = input_stack:peek_item(recipe.required_count) print("Taking", consumed_stack:to_string(), "for recipe", recipe.result:to_string()) -- FIXME: once the deltas are being used instead of fixed time, this can be changed meta:set_float("recipe_time", recipe.duration) meta:set_float("recipe_time_max", recipe.duration) inv:remove_item("roller_input", consumed_stack) inv:set_stack("roller_processing", 1, consumed_stack) else yatm.devices.set_idle(meta, 2) end end end end do local processing_stack = inv:get_stack("roller_processing", 1) if not itemstack_is_blank(processing_stack) then if metaref_dec_float(meta, "recipe_time", dtime) <= 0 then local recipe = RollerRegistry:get_roller_recipe(processing_stack) if recipe then if inv:room_for_item("roller_output", recipe.result) then print("Adding to roller_output", recipe.result:to_string()) inv:add_item("roller_output", recipe.result) inv:set_stack("roller_processing", 1, ItemStack(nil)) meta:set_float("recipe_time", 0) meta:set_float("recipe_time_max", 0) yatm.queue_refresh_infotext(pos, node) end end else energy_consumed = energy_consumed + 5 end end end return energy_consumed end local item_interface = ItemInterface.new_directional(function (self, pos, dir) local node = minetest.get_node(pos) local new_dir = Directions.facedir_to_face(node.param2, dir) if new_dir == Directions.D_UP or new_dir == Directions.D_DOWN then return "roller_output" end return "roller_input" end) yatm.devices.register_stateful_network_device({ basename = "yatm_machines:roller", description = "Roller", groups = { cracky = 1, item_interface_in = 1, item_interface_out = 1, yatm_energy_device = 1, }, drop = roller_yatm_network.states.off, sounds = yatm.node_sounds:build("metal"), tiles = { "yatm_roller_top.off.png", "yatm_roller_bottom.png", "yatm_roller_side.off.png", "yatm_roller_side.off.png^[transformFX", "yatm_roller_back.off.png", "yatm_roller_front.off.png" }, paramtype = "none", paramtype2 = "facedir", on_construct = function (pos) yatm.devices.device_on_construct(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() inv:set_size("roller_input", 1) inv:set_size("roller_processing", 1) inv:set_size("roller_output", 1) end, on_rightclick = function (pos, node, user) minetest.show_formspec( user:get_player_name(), "yatm_machines:roller", get_roller_formspec(pos, user) ) end, can_dig = function (pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() return inv:is_empty("roller_input") and inv:is_empty("roller_processing") and inv:is_empty("roller_output") end, yatm_network = roller_yatm_network, item_interface = item_interface, refresh_infotext = roller_refresh_infotext, }, { error = { tiles = { "yatm_roller_top.error.png", "yatm_roller_bottom.png", "yatm_roller_side.error.png", "yatm_roller_side.error.png^[transformFX", "yatm_roller_back.error.png", "yatm_roller_front.error.png" }, }, on = { tiles = { "yatm_roller_top.on.png", "yatm_roller_bottom.png", "yatm_roller_side.on.png", "yatm_roller_side.on.png^[transformFX", "yatm_roller_back.on.png", { name = "yatm_roller_front.on.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.25 }, }, }, } })
--- -- Lua module to use a hd44780 compatible LCD display with the Raspberry Pi GPIO interface. -- @module GPIO.lcd-hd44780 -- -- based on code from lrvick, LiquidCrystal and Adafruit -- -- lrvic - `https://github.com/lrvick/raspi-hd44780/blob/master/hd44780.py` -- -- LiquidCrystal - `https://github.com/arduino/Arduino/blob/master/libraries/LiquidCrystal/LiquidCrystal.cpp` -- -- Adafruit - `https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/blob/master/Adafruit_CharLCD/Adafruit_CharLCD.py` -- -- @copyright (c); Adafruit for the Python library, Thijs Schreijer for the Lua migration -- Load some modules local GPIO = require("GPIO") local bit32 = bit32 or require("bit32") pcall(require, "socket") -- try and load LuaSocket for the sleep function -- create some shortcuts local bor, band, bnot, btest = bit32.bor, bit32.band, bit32.bnot, bit32.btest local M = {} -- module table to export -- commands M.LCD_CLEARDISPLAY = 0x01 M.LCD_RETURNHOME = 0x02 M.LCD_ENTRYMODESET = 0x04 M.LCD_DISPLAYCONTROL = 0x08 M.LCD_CURSORSHIFT = 0x10 M.LCD_FUNCTIONSET = 0x20 M.LCD_SETCGRAMADDR = 0x40 M.LCD_SETDDRAMADDR = 0x80 -- flags for display entry mode M.LCD_ENTRYRIGHT = 0x00 M.LCD_ENTRYLEFT = 0x02 M.LCD_ENTRYSHIFTINCREMENT = 0x01 M.LCD_ENTRYSHIFTDECREMENT = 0x00 -- flags for display on/off control M.LCD_DISPLAYON = 0x04 M.LCD_DISPLAYOFF = 0x00 M.LCD_CURSORON = 0x02 M.LCD_CURSOROFF = 0x00 M.LCD_BLINKON = 0x01 M.LCD_BLINKOFF = 0x00 -- flags for display/cursor shift M.LCD_DISPLAYMOVE = 0x08 M.LCD_CURSORMOVE = 0x00 -- flags for display/cursor shift M.LCD_DISPLAYMOVE = 0x08 M.LCD_CURSORMOVE = 0x00 M.LCD_MOVERIGHT = 0x04 M.LCD_MOVELEFT = 0x00 -- flags for function set M.LCD_8BITMODE = 0x10 M.LCD_4BITMODE = 0x00 M.LCD_2LINE = 0x08 M.LCD_1LINE = 0x00 M.LCD_5x10DOTS = 0x04 M.LCD_5x8DOTS = 0x00 -- actually writes a byte of data to the display unit. -- a byte is writen as 2x 4bits -- @param self the LCD object to use -- @param bits a byte value (0-255) containing the bits to write -- @param char_mode a boolean (optional) indicating whether character mode is to be used (true), or command mode (false) local function write4bits(self, bits, char_mode) if char_mode then char_mode=true else char_mode=false end M.delayMicroseconds(1000) -- 1000 microsecond sleep GPIO.output(self.pin_rs, char_mode) for n = 1, 2 do for i, pin in ipairs(self.pin_db) do local bit = (2-n)*4 + (i-1) local val = (btest(bits, 2^bit)) GPIO.output(pin, val) --print(" ", pin, val, "i="..i, "n="..n) end self:pulseEnable() end end --- -- Sets the display size. -- @param self display object -- @param cols nr of columns -- @param lines nr of lines local function begin(self, cols, lines) if (lines > 1) then self.numlines = lines self.displayfunction = bor(self.displayfunction, M.LCD_2LINE) self.currline = 0 end end local function home(self) write4bits(self, M.LCD_RETURNHOME) -- set cursor position to zero M.delayMicroseconds(3000) -- this command takes a long time! end local function clear(self) write4bits(self, M.LCD_CLEARDISPLAY) -- command to clear display M.delayMicroseconds(3000) -- 3000 microsecond sleep, clearing the display takes a long time end local row_offsets = { 0x00, 0x40, 0x14, 0x54 } local function setCursor(self, col, row) if row > self.numlines then row = self.numlines - 1 -- we count rows starting w/0 end --TODO does python index from 0 ??? write4bits(self, bor(M.LCD_SETDDRAMADDR, (col + row_offsets[row]))) end local function noDisplay(self) self.displaycontrol = band(self.displaycontrol, bnot(M.LCD_DISPLAYON)) write4bits(bor(self, M.LCD_DISPLAYCONTROL, self.displaycontrol)) end local function display(self) self.displaycontrol = bor(self.displaycontrol, M.LCD_DISPLAYON) write4bits(self, bor(M.LCD_DISPLAYCONTROL, self.displaycontrol)) end local function noCursor(self) self.displaycontrol = band(self.displaycontrol, bnot(M.LCD_CURSORON)) write4bits(self, bor(M.LCD_DISPLAYCONTROL, self.displaycontrol)) end local function cursor(self) self.displaycontrol = bor(self.displaycontrol, M.LCD_CURSORON) write4bits(self, bor(M.LCD_DISPLAYCONTROL, self.displaycontrol)) end local function noBlink(self) self.displaycontrol = band(self.displaycontrol, bnot(M.LCD_BLINKON)) write4bits(self, bor(M.LCD_DISPLAYCONTROL, self.displaycontrol)) end local function blink(self) self.displaycontrol = bor(self.displaycontrol, M.LCD_BLINKON) write4bits(self, bor(M.LCD_DISPLAYCONTROL, self.displaycontrol)) end local function scrollDisplayLeft(self) write4bits(self, bor(M.LCD_CURSORSHIFT, M.LCD_DISPLAYMOVE, M.LCD_MOVELEFT)) end local function scrollDisplayRight(self) write4bits(self, bor(M.LCD_CURSORSHIFT, M.LCD_DISPLAYMOVE, M.LCD_MOVERIGHT)) end local function leftToRight(self) self.displaymode = bor(self.displaycontrol, M.LCD_ENTRYLEFT) write4bits(self, bor(M.LCD_ENTRYMODESET, self.displaymode)) end local function rightToLeft(self) self.displaymode = band(self.displaymode, bnot(M.LCD_ENTRYLEFT)) write4bits(self, bor(M.LCD_ENTRYMODESET, self.displaymode)) end local function autoscroll(self) self.displaymode = bor(self.displaycontrol, M.LCD_ENTRYSHIFTINCREMENT) write4bits(self, bor(M.LCD_ENTRYMODESET, self.displaymode)) end local function noAutoscroll(self) self.displaymode = band(self.displaymode, bnot(M.LCD_ENTRYSHIFTINCREMENT)) write4bits(self, bor(M.LCD_ENTRYMODESET, self.displaymode)) end local function pulseEnable(self) GPIO.output(self.pin_e, false) M.delayMicroseconds(1) -- 1 microsecond pause - enable pulse must be > 450ns GPIO.output(self.pin_e, true) M.delayMicroseconds(1) -- 1 microsecond pause - enable pulse must be > 450ns GPIO.output(self.pin_e, false) M.delayMicroseconds(37) -- commands need > 37us to settle end local function message(self, text) text = text:gsub("\n", string.char(0xC0)) for i = 1, #text do local c = text:byte(i) write4bits(self, c, (c ~= 0xC0)) -- newline should pass 'false' end end --- -- This function will sleep for a number om micro (NOT milli!) seconds. -- On first call it will replace itself with a new implementation based on LuaSocket -- or the OS. NOTE: the OS version is really slow! -- @param microseconds number of microseconds to sleep function M.delayMicroseconds(microseconds) local sleep = (package.loaded.socket or {}).sleep if sleep then -- use LuaSocket sleep function M.delayMicroseconds = function(microseconds) sleep(microseconds/1000000) end else -- LuaSocket sleep function not found, so go and use OS M.delayMicroseconds = function(microseconds) os.execute(string.format("sleep %.6f", microseconds/1000000)) end end return M.delayMicroseconds(microseconds) -- invoke the new implementation end --- Creates a new display object with its pin configuration. -- @param pin_rs pin number for rs (according to current pin numbering scheme) -- @param pin_e pin number for e (according to current pin numbering scheme) -- @param pin_db table/list with 4 pin numbers for data (according to current pin numbering scheme) -- @return New display object function M.initialize(pin_rs, pin_e, pin_db) local self = { pin_rs = pin_rs, pin_e = pin_e, pin_db = { pin_db[1], pin_db[2], pin_db[3], pin_db[4] } } GPIO.setup(self.pin_rs, GPIO.OUT) GPIO.setup(self.pin_e, GPIO.OUT) for i, pin in ipairs(self.pin_db) do GPIO.setup(pin, GPIO.OUT) end self.displaycontrol = bor(M.LCD_DISPLAYON, M.LCD_CURSOROFF, M.LCD_BLINKOFF) self.displayfunction = bor(M.LCD_4BITMODE, M.LCD_1LINE, M.LCD_5x8DOTS, M.LCD_2LINE) self.displaymode = bor(M.LCD_ENTRYLEFT, M.LCD_ENTRYSHIFTDECREMENT) self.begin = begin self.home = home self.clear = clear self.setCursor = setCursor self.noDisplay = noDisplay self.display = display self.noCursor = noCursor self.cursor = cursor self.noBlink = noBlink self.blink = blink self.scrollDisplayLeft = scrollDisplayLeft self.scrollDisplayRight = scrollDisplayRight self.leftToRight = leftToRight self.rightToLeft = rightToLeft self.autoScroll = autoScroll self.noAutoScroll = noAutoScroll self.pulseEnable = pulseEnable self.message = message write4bits(self, 0x33) -- initialization write4bits(self, 0x32) -- initialization write4bits(self, 0x28) -- 2 line 5x7 matrix write4bits(self, 0x0C) -- turn cursor off 0x0E to enable cursor write4bits(self, 0x06) -- shift cursor right write4bits(self, bor(M.LCD_ENTRYMODESET, self.displaymode)) -- set the entry mode self:clear() return self end return M
local games = require "src.games" local title = true local success = false local failure = false local updateTime = 0.2 local gameTime = 0 local game = games.create() function love.load() math.randomseed(os.time()) end function love.update(deltaTime) if (not title and not success and not failure) then gameTime = gameTime + deltaTime if (gameTime > updateTime) then gameTime = gameTime % updateTime local state = game.tick() if (state ~= nil) then success = state failure = not state end end end end function love.draw() game.draw(gameTime / updateTime) if (title) then love.graphics.draw(love.graphics.newImage("res/title.png"), 0, 0) elseif (success) then love.graphics.draw(love.graphics.newImage("res/success.png"), 0, 0) elseif (failure) then love.graphics.draw(love.graphics.newImage("res/failure.png"), 0, 0) end end function love.keypressed(key) if (key == 'escape') then love.event.quit() end if (title) then title = false elseif (success or failure) then game = games.create() success = false failure = false else if (key == 'up') then game.rogue.command(0, -1) elseif (key == 'down') then game.rogue.command(0, 1) elseif (key == 'left') then game.rogue.command(-1, 0) elseif (key == 'right') then game.rogue.command(1, 0) end end end
local jsp = require("./jspower.lua") local String = jsp.String print(String.fromCharCode(97)) -- a print(String.charAt("hello, world!",8)) -- w print(String.charCodeAt("hello, world!",8)) -- 119 print(String.concat("hello,", " lua!")) -- hello, lua! print(String.startsWith("banana", "ba")) -- true print(String.endsWith("coconut", "nut")) -- true print(String.includes("javascript", "vasc")) -- true -- Alternatively, use jsp.extendLuaString() jsp.extendLuaString() -- After this, you can do: print(("hello, world!"):charAt(8)) -- w print(("hello,"):concat(" lua!")) -- hello, lua! print(("banana"):startsWith("ba")) -- true print(("coconut"):endsWith("nut")) -- true print(("javascript"):includes("vasc")) -- true local str = " trim me daddy " print(str:trim()) -- "trim me daddy" print(str:trimEnd()) -- " trim me daddy" print(str:trimStart()) -- "trim me daddy " local str = "Use the power of JS in Lua" print(str:split(" ")) -- { "Use", "the", "power", "of", "JS", "in", "Lua" } print(str:split("JS")) -- { "Use the power of ", " in Lua" } print(str:toUpperCase()) -- USE THE POWER OF JS IN LUA print(str:toLowerCase()) -- use the power of js in lua
-- Random utilities local glmath = require("moonglmath") local random = math.random local randomseed = math.randomseed local pi = math.pi local sqrt = math.sqrt local sin, cos = math.sin, math.cos local vec3 = glmath.vec3 local function uniform_hemisphere() local x1, x2 = random(), random() local s = sqrt(1.0- x1*x1) local pi2x2 = 2*pi*x2 return vec3(cos(pi2x2)*s, sin(pi2x2)*s, x1) end local function uniform_circle() local x = random() local pi2x = 2*pi*x return vec3(cos(pi2x), sin(pi2x), 0) end local function shuffle(t) -- Shuffles the elements of table t (in place) so that each ordering has the same probability -- Rfr: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm local n = #t local j for i = 1, n-1 do j = random(i, n) -- random integer s.t. i <= j < n+1 t[i], t[j] = t[j], t[i] end end return { seed = randomseed, uniform = random, uniform_hemisphere = uniform_hemisphere, uniform_circle = uniform_circle, shuffle = shuffle, }
-- Autogenerated from KST: please remove this line if doing any edits by hand! local luaunit = require("luaunit") require("nav_parent3") TestNavParent3 = {} function TestNavParent3:test_nav_parent3() local r = NavParent3:from_file("src/nav_parent2.bin") luaunit.assertEquals(r.ofs_tags, 8) luaunit.assertEquals(r.num_tags, 2) luaunit.assertEquals(r.tags[1].name, "RAHC") luaunit.assertEquals(r.tags[1].ofs, 32) luaunit.assertEquals(r.tags[1].num_items, 3) luaunit.assertEquals(r.tags[1].tag_content.content, "foo") luaunit.assertEquals(r.tags[2].name, "RAHC") luaunit.assertEquals(r.tags[2].ofs, 35) luaunit.assertEquals(r.tags[2].num_items, 6) luaunit.assertEquals(r.tags[2].tag_content.content, "barbaz") end
-- ADADELTA -- For single worker only -- Author: Minwei Feng (mfeng@us.ibm.com) require 'optim' function optim.adadeltasingle(opfunc, w, config, state) local config = config or {} local state = state or config local rho = config.rho or 0.9 local epsilon = config.epsilon or 1e-6 local pc = config.pclient or nil local lr = config.lr state.pversion = state.pversion or 0 local fx,dfdx = opfunc(w) if not state.paramVariance then state.paramVariance = torch.Tensor():typeAs(w):resizeAs(dfdx):zero() state.paramStd = torch.Tensor():typeAs(w):resizeAs(dfdx):zero() state.delta = torch.Tensor():typeAs(w):resizeAs(dfdx):zero() state.accDelta = torch.Tensor():typeAs(w):resizeAs(dfdx):zero() end state.paramVariance:mul(rho):addcmul(1-rho,dfdx,dfdx) state.paramStd:resizeAs(state.paramVariance):copy(state.paramVariance):add(epsilon):sqrt() state.delta:resizeAs(state.paramVariance):copy(state.accDelta):add(epsilon):sqrt():cdiv(state.paramStd):cmul(dfdx) w:add(-lr, state.delta) state.accDelta:mul(rho):addcmul(1-rho, state.delta, state.delta) state.pversion = state.pversion + 1 -- send pc:async_send_param() pc:wait() return w,{fx} end
CheckTimer = {} playerElement = nil function CreateCheckWindow() Window = {} Button = {} Label = {} Image = {} Window[1] = guiCreateWindow(28,271,454,248,"Player check.",false) --Button[1] = guiCreateButton(0.3524,0.8387,0.2026,0.0968,"Recon player.",true,Window[1]) --addEventHandler( "onClientGUIClick", Button[1], ReconPlayer) --Button[2] = guiCreateButton(0.5705,0.8387,0.2026,0.0968,"Freeze player.",true,Window[1]) --addEventHandler( "onClientGUIClick", Button[2], FreezePlayer) Button[3] = guiCreateButton(0.7885,0.8387,0.1894,0.0968,"Close window.",true,Window[1]) addEventHandler( "onClientGUIClick", Button[3], CloseCheck ) Label[1] = guiCreateLabel(0.0529,0.1331,0.9524,0.0887,"Name: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[1],"top") guiLabelSetHorizontalAlign(Label[1],"left",false) Label[2] = guiCreateLabel(0.0529,0.2056,0.3524,0.0887,"IP: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[2],"top") guiLabelSetHorizontalAlign(Label[2],"left",false) Label[3] = guiCreateLabel(0.0529,0.3823,0.9524,0.0887,"Money: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[3],"top") guiLabelSetHorizontalAlign(Label[3],"left",false) Label[4] = guiCreateLabel(0.0529,0.4556,0.2093,0.0806,"Health: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[4],"top") guiLabelSetHorizontalAlign(Label[4],"left",false) Label[5] = guiCreateLabel(0.2621,0.4516,0.2093,0.0806,"Armour: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[5],"top") guiLabelSetHorizontalAlign(Label[5],"left",false) Label[6] = guiCreateLabel(0.0529,0.5323,0.2093,0.0806,"Skin: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[6],"top") guiLabelSetHorizontalAlign(Label[6],"left",false) Label[7] = guiCreateLabel(0.2621,0.5242,0.2093,0.0806,"Weapon: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[7],"top") guiLabelSetHorizontalAlign(Label[7],"left",false) Label[8] = guiCreateLabel(0.0529,0.6048,0.4531,0.0806,"Faction: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[8],"top") guiLabelSetHorizontalAlign(Label[8],"left",false) Label[9] = guiCreateLabel(0.0529,0.6773,0.2093,0.0806,"Ping: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[9],"top") guiLabelSetHorizontalAlign(Label[9],"left",false) Label[10] = guiCreateLabel(0.0529,0.804,0.2093,0.0806,"Vehicle: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[10],"top") guiLabelSetHorizontalAlign(Label[10],"left",false) Label[11] = guiCreateLabel(0.0529,0.8806,0.2093,0.0806,"Vehicle ID: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[11],"top") guiLabelSetHorizontalAlign(Label[11],"left",false) Label[12] = guiCreateLabel(0.5441,0.4435,0.4031,0.0766,"Location: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[12],"top") guiLabelSetHorizontalAlign(Label[12],"left",false) Label[18] = guiCreateLabel(0.5441,0.36035,0.4031,0.0766,"Admin Reports: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[18],"top") guiLabelSetHorizontalAlign(Label[18],"left",false) Label[13] = guiCreateLabel(0.5441,0.5323,0.4031,0.0766,"X:",true,Window[1]) guiLabelSetVerticalAlign(Label[13],"top") guiLabelSetHorizontalAlign(Label[13],"left",false) Label[14] = guiCreateLabel(0.5441,0.6169,0.4031,0.0766,"Y: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[14],"top") guiLabelSetHorizontalAlign(Label[14],"left",false) Label[15] = guiCreateLabel(0.5441,0.7056,0.4031,0.0766,"Z: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[15],"top") guiLabelSetHorizontalAlign(Label[15],"left",false) Label[16] = guiCreateLabel(0.6674,0.129,0.2907,0.0806,"Interior: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[16],"top") guiLabelSetHorizontalAlign(Label[16],"left",false) Label[17] = guiCreateLabel(0.6674,0.1935,0.2907,0.0806,"Dimension: N/A",true,Window[1]) guiLabelSetVerticalAlign(Label[17],"top") guiLabelSetHorizontalAlign(Label[17],"left",false) Image[1] = guiCreateStaticImage(0.4758,0.1089,0.1278,0.2177,"search.png",true,Window[1]) guiSetVisible(Window[1], false) end addEventHandler("onClientResourceStart", getResourceRootElement(getThisResource()), function () CreateCheckWindow() end ) function OpenCheck(watcher,noob,x,y,z,ip,health,armour,skin,weapon,team,ping,carid,carname,loc,int,world,gameaccountusername, money, bankmoney, adminreports) playerElement = noob guiSetText ( Label[1], "Name: " .. noob .. " (" .. gameaccountusername .. ")") guiSetText ( Label[13], "X: " .. x ) guiSetText ( Label[14], "Y: " .. y ) guiSetText ( Label[15], "Z: " .. z ) guiSetText ( Label[2], "IP: " .. ip ) guiSetText ( Label[3], "Money: " .. money .. "$ (Bank: " .. bankmoney .. "$)") guiSetText ( Label[4], "Health: " .. health ) guiSetText ( Label[5], "Armour: " .. armour ) guiSetText ( Label[6], "Skin: " .. skin ) guiSetText ( Label[7], "Weapon: " .. weapon ) if(team ~= nil) then guiSetText ( Label[8], "Faction: " .. team ) else guiSetText ( Label[8], "Faction: N/A") end guiSetText ( Label[9], "Ping: " .. ping ) if(carname ~= nil) then guiSetText ( Label[10], "Vehicle: " .. carname ) guiSetText ( Label[11], "Vehicle ID: " .. carid ) else guiSetText ( Label[10], "Vehicle: N/A") guiSetText ( Label[11], "Vehicle ID: N/A") end guiSetText ( Label[12], "Location: " .. loc) guiSetText ( Label[16], "Interior: " .. int) guiSetText ( Label[17], "Dimension: " .. world) guiSetText ( Label[18], "Admin Reports: " .. adminreports) if(guiGetVisible ( Window[1] ) == false) then guiSetVisible(Window[1], true) showCursor ( true ) local event = function() triggerServerEvent ( "onChecking", getRootElement(), watcher,noob) end --CheckTimer = setTimer( event, 2000, 0) end end addEvent( "onCheck", true ) addEventHandler( "onCheck", getRootElement(), OpenCheck ) function CloseCheck(sourcePlayer, command) guiSetVisible(Window[1], false) showCursor ( false ) if(CheckTimer ~= false and CheckTimer ~= nil) then end end function ReconPlayer() triggerServerEvent("remoteReconPlayer", getLocalPlayer(), getLocalPlayer(), "recon", playerElement) end function FreezePlayer() triggerServerEvent("remoteFreezePlayer", getLocalPlayer(), getLocalPlayer(), "freeze", playerElement) end
-- // Name: http.lua -- // Description: HTTP request handler -- // Author: @Jumpathy -- // Credits: @evaera (promises) local http,internal = {},{}; local httpService = game:GetService("HttpService"); local promise = require(script:WaitForChild("promise")); local encode = function(...) return httpService:JSONEncode(...); end function http.encode(query) return game:GetService("HttpService"):UrlEncode(query); end function http.request(method,url,headers,body) return promise.async(function(resolve,reject) local success,response = pcall(httpService.RequestAsync,httpService,{ Url = url, Method = method, Headers = headers, Body = (body ~= nil and ((type(body) == "table" and encode(body) or body)) or nil) }); if(success and (response.StatusCode == 200)) then resolve(response); else reject(response); end end) end return http;
for i,arg1 in pairs(arg) do print(i,arg1) end
--[[ Jamba - Jafula's Awesome Multi-Boxer Assistant Copyright 2008 - 2015 Michael "Jafula" Miller License: The MIT License ]]-- local L = LibStub("AceLocale-3.0"):NewLocale( "Jamba-Team", "enUS", true ) L["Slash Commands"] = true L["Team"] = true L["Core: Team"] = true L["Add"] = true L["Add a member to the team list."] = true L["Remove"] = true L["Remove a member from the team list."] = true L["Master"] = true L["Set the master character."] = true L["I Am Master"] = true L["Set this character to be the master character."] = true L["Invite"] = true L["Invite team members to a party."] = true L["Disband"] = true L["Disband all team members from their parties."] = true L["Push Settings"] = true L["Push the team settings to all characters in the team."] = true L["Team List"] = true L["Up"] = true L["Down"] = true L["Set Master"] = true L["Master Control"] = true L["When Focus changes, set the Master to the Focus."] = true L["When Master changes, promote Master to party leader."] = true L["Party Invitations Control"] = true L["Accept from team."] = true L["Accept from friends."] = true L["Accept from guild."] = true L["Decline from strangers."] = true L["Party Loot Control"] = true L["Automatically set the Loot Method to..."] = true L["Free For All"] = true L["Master Looter"] = true L["Slaves Opt Out of Loot"] = true L["Slave"] = true L["(Offline)"] = true L["Enter name of character to add:"] = true L["Are you sure you wish to remove %s from the team list?"] = true L["A is not in my team list. I can not set them to be my master."] = function( characterName ) return characterName.." is not in my team list. I can not set them to be my master." end L["Settings received from A."] = function( characterName ) return "Settings received from "..characterName.."." end L["Jamba-Team"] = true L["Invite Team To Group"] = true L["Disband Group"] = true L["Override: Set loot to Group Loot if stranger in group."] = true L["Add Party Members"] = true L["Add members in the current party to the team."] = true L["Friends Are Not Strangers"] = true L["Remove All Members"] = true L["Remove all members from the team."] = true L["Auto activate click-to-move on Slaves and deactivate on Master."] = true
local druid = require("druid.druid") local druid_style = require("example.ysdkdebug.druid_style") local yagames = require("yagames.yagames") local log_print = require("example.ysdkdebug.log_print") local print = log_print.print local M = {} function M.init(self) local is_desktop = gui.get_node("text_is_desktop") local is_mobile = gui.get_node("text_is_mobile") local is_tablet = gui.get_node("text_is_tablet") local alpha1 = vmath.vector4(0, 0, 0, 1) local alpha2 = vmath.vector4(0, 0, 0, 0.25) gui.set_color(is_desktop, yagames.device_info_is_desktop() and alpha1 or alpha2) gui.set_color(is_mobile, yagames.device_info_is_mobile() and alpha1 or alpha2) gui.set_color(is_tablet, yagames.device_info_is_tablet() and alpha1 or alpha2) print("yagames.device_info_type():", yagames.device_info_type()) end return M
if SL.Global.GameMode == "StomperZ" then return end local player = ... local playerStats = STATSMAN:GetCurStageStats():GetPlayerStageStats(player) local grade = playerStats:GetGrade() local style = ThemePrefs.Get("VisualTheme") local c = GetCurrentColor() -- "I passd with a q though." local title = GAMESTATE:GetCurrentSong():GetDisplayFullTitle() if title == "D" then grade = "Grade_Tier99" end local t = Def.ActorFrame{} t[#t+1] = LoadActor(THEME:GetPathG("", "_grades/"..grade..".lua"), playerStats)..{ InitCommand=function(self) self:x(70 * (player==PLAYER_1 and -1 or 1)) self:y(_screen.cy-134):diffusealpha(0):zoom(0.45) if AllowThonk() then self:bob():effectmagnitude(0,3,0) end end, OnCommand=function(self) self:diffusealpha(0):sleep(2.25):smooth(0.1):zoom(0.4):diffusealpha(1) end } t[#t+1] = LoadActor(THEME:GetPathG("", "_VisualStyles/"..style.."/Combo 100milestone splode"))..{ InitCommand=function(self) self:xy(70 * (player==PLAYER_1 and -1 or 1), _screen.cy - 134):diffusealpha(0):blend("BlendMode_Add") end, OnCommand=function(self) self:sleep(2.35):diffuse(c):rotationz(10):zoom(0.25):diffusealpha(.6):decelerate(0.6):rotationz(0):zoom(2):diffusealpha(0) end } t[#t+1] = LoadActor(THEME:GetPathG("", "_VisualStyles/"..style.."/Combo 100milestone splode"))..{ InitCommand=function(self) self:xy(70 * (player==PLAYER_1 and -1 or 1), _screen.cy - 134):diffusealpha(0):blend("BlendMode_Add") end, OnCommand=function(self) self:sleep(2.35):diffuse(c):rotationz(40):zoom(0.25):diffusealpha(.6):decelerate(0.6):rotationz(20):zoom(1):diffusealpha(0) end } t[#t+1] = LoadActor(THEME:GetPathG("", "_VisualStyles/"..style.."/Combo 100milestone minisplode"))..{ InitCommand=function(self) self:xy(70 * (player==PLAYER_1 and -1 or 1), _screen.cy - 134):diffusealpha(0):blend("BlendMode_Add") end, OnCommand=function(self) self:sleep(2.35):diffuse(c):rotationz(10):zoom(0.25):diffusealpha(1):decelerate(0.4):rotationz(0):zoom(1.8):diffusealpha(0) end } return t
----------------------------------- -- Area: Labyrinth of Onzozo -- Mob: Labyrinth Manticore -- Note: Place holder Narasimha ----------------------------------- local ID = require("scripts/zones/Labyrinth_of_Onzozo/IDs") require("scripts/globals/regimes") require("scripts/globals/mobs") ----------------------------------- function onMobDeath(mob, player, isKiller) tpz.regime.checkRegime(player, mob, 775, 2, tpz.regime.type.GROUNDS) end function onMobDespawn(mob) tpz.mob.phOnDespawn(mob, ID.mob.NARASIMHA_PH, 5, math.random(21600, 36000)) -- 6 to 10 hours end
local KUI, E, L, V, P, G = unpack(select(2, ...)) local FQ = KUI:NewModule("FlightQueue", "AceEvent-3.0", "AceTimer-3.0") local queueSlotIndex = 0 local queueIsFerry = false local queueNodeID = 0 local queueContinent = 0 local bypass = false --local changed = false --local firstRun = false function GetCurrentMapContinent(relative) local currentMapId = WorldMapFrame:GetMapID() or 0 if relative == "player" then currentMapId = C_Map.GetBestMapForUnit('player') end local continentInfo = MapUtil.GetMapParentInfo(currentMapId, Enum.UIMapType.Continent, true) if continentInfo then return continentInfo.mapID else return 0 end end function OnUpdateHandler(poi) poi:SetSize(24,24) end function OnEnterHandler(poi) for i in pairs(nodes) do if nodes[i].name == poi.name then GameTooltip:SetOwner(poi, "ANCHOR_RIGHT") GameTooltip:SetText("|cfff960d9KlixUI|r: "..nodes[i].name) GameTooltip:Show() end end end function ClickHandler(poi,button) local c = GetCurrentMapContinent() if button == "LeftButton" then local poiIsFerry = string.find(poi.Texture:GetAtlas(), "Ferry") for i in pairs(nodes) do local nodeIsFerry = nodes[i].textureKitPrefix == "FlightMaster_Ferry" if nodes[i].name == poi.name then if (poiIsFerry and nodeIsFerry) or (not poiIsFerry and not nodeIsFerry) then if queueSlotIndex == nodes[i].slotIndex then queueSlotIndex = 0 queueNodeID = 0 KUI:Print("Flight Point Cleared") return elseif fcontinent[c] ~= nil then queueSlotIndex = nodes[i].slotIndex queueNodeID = nodes[i].nodeID queueIsFerry = poiIsFerry queueContinent = c KUI:Print(nodes[i].name) return end end end end if fcontinent[c] == true then KUI:Print("You have not visited a flight master on this continent yet.") else KUI:Print(TAXI_PATH_UNREACHABLE) --Not Discovered end end end --[[function FQ:ZONE_CHANGED_NEW_AREA() changed = true KUI:Print(changed) end]] function FQ:TAXIMAP_OPENED() local newnodes = C_TaxiMap:GetAllTaxiNodes() if nodes == nil then nodes = newnodes for k in pairs(nodes) do if nodes[k].state == Enum.FlightPathState.Unreachable then nodes[k]=nil end end end local added = "" for k in pairs(newnodes) do if newnodes[k].state ~= Enum.FlightPathState.Unreachable then local mergeNode = true for K in pairs(nodes) do if nodes[K].nodeID == newnodes[k].nodeID then mergeNode = false nodes[K].state=newnodes[k].state end end if mergeNode == true then table.insert(nodes,newnodes[k]) added = added..string.match(newnodes[k].name, "(.+),")..", " end end end if added~="" then KUI:Print("New Nodes: "..string.sub(added,1,-3)) end fcontinent[GetCurrentMapContinent("player")]=false if queueSlotIndex > 0 then bypass = false local nodeState local destinationIsFerry local departureIsFerry for k in pairs(newnodes) do if newnodes[k].nodeID == queueNodeID then nodeState=newnodes[k].state destinationIsFerry = newnodes[k].textureKitPrefix == "FlightMaster_Ferry" end if newnodes[k].state==0 then --KUI:Print(newnodes[k].textureKitPrefix) departureIsFerry = newnodes[k].textureKitPrefix == "FlightMaster_Ferry" end end --KUI:Print(departureIsFerry) --KUI:Print(destinationIsFerry) if IsShiftKeyDown()~=true and GetCurrentMapContinent("player") == queueContinent and ((departureIsFerry and destinationIsFerry) or (not departureIsFerry and not destinationIsFerry)) and nodeState==1 then TakeTaxiNode(queueSlotIndex); for i=1,8 do C_Timer.After(i/4,function () if UnitOnTaxi("player") == false then TakeTaxiNode(queueSlotIndex) end;end) end elseif IsShiftKeyDown() then bypass = true end end end function FQ:PLAYER_CONTROL_LOST() if bypass == false then if queueSlotIndex > 0 and GetCurrentMapContinent("player") == queueContinent then C_Timer.After(5,function() if UnitOnTaxi("player") then queueSlotIndex = 0 queueNodeID = 0 end end) end end end function FQ:QUEST_LOG_UPDATE() if not IsInInstance() then local NewContinent = GetCurrentMapContinent("player") if fcontinent[NewContinent] == nil and NewContinent > 0 then --changed and not IsInInstance() then --KUI:Print("player"..NewContinent) --for k in pairs(fcontinent) do --KUI:Print(k..tostring(fcontinent[k])) --fcontinent[k]=false --end --if fcontinent[NewContinent] == nil and NewContinent>0 then KUI:Print("New Continent. Visit a Flight Master to load new taxi nodes.") fcontinent[NewContinent] = true end --changed = false end if WorldMapFrame:IsVisible() and nodes ~= nil then for pin in WorldMapFrame:EnumeratePinsByTemplate("GroupMembersPinTemplate") do if E.db.KlixUI.misc.whistleLocation then pin:SetFrameStrata("MEDIUM") else pin:SetFrameStrata("FULLSCREEN_DIALOG") end end for node in WorldMapFrame:EnumeratePinsByTemplate("FlightPointPinTemplate") do node:HookScript("OnEnter",OnEnterHandler) node:SetScript("OnMouseDown", ClickHandler) node:HookScript("OnLeave",function() GameTooltip_Hide() end) node:HookScript("OnUpdate",OnUpdateHandler) if WorldMapFrame:GetFrameStrata() == "FULLSCREEN" then node:SetFrameStrata("FULLSCREEN_DIALOG") else if E.db.KlixUI.misc.whistleLocation then node:SetFrameStrata("MEDIUM") else node:SetFrameStrata("DIALOG") end end end end end function FQ:Initialize() if not E.db.KlixUI.maps.worldmap.flightQ then return end self:RegisterEvent("TAXIMAP_OPENED") self:RegisterEvent("QUEST_LOG_UPDATE") --self:RegisterEvent("ZONE_CHANGED_NEW_AREA") self:RegisterEvent("PLAYER_CONTROL_LOST") if fcontinent == nil then fcontinent = {} end end KUI:RegisterModule(FQ:GetName())
function outlook_archive_email() hs.application.launchOrFocus("Microsoft Outlook") local outlook = hs.appfinder.appFromName("Microsoft Outlook") local str_archive = {"Message", "Archive"} local archive = outlook:findMenuItem(str_archive) outlook:selectMenuItem(str_archive) end hs.hotkey.bind({"cmd", "alt"}, "a", outlook_archive_email)
_.states['test'] = { tests = {}, coverage = {}, to_cover = {}, init = function(this) cls() print("loading coverage items...",5) local omitlist = {"draw", "update", "draw_path"} for cover, item in pairs(this.coverage) do for k,v in pairs(item) do if type(v) == 'function' and not contains(omitlist,k) then local cover_key = cover..":"..k add(this.to_cover, cover_key) item[k] = function(...) del(this.to_cover, cover_key) return v(...) end end end end local total_cover = #this.to_cover print(#this.to_cover.." items to cover!",12) print("⧗ running tests!",5) for k,v in pairs(this.tests) do color(11) print(k..":\0") foreach(v, function(test) test() print(".\0") end) print("♥") end print("♥ testing done!",12) print("covered "..total_cover-#this.to_cover.."/"..total_cover.." coverage items",5) if #this.to_cover > 0 then print("missing... ",9) foreach(this.to_cover, function(missed) print(missed,8) end) end stop() end, } _fixtures = {} _tests = _.states['test'].tests _coverage = _.states['test'].coverage -->8 -- test overrides spr = function() end
-- base global environment code to bootstrap a rascal thread -- defines detach, as a standard way to split off other threads -- copyright 2014 Samuel Baird MIT Licence -- lua modules local table = require('table') -- core module, class, array, queue local array = require('core.array') -- rascal lua globals -- debug = false display_worker_code = false -- zeromq modules zmq = require('lzmq') zloop = require('lzmq.loop') ztimer = require('lzmq.timer') zthreads = require('lzmq.threads') -- am I the main thread is_main_thread = false ctx = zthreads.get_parent_ctx() if not ctx then is_main_thread = true ctx = zmq.init(1) elseif not is_detached then -- determine if this is the main thread context and has been automatically -- created as new versions of lzmq seem to do is_main_thread = true end -- dummy log = function (type, text) error('early log ' .. (type or '') .. ' ' .. (text or ''), 2) end -- loop for this thread loop = zloop.new() -- global high res time function function utc_time() return ztimer.absolute_time() / 1000 end -- share simple global values with other threads local shared_globals = {} share_global = function (key, value) rawset(_G, key, value) shared_globals[key] = value end share_globals = function (table) for key, value in pairs(table) do share_global(key, value) end end -- TODO: include function to include inline code as a called function? -- run a service in its own thread detach = function (code, args) local thread_code = array() args = args or {} args.package_path = package.path args.shared_globals = shared_globals -- preamble thread_code:push([[local args = ...]]) for name, _ in pairs(args) do thread_code:push('local ' .. name .. ' = args.' .. name) end thread_code:push('package.path = package_path') thread_code:push('for key, value in pairs(shared_globals) do') thread_code:push(' _G[key] = value') thread_code:push('end') thread_code:push('is_detached = true -- global flag that this is a child thread') -- insert custom code if type(code) == 'string' then thread_code:push(code) elseif type(code) == 'table' then for _, line in ipairs(code) do thread_code:push(line) end end -- assemble the code local code_string = table.concat(thread_code, '\n') -- print code and test compile if display_worker_code then print('-- launch worker') print(code_string) end if debug then local fn, error = loadstring(code_string, 'worker') assert(fn, error) end zthreads.run(ctx, code_string, args):start(true) end detach_process = function (code, args) -- gather environment arg, encode as hex msgpack binary local environment = {} environment.shared_globals = shared_globals or {} -- add argument unpacking to the supplied code and include that code in the environment for safe packing local task_code = array() task_code:push('local args = ...') for name, _ in pairs(args) do task_code:push('local ' .. name .. ' = args.' .. name) end task_code:push(code) environment.code = task_code:concat('\n') environment.args = args or {} -- msgpack to encode the environment and hex packing to safely escape it as part of a commandline argument local cmsgpack = require('cmsgpack') local binary_to_hex = function (binary) return (binary:gsub('.', function (c) return string.format('%02X', string.byte(c)) end)) end -- preamble local process_code = array() process_code:push([[local hex_to_binary = function (hex) return (hex:gsub('..', function (cc) return string.char(tonumber(cc, 16)) end)) end]]) process_code:push([[package.path = hex_to_binary(']] .. binary_to_hex(package.path) .. [[')]]) process_code:push([[rascal = require('rascal.core')]]) -- smuggle serialised environment process_code:push([[local packed_environment = ']] .. binary_to_hex(cmsgpack.pack(environment)) .. [[']]) process_code:push([[local environment = cmsgpack.unpack(hex_to_binary(packed_environment))]]) process_code:push('for key, value in pairs(environment.shared_globals) do') process_code:push(' _G[key] = value') process_code:push('end') process_code:push('is_detached_process = true') -- now unpack the smuggled source code and args to begin process_code:push('loadstring(environment.code)(environment.args)') -- run this packed code as a separate process if type(rawget(_G, 'jit')) == 'table' then os.execute('luajit -e "' .. process_code:concat(' ') .. '"&') else os.execute('lua -e "' .. process_code:concat(' ') .. '"&') end end -- no uninitialised reads or writes to global variables after this setmetatable(_G, { __index = function (obj, property) error('uninitialised read from global ' .. tostring(property), 2) end, }) -- optionally prevent uninitialised writes as well function strict() setmetatable(_G, { __index = function (obj, property) error('uninitialised read from global ' .. tostring(property), 2) end, __newindex = function (obj, property, value) error('uninitialised write to global ' .. tostring(property), 2) end, }) end -- enhanced pcall with stack trace captured pcall_trace = function (f, ...) local debug = require('debug') local handle_by_capturing_stack_trace = function (err) if debug then return debug.traceback(tostring(err)) else return tostring(err) end end -- capture varargs local varargs = { n = select("#", ...), ... } return xpcall(function(...) return f(unpack(varargs, 1, varargs.n)) end, handle_by_capturing_stack_trace) end
number = {} sign = {} oper = {} sp = "\( \) " min_range = 39 max_range = 60 test = 0 for i = 1,3 do number[i] = min_range - math.random(max_range); if (i > 1 and number[i] < 0) then test = 1 end end if (test == 0) then ch = 1 + math.random(2) number[ch] = -number[ch] end result = number[1] for i = 1,2 do sign[i] = math.random(2) if (sign[i] == 1) then result = result + number[i+1] oper[i] = "+" else result = result - number[i+1] oper[i] = "-" end end ind = math.random(3) if (ind == 1) then answ = lib.check_number(number[1],30) .. " " .. oper[1] .. " ( " .. number[2] .. " ) " .. oper[2] .. " ( " .. number[3] .. " ) " .. sp .. " = " .. sp .. result end if (ind == 2) then answ = number[1] .. " " .. oper[1] .. " ( " .. lib.check_number(number[2],30) .. " ) " .. oper[2] .. " ( " .. number[3] .. " ) " .. sp .. " = " .. sp .. result end if (ind == 3) then answ = number[1] .. " " .. oper[1] .. " ( " .. number[2] .. " ) " .. oper[2] .. " ( " .. lib.check_number(number[3],30) .. " ) " .. sp .. " = " .. sp .. result end
function onCreate() makeLuaSprite('bg','sky',-150,-600) addLuaSprite('bg',false) setLuaSpriteScrollFactor('bg', 0, 0) makeAnimatedLuaSprite('clouds','clouds',-5000,-300) addAnimationByPrefix('clouds','move','Float',24,true) addLuaSprite('clouds',false) objectPlayAnimation('clouds','move',false) setLuaSpriteScrollFactor('clouds', 0.1, 0.1) makeLuaSprite('mountaiinssss','mountains',-50,0) addLuaSprite('mountaiinssss',false) setLuaSpriteScrollFactor('mountaiinssss', 0.3, 0.1) makeLuaSprite('floor2','anothaflorr',700,400) addLuaSprite('floor2',false) setLuaSpriteScrollFactor('floor2', 0.6, 0.5) makeLuaSprite('farm','farm',1450,50) addLuaSprite('farm',false) setLuaSpriteScrollFactor('farm', 0.6, 0.5) makeLuaSprite('floor','floor',650,300) addLuaSprite('floor',false) setLuaSpriteScrollFactor('floor', 1, 1) makeLuaSprite('corn','pcorn',600,300) addLuaSprite('corn',false) setLuaSpriteScrollFactor('corn', 1, 1) makeLuaSprite('fence','fence',700,650) addLuaSprite('fence',false) setLuaSpriteScrollFactor('fence', 1, 1) makeLuaSprite('bamb','sing',900,550) addLuaSprite('bamb',false) setLuaSpriteScrollFactor('bamb', 1, 1) end
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf/protobuf" module('ItemFuse_pb') ITEMFUSE = protobuf.Descriptor(); local ITEMFUSE_FUSELEVEL_FIELD = protobuf.FieldDescriptor(); local ITEMFUSE_FUSEEXPCOUNT_FIELD = protobuf.FieldDescriptor(); ITEMFUSE_FUSELEVEL_FIELD.name = "fuseLevel" ITEMFUSE_FUSELEVEL_FIELD.full_name = ".KKSG.ItemFuse.fuseLevel" ITEMFUSE_FUSELEVEL_FIELD.number = 1 ITEMFUSE_FUSELEVEL_FIELD.index = 0 ITEMFUSE_FUSELEVEL_FIELD.label = 1 ITEMFUSE_FUSELEVEL_FIELD.has_default_value = false ITEMFUSE_FUSELEVEL_FIELD.default_value = 0 ITEMFUSE_FUSELEVEL_FIELD.type = 13 ITEMFUSE_FUSELEVEL_FIELD.cpp_type = 3 ITEMFUSE_FUSEEXPCOUNT_FIELD.name = "fuseExpCount" ITEMFUSE_FUSEEXPCOUNT_FIELD.full_name = ".KKSG.ItemFuse.fuseExpCount" ITEMFUSE_FUSEEXPCOUNT_FIELD.number = 2 ITEMFUSE_FUSEEXPCOUNT_FIELD.index = 1 ITEMFUSE_FUSEEXPCOUNT_FIELD.label = 1 ITEMFUSE_FUSEEXPCOUNT_FIELD.has_default_value = false ITEMFUSE_FUSEEXPCOUNT_FIELD.default_value = 0 ITEMFUSE_FUSEEXPCOUNT_FIELD.type = 13 ITEMFUSE_FUSEEXPCOUNT_FIELD.cpp_type = 3 ITEMFUSE.name = "ItemFuse" ITEMFUSE.full_name = ".KKSG.ItemFuse" ITEMFUSE.nested_types = {} ITEMFUSE.enum_types = {} ITEMFUSE.fields = {ITEMFUSE_FUSELEVEL_FIELD, ITEMFUSE_FUSEEXPCOUNT_FIELD} ITEMFUSE.is_extendable = false ITEMFUSE.extensions = {} ItemFuse = protobuf.Message(ITEMFUSE)
-- local null_ls = require("null-ls") -- local formatting = null_ls.builtins.formatting -- local diagnostics = null_ls.builtins.diagnostics -- local completion = null_ls.builtins.completion -- local sources = { -- sources = { -- -- Formatoes -- -- formatting.autopep8, -- -- formatting.isort, -- formatting.json_tool, -- formatting.stylua.with({ -- extra_args = { "--indent-type", "Tabs", "--indent-width", "2" }, -- }), -- -- Dags -- diagnostics.eslint_d, -- -- diagnostics.mypy, -- -- diagnostics.flake8, -- diagnostics.pylint, -- diagnostics.hadolint, -- diagnostics.yamllint, -- -- Completoes -- completion.luasnip, -- }, -- } -- null_ls.setup({ sources = sources, update_in_insert = true })
-- Export all detail maps from legends -- version 1.0 gui = require 'gui' local vs = dfhack.gui.getCurViewscreen() local i = 0 local MAPS = { [0] = "Standard biome+site map", "Elevations including lake and ocean floors", "Elevations respecting water level", "Biome", "Hydrosphere", "Temperature", "Rainfall", "Drainage", "Savagery", "Volcanism", "Current vegetation", "Evil", "Salinity", "Structures/fields/roads/etc.", "Trade", "Nobility/holdings", "Diplomacy", } function wait_for_legends_vs() vs = dfhack.gui.getCurViewscreen() if i < 17 then if df.viewscreen_legendsst:is_instance(vs) then gui.simulateInput(vs, 'LEGENDS_EXPORT_DETAILED_MAP') -- "d" on screen some number internally dfhack.timeout(10,'frames',wait_for_export_maps_vs) else dfhack.timeout(10,'frames',wait_for_legends_vs) end end end function wait_for_export_maps_vs() vs = dfhack.gui.getCurViewscreen() if df.viewscreen_export_graphical_mapst:is_instance(vs) then vs.anon_13 = i -- anon_13 appears to be the selection cursor for this viewscreen print('Exporting: '..MAPS[i]) i = i + 1 gui.simulateInput(vs, 'SELECT') -- 1 internally, enter on screen dfhack.timeout(10,'frames',wait_for_legends_vs) else dfhack.timeout(10,'frames',wait_for_export_maps_vs) end end if df.viewscreen_legendsst:is_instance( vs ) then -- dfhack.gui.getCurFocus() == "legends" wait_for_legends_vs() elseif df.viewscreen_export_graphical_mapst:is_instance(vs) then wait_for_export_maps_vs() else dfhack.printerr('Not in legends view') end
function onSay(cid, words, param, channel) local toPos = getCreatureLookPosition(cid) if(isInArray({"full", "all"}, param:lower())) then doCleanTile(toPos, false) doSendMagicEffect(toPos, CONST_ME_MAGIC_RED) return true end local amount = 1 param = tonumber(param) if(param) then amount = param end toPos.stackpos = STACKPOS_TOP_MOVEABLE_ITEM_OR_CREATURE local tmp = getThingFromPos(toPos) if(tmp.uid ~= 0) then if(isCreature(tmp.uid)) then doRemoveCreature(tmp.uid) else doRemoveItem(tmp.uid, math.min(math.max(1, tmp.type), amount)) end doSendMagicEffect(toPos, CONST_ME_MAGIC_RED) return true end toPos.stackpos = STACKPOS_TOP_FIELD tmp = getThingFromPos(toPos) if(tmp.uid ~= 0) then doRemoveItem(tmp.uid, math.min(math.max(1, tmp.type), amount)) doSendMagicEffect(toPos, CONST_ME_MAGIC_RED) return true end toPos.stackpos = STACKPOS_TOP_CREATURE tmp = getThingFromPos(toPos) if(tmp.uid ~= 0) then doRemoveCreature(tmp.uid) doSendMagicEffect(toPos, CONST_ME_MAGIC_RED) return true end for i = 5, 1, -1 do toPos.stackpos = i tmp = getThingFromPos(toPos) if(tmp.uid ~= 0) then if(isCreature(tmp.uid)) then doRemoveCreature(tmp.uid) else doRemoveItem(tmp.uid, math.min(math.max(1, tmp.type), amount)) end doSendMagicEffect(toPos, CONST_ME_MAGIC_RED) return true end end doSendMagicEffect(getCreaturePosition(cid), CONST_ME_POFF) return true end
object_tangible_quest_quest_start_ep3_hunt_loot_spiketop_horn = object_tangible_quest_quest_start_shared_ep3_hunt_loot_spiketop_horn:new { } ObjectTemplates:addTemplate(object_tangible_quest_quest_start_ep3_hunt_loot_spiketop_horn, "object/tangible/quest/quest_start/ep3_hunt_loot_spiketop_horn.iff")
local dict = { critical = "critical", error = "error", warning = "warning", info = "info", } local key_default = secrets:get("pagerduty_key_default") local routing_keys = { default = key_default, critical = secrets:get("pagerduty_key_critical") or key_default, error = secrets:get("pagerduty_key_error") or key_default, warning = secrets:get("pagerduty_key_warning") or key_default, info = secrets:get("pagerduty_key_info") or key_default, } -- return routing local function routing(alert) return {severity=dict.critical, key=routing_keys[dict.critical]} end return routing
local var = ngx.var local i = var.a local j = var.b local sequare = require("sequare") local s1 = sequare:new(i, j) return s1:get_square()
test_run = require('test_run').new() -- -- gh-2677: box.session.push binary protocol tests. -- -- -- Usage. -- box.session.push() box.session.push(1, 'a') fiber = require('fiber') messages = {} test_run:cmd("setopt delimiter ';'") -- Do push() with no explicit sync. Use session.sync() by default. function do_pushes() for i = 1, 5 do box.session.push(i) fiber.sleep(0.01) end return 300 end; test_run:cmd("setopt delimiter ''"); netbox = require('net.box') box.schema.user.grant('guest', 'read,write,execute', 'universe') c = netbox.connect(box.cfg.listen) c:ping() c:call('do_pushes', {}, {on_push = table.insert, on_push_ctx = messages}) messages -- Add a little stress: many pushes with different syncs, from -- different fibers and DML/DQL requests. catchers = {} started = 0 finished = 0 s = box.schema.create_space('test', {format = {{'field1', 'integer'}}}) pk = s:create_index('pk') c:reload_schema() test_run:cmd("setopt delimiter ';'") function dml_push_and_dml(key) local sync = box.session.sync() box.session.push('started dml', sync) s:replace{key} box.session.push('continued dml', sync) s:replace{-key} box.session.push('finished dml', sync) return key end; function do_pushes(val) local sync = box.session.sync() for i = 1, 5 do box.session.push(i, sync) fiber.yield() end return val end; function push_catcher_f() fiber.yield() started = started + 1 local catcher = {messages = {}, retval = nil, is_dml = false} catcher.retval = c:call('do_pushes', {started}, {on_push = table.insert, on_push_ctx = catcher.messages}) table.insert(catchers, catcher) finished = finished + 1 end; function dml_push_and_dml_f() fiber.yield() started = started + 1 local catcher = {messages = {}, retval = nil, is_dml = true} catcher.retval = c:call('dml_push_and_dml', {started}, {on_push = table.insert, on_push_ctx = catcher.messages}) table.insert(catchers, catcher) finished = finished + 1 end; -- At first check that a pushed message can be ignored in a binary -- protocol too. c:call('do_pushes', {300}); -- Then do stress. for i = 1, 200 do fiber.create(dml_push_and_dml_f) fiber.create(push_catcher_f) end; while finished ~= 400 do fiber.sleep(0.1) end; failed_catchers = {}; for _, c in pairs(catchers) do if c.is_dml then if #c.messages ~= 3 or c.messages[1] ~= 'started dml' or c.messages[2] ~= 'continued dml' or c.messages[3] ~= 'finished dml' or s:get{c.retval} == nil or s:get{-c.retval} == nil then table.insert(failed_catchers, c) end else if c.retval == nil or #c.messages ~= 5 then table.insert(failed_catchers, c) else for k, v in pairs(c.messages) do if k ~= v then table.insert(failed_catchers, c) break end end end end end; test_run:cmd("setopt delimiter ''"); failed_catchers #s:select{} -- -- Ok to push NULL. -- function push_null() box.session.push(box.NULL) end messages = {} c:call('push_null', {}, {on_push = table.insert, on_push_ctx = messages}) messages -- -- Test binary pushes. -- ibuf = require('buffer').ibuf() msgpack = require('msgpack') messages = {} resp_len = c:call('do_pushes', {300}, {on_push = table.insert, on_push_ctx = messages, buffer = ibuf}) resp_len messages decoded = {} r = nil for i = 1, #messages do r, ibuf.rpos = msgpack.decode_unchecked(ibuf.rpos) table.insert(decoded, r) end decoded r, _ = msgpack.decode_unchecked(ibuf.rpos) r -- -- Test error in __serialize. -- ok = nil err = nil messages = {} t = setmetatable({100}, {__serialize = function() error('err in ser') end}) function do_push() ok, err = box.session.push(t) end c:call('do_push', {}, {on_push = table.insert, on_push_ctx = messages}) ok, err messages -- -- Test push from a non-call request. -- s:truncate() _ = s:on_replace(function() box.session.push('replace') end) c:reload_schema() c.space.test:replace({200}, {on_push = table.insert, on_push_ctx = messages}) messages s:select{} c:close() s:drop() -- -- Ensure can not push in background. -- f = fiber.create(function() ok, err = box.session.push(100) end) while f:status() ~= 'dead' do fiber.sleep(0.01) end ok, err -- -- Async iterable pushes. -- c = netbox.connect(box.cfg.listen) cond = fiber.cond() test_run:cmd("setopt delimiter ';'") function do_pushes() local sync = box.session.sync() for i = 1, 5 do box.session.push(i + 100, sync) cond:wait() end return true end; test_run:cmd("setopt delimiter ''"); -- Can not combine callback and async mode. ok, err = pcall(c.call, c, 'do_pushes', {}, {is_async = true, on_push = function() end}) ok err:find('use future:pairs()') ~= nil future = c:call('do_pushes', {}, {is_async = true}) -- Try to ignore pushes. while not future:wait_result(0.01) do cond:signal() end future:result() -- Even if pushes are ignored, they still are available via pairs. messages = {} keys = {} for i, message in future:pairs() do table.insert(messages, message) table.insert(keys, i) end messages keys -- Test error. s = box.schema.create_space('test') pk = s:create_index('pk') s:replace{1} function do_push_and_duplicate() box.session.push(100) s:insert{1} end future = c:call('do_push_and_duplicate', {}, {is_async = true}) future:wait_result(1000) messages = {} keys = {} for i, message in future:pairs() do table.insert(messages, message) table.insert(keys, i) end messages keys s:drop() c:close() box.schema.user.revoke('guest', 'read,write,execute', 'universe')
--[=[ @class IKResource ]=] local BaseObject = require(script.Parent.Parent.Parent.Classes.BaseObject) local Janitor = require(script.Parent.Parent.Parent.Parent.Janitor) local IKResource = setmetatable({}, BaseObject) IKResource.ClassName = "IKResource" IKResource.__index = IKResource function IKResource.new(Data) local self = setmetatable(BaseObject.new(), IKResource) self.Data = assert(Data, "Bad data") assert(Data.Name, "Bad data.name") assert(Data.RobloxName, "Bad data.robloxName") self.Instance = nil self.ChildResourceMap = {} -- [robloxName] = { data = data; ikResource = ikResource } self.DescendantLookupMap = {[Data.Name] = self} self.Ready = self.Janitor:Add(Instance.new("BoolValue"), "Destroy") self.ReadyChanged = self.Ready.Changed if self.Data.Children then for _, ChildData in ipairs(self.Data.Children) do self:_AddResource(IKResource.new(ChildData)) end end return self end function IKResource:GetData() return self.Data end function IKResource:IsReady() return self.Ready.Value end function IKResource:Get(DescendantName) local Resource = self.DescendantLookupMap[DescendantName] if not Resource then error(string.format("[IKResource.Get] - Resource %q does not exist", tostring(DescendantName))) end local Result = Resource:GetInstance() if not Result then error("[IKResource.Get] - Not ready!") end return Result end function IKResource:GetInstance() if self.Data.IsLink then if self.Instance then return self.Instance.Value else return nil end end return self.Instance end function IKResource:SetInstance(Object) if self.Instance == Object then return end self.Janitor:Remove("InstanceJanitor") self.Instance = Object local InstanceJanitor = Janitor.new() if next(self.ChildResourceMap) then if Object then self:_StartListening(InstanceJanitor, Object) else self:_ClearChildren() end end if Object and self.Data.IsLink then assert(Object:IsA("ObjectValue")) self.Janitor:Add(Object.Changed:Connect(function() self:_UpdateReady() end), "Disconnect") end self.Janitor:Add(InstanceJanitor, "Destroy", "InstanceJanitor") self:_UpdateReady() end function IKResource:GetLookupTable() return self.DescendantLookupMap end function IKResource:_StartListening(InstanceJanitor, Object) for _, Child in ipairs(Object:GetChildren()) do self:_HandleChildAdded(Child) end InstanceJanitor:Add(Object.ChildAdded:Connect(function(Child) self:_HandleChildAdded(Child) end), "Disconnect") InstanceJanitor:Add(Object.ChildRemoved:Connect(function(Child) self:_HandleChildRemoved(Child) end), "Disconnect") end function IKResource:_AddResource(IkResource) local Data = IkResource.Data assert(Data.Name, "Bad data.name") assert(Data.RobloxName, "Bad data.robloxName") assert(type(Data.RobloxName) == "string", "Bad data.robloxName") assert(not self.ChildResourceMap[Data.RobloxName], "Data already exists") assert(not self.DescendantLookupMap[Data.Name], "Data already exists") self.ChildResourceMap[Data.RobloxName] = IkResource self.Janitor:Add(IkResource, "Destroy") self.Janitor:Add(IkResource.ReadyChanged:Connect(function() self:_UpdateReady() end), "Disconnect") -- Add to _descendantLookupMap, including the actual ikResource for Name, Resource in next, IkResource:GetLookupTable() do assert(not self.DescendantLookupMap[Name], "Resource already exists with name") self.DescendantLookupMap[Name] = Resource end end function IKResource:_HandleChildAdded(Child) local Resource = self.ChildResourceMap[Child.Name] if not Resource then return end Resource:SetInstance(Child) end function IKResource:_HandleChildRemoved(Child) local Resource = self.ChildResourceMap[Child.Name] if not Resource then return end if Resource:GetInstance() == Child then Resource:SetInstance(nil) end end function IKResource:_ClearChildren() for _, Child in next, self.ChildResourceMap do Child:SetInstance(nil) end end function IKResource:_UpdateReady() self.Ready.Value = self:_CalculateIsReady() end function IKResource:_CalculateIsReady() if not self.Instance then return false end if self.Data.IsLink then if not self.Instance.Value then return false end end for _, Child in next, self.ChildResourceMap do if not Child:IsReady() then return false end end return true end function IKResource:__tostring() return "IKResource" end table.freeze(IKResource) return IKResource
--[[-- Initialization. This module handles the initialization of the plugin. ]] local kommentary = require("kommentary.kommentary") local config = require("kommentary.config") local util = require("kommentary.util") local M = {} local context = config.context local modes = config.get_modes() --[[-- Function to be called by mappings. This function should be called by all the mappings. It will receive the context of the call, meaning if the mapping was triggered in on a single line, or from a selection/motion, and performs the appropriate setup to comment lines. This function does not, however, manipulate the buffer in any way, that is left up to other functions to allow for greater customizability. At the end of this function, it will do one of two things - * call a *callback* function with the following arguments: line_number_start, line_number_end, context This callback function, by default, will be `kommentary.toggle_comment`, and will toggle the range specified. If you wish to use a different function, you can provide it in a table as the third argument to this function `kommentary.go`, for example, if the desired callback function were called `kommentary.toggle_comment_singles`, then you would call this function like this: `kommentary.go(context, {kommentary.toggle_comment_singles})` * set the operatorfunc to the appropriate callback, and return the keys to be used in an <expr> mapping @tparam int ... The calling context, one of `kommentary.config.context` @tparam string ... The name of the mapping that is calling this function @treturn ?string|nil If called from linewise or motion modes, sets the operatorfunc and returns 'g@' to be used in an expression mapping, otherwise it will comment out and not return anything. ]] function M.go(...) if not vim.bo.modifiable then return end local args = {...} --[[ The first argument passed to this function represents one of 3 possible contexts in which this function can be called - linewise, motion or visual. The second argument is the name of the mapping, which is used to retrieve any custom callbacks that are defined for that mapping]] local calling_context = args[1] local map_name = args[2] --[[ When called from visual mode, a new toggle function is created and immediately executed, since we do not support dot-repeat for visual mode. For other modes (linewise, motion), the toggle function is created and stored in a variable, and the operatorfunc is set to that variable (see ':h operatorfunc'). If the function is called with a motion, 'g@' is returned, which calls the current operatorfunc with the subsequent motion. Else (linewise commenting), we return 'g@l', which just calls operatorfunc with a dummy motion 'l', which is ignored in the handler for linewise commenting. By returning 'g@', the '.' operator can now repeat linewise and motion commenting by calling operatorfunc again]] if calling_context == context.visual then M.create_next_toggle_func(calling_context, util.callbacks[map_name])() return end M.next_toggle_func = M.create_next_toggle_func(calling_context, util.callbacks[map_name]) vim.api.nvim_set_option('operatorfunc', 'v:lua.kommentary.next_toggle_func') return 'g@' .. (calling_context==context.motion and '' or 'l') end -- The function to be used to toggle comments. Initially set to a dummy function M.next_toggle_func = function() return end --[[ Returns a new toggle function based on the calling context(linewise, visual or motion). If a callback function is provided, the callback function is used, else the toggle_comment function is used]] function M.create_next_toggle_func(calling_context, callback) return function() local line_number_start, line_number_end = M.get_lines_from_context(calling_context) if callback ~= nil then callback(line_number_start, line_number_end, calling_context) else M.toggle_comment(line_number_start, line_number_end, calling_context) end end end -- Returns the starting and ending lines to be commented based on the calling context. function M.get_lines_from_context(calling_context) local line_number_start = nil local line_number_end = nil if calling_context == context.line then line_number_start = vim.fn.line('.') line_number_end = line_number_start elseif calling_context == context.visual then line_number_start = vim.fn.line('v') line_number_end = vim.fn.line('.') elseif calling_context == context.motion then line_number_start = vim.fn.getpos("'[")[2] line_number_end = vim.fn.getpos("']")[2] end return line_number_start, line_number_end end function M.toggle_comment(...) local args = {...} local line_number_start, line_number_end = args[1], args[2] kommentary.toggle_comment_range(line_number_start, line_number_end, modes.normal) end function M.toggle_comment_singles(...) local args = {...} local line_number_start, line_number_end = args[1], args[2] local mode = modes.force_single kommentary.toggle_comment_range(line_number_start, line_number_end, mode) end return M
if not pcall(node.flashindex("_init")) then return nil; end require("helper") require("ap") require("sta") require("udp") require("webserver") -- set dht11 pin dht_pin = 2 dht_info = {} dht_info.temp = nil dht_info.humi = nil -- set wifi mode wifi.setmode(wifi.STATIONAP) -- set egc mode node.egc.setmode(node.egc.ALWAYS, 4096) --set timer id and ms for each moudle tmr_tab = {} tmr_tab.ap = tmr.create() tmr_tab.sta = tmr.create() tmr_tab.dht = tmr.create() tmr_tab.udp = tmr.create() tmr_tab.cookie = tmr.create() -- set ap timer, it will run forever until ap setup success ap.setTimer(tmr_tab.ap) tmr_tab.ap:alarm( 3000, tmr.ALARM_AUTO, ap.setup ) -- set sta timer, it will run forever until connect wifi success sta.setTimer(tmr_tab.sta) tmr_tab.sta:alarm( 5000, tmr.ALARM_AUTO, sta.setup ) -- get temperature and humidity tmr_tab.dht:alarm( 2000, tmr.ALARM_AUTO, function() status, temp, humi, temp_dec, humi_dec = dht.read(dht_pin) if status == dht.OK then print("DHT Temperature:"..temp..";".."Humidity:"..humi) dht_info.temp = temp dht_info.humi = humi elseif status == dht.ERROR_CHECKSUM then print( "DHT Checksum error." ) elseif status == dht.ERROR_TIMEOUT then print( "DHT timed out." ) end end ) -- set udp serve timer tmr_tab.udp:alarm( 6000, tmr.ALARM_AUTO, udp.setup ) -- set cookie timer tmr_tab.cookie:alarm( 60000, tmr.ALARM_AUTO, helper.cookieTimer ) -- require routes dofile("routes.lua")
-- String: A text entry that will send whenever it loses focus nzu.AddExtensionSettingType("String", { NetRead = net.ReadString, NetWrite = net.WriteString, Panel = { Create = function(parent) local p = vgui.Create("DTextEntry", parent) p:SetTall(40) function p:OnFocusChanged(b) if not b then p:Send() end -- Trigger networking on text field focus lost end return p end, Set = function(p,v) p:SetText(v or "") end, Get = function(p) return p:GetText() end } }) -- Number: A networked double with a Number Wang nzu.AddExtensionSettingType("Number", { NetRead = net.ReadDouble, NetWrite = net.WriteDouble, Panel = { Create = function(parent) local p = vgui.Create("Panel", parent) p.N = p:Add("DNumberWang") p.N:Dock(FILL) p.N:SetMinMax(nil,nil) p:SetTall(40) function p.N.OnValueChanged() if p.Send then p:Send() end -- Trigger networking whenever it changes end return p end, Set = function(p,v) p.N:SetValue(v) end, Get = function(p) return p.N:GetValue() end } }) -- Boolean: A true/false value that appears as a checkbox, networked whenever clicked nzu.AddExtensionSettingType("Boolean", { NetRead = net.ReadBool, NetWrite = net.WriteBool, Panel = { Create = function(parent) local p = vgui.Create("DTextEntry", parent) p:SetTall(40) function p:OnFocusChanged(b) if not b then p:Send() end -- Trigger networking on text field focus lost end return p end, Set = function(p,v) p:SetText(v or "") end, Get = function(p) return p:GetText() end } }) -- Vector: 3 number wangs with an associated Save button. Uses DVectorEntry (included in nZU) nzu.AddExtensionSettingType("Vector", { NetRead = net.ReadVector, NetWrite = net.WriteVector, Panel = { Create = function(parent) local p = vgui.Create("Panel", parent) p.S = p:Add("DButton") p.S:SetText("Save") p.S:Dock(RIGHT) p.S:SetWide(50) p.V = p:Add("DVectorEntry") p.V:Dock(FILL) p:SetSize(200,20) p.S.DoClick = function() p:Send() end -- Network on button click return p end, Set = function(p,v) p.V:SetVector(v) end, Get = function(p) return p.V:GetVector() end } }) -- Angle: 3 number wangs with an associated Save button, similar to Vector nzu.AddExtensionSettingType("Angle", { NetRead = net.ReadAngle, NetWrite = net.WriteAngle, Panel = { Create = function(parent) local p = vgui.Create("Panel", parent) p.S = p:Add("DButton") p.S:SetText("Save") p.S:Dock(RIGHT) p.S:SetWide(50) p.A = p:Add("DAngleEntry") p.A:Dock(FILL) p:SetSize(200,20) p.S.DoClick = function() p:Send() end -- Network on button click return p end, Set = function(p,v) p.A:SetAngles(v) end, Get = function(p) return p.A:GetAngles() end } }) -- Matrix: 4x4 number wangs with an associated Save button, also similar to Angle and Vector nzu.AddExtensionSettingType("Matrix", { NetRead = net.ReadMatrix, NetWrite = net.WriteMatrix, Panel = { Create = function(parent) local p = vgui.Create("Panel", parent) p.S = p:Add("DButton") p.S:SetText("Save") p.S:Dock(BOTTOM) p.S:SetTall(20) p.M = p:Add("DMatrixEntry") p.M:Dock(FILL) p:SetSize(200,100) p.S.DoClick = function() p:Send() end -- Network on button click return p end, Set = function(p,v) p.M:SetMatrix(v) end, Get = function(p) return p.M:GetMatrix() end } }) -- Color: A color select with a Save button nzu.AddExtensionSettingType("Color", { NetRead = net.ReadColor, NetWrite = net.WriteColor, Load = function(t) return IsColor(t) and t or Color(t.r, t.g, t.b, t.a) end, Panel = { Create = function(parent) local p = vgui.Create("Panel", parent) p.S = p:Add("DButton") p.S:SetText("Save") p.S:Dock(BOTTOM) p.S:SetTall(20) p.C = p:Add("DColorMixer") p.C:Dock(FILL) p:SetSize(200,185) p.S.DoClick = function() p:Send() end -- Network on button click return p end, Set = function(p,v) p.C:SetColor(v) end, Get = function(p) local c = p.C:GetColor() return Color(c.r,c.g,c.b,c.a) end } }) -- Weapon: A text field dropdown that contains all installed weapons, including a search field to filter the dropdown nzu.AddExtensionSettingType("Weapon", { NetWrite = net.WriteString, NetRead = net.ReadString, Panel = { Create = function(parent, ext, setting) local p = vgui.Create("DSearchComboBox", parent) p:AddChoice(" [None]", "") -- Allow the choice of none for k,v in pairs(weapons.GetList()) do p:AddChoice((v.PrintName or "").." ["..v.ClassName.."]", v.ClassName) end p:SetAllowCustomInput(true) function p:OnSelect(index, value, data) self:Send() end return p end, Set = function(p,v) for k,class in pairs(p.Data) do if class == v then p:SetText(p:GetOptionText(k)) p.selected = k return end end p.Choices[0] = v p.Data[0] = v p.selected = 0 p:SetText(v) end, Get = function(p) local str,data = p:GetSelected() return data end, } }) -- Option Set: A dropdown containing a selection of options networked from the Server. -- Note: This setting requires implementing GetOptions which should return a table of pairs: {Option = data, Display = pretty} -- where 'data' is the value networked, and 'pretty' is a pretty display name for the dropdown. If pretty doesn't exist, data is used in its place. local optionset = { NetWrite = net.WriteString, NetRead = net.ReadString, GetOptions = function() return {} -- Nothing by default! You must implement this if you want any options! end, } if SERVER then util.AddNetworkString("nzu_optionset") local function networkoptions(ext, s, ply) if type(ext) == "string" then ext = nzu.GetExtension(ext) end if ext then local setting = ext:GetSettingsMeta()[s] if setting and setting.GetOptions then local tbl = setting.GetOptions() local num = #tbl if num > 0 then net.Start("nzu_optionset") net.WriteString(k) net.WriteUInt(num, 16) for i = 1,num do net.WriteString(tbl[i].Option) net.WriteString(tbl[i].Display) end net.Send(ply) end end end end -- In Sandbox, cache all option sets created and network them to any player joining if NZU_SANDBOX then local sets = {} optionset.Create = function(ext, setting) sets[setting] = ext end hook.Add("PlayerInitialSpawn", "nzu_Extensions_OptionSetNetwork", function(ply) for k,v in pairs(sets) do networkoptions(v, k, ply) end end) else -- In nZombies, only respond to admin requests net.Receive("nzu_optionset", function(len, ply) if nzu.IsAdmin(ply) then local ext = net.ReadString() local id = net.ReadString() networkoptions(ext, id, ply) end end) end else local function readoptions() local id = net.ReadString() local num = net.ReadUInt(16) local tbl = {} for i = 1,num do local t = {} t.Option = net.ReadString() t.Display = net.ReadString() table.insert(tbl, t) end return id, tbl end local sets if NZU_SANDBOX then sets = {} end net.Receive("nzu_optionset", function() local id,tbl = readoptions() if sets then sets[id] = tbl end -- Only do this in Sandbox pretty much hook.Run("nzu_OptionSetUpdated", id, tbl) end) optionset.Panel = { Create = function(parent, ext, setting) local p = vgui.Create("DComboBox", parent) function p:Populate(id, tbl) if id == setting then self:Clear() for k,v in pairs(tbl) do self:AddChoice(v.Display, v.Option) end end end if NZU_SANDBOX then if sets and sets[setting] then p:Populate(setting, sets[setting]) end else -- Request options net.Start("nzu_optionset") net.WriteString(ext.ID) net.WriteString(setting) net.SendToServer() end hook.Add("nzu_OptionSetUpdated", p, p.Populate) function p:OnSelect(index, value, data) self:Send() end return p end, Set = function(p,v) for k,data in pairs(p.Data) do if data == v then p:SetText(p:GetOptionText(k)) p.selected = k return end end p.Choices[0] = v p.Data[0] = v p.selected = 0 p:SetText(v) end, Get = function(p) local str,data = p:GetSelected() return data end, } end nzu.AddExtensionSettingType("OptionSet", optionset)
SkillConfig = { } SkillConfig[100001]={id=100001,remark='技能描述',type=1,icon='icon_skill_0000',name='Base',cooldown=0,animName='skill1'} SkillConfig[100002]={id=100002,remark='技能描述',type=1,icon='icon_skill_0001',name='Base',cooldown=0,animName='skill2'} SkillConfig[100003]={id=100003,remark='技能描述',type=1,icon='icon_skill_0002',name='Base',cooldown=0,animName='skill3'} SkillConfig[100004]={id=100004,remark='技能描述',type=1,icon='icon_skill_0003',name='Base',cooldown=0,animName='skill1'} SkillConfig[100005]={id=100005,remark='技能描述',type=1,icon='icon_skill_0004',name='Base',cooldown=0,animName='skill2'} SkillConfig[100006]={id=100006,remark='技能描述',type=1,icon='icon_skill_0005',name='Base',cooldown=0,animName='skill3'} SkillConfig[100007]={id=100007,remark='技能描述',type=1,icon='icon_skill_0006',name='Base',cooldown=0,animName='skill1'} SkillConfig[100008]={id=100008,remark='技能描述',type=1,icon='icon_skill_0007',name='Base',cooldown=0,animName='skill2'} SkillConfig[100009]={id=100009,remark='技能描述',type=1,icon='icon_skill_0008',name='Base',cooldown=0,animName='skill3'} SkillConfig[100010]={id=100010,remark='技能描述',type=1,icon='icon_skill_0009',name='Base',cooldown=0,animName='skill1'} SkillConfig[200001]={id=200001,remark='技能描述',type=2,icon='icon_skill_0010',name='冰箱',cooldown=3,animName='skill2'} SkillConfig[200002]={id=200002,remark='技能描述',type=2,icon='icon_skill_0011',name='回春',cooldown=4,animName='skill3'} SkillConfig[200003]={id=200003,remark='技能描述',type=2,icon='icon_skill_0012',name='电邢',cooldown=5,animName='skill1'} SkillConfig[200004]={id=200004,remark='技能描述',type=2,icon='icon_skill_0013',name='疾跑',cooldown=6,animName='skill2'} SkillConfig[200005]={id=200005,remark='技能描述',type=2,icon='icon_skill_0014',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200006]={id=200006,remark='技能描述',type=2,icon='icon_skill_0015',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200007]={id=200007,remark='技能描述',type=2,icon='icon_skill_0016',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200008]={id=200008,remark='技能描述',type=2,icon='icon_skill_0017',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200009]={id=200009,remark='技能描述',type=2,icon='icon_skill_0018',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200010]={id=200010,remark='技能描述',type=2,icon='icon_skill_0019',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200011]={id=200011,remark='技能描述',type=2,icon='icon_skill_0020',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200012]={id=200012,remark='技能描述',type=2,icon='icon_skill_0021',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200013]={id=200013,remark='技能描述',type=2,icon='icon_skill_0022',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200014]={id=200014,remark='技能描述',type=2,icon='icon_skill_0023',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200015]={id=200015,remark='技能描述',type=2,icon='icon_skill_0024',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200016]={id=200016,remark='技能描述',type=2,icon='icon_skill_0025',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200017]={id=200017,remark='技能描述',type=2,icon='icon_skill_0026',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200018]={id=200018,remark='技能描述',type=2,icon='icon_skill_0027',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200019]={id=200019,remark='技能描述',type=2,icon='icon_skill_0028',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200020]={id=200020,remark='技能描述',type=2,icon='icon_skill_0029',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200021]={id=200021,remark='技能描述',type=2,icon='icon_skill_0030',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200022]={id=200022,remark='技能描述',type=2,icon='icon_skill_0031',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200023]={id=200023,remark='技能描述',type=2,icon='icon_skill_0032',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200024]={id=200024,remark='技能描述',type=2,icon='icon_skill_0033',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200025]={id=200025,remark='技能描述',type=2,icon='icon_skill_0034',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200026]={id=200026,remark='技能描述',type=2,icon='icon_skill_0035',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200027]={id=200027,remark='技能描述',type=2,icon='icon_skill_0036',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200028]={id=200028,remark='技能描述',type=2,icon='icon_skill_0037',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200029]={id=200029,remark='技能描述',type=2,icon='icon_skill_0038',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200030]={id=200030,remark='技能描述',type=2,icon='icon_skill_0039',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200031]={id=200031,remark='技能描述',type=2,icon='icon_skill_0040',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200032]={id=200032,remark='技能描述',type=2,icon='icon_skill_0041',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200033]={id=200033,remark='技能描述',type=2,icon='icon_skill_0042',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200034]={id=200034,remark='技能描述',type=2,icon='icon_skill_0043',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200035]={id=200035,remark='技能描述',type=2,icon='icon_skill_0044',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200036]={id=200036,remark='技能描述',type=2,icon='icon_skill_0045',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200037]={id=200037,remark='技能描述',type=2,icon='icon_skill_0046',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200038]={id=200038,remark='技能描述',type=2,icon='icon_skill_0047',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200039]={id=200039,remark='技能描述',type=2,icon='icon_skill_0048',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200040]={id=200040,remark='技能描述',type=2,icon='icon_skill_0049',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200041]={id=200041,remark='技能描述',type=2,icon='icon_skill_0050',name='闪现',cooldown=3,animName='skill3'} SkillConfig[200042]={id=200042,remark='技能描述',type=2,icon='icon_skill_0051',name='闪现',cooldown=3,animName='skill1'} SkillConfig[200043]={id=200043,remark='技能描述',type=2,icon='icon_skill_0052',name='闪现',cooldown=3,animName='skill2'} SkillConfig[200044]={id=200044,remark='技能描述',type=2,icon='icon_skill_0053',name='闪现',cooldown=3,animName='skill3'} SkillConfig[300001]={id=300001,remark='技能描述',type=3,icon='icon_skill_0054',name='闪现',cooldown=3,animName='skill1'} SkillConfig[300002]={id=300002,remark='技能描述',type=3,icon='icon_skill_0055',name='治疗',cooldown=6,animName='skill2'} SkillConfig[300003]={id=300003,remark='技能描述',type=3,icon='icon_skill_0056',name='闪现',cooldown=8,animName='skill3'} SkillConfig[300004]={id=300004,remark='技能描述',type=3,icon='icon_skill_0057',name='闪现',cooldown=3,animName='skill1'} SkillConfig[300005]={id=300005,remark='技能描述',type=3,icon='icon_skill_0058',name='闪现',cooldown=3,animName='skill2'} SkillConfig[300006]={id=300006,remark='技能描述',type=3,icon='icon_skill_0059',name='闪现',cooldown=3,animName='skill3'} SkillConfig[300007]={id=300007,remark='技能描述',type=3,icon='icon_skill_0060',name='闪现',cooldown=3,animName='skill1'} SkillConfig[300008]={id=300008,remark='技能描述',type=3,icon='icon_skill_0061',name='闪现',cooldown=3,animName='skill2'} SkillConfig[300009]={id=300009,remark='技能描述',type=3,icon='icon_skill_0062',name='闪现',cooldown=3,animName='skill3'} SkillConfig[300010]={id=300010,remark='技能描述',type=3,icon='icon_skill_0063',name='闪现',cooldown=3,animName='skill1'} SkillConfig[300011]={id=300011,remark='技能描述',type=3,icon='icon_skill_0064',name='闪现',cooldown=3,animName='skill2'} SkillConfig[300012]={id=300012,remark='技能描述',type=3,icon='icon_skill_0065',name='闪现',cooldown=3,animName='skill3'} SkillConfig[300013]={id=300013,remark='技能描述',type=3,icon='icon_skill_0066',name='闪现',cooldown=3,animName='skill1'} SkillConfig[300014]={id=300014,remark='技能描述',type=3,icon='icon_skill_0067',name='闪现',cooldown=3,animName='skill2'} SkillConfig[300015]={id=300015,remark='技能描述',type=3,icon='icon_skill_0068',name='闪现',cooldown=3,animName='skill3'}
object_ship_bwing_tier8 = object_ship_shared_bwing_tier8:new { } ObjectTemplates:addTemplate(object_ship_bwing_tier8, "object/ship/bwing_tier8.iff")
local RTG = {} local RTGTypes = { "image", "gif" } function RTG:Init() self.offset = { ["x"] = 0, ["y"] = 0, ["w"] = 0, ["h"] = 0 } self.useOffset = false self.doRender = true self.prevDoRender = true self.color = Color( 255, 255, 255, 255 ) self.sizeScale = nil end function RTG:SetSizeScale( x, y ) self.sizeScale = { x = x, y = y } end function RTG:GetSizeScale() return self.sizeScale end function RTG:SetType( t ) if table.HasValue( RTGTypes, t ) then self.type = t self:UpdateGraphic() else self.type = "image" MsgC( Color( 255, 0, 0 ), "[RicherTextGraphic] Invalid graphic type \"" .. t .. "\"" ) end end function RTG:GetTextColor() return self.color end function RTG:SetTextColor( col ) self.color = col self:UpdateColor() end function RTG:UpdateColor() self:SetAlpha( self.color.a ) if self.type == "gif" and self.graphic and IsValid( self.graphic ) then local a = self:GetAlpha() self.graphic:RunJavascript( [[ var element = document.getElementsByTagName("img")[0] if (element) { element.style.opacity = ]] .. ( a / 255 ) .. [[; }]] ) end end function RTG:SetSubImage( x, y, w, h ) if x == nil then self.useOffset = false else self.offset.x = x self.offset.y = y self.offset.w = w self.offset.h = h self.useOffset = true end self:UpdateGraphic() end function RTG:SetPath( path ) self.path = path self:UpdateGraphic() end function RTG:UpdateGraphic() if self.graphic then self.graphic:Remove() end if not self.doRender then return end if not self.path or not self.type then return end if self.type == "image" then local g = vgui.Create( "DImage", self ) g:Dock( FILL ) local mat = Material( self.path ) g.m_Material = mat g.offset = self.offset g.useOffset = self.useOffset function g:Paint( w, h ) if ( !self.m_Material ) then return true end surface.SetMaterial( self.m_Material ) surface.SetDrawColor( self.m_Color.r, self.m_Color.g, self.m_Color.b, self.m_Color.a ) if not self.useOffset then surface.DrawTexturedRect( 0, 0, w, h ) else local sx, sy = self.m_Material:Width(), self.m_Material:Height() local u0, u1, v0, v1 = self.offset.x / sx, self.offset.y / sy, ( self.offset.x + self.offset.w ) / sx, ( self.offset.y + self.offset.h ) / sy surface.DrawTexturedRectUV( 0, 0, w, h, u0, u1, v0, v1 ) end end self.graphic = g else local g = vgui.Create( "DHTML", self ) g:Dock( FILL ) g:SetHTML( [[ <style> body, div, img { margin: 0px; overflow: hidden; width: ]] .. self:GetWide() .. [[px; height: ]] .. self:GetTall() .. [[px; } </style> ]] .. "<body><div><img src=\"" .. self.path .. "\"></div></body>" ) self.graphic = g end end function RTG:SetDoRender( r ) if self.doRender == r then return end self.doRender = r timer.Simple( 0.1, function() self:UpdateDoRender() end ) end function RTG:UpdateDoRender() if self.prevDoRender == self.doRender then return end local r = self.doRender if self.type == "image" then if r then self.graphic:Show() else self.graphic:Hide() end else if r then self:UpdateGraphic() else self.graphic:Remove() end end self.prevDoRender = self.doRender end vgui.Register( "DRicherTextGraphic", RTG, "Panel" )
--[[ Jamba - Jafula's Awesome Multi-Boxer Assistant Copyright 2008 - 2015 Michael "Jafula" Miller License: The MIT License ]]-- local L = LibStub("AceLocale-3.0"):NewLocale( "Jamba-QuestWatcher", "enUS", true ) L["Slash Commands"] = true L["Quest"] = true L["Quest: Watcher"] = true L["Quest Watcher"] = true L["Push Settings"] = true L["Push the quest settings to all characters in the team."] = true L["Settings received from A."] = function( characterName ) return string.format( "Settings received from %s.", characterName ) end L["N/A"] = true L["Update"] = true L["Border Colour"] = true L["Background Colour"] = true L["<Map>"] = true L["Lines Of Info To Display (Reload UI To See Change)"] = true L["Quest Watcher Width (Reload UI To See Change)"] = true L["DONE"] = true L["Unlock Quest Watcher Frame (To Move It)"] = true L["Hide Blizzard's Objectives Watch Frame"] = true L["Show Completed Objectives As 'DONE'"] = true L["Do Not Hide An Individuals Completed Objectives"] = true L["Hide Quests Completed By Team"] = true L["Enable Team Quest Watcher"] = true L["Jamba Quest Watcher"] = true L["Blizzard Tooltip"] = true L["Blizzard Dialog Background"] = true L["Hide Quest Watcher In Combat"] = true L["Show Team Quest Watcher On Master Only"] = true L["Border Style"] = true L["Transparency"] = true L["Scale"] = true L["Background"] = true L["Show Quest Watcher"] = true L["Show the quest watcher window."] = true L["Hide Quest Watcher"] = true L["Hide the quest watcher window."] = true L["Send Message Area"] = true L["Send Progress Messages To Message Area"] = true
-------------------------------------------------------------------------------- --- Head: Require -- -- Standard awesome library local gears = require("gears") local awful = require("awful") require("awful.autofocus") -- Widget and layout library local wibox = require("wibox") -- -- Tail: Require -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- Head: Main -- -- https://awesomewm.org/doc/api/classes/wibox.html screen.connect_signal("request::desktop_decoration", function(s) -- do something print('request::desktop_decoration') -- set wallpaper gears.wallpaper.maximized("/usr/share/backgrounds/Spices_in_Athens_by_Makis_Chourdakis.jpg", s) s.xbox = wibox ({ screen = s, visible = true, width = 400, height = 36, bg = "#161616", }) end) -- --- Tail: Main --------------------------------------------------------------------------------
-- Beatmap Download List -- Part of Live Simulator: 2 -- See copyright notice in main.lua local love = require("love") local Luaoop = require("libs.Luaoop") local JSON = require("libs.JSON") local AssetCache = require("asset_cache") local Gamestate = require("gamestate") local LoadingInstance = require("loading_instance") local lily = require("lily") local log = require("logging") local Async = require("async") local color = require("color") local MainFont = require("main_font") local Util = require("util") local L = require("language") local ColorTheme = require("game.color_theme") local download = require("game.dm") local md5 = require("game.md5") local Glow = require("game.afterglow") local Ripple = require("game.ui.ripple") local CircleIconButton = require("game.ui.circle_icon_button") local ProgressBar = require("game.ui.progress") local SERVER_ADDRESS = require("game.beatmap.download_address") local mipmaps = {mipmaps = true} local beatmapDLSelectButton = Luaoop.class("Livesim2.Download.BeatmapSelectButton", Glow.Element) do local coverShader local function commonPressed(self, _, x, y) self.isPressed = true self.ripple:pressed(x, y) end local function commonReleased(self) self.isPressed = false self.ripple:released() end local defaultColor = {255, 255, 255, color.white} function beatmapDLSelectButton:new(state, name, typeID, coverImage) coverShader = coverShader or state.data.coverMaskShader -- Color from type ID local col = ColorTheme[typeID] and ColorTheme[typeID].currentColor or defaultColor self.typeColor = col self.name = love.graphics.newText(state.data.statusFont) self.name:addf({col[4], name}, 310, "left") self:setCoverImage(coverImage) self.width, self.height = 420, 94 self.x, self.y = 0, 0 self.ripple = Ripple(460.691871) self.stencilFunc = function() love.graphics.rectangle("fill", self.x, self.y, self.width, self.height) end self.isPressed = false self:addEventListener("mousepressed", commonPressed) self:addEventListener("mousereleased", commonReleased) self:addEventListener("mousecanceled", commonReleased) end function beatmapDLSelectButton:setCoverImage(coverImage) if coverImage then local w, h = coverImage:getDimensions() self.coverScaleW, self.coverScaleH = 82 / w, 82 / h end self.coverImage = coverImage end function beatmapDLSelectButton:update(dt) self.ripple:update(dt) end function beatmapDLSelectButton:render(x, y) local shader = love.graphics.getShader() self.x, self.y = x, y love.graphics.setColor(color.hex434242) love.graphics.rectangle("fill", x, y, self.width, self.height) love.graphics.setShader(Util.drawText.workaroundShader) love.graphics.setColor(self.typeColor[4]) love.graphics.draw(self.name, x + 110, y + 20) love.graphics.setColor(color.white) if self.coverImage then love.graphics.setShader(coverShader) love.graphics.draw(self.coverImage, x + 6, y + 6, 0, self.coverScaleW, self.coverScaleH) else love.graphics.setShader() love.graphics.setColor(color.hexC4C4C4) love.graphics.rectangle("fill", x + 6, y + 6, 82, 82, 12, 12) love.graphics.rectangle("line", x + 6, y + 6, 82, 82, 12, 12) end love.graphics.setShader(shader) if self.ripple:isActive() then love.graphics.stencil(self.stencilFunc, "replace", 1, false) love.graphics.setStencilTest("equal", 1) self.ripple:draw(self.typeColor[1], self.typeColor[2], self.typeColor[3], x, y) love.graphics.setStencilTest() end end end local function leave() return Gamestate.leave(LoadingInstance.getInstance()) end local function onSelectButton(_, data) if data[4].persist.selectedIndex == nil then data[4].persist.selectedIndex = data[3] Gamestate.enter(nil, "beatmapInfoDL", {data[1], data[2]}) end end local function getHashedName(str) local keyhash = Util.stringToHex(md5("The quick brown fox jumps over the lazy dog"..str)) local filehash = Util.stringToHex(md5(str)) local strb = {} local seed = tonumber(keyhash:sub(1, 8), 16) % 2147483648 for _ = 1, 20 do local chr = math.floor(seed / 33) % 32 local sel = chr >= 16 and keyhash or filehash chr = (chr % 16) + 1 strb[#strb + 1] = sel:sub(2 * chr - 1, 2 * chr) seed = (214013 * seed + 2531011) % 2147483648 end strb[#strb + 1] = str return table.concat(strb) end local function getLiveIconPath(icon) return "live_icon/"..getHashedName(Util.basename(icon)) end local function handleInvalidCover(path) log.errorf("download_list", "cannot load cover '%s', deleting.", path) love.filesystem.remove(path) end local function loadCoverImage(elem, coverPath) local coverImage = AssetCache.loadImage(coverPath, mipmaps, handleInvalidCover) elem:setCoverImage(coverImage) end local function initializeBeatmapList(self, mapdata, etag) if not(mapdata) then -- Load maps.json local sync = Async.syncLily(lily.decompress("zlib", love.filesystem.newFileData("maps.json"))) sync:sync() mapdata = JSON:decode(sync:getValues()) elseif etag then -- Save maps.json local mapString = love.filesystem.newFileData(mapdata, "") local sync = Async.syncLily(lily.compress("zlib", mapString, 9)) love.filesystem.write("maps.json.etag", etag) sync:sync() love.filesystem.write("maps.json", sync:getValues()) mapdata = JSON:decode(mapdata) end self.persist.mapData = mapdata local liveTrack = {} for _, v in ipairs(mapdata) do -- Ignore it if it's TECHNICAL difficulty if v.difficulty_text ~= "TECHNICAL" then -- According to ieb, if the `live_difficulty_id` is 20000 and later -- then it's SIFAC beatmap. if v.live_setting_id >= 20000 then v.difficulty_text = "SIFAC" end local trackidx -- Find the live track for j = 1, #liveTrack do if liveTrack[j].track == v.live_track_id then trackidx = liveTrack[j] break end end if not(trackidx) then trackidx = {} liveTrack[#liveTrack + 1] = trackidx trackidx.track = v.live_track_id trackidx.name = v.name trackidx.song = v.sound_asset trackidx.icon = v.live_icon_asset trackidx.member = v.member_category trackidx.live = {} if trackidx.name:find("* ", 1, true) == 1 then -- Unofficial romaji, but we don't care ¯\_(ツ)_/¯ trackidx.name = trackidx.name:sub(3) end end -- Create information data local infodata = {difficulty = v.difficulty_text} trackidx.live[v.difficulty_text] = infodata -- in C, B, A, S format infodata.score = {} infodata.score[1], infodata.score[2] = v.c_rank_score, v.b_rank_score infodata.score[3], infodata.score[4] = v.a_rank_score, v.s_rank_score infodata.combo = {} infodata.combo[1], infodata.combo[2] = v.c_rank_combo, v.b_rank_combo infodata.combo[3], infodata.combo[4] = v.a_rank_combo, v.s_rank_combo -- Background infodata.background = math.min(v.stage_level, 12) infodata.star = v.stage_level if v.member_category == 2 and v.stage_level < 4 then infodata.background = 12 + v.stage_level end -- Livejson info infodata.livejson = "livejson/"..v.notes_setting_asset end end self.persist.beatmapListGroup = liveTrack self.persist.beatmapListElem = {} -- Setup frame for i = 1, #liveTrack do local track = liveTrack[i] local x = 30 + ((i - 1) % 2) * 480 local y = math.floor((i - 1) / 2) * 94 local elem = beatmapDLSelectButton(self, track.name, track.member) elem:addEventListener("mousereleased", onSelectButton) elem:setData({self.persist.download, track, i, self}) self.persist.frame:addElement(elem, x, y) self.persist.beatmapListElem[i] = elem local coverPath = getLiveIconPath(track.icon) if Util.fileExists(coverPath) then Async.runFunction(loadCoverImage):run(elem, coverPath) end end end local function setStatusText(self, text, blink) self.persist.statusText:clear() if not(text) or #text == 0 then return end self.persist.statusText:add(text, 32, 550) if blink then if self.persist.statusTextBlink == math.huge then self.persist.statusTextBlink = 0 end else self.persist.statusTextBlink = math.huge end end local function downloadResponseCallback(self, statusCode, headers, length) if statusCode == 304 then Glow.removeElement(self.data.progress) setStatusText(self) -- Load local copy using async system Async.runFunction(initializeBeatmapList):run(self) elseif statusCode == 200 then self.persist.downloadData = { data = {}, bytesWritten = 0, header = headers, length = length } if length then self.data.progress:setMaxValue(length) end else self.data.progress:setValue(math.huge) setStatusText(self, L("beatmapSelect:download:errorStatusCode", {code = statusCode})) end end local function downloadReceiveCallback(self, data) local dldata = self.persist.downloadData dldata.data[#dldata.data + 1] = data dldata.bytesWritten = dldata.bytesWritten + #data if dldata.length then self.data.progress:setValue(dldata.bytesWritten) setStatusText(self, L("beatmapSelect:download:downloadingBytesProgress", { a = dldata.bytesWritten, b = dldata.length }), true) end end local function downloadFinishCallback(self) local dldata = self.persist.downloadData -- If dldata is nil, that means it's loaded in responseCallback if dldata then local mapData = table.concat(dldata.data) -- Save map data and initialize Async.runFunction(initializeBeatmapList):run(self, mapData, dldata.header.etag) self.persist.downloadData = nil setStatusText(self) Glow.removeElement(self.data.progress) end end local function downloadErrorCallback(self, message) setStatusText(self, L("beatmapSelect:download:errorGeneric", {message = message})) self.persist.downloadData = nil self.data.progress:setValue(math.huge) end local beatmapDownload = Gamestate.create { images = { coverMask = {"assets/image/ui/cover_mask.png", mipmaps}, navigateBack = {"assets/image/ui/over_the_rainbow/navigate_back.png", mipmaps}, }, fonts = {} } function beatmapDownload:load() Glow.clear() self.data.titleFont, self.data.statusFont = MainFont.get(31, 24) if self.data.back == nil then self.data.back = CircleIconButton(color.hex333131, 36, self.assets.images.navigateBack, 0.48, ColorTheme.get()) self.data.back:setData(self) self.data.back:addEventListener("mousereleased", leave) end Glow.addFixedElement(self.data.back, 32, 4) if self.data.shadowGradient == nil then self.data.shadowGradient = Util.gradient("vertical", color.black75PT, color.transparent) end if self.data.coverMaskShader == nil then self.data.coverMaskShader = love.graphics.newShader("assets/shader/mask.fs") self.data.coverMaskShader:send("mask", self.assets.images.coverMask) end if self.persist.frame == nil then self.persist.frame = Glow.Frame(0, 68, 960, 512) end if self.data.titleText == nil then self.data.titleText = love.graphics.newText(self.data.titleFont) self.data.titleText:add(L"beatmapSelect:download") end if self.data.progress == nil then self.data.progress = ProgressBar(896, 24) end end function beatmapDownload:start() self.persist.frame = Glow.Frame(0, 80, 960, 560) self.persist.frame:setSliderColor(color.hex434242) self.persist.frame:setSliderHandleColor(ColorTheme.get()) Glow.addFrame(self.persist.frame) self.persist.statusText = love.graphics.newText(self.data.statusFont) self.persist.statusTextBlink = math.huge self.persist.selectedIndex = nil local hasEtag = Util.fileExists("maps.json.etag") if not(hasEtag and Util.fileExists("maps.json")) then hasEtag = false love.filesystem.remove("maps.json") love.filesystem.remove("maps.json.etag") end -- maps.json cache local lastTag if hasEtag then lastTag = love.filesystem.read("maps.json.etag") end setStatusText(self, L"beatmapSelect:download:downloading", true) self.persist.download = download() :setData(self) :setResponseCallback(downloadResponseCallback) :setReceiveCallback(downloadReceiveCallback) :setFinishCallback(downloadFinishCallback) :setErrorCallback(downloadErrorCallback) :download(SERVER_ADDRESS.QUERY.."/maps.json", { ["If-None-Match"] = lastTag }) Glow.addElement(self.data.progress, 32, 584) end function beatmapDownload:update(dt) self.persist.frame:update(dt) if self.persist.statusTextBlink ~= math.huge then self.persist.statusTextBlink = (self.persist.statusTextBlink + dt) % 2 end end function beatmapDownload:draw() love.graphics.setColor(color.hex434242) love.graphics.rectangle("fill", -88, -43, 1136, 726) self.persist.frame:draw() love.graphics.setColor(color.white) love.graphics.draw(self.data.shadowGradient, -88, 77, 0, 1136, 8) love.graphics.setColor(color.hex333131) love.graphics.rectangle("fill", -88, 0, 1136, 80) love.graphics.setColor(color.white) love.graphics.draw(self.data.titleText, 112, 24) if self.persist.statusTextBlink ~= math.huge then love.graphics.setColor(color.compat(255, 255, 255, math.abs(1 - self.persist.statusTextBlink))) end Util.drawText(self.persist.statusText) Glow.draw() end function beatmapDownload:resumed() Glow.addFrame(self.persist.frame) if self.persist.selectedIndex then -- Try to set the cover art local i = self.persist.selectedIndex Async.runFunction(function() local track = self.persist.beatmapListGroup[i] local coverPath = getLiveIconPath(track.icon) if Util.fileExists(coverPath) then self.persist.beatmapListElem[i]:setCoverImage(AssetCache.loadImage(coverPath, mipmaps, handleInvalidCover)) end end):run() self.persist.selectedIndex = nil end end return beatmapDownload
-- -- This test checks that when the WAL thread runs out of disk -- space it automatically deletes old WAL files and notifies -- the TX thread so that the latter can shoot off WAL consumers -- that need them. See gh-3397. -- test_run = require('test_run').new() engine = test_run:get_cfg('engine') fio = require('fio') errinj = box.error.injection test_run:cmd("setopt delimiter ';'") function check_file_count(dir, glob, count) local files = fio.glob(fio.pathjoin(dir, glob)) if #files == count then return true end return false, files end; function check_wal_count(count) return check_file_count(box.cfg.wal_dir, '*.xlog', count) end; function check_snap_count(count) return check_file_count(box.cfg.memtx_dir, '*.snap', count) end; test_run:cmd("setopt delimiter ''"); box.cfg{checkpoint_count = 2} test_run:cleanup_cluster() box.schema.user.grant('guest', 'replication') s = box.schema.space.create('test', {engine = engine}) _ = s:create_index('pk') box.snapshot() -- -- Create a few dead replicas to pin WAL files. -- test_run:cmd("create server replica with rpl_master=default, script='replication/replica.lua'") test_run:cmd("start server replica") test_run:cmd("stop server replica") test_run:cmd("cleanup server replica") s:auto_increment{} box.snapshot() test_run:cmd("start server replica") test_run:cmd("stop server replica") test_run:cmd("cleanup server replica") s:auto_increment{} box.snapshot() test_run:cmd("start server replica") test_run:cmd("stop server replica") test_run:cmd("cleanup server replica") test_run:cmd("delete server replica") -- -- Make a few checkpoints and check that old WAL files are not -- deleted. -- s:auto_increment{} box.snapshot() s:auto_increment{} box.snapshot() s:auto_increment{} check_wal_count(5) check_snap_count(2) gc = box.info.gc() #gc.consumers -- 3 #gc.checkpoints -- 2 gc.signature == gc.consumers[1].signature -- -- Inject a ENOSPC error and check that the WAL thread deletes -- old WAL files to prevent the user from seeing the error. -- errinj.set('ERRINJ_WAL_FALLOCATE', 2) s:auto_increment{} -- success errinj.info()['ERRINJ_WAL_FALLOCATE'].state -- 0 check_wal_count(3) check_snap_count(2) gc = box.info.gc() #gc.consumers -- 1 #gc.checkpoints -- 2 gc.signature == gc.consumers[1].signature -- -- Check that the WAL thread never deletes WAL files that are -- needed for recovery from the last checkpoint, but may delete -- older WAL files that would be kept otherwise for recovery -- from backup checkpoints. -- errinj.set('ERRINJ_WAL_FALLOCATE', 3) s:auto_increment{} -- failure errinj.info()['ERRINJ_WAL_FALLOCATE'].state -- 0 check_wal_count(1) check_snap_count(2) gc = box.info.gc() #gc.consumers -- 0 #gc.checkpoints -- 2 gc.signature == gc.checkpoints[2].signature s:drop() box.schema.user.revoke('guest', 'replication') test_run:cleanup_cluster() -- Check that the garbage collector vclock is recovered correctly. test_run:cmd("restart server default") gc = box.info.gc() #gc.checkpoints -- 2 gc.signature == gc.checkpoints[2].signature
local main = require(game.Nanoblox) local User = require(main.shared.Packages.Remote.ClientRemote) return User
--- A defines module for retrieving colors by name. -- Extends the Factorio defines table. -- @usage require('stdlib/utils/defines/anticolor') -- @module defines.anticolor -- @see Concepts.Color --- Returns white for dark colors or black for lighter colors. -- @table anticolor -- @tfield Concepts.Color green defines.color.black -- @tfield Concepts.Color grey defines.color.black -- @tfield Concepts.Color lightblue defines.color.black -- @tfield Concepts.Color lightgreen defines.color.black -- @tfield Concepts.Color lightgrey defines.color.black -- @tfield Concepts.Color lightred defines.color.black -- @tfield Concepts.Color orange defines.color.black -- @tfield Concepts.Color white defines.color.black -- @tfield Concepts.Color yellow defines.color.black -- @tfield Concepts.Color black defines.color.white -- @tfield Concepts.Color blue defines.color.white -- @tfield Concepts.Color brown defines.color.white -- @tfield Concepts.Color darkblue defines.color.white -- @tfield Concepts.Color darkgreen defines.color.white -- @tfield Concepts.Color darkgrey defines.color.white -- @tfield Concepts.Color darkred defines.color.white -- @tfield Concepts.Color pink defines.color.white -- @tfield Concepts.Color purple defines.color.white -- @tfield Concepts.Color red defines.color.white local anticolor = {} local colors = require('stdlib/utils/defines/color_list') local anticolors = { green = colors.black, grey = colors.black, lightblue = colors.black, lightgreen = colors.black, lightgrey = colors.black, lightred = colors.black, orange = colors.black, white = colors.black, yellow = colors.black, black = colors.white, blue = colors.white, brown = colors.white, darkblue = colors.white, darkgreen = colors.white, darkgrey = colors.white, darkred = colors.white, pink = colors.white, purple = colors.white, red = colors.white } local _mt = { __index = function(_, c) return anticolors[c] and {r = anticolors[c]['r'], g = anticolors[c]['g'], b = anticolors[c]['b'], a = anticolors[c]['a'] or 1} or {r = 1, g = 1, b = 1, a = 1} end, __pairs = function() local k = nil local c = anticolors return function() local v k, v = next(c, k) return k, (v and {r = v['r'], g = v['g'], b = v['b'], a = v['a'] or 1}) or nil end end } setmetatable(anticolor, _mt) _G.defines = _G.defines or {} _G.defines.anticolor = anticolor return anticolor
OptionsState = Class { __includes = BaseState } local noTrailImage = love.graphics.newImage('assets/images/noTrail.png') local TrailImage = love.graphics.newImage('assets/images/trail.png') local musicSlider local SFXValue function OptionsState:enter(params) self.suit = Suit.new() settingsOption = { BallTrail = { checked = options.BallTrail }, FullScreen = { checked = options.FullScreen }, music = { checked = options.music }, SFX = { checked = options.SFX } } musicSlider = { value = options.musicValue, min = 0, max = 1, step = 0.1 } SFXValue = { value = options.SFXValue, min = 0, max = 1, step = 0.1 } end function OptionsState:update(dt) if self.suit:Button('Back', { font = fonts['Semibold40'] }, 50, 600, 240, 60).hit or love.keyboard.wasPressed('escape') then gStateMachine:change('start') end if self.suit:Checkbox(settingsOption.BallTrail, 215, 130, 50, 39).hit then options.BallTrail = settingsOption.BallTrail.checked end if self.suit:Button('<', { font = fonts['Semibold40'] }, Window.width / 2 - 69.42 - 25, 295, 50, 50).hit then PreviousBallColor() end if self.suit:Button('>', { font = fonts['Semibold40'] }, Window.width / 2 + 69.42 - 25, 295, 50, 50).hit then NextBallColor() end if self.suit:Button('Report an Issue', {font = fonts['Semibold40']}, Window.width - 350 - 50, 600, 350, 60).hit then love.system.openURL("mailto:adawoud1000@hotmail.com") end --[[ Full Screen ]] if self.suit:Checkbox(settingsOption.FullScreen, 1038, 130, 50, 39).hit then options.FullScreen = settingsOption.FullScreen.checked if options.FullScreen then push:setupScreen(Window.width, Window.height, Window.width, Window.height, { fullscreen = true, resizable = false, vsync = true }) else push:setupScreen(Window.width, Window.height, Window.width, Window.height, { fullscreen = false, resizable = true, vsync = true }) end end --[[ Music ]] if self.suit:Checkbox(settingsOption.music, 1038, 230, 50, 39).hit then options.music = settingsOption.music.checked if options.music then sounds['main']:setVolume(musicSlider.value) sounds['play']:setVolume(musicSlider.value) else sounds['main']:setVolume(0) sounds['play']:setVolume(0) end end --[[ SFX ]] if self.suit:Checkbox(settingsOption.SFX, 1038, 330, 50, 39).hit then options.SFX = settingsOption.SFX.checked if options.SFX then sounds['clack']:setVolume(musicSlider.value) else sounds['clack']:setVolume(0) end end --[[ Music Slider ]] if self.suit:Slider(musicSlider, 55, 454, 185, 50).changed then options.musicValue = musicSlider.value if options.music then sounds['main']:setVolume(musicSlider.value) sounds['play']:setVolume(musicSlider.value) end end --[[ VFX Slider ]] if self.suit:Slider(SFXValue, 315, 454, 185, 50).changed then options.SFXValue = SFXValue.value if options.SFX then sounds['clack']:setVolume(SFXValue.value) end end end function OptionsState:render() love.graphics.clear(0.1, 0.12, 0.15) love.graphics.setFont(fonts['ExtraBold60']) love.graphics.printf("Options", 0, 20, Window.width, 'center') --[[ Ball Trail ]] -- Big Rectangle love.graphics.rectangle('line', 38, 113, 221, 260, 30, 30) -- The Word "Ball Trail" love.graphics.setFont(fonts['Bold32']) love.graphics.print("Ball Trail", 50, 130) -- Description love.graphics.setFont(fonts['Regular13']) love.graphics.print("The Path That Follows The Ball\n(Better Visualization)", 50, 170) -- Photo Representation love.graphics.draw(options.BallTrail and TrailImage or noTrailImage, 75, 200) self.suit:draw() --[[ Ball Color ]] -- Big Rectangle love.graphics.rectangle('line', Window.width / 2 - 266 / 2, 113, 266, 260, 30, 30) -- The Word "Ball Color" love.graphics.setFont(fonts['Bold32']) love.graphics.printf("Ball Colour", 0, 130, Window.width, 'center') -- Description love.graphics.setColor(options.BallColor[1], options.BallColor[2], options.BallColor[3]) love.graphics.setFont(fonts['Regular13']) love.graphics.printf("Change The Colour of the ball", 0, 170, Window.width, 'center') -- Colour Representation love.graphics.circle('fill', Window.width / 2, 245, 40) love.graphics.setColor(1, 1, 1, 1) --[[ Full Screen ]] -- Big Rectangle love.graphics.rectangle('line', 817, 113, 287, 71, 13, 13) -- The Word "Full Screen" love.graphics.setFont(fonts['Bold32']) love.graphics.print("Full Screen", 833, 130) --[[ Music ]] love.graphics.rectangle('line', 817, 213, 287, 71, 13, 13) -- The Word "Full Screen" love.graphics.setFont(fonts['Bold32']) love.graphics.print("Music", 833, 230) --[[ Music Toggle ]] love.graphics.rectangle('line', 817, 313, 287, 71, 13, 13) -- The Word "Full Screen" love.graphics.setFont(fonts['Bold32']) love.graphics.print("SFX", 833, 330) --[[ Music Slider ]] love.graphics.rectangle('line', 38, 402, 221, 108, 13, 13) love.graphics.setFont(fonts['Bold32']) love.graphics.print("Music: " .. math.floor(musicSlider.value * 100) .. "%", 38 + 11, 402 + 18) --[[ SFX Slider ]] love.graphics.rectangle('line',298, 402, 221, 108, 13, 13) love.graphics.setFont(fonts['Bold32']) love.graphics.print("SFX: " .. math.floor(SFXValue.value * 100) .. "%", 298 + 11, 402 + 18) end function OptionsState:exit() SaveGame() end function NextBallColor() local cuurentColor = options.BallColor for i, v in ipairs(BallColors) do if cuurentColor[1] == v[1] and cuurentColor[2] == v[2] and cuurentColor[3] == v[3] then if i == #BallColors then options.BallColor = BallColors[1] else options.BallColor = BallColors[i + 1] end break end end end function PreviousBallColor() local cuurentColor = options.BallColor for i, v in ipairs(BallColors) do if cuurentColor[1] == v[1] and cuurentColor[2] == v[2] and cuurentColor[3] == v[3] then if i == 1 then options.BallColor = BallColors[#BallColors] else options.BallColor = BallColors[i - 1] end break end end end
----------------------------- ----------------------------- ---------BASE CODE----------- ----------------------------- ----------------------------- --RECT ----------------------------- function Rect_new(self, x, y, width, height) self.type = "Rect" self.x = x or 0 self.y = y or self.x self.width = width or 0 self.height = height or self.width return self end function Rect_draw(self) if self.color then color(self.color) end rect(self.x, self.y, self.width, self.height) end function Rect_set(self, x, y, width, height) self.x = x or self.x self.y = y or self.y self.width = width or self.width self.height = height or self.height end function Rect_get(self) return self.x, self.y, self.width, self.height end function Rect_clone(self, r) self.x = r.x self.y = r.y self.width = r.width self.height = r.height end --If rect overlaps with rect or point function Rect_overlaps(self, r) return self.x + self.width > r.x and self.x < r.x + (r.width or 0) and self.y + self.height > r.y and self.y < r.y + (r.height or 0) end function Rect_overlapsX(self, r) return self.x + self.width > r.x and self.x < r.x + (r.width or 0) end function Rect_overlapsY(self, r) return self.y + self.height > r.y and self.y < r.y + (r.height or 0) end function Rect_top(self, val) if val then self.y = val end return self.y end function Rect_bottom(self, val) if val then self.y = val - self.height end return self.y + self.height end function Rect_centerX(self, val) if val then self.x = val - self.width / 2 end return self.x + self.width / 2 end function Rect_centerY(self, val) if val then self.y = val - self.height / 2 end return self.y + self.height / 2 end function Rect_distance(self, r) return sqrt(abs(self.x - r.x)^2 + abs(self.y - r.y)^2) end function Rect_distanceCenter(self, r) return sqrt(abs(self.x + self.width/2 - r.x + r.width/2)^2 + abs(self.y + self.height/2 - r.y + r.height/2)) end function Rect_distanceY(self, r) return abs(self.y - r.y) end function Rect_distanceCenterX(self, r) return abs((self.x + self.width/2) - (r.x + r.width/2)) end function Rect_distanceCenterY(self, r) return abs((self.y + self.height/2) - (r.y + r.height/2)) end ----------------------------- --Spr ----------------------------- function Spr_new(self, x, y, img) Rect_new(self, x, y, 8) self.type = "Spr" self.__save = {} self.dead = nil self.img = img self.imgWidth = 1 self.imgHeight = 1 -- self.flip = {x = nil, y = nil} self.flip_x = nil self.flip_y = nil self.offset_x = 0 self.offset_y = 0 self.visible = true self.frame = 1 self.frameTimer = 1 self.frameTimerDir = 1 self.anim = nil -- self.anims = {} self.animEnded = nil return self end function Spr_update(self) Spr_simplify(self) Spr_animate(self) end function Spr_draw(self) if self.visible and not self.dead then blit(self.img + (self.anim and self["anim__" .. self.anim][self.frame] * self.imgWidth - 1 or 0), self.x + self.offset_x, self.y + self.offset_y, self.imgWidth, self.imgHeight, self.flip_x, self.flip_y) end end function Spr_animate(self) if self.anim then local ani = self["anim__" .. self.anim] if not (ani.mode == "once" and self.animEnded) then self.frameTimer = self.frameTimer + 1 / self["anim__" .. self.anim].speed if self.frameTimer >= #ani + 1 or self.frameTimer <= 0 then if self.mode == "pingpong" then self.frameTimerDir = -self.frameTimerDir self.frameTimer = self.frameTimerDir > 0 and 2 or self.frameTimer - #ani elseif ani.mode == "once" then self.frameTimer = #ani else self.frameTimer = self.frameTimer - #ani end self.animEnded = true end self.frame = flr(self.frameTimer) end end end function Spr_addAnim(self, name, t, speed, mode) local a = {} self["anim__" .. name] = a a.speed = speed or 1 a.mode = mode or "loop" for i=1,#t do a[i] = t[i] end end function Spr_setAnim(self, anim, force) if self.anim ~= anim or force then self.frame = 1 self.frameTimer = 1 self.frameTimerDir = 1 self.anim = anim self.animEnded = nil end end function Spr_simplify(self) if self.type == "Eye" then return Eye_simplify(self) else return Spr_simplify_real(self) end end function Spr_simplify_real(self) --I check if it's out of screen, then I save the important variables, and remove everything else if Spr_canSimplify(self) then puts(self.__save,{"x","y","width","height","type","__save"}) local new = {} for i,k in pairs(self.__save) do new[k] = self[k] end new.simplified = true local t = data(new.type) local i = find(t, self) del(t, i) put(t, new) end end function Spr_renew(self) if not Spr_canSimplify(self) then local old = {} for i,k in ipairs(self.__save) do if k ~= "__save" then old[k] = self[k] end end self.simplified = nil data(self.type, true)(self, self.x, self.y) for k,v in pairs(old) do self[k] = old[k] end return true end return nil end function Spr_canSimplify(self) if self.type == "Plr" then return nil elseif self.type == "Torch" then return Torch_canSimplify(self) elseif self.type == "Bat" then return Bat_canSimplify(self) elseif self.type == "Spider" then return Spd_canSimplify(self) elseif self.type == "Spear" then return Spear_canSimplify(self) elseif self.type == "Lava" then return Lava_canSimplify(self) elseif self.type == "Bolt" then return nil elseif self.type == "Wzrd" then return nil elseif self.type == "Crown" then return nil elseif self.type == "Stairs" then return nil elseif self.type == "Platform" then return nil else return Spr_canSimplify_real(self) end end function Spr_canSimplify_real(self) return not Rect_overlaps(self, {x = cam_x, y = cam_y, width = cam_width, height = cam_height}) end ----------------------------- --Ent ----------------------------- function Ent_new(self, x, y, img) Spr_new(self, x, y, img) self.type = "Ent" self.velocity_x = 0 self.velocity_y = 0 self.last = Rect_new({}, x, y) self.priority_x = 0 self.priority_y = 0 self._prior_x = 0 self._prior_y = 0 self.bounce_x = 0 self.bounce_y = 0 self.mass = 0 self.ignoreMap = nil self.grounded = nil self.solid = true self.dead = nil return self end function Ent_update(self) if not self.dead then Rect_clone(self.last, self) self._prior_x = self.priority_x self._prior_y = self.priority_y self.velocity_y = self.velocity_y + self.mass self.velocity_y = min(5, self.velocity_y) self.x = self.x + self.velocity_x self.y = self.y + self.velocity_y if not self.ignoreMap then Ent_resolveMapCollision(self) end if self.velocity_x ~= 0 then self.flip_x = self.velocity_x < 0 end Spr_update(self) end end function Ent_resolveMapCollision(self) --I feel like this can be optimized. Not sure how much it would save kb wise though if self.x - self.last.x > 0 then if getWOP(self.x + self.width-1, self.y) and not getWOP(self.last.x + self.width-1, self.y) then Ent_hitMapRight(self) elseif getWOP(self.x + self.width-1, self.y + self.height-1) and not getWOP(self.last.x + self.width-1, self.y + self.height-1) then Ent_hitMapRight(self) end else if getWOP(self.x, self.y) and not getWOP(self.last.x, self.y) then Ent_hitMapLeft(self) elseif getWOP(self.x, self.y + self.height-1) and not getWOP(self.last.x, self.y + self.height-1) then Ent_hitMapLeft(self) end end if self.y - self.last.y > 0 then if getWOP(self.x, self.y + self.height-1) and not getWOP(self.x, self.last.y + self.height-1) then Ent_hitMapBottom(self) elseif getWOP(self.x + self.width-1, self.y + self.height-1) and not getWOP(self.x + self.width-1, self.last.y + self.height-1) then Ent_hitMapBottom(self) end else if getWOP(self.x, self.y) and not getWOP(self.x, self.last.y) then Ent_hitMapTop(self) elseif getWOP(self.x + self.width-1, self.y) and not getWOP(self.x + self.width-1, self.last.y) then Ent_hitMapTop(self) end end end function Ent_overlaps(self, e) return self ~= e and not self.dead and not e.dead and Rect_overlaps(self, e) end function Ent_resolveCollision(self, e) if self.simplified or e.simplified then return end if Ent_overlaps(self, e) then Ent_onOverlap(self, e) end end function Ent_onOverlap(self, e) if self.type == "Plr" then Plr_onOverlap(self, e) elseif self.type == "Crate" then Crate_onOverlap(self, e) elseif self.type == "Button" then Btn_onOverlap(self, e) elseif self.type == "Switch" then Stc_onOverlap(self, e) elseif self.type == "Bat" then Bat_onOverlap(self, e) elseif self.type == "Spider" then Spd_onOverlap(self, e) elseif self.type == "Wzrd" then Wzrd_onOverlap(self, e) else Ent_onOverlap_real(self) end end function Ent_onOverlap_real(self, e) if self.solid and e.solid then Ent_separate(self, e) end end function Ent_separate(self, e) Ent_separateAxis(self, e, Rect_overlapsY(self.last, e.last) and "x" or "y") end function Ent_separateAxis(self, e, a) local s = a == "x" and "width" or "height" if self["_prior_" .. a] >= e["_prior_" .. a] then if (e.last[a] + e.last[s] / 2) < (self.last[a] + self.last[s] / 2) then e[a] = self[a] - e[s] else e[a] = self[a] + self[s] end e["velocity_" .. a] = e["velocity_" .. a] * -e["bounce_" .. a] e["_prior_" .. a] = self["_prior_" .. a] else Ent_separateAxis(e, self, a) end Ent_resolveMapCollision(e) end function Ent_hitMapBottom(self) if self.type == "Plr" then Plr_hitMapBottom(self) elseif self.type == "Crate" then Crate_hitMapBottom(self) elseif self.type == "Spider" then Spd_hitMapBottom(self) elseif self.type == "Crown" then Crown_hitMapBottom(self) elseif self.type == "Spear" then Spear_hitMapBottom(self) else Ent_hitMapBottom_real(self) end end function Ent_hitMapTop(self) if self.type == "Bat" then Bat_hitMapTop(self) elseif self.type == "Spider" then Spd_hitMapTop(self) elseif self.type == "Spear" then Spear_hitMapTop(self) else Ent_hitMapTop_real(self) end end function Ent_hitMapLeft(self) if self.type == "Crate" then Crate_hitMapLeft(self) else Ent_hitMapLeft_real(self) end end function Ent_hitMapRight(self) if self.type == "Crate" then Crate_hitMapRight(self) else Ent_hitMapRight_real(self) end end function Ent_hitMapLeft_real(self) self.velocity_x = self.velocity_x * -self.bounce_x self.x = toGrid(self.x + self.width)*8 self._prior_x = 10000 end function Ent_hitMapTop_real(self) self.velocity_y = self.velocity_y * -self.bounce_y self.y = toGrid(self.y + self.height)*8 self._prior_y = 10000 end function Ent_hitMapRight_real(self) self.velocity_x = self.velocity_x * -self.bounce_x self.x = toGrid(self.x + self.width)*8 - self.width self._prior_x = 10000 end function Ent_hitMapBottom_real(self) self.velocity_y = self.velocity_y * -self.bounce_y self.y = toGrid(self.y + self.height)*8 - self.height self._prior_y = 10000 self.grounded = true end ----------------------------- --UTILS ----------------------------- function ceil(a) local b = flr(a) return b < a and b + 1 or a end function round(a) local b = flr(a) return a - b < 0.5 and b or b + 1 end function sign(a) return a > 0 and 1 or -1 end function random(a, b) if not b then b = a a = 0 end return a + flr(rand() * (b-a+1)) end function frandom(a, b) if not b then b = a a = 0 end return a + rand() * (b-a+1) end function toGrid(x, y) if y then return flr(round(x) / 8), flr(round(y) / 8) else return flr(round(x) / 8) end end function puts(t, a) for i,v in ipairs(a) do put(t, v) end end --get Map On Position function getWOP(x, y) return isWall(mget(toGrid(x, y))) end function isWall(a) return a >= 29 and a <= 63 end function simple(v) return v.simplified and not Spr_renew(v) end function has(t, val) for i,v in ipairs(t) do if v == val then return true end end return nil end function find(t, val) for i,v in ipairs(t) do if v == val then return i end end return -1 end function data(class, a) if class == "Bat" then return a and Bat_new or bats elseif class == "Spider" then return a and Spd_new or spiders elseif class == "Torch" then return a and Torch_new or torches elseif class == "Crate" then return a and Crate_new or crates elseif class == "Door" then return a and Door_new or doors elseif class == "Button" then return a and Btn_new or buttons elseif class == "Switch" then return a and Stc_new or switches elseif class == "Key" then return a and Key_new or keys elseif class == "Coin" then return a and Coin_new or coins elseif class == "Spring" then return a and Spring_new or springs elseif class == "Spikes" then return a and Spk_new or spikes elseif class == "Lava" then return a and Lava_new or lavas elseif class == "Platform" then return a and Platform_new or platforms elseif class == "Spear" then return a and Spear_new or spears elseif class == "Window" then return a and Window_new or windows end end voice = 0 function sfx(b, c, d, e, f, g) if MENU then return end voice = (voice + 1) % 3 play(voice, b, c, d, e ,f ,g) end ----------------------------- ----------------------------- -----------GAME-------------- ----------------------------- ----------------------------- function init() LEVEL = random(1, 6) BOSS = 8 CREDITS = 9 CONGRATS = 11 -- MENU = LEVEL == 1 MENU = true SPECIAL = 0 SPEEDRUN = false cam_x, cam_y = 0, 0 cam_width, cam_height = 128, 128 cam_scene = nil cam_sceneTo = {x = 0, y = 0, width = 1, height = 1} lightsTimer = 0 speed_timer = 0 restart_timer = 90 level_init() end function update(s) if fadeDir ~= 0 then fadeTimer = fadeTimer + fadeDir if fadeTimer >= 20 then fadeDir = 0 if Plr.dead then level_reset() elseif Plr.onStairs then LEVEL = LEVEL + 1 level_reset() return elseif MENU then LEVEL = 1 MENU = nil level_reset() end elseif fadeTimer <= 0 then fadeDir = 0 end end if LEVEL == CONGRATS then cam_x = level.x cam_y = level.y - 32 camera(cam_x, cam_y) if button(4, true) then init() end return end Plr_update(Plr) if crown then Ent_resolveCollision(Plr, crown) end if stairs and not MENU then Stairs_update(stairs) Ent_resolveCollision(Plr, stairs) end lightsTimer = (lightsTimer + 0.2) if lightsTimer >= 13 then lightsTimer = lightsTimer - 14 end if #eyes > 6 then del(eyes, 1) del(eyes, 1) end if LEVEL == BOSS then if crown then Ent_update(crown) end Wzrd_update(Wzrd) for i,v in ipairs(bolts) do if Bolt_update(v) then del(bolts, i) else Ent_resolveCollision(Wzrd, v) Ent_resolveCollision(Plr, v) end end for i,v in ipairs(light_clouds) do Cloud.update(v) end for i,v in ipairs(dark_clouds) do Cloud.update(v) end end if scene then scene_update() end for i,v in ipairs(platforms) do if not simple(v) then for i=1,4 do Ent_resolveCollision(Plr, v) for j,w in ipairs(platforms) do Ent_resolveCollision(v, w) end end Ent_update(v) end end for i,v in ipairs(eyes) do if not simple(v) then Eye_update(v) end end for i,v in ipairs(coins) do if not simple(v) then Coin_update(v) if v.dead then del(coins, i) end end end for i,v in ipairs(keys) do if not simple(v) then Key_update(v) for j,w in ipairs(doors) do Ent_resolveCollision(v, w) end if v.dead then del(keys, i) end end end for i,v in ipairs(doors) do if not simple(v) then Door_update(v) Ent_resolveCollision(Plr, v) end end for i,v in ipairs(springs) do if not simple(v) then Spring_update(v) Ent_resolveCollision(Plr, v) end end for i,v in ipairs(crates) do if not simple(v) then Crate_update(v) for i=1,4 do Ent_resolveCollision(Plr, v) for j,w in ipairs(crates) do Ent_resolveCollision(v, w) end for j,w in ipairs(doors) do Ent_resolveCollision(v, w) end end end end for i,v in ipairs(buttons) do if not simple(v) then Btn_update(v) for i=1,4 do Ent_resolveCollision(v, Plr) for j,w in ipairs(crates) do Ent_resolveCollision(v, w) end end end end for i,v in ipairs(switches) do if not simple(v) then Stc_update(v) Ent_resolveCollision(v, Plr) end end for i,v in ipairs(bats) do if not simple(v) then Bat_update(v) Ent_resolveCollision(Plr, v) for i=1,4 do for j,w in ipairs(doors) do Ent_resolveCollision(v, w) end end if LEVEL == BOSS and v.anim == "sleeping" then del(bats, i) end end end for i,v in ipairs(spiders) do if not simple(v) then Spd_update(v) Ent_resolveCollision(Plr, v) for i=1,4 do for j,w in ipairs(doors) do Ent_resolveCollision(v, w) end end if LEVEL == BOSS and v.anim == "sleeping" then del(spiders, i) end end end for i,v in ipairs(spikes) do if not simple(v) then Spk_update(v) Ent_resolveCollision(Plr, v) end end for i,v in ipairs(torches) do if not simple(v) then Spr_update(v) end end for i,v in ipairs(spears) do if not simple(v) then Spear_update(v) Ent_resolveCollision(Plr, v) end end for i,v in ipairs(lavas) do if not simple(v) then Ent_update(v) Ent_resolveCollision(Plr, v) end end for i,v in ipairs(windows) do if not simple(v) then Spr_update(v) end end if LEVEL == CREDITS then credit_x = credit_x - 1 if Plr.x >= level.x + level.width + 140 then if button(4, true) then level_reset(true) return end end end cam_update() if music.play then playMusic(music.play) end if tune then playMusic(tune, true) end if MENU then cam_x = level.x + level.width / 2 - 64 cam_y = level.y + level.height / 2 - 64 camera(cam_x, cam_y) if button(4, true) or button(0, true) then fadeDir = 1 elseif button(5, true) then SPEEDRUN = true fadeDir = 1 end elseif LEVEL ~= CREDITS then if button(5) then restart_timer = restart_timer - 1 if restart_timer <= 0 then level_reset(true) end else restart_timer = 90 end end end function draw() color(0) clear() if LEVEL == BOSS then for i,v in ipairs(light_clouds) do Cloud.draw(v) end end if LEVEL == CONGRATS then color(3) rect(level.x, level.y, level.width, level.height) mblit() color(1) rect(level.x, level.y-32, level.width, 32) rect(level.x, level.y+56, level.width, 64) color(2) print("CONGRATULATIONS!", level.x + 33, level.y - 16) print("THOU ART WONDROUS", level.x + 33, level.y + 70) if SPEEDRUN then print("Time: " .. flr(speed_timer/30), level.x + 40, level.y + 85) end return end for i,v in ipairs(torches) do if not simple(v) then Torch_draw(v) end end for i,v in ipairs(windows) do if not simple(v) then Window_draw(v) end end if stairs then Stairs_draw(stairs) end for i,v in ipairs(coins) do if not simple(v) then Spr_draw(v) end end for i,v in ipairs(keys) do if not simple(v) then Spr_draw(v) end end for i,v in ipairs(springs) do if not simple(v) then Spr_draw(v) end end for i,v in ipairs(crates) do if not simple(v) then Spr_draw(v) end end for i,v in ipairs(platforms) do if not simple(v) then Spr_draw(v) end end for i,v in ipairs(bats) do if not simple(v) then Spr_draw(v) end end for i,v in ipairs(doors) do if not simple(v) then Door_draw(v) end end for i,v in ipairs(spiders) do if not simple(v) then Spd_draw(v) end end if LEVEL == BOSS or LEVEL == BOSS - 1 then Wzrd_draw(Wzrd) end Plr_draw(Plr) if crown then Spr_draw(crown) end mblit() if LEVEL == BOSS then for i,v in ipairs(bolts) do Bolt_draw(v) end for i,v in ipairs(dark_clouds) do Cloud.draw(v, true) end for i,v in ipairs(dark_clouds) do Cloud.draw(v) end end -- for i,v in ipairs(walls) do -- blit(v.img, v.x, v.y) -- end for i,v in ipairs(secrets) do Spr_draw(v) end for i,v in ipairs(eyes) do if not simple(v) then Spr_draw(v) end end for i,v in ipairs(buttons) do if not simple(v) then Btn_draw(v) end end for i,v in ipairs(switches) do if not simple(v) then Stc_draw(v) end end for i,v in ipairs(spikes) do if not simple(v) then Spr_draw(v) end end for i,v in ipairs(spears) do if not simple(v) then Spear_draw(v) end end for i,v in ipairs(lavas) do if not simple(v) then Lava_draw(v) end end color(1) rect(level.x-128, level.y-128, level.width + 128 + 8, 128) rect(level.x-128, level.y + level.height + 8, level.width + 128 + 8, 128) rect(level.x + level.width + 8, level.y - 128, 128, level.height + 256) rect(level.x-128, level.y - 128, 128, level.height + 256) color(2) if scene then if scene.text1 then print(scene.text1, cam_x + 64 - #scene.text1*2, cam_y + 20) end if scene.text2 then print(scene.text2, cam_x + 64 - #scene.text2*2, cam_y + 30) end end if LEVEL ~= CREDITS and not MENU then for i=0,2 do blit(i < Plr.health and 160 or 161, cam_x + 1 + 9 * i, cam_y) end if SPEEDRUN then color(2) print("Time: " .. flr(speed_timer/30), cam_x, cam_y + 120) end if button(5) then color(2) print("Hold to restart game", cam_x + 45, cam_y + 2) rect(cam_x + 45, cam_y + 8, restart_timer / 1.2, 1) end elseif SPEEDRUN and LEVEL == CREDITS then color(2) print("Time: " .. flr(speed_timer/30), cam_x, cam_y + 120) end if MENU then color(2) rect(cam_x + 31, cam_y + 47, 66, 34) rect(cam_x + 29, cam_y + 45, 5, 5) rect(cam_x + 94, cam_y + 45, 5, 5) rect(cam_x + 94, cam_y + 78, 5, 5) rect(cam_x + 29, cam_y + 78, 5, 5) color(1) rect(cam_x + 33, cam_y + 49, 62, 30) color(2) local xprove, yprove = 53, 53 local xworth, yworth = 33, 66 for i=-1,1 do for j=-1,1 do blit(125, cam_x + xprove + i, cam_y + yprove + j, 3) blit(153, cam_x + xworth + i, cam_y + yworth + j, 7) end end blit(122, cam_x + xprove, cam_y + yprove, 3) blit(137, cam_x + xworth, cam_y + yworth, 7) color(1) for i=-1,1 do for j=-1,1 do print("Press JUMP to start", cam_x + 27 + i, cam_y + 90 + j) end end color(2) print("Press JUMP to start", cam_x + 27, cam_y + 90) color(1) for i=-1,1 do for j=-1,1 do print("Made by Sheepolution", cam_x + 25 + i, cam_y + 115 + j) end end color(2) print("Made by Sheepolution", cam_x + 25, cam_y + 115) end color(1) --SAVE! Merge with borders? rect(cam_x, cam_y, cam_width, fadeTimer * 4) rect(cam_x, cam_y + cam_height - fadeTimer * 4, cam_width, cam_height) rect(cam_x, cam_y, fadeTimer * 4, cam_height) rect(cam_x + cam_width - fadeTimer * 4, cam_y, cam_width, cam_height) if LEVEL == CREDITS then color(2) for i,v in ipairs(credits) do print(v, cam_x + credit_x + 128 * i, cam_y + 100) end end end function level_init(RESET) local levels = { {--1 x = 0, y = 0, width = 59, height = 8, doors_locked = {nil, nil, true, true}, doors_solidWhenOn = {true}, Btn_targets = {{2}}, Stc_targets = {{1}}, coins = 6 }, { --2 x = 0, y = 8, width = 59, height = 12, doors_locked = {nil, nil, true, nil, true}, doors_solidWhenOn = {}, Btn_targets = {{1},{4}}, Stc_targets = {{2}}, coins = 6 }, {--3 x = 0, y = 33, width = 30, height = 15, doors_locked = {true, nil, nil, nil}, doors_solidWhenOn = {nil, true, nil, true}, Btn_targets = {{3}}, Stc_targets = {{4},{2}}, coins = 3 }, {--4 x = 30, y = 33, width = 30, height = 15, doors_locked = {true, nil, nil, nil}, doors_solidWhenOn = {nil, nil, true, false}, Btn_targets = {{2}}, Stc_targets = {{3,4}}, coins = 4 }, {--5 x = 28, y = 20, width = 31, height = 13, doors_locked = {true, true, nil, true, true}, doors_solidWhenOn = {}, Btn_targets = {{3}}, Stc_targets = {}, coins = 0 }, {--6 x = 0, y = 20, width = 28, height = 13, doors_locked = {nil, nil, nil, true, true}, doors_solidWhenOn = {}, Btn_targets = {{1},{2},{3}}, coins = 3 }, {--BOSS ENTRANCE x = 85, y = 0, width = 43, height = 4, coins = 1 }, {--BOSS FIGHT x = 60, y = 0, width = 24, height = 17, doors_locked = {true}, doors_solidWhenOn = {}, }, {--CREDITS x = 85, y = 0, width = 43, height = 4, }, {--SPECIAL x = 59, y = 16, width = 100, height = 100, coins = 18 }, {--CONGRATS x = 97, y = 8, width = 16, height = 6 } } local self = levels[LEVEL] level = self inventory = {} inventory.coins = 0 inventory.keys = 0 --Lots of tables, but that's for the sake of drawing order mostly. --Maybe different tables for each layer? But not sure how much that would save. eyes = {} coins = {} torches = {} keys = {} doors = {} crates = {} springs = {} platforms = {} buttons = {} switches = {} lavas = {} bats = {} windows = {} spiders = {} spikes = {} secrets = {} spears = {} level_save = {} if LEVEL == BOSS then dark_clouds = {} light_clouds = {} bolts = {} for i=1,20 do put(light_clouds, Cloud_new((level.x * 8) + i * 20, level.y + 66 + random(0, 20), 1)) put(dark_clouds, Cloud_new((level.x * 8) + i * 20, level.y - 14 + random(0, 20), 2)) end end local wall = {{29,30,31}, {45,46,47}, {61,62,63}} local fakewall = {{77,78,79}, {93,94,95}, {109,110,111}} Plr = {x = 0, y = 0} for i=self.x, self.x + self.width do for j=self.y, self.y + self.height do local obj local a = mget(i, j) local x = i * 8 local y = j * 8 local del = true if a == 29 then mset(i,j,wall[(j % 3) + 1][(i % 3) + 1]) del = nil elseif a == 28 then mset(i,j,fakewall[(j % 3) + 1][(i % 3) + 1]) del = nil elseif a == 99 then del = nil -- mset(i,j,0) -- put(walls, {x = i*8, y = j*8, img = wall[(j % 3) + 1][(i % 3) + 1]}) elseif a == 224 then Plr = Plr_new({}, x, y) elseif a == 225 then obj = Coin_new({}, x, y) elseif a == 226 then obj = Torch_new({}, x, y) elseif a == 227 then obj = Key_new({}, x, y) elseif a == 228 then obj = Door_new({}, x, y, self.doors_locked[#doors + 1], self.doors_solidWhenOn[#doors + 1]) elseif a == 229 then obj = Crate_new({}, x, y) elseif a == 230 then obj = Platform_new({}, x, y) elseif a == 231 then obj = Btn_new({}, x, y + 3, self.Btn_targets[#buttons+1]) elseif a == 232 then obj = Bat_new({}, x, y) elseif a == 233 then obj = Stc_new({}, x, y, self.Stc_targets[#switches+1]) elseif a == 234 then obj = Lava_new({}, x, y) elseif a == 235 then obj = Window_new({}, x, y) elseif a == 236 then obj = Spd_new({}, x, y) elseif a == 237 then obj = Spk_new({}, x+1, y+5) elseif a == 238 then obj = Spring_new({}, x, y) elseif a == 239 then stairs = Stairs_new({}, x, y, LEVEL == CREDITS) elseif a == 240 then Wzrd = Wzrd_new({}, x, y) elseif a == 241 then obj = Coin_new({}, x, y, true) put(level_save, {i, j, a}) mset(i,j,fakewall[(j % 3) + 1][(i % 3) + 1]) del = nil elseif a == 242 then put(spears, Spear_new({}, x, y)) end if obj then put(data(obj.type), obj) Spr_simplify(obj) end if del and a >= 224 then mset(i, j, 0) put(level_save, {i, j, a}) end end end if Plr.width then cam_x = Plr.x + Plr.width/2 - 64 cam_y = Plr.y + Plr.height/2 - 64 cam_update() end self.x = self.x * 8 self.y = self.y * 8 self.width = self.width * 8 self.height = self.height * 8 fadeTimer = 16 fadeDir = -1 if LEVEL == BOSS - 1 then scene = {step = 0, timer = 0} Wzrd.x = Wzrd.x + 16 music.play = nil end if LEVEL == BOSS then scene = {step = 0, timer = 0} music.play = "boss" end if LEVEL == CREDITS then stairs = Stairs_new({}, stairs.x-16, stairs.y-5, true) coins = {} Wzrd = nil Plr.crown = true credits = {"Made by Sheepolution", "Special thanks to", "rxi for creating the framework", " The Ludum Dare Community", "Thank you for playing!"} mset(127, 1, 0) mset(127, 2, 0) mset(127, 3, 0) credit_x = 50 music.play = "main" end end function level_reset(full) for i,v in ipairs(level_save) do mset(v[1],v[2],v[3]) end scene = nil stairs = nil level.x = level.x / 8 level.y = level.y / 8 level.width = level.width / 8 level.height = level.height / 8 if full then init() else level_init() end end ----------------------------- ----------------------------- ----------------------------- --Plr ----------------------------- function Plr_new(self, x, y) Ent_new(self, x, y+2, 0) self.type = "Plr" Spr_addAnim(self,"idle",{1}) Spr_addAnim(self,"jump",{2}) Spr_addAnim(self,"walk",{3, 1, 2}, 3) Spr_addAnim(self,"explode",{14, 15, 16}, 2.5, "once") self.anim = "idle" self.width = 6 self.height = 6 self.offset_y = -2 self.offset_x = -1 self.idleTimer = 0 self.deadTimer = 50 self.invisTimer = 0 self.groundTimer = 3 self.grounded = true self.walkSpeed = 1.3 self.mass = 0.2 self.health = 3 -- self.jumpPower = 2.65 self.jumpPower = 3.2 self.dead = nil self.exploding = nil self.onPlatform = nil self.platformOffset = 0 self.start = {x = x, y = y} self.onStairs = nil self.crown = LEVEL >= CREDITS return self end function Plr_update(self) if not dead and not self.onStairs then if not self.exploding then if self.invisTimer > 0 then self.invisTimer = self.invisTimer - 1 if self.invisTimer == 0 then self.visible = true else self.visible = self.invisTimer % 6 > 3 end end if self.anim == "idle" then if self.idleTimer < 25 then self.idleTimer = self.idleTimer + 1 if self.idleTimer == 25 then if rand() < 0.5 then Spr_addAnim(self,"idle",{4, 5, 6, 7, 8, 8, 7, 6, 5, 4}, 3) else Spr_addAnim(self,"idle",{9, 10, 11, 12, 13, 13, 12, 11, 10, 9}, 3) end end end else if self.idleTimer == 25 then Spr_addAnim(self,"idle",{1}) end self.idleTimer = 0 end if not cam_scene and not MENU then if SPEEDRUN and LEVEL ~= CREDITS then speed_timer = speed_timer + 1 end if button(3) then self.velocity_x = self.walkSpeed elseif button(2) then self.velocity_x = -self.walkSpeed else if not self.onPlatform then self.velocity_x = 0 else if self.anim ~= "idle" then self.velocity_x = 0 end end end if self.grounded then if button(4, true) or button(0, true) then self.velocity_y = -self.jumpPower self.grounded = nil self.onPlatform = nil sfx(10 + 5, 0.4, 3, 120, -200) else self.groundTimer = self.groundTimer - 1 if self.groundTimer < 0 then self.grounded = nil end end end end if LEVEL == CREDITS then if stairs.anim == "open" then self.velocity_x = 0 elseif not cam_scene then self.velocity_x = 1 end if credit_x > -600 then if self.x >= level.x + 170 then self.x = self.x - 48 end end if self.x > level.x + level.width then -- init() self.y = self.start.y + 2 self.velocity_y = 0 self.mass = 0 end end if self.grounded then Spr_setAnim(self,self.velocity_x == 0 and "idle" or "walk") else Spr_setAnim(self,"jump") end end if self.anim == "explode" and self.animEnded then self.dead = true self.deadTimer = self.deadTimer - 1 if self.deadTimer <= 0 then self.dead = true fadeDir = 1 end end if LAST_SPEECH then if (not Wzrd.flip_x and self.x < Wzrd.x + 25) or (Wzrd.flip_x and self.x > Wzrd.x - 17) then self.velocity_x = 1 * (Wzrd.flip_x and -1 or 1) elseif Rect_distanceCenterX(self, Wzrd) > 27 then self.velocity_x = -1 * (Wzrd.flip_x and -1 or 1) else self.velocity_x = 0 self.flip_x = not Wzrd.flip_x end end if LEVEL == BOSS and self.x > level.x + level.width-8 then LEVEL = LEVEL + 1 level_reset() end Ent_update(self) end end function Plr_draw(self) if MENU then return end if self.visible then Spr_draw(self) if self.crown then local x, y = self.x - 1, self.y - 8 local frame = self["anim__" .. self.anim][self.frame] if frame >= 9 and frame <= 13 then y = y - 1 elseif frame >= 4 and frame <= 8 then y = y + 2 elseif frame == 2 then y = y - 1 end blit(162, x, y, 1, 1, self.flip_x) end end end function Plr_hitMapBottom(self) self.groundTimer = 2 Ent_hitMapBottom_real(self) end function Plr_kill(self) if not self.exploding then sfx(frandom(5), 0.4, 4, 180, -1800 + frandom(400)) self.velocity_x = 0 self.velocity_y = 0 self.mass = 0 Spr_setAnim(self, "explode") self.exploding = true local a = self.flip_x and 0 or 5 put(eyes, Eye_new({}, self.x + a, self.y, true)) put(eyes, Eye_new({}, self.x+2 + a, self.y)) if LEVEL == BOSS then for i=1,12 do if i % 4 == 0 then mset(level.x/8 + 4 + i, level.y/8 + 7, 0) end end end end end function Plr_damage(self) if self.invisTimer <= 0 then self.health = self.health -1 if self.health <= 0 then Plr_kill(self) end self.invisTimer = 30 sfx(20, 0.6, 4, 140, -400) end end function Plr_onOverlap(self, e) if e.type == "Stairs" then if e.anim == "idle_open" then self.visible = nil tune = "complete" Spr_setAnim(e,"climb") self.onStairs = true return end end if e.type == "Spring" then if not self.grounded and self.velocity_y ~= 0 and e.anim == "idle" then Spr_setAnim(e, "jump") self.velocity_y = -5 sfx(40, 0.4, 1, 250, -300) self.y = e.y - self.height -- sfx(40, 0.8, 3, 200, -200) end end if e.type == "Crate" then if Rect_top(self.last) > Rect_bottom(e.last) then if self.grounded then Plr_kill(self) end elseif not Rect_overlapsY(self.last, e.last) then Plr_hitMapBottom(self) else Crate_playMove(e) end end if e.type == "Platform" then if not Rect_overlapsY(self.last, e.last) then self.grounded = true self.onPlatform = true if not (button(3) or button(2)) then Spr_setAnim(self, "idle") self.velocity_x = e.velocity_x self.flip_x = self.velocity_x < 0 end end end if e.type == "Door" then if e.solid then self.grounded = true Spr_setAnim(self, self.velocity_x == 0 and "idle" or "walk") end end if not cam_scene then if e.type == "Bat" then if e.anim == "flying" then Plr_damage(self) end return end if e.type == "Spider" then if e.anim ~= "sleeping" and e.anim ~= "sleeping_eyes" then Plr_damage(self) end return end if e.type == "Lava" then Plr_damage(self) return end if e.type == "Spikes" then Plr_damage(self) return end if e.type == "Bolt" then if e.timer > 0 then Plr_damage(self) end return end if e.type == "Spear" then Plr_damage(self) return end if e == crown then self.crown = true crown = nil cam_backToPlr(true) self.scene = true tune = "crown" mset(80, 9, 0) end end Ent_onOverlap_real(self, e) end function Plr_canSimplify(self) return nil end ----------------------------- --EYE ----------------------------- function Eye_new(self, x, y, left) Ent_new(self, x, y, 112) self.type = "Eye" self.width = 1 self.height = 1 self.bounce_y = 2 self.mass = 0.4 self.velocity_y = -1 - (left and 0.4 or 0) self.left = left self.sleep = nil return self end function Eye_update(self) self.grounded = nil Ent_update(self) if self.simplified then return end if self.grounded then if not self.sleep and self.left then sfx(64, 0.4, 3, 120, -200) end if self.bounce_y == 0 then self.sleep = true elseif self.bounce_y > 0 then self.velocity_y = -self.bounce_y self.bounce_y = 0 end end end function Eye_simplify(self) if Spr_canSimplify(self) then self.dead = true end end ----------------------------- --COIN ----------------------------- function Coin_new(self, x, y, secret) Ent_new(self, x, y, secret and 70 or 64) self.type = "Coin" self.__save = {"img"} Spr_addAnim(self,"idle",{1, 2, 3, 4, 5, 6}, 2.4) Spr_addAnim(self,"vanish",{1,1,1,1,1,1,1,1,1,1,1,2,3,4}, 1) self.anim = "idle" self.start = {x = self.x, y = self.y} return self end function Coin_update(self) if not self.dead then if self.anim ~= "vanish" then if Ent_overlaps(self, Plr) then Spr_setAnim(self, "vanish") if self.img == 70 then put(secrets, self) tune = "coin" SPECIAL = SPECIAL + 1 for i,v in ipairs(level_save) do if v[3] == 241 then del(level_save, i) KAAS = "POEP" end end else sfx(60, 0.4, 3) end self.ignoreMap = true end end Ent_update(self) if self.anim == "vanish" then self.velocity_y = -4 if self.y < self.start.y - 8 then self.y = self.start.y - 8 if self.animEnded then if self.img == 64 then inventory.coins = inventory.coins + 1 end self.dead = true end end end end end ----------------------------- --TORCH ----------------------------- function Torch_new(self, x, y) Spr_new(self, x, y, 80) Spr_addAnim(self,"idle",{3, 2, 1, 2}, 2) self.type = "Torch" self.anim = "idle" self.imgHeight = 2 self.width = 23 self.height = 23 self.bckgr = Light_new({}, self.x + 4, self.y + 4) return self end function Torch_draw(self) Light_draw(self.bckgr) Spr_draw(self) end function Torch_canSimplify(self) if Spr_canSimplify_real(self) then if self.x - 23 > cam_x + cam_width then return true end end end ----------------------------- --LIGHT ----------------------------- function Light_new(self, x, y) self.x = x self.y = y self.size = 20 self.maxSize = 23 self.defSize = 20 self.minSize = 17 self.growDir = 1 self.growSpeed = 0.3 return self end function Light_draw(self) color(3) circ(self.x, self.y, round(self.minSize + (lightsTimer > 6 and 12 - lightsTimer or lightsTimer))) end ----------------------------- --KEY ----------------------------- function Key_new(self, x, y) Ent_new(self, x, y, 128) self.type = "Key" self.start = {x = self.x, y = self.y} self.pickedUp = nil self.deadTimer = 0 -- self.mass = 0.3 return self end function Key_update(self) if not self.dead then if not self.pickedUp then if Ent_overlaps(self, Plr) then sfx(64, 0.4, 3) self.start.y = self.y self.ignoreMap = true self.pickedUp = true inventory.keys = inventory.keys + 1 end end Ent_update(self) if self.pickedUp then self.deadTimer = self.deadTimer + 1 self.velocity_y = -4 if self.y < self.start.y - 8 then self.y = self.start.y - 8 end if self.deadTimer > 20 then self.dead = true end end end end ----------------------------- --DOOR ----------------------------- function Door_new(self, x, y, locked, on) Ent_new(self, x, y, locked and 132 or 131) self.type = "Door" self.__save = {"locked", "solidWhenOn", "solid", "img"} self.locked = locked self.priority_x = 100 self.priority_y = 100 self.solidWhenOn = on self.solid = not on or locked Rect_clone(self.last, self) self._prior_x = self.priority_x self._prior_y = self.priority_y return self end function Door_update(self) if not self.dead then if self.locked then if inventory.keys > 0 then if Ent_overlaps(self, Plr) then sfx(60, 0.4, 3) self.dead = true inventory.keys = inventory.keys - 1 end end end end end function Door_draw(self) if self.locked or self.solid then Spr_draw(self) end end function Door_stateOff(self) local old = self.solid self.solid = not self.solidWhenOn if self.solid ~= old then if self.solid then Door_playClosed(self) else Door_playOpen(self) end end end function Door_stateOn(self) local old = self.solid self.solid = self.solidWhenOn if self.solid ~= old then if self.solid then Door_playClosed(self) else Door_playOpen(self) end end end function Door_playOpen() sfx(10 + 5, 0.4, 4, 120, 200) end function Door_playClosed() sfx(10 + 5, 0.4, 4, 120, -200) end ----------------------------- --CRATE ----------------------------- function Crate_new(self, x, y) Ent_new(self, x, y, 144) self.type = "Crate" self.mass = 0.8 self.priority_y = 99 self.playTimer = 10 self.wallTimer = 3 self.solidTimer = 10 return self end function Crate_update(self) self.playTimer = self.playTimer - 1 self.wallTimer = self.wallTimer + 0.1 self.wallTimer = min(self.wallTimer, 3) if not self.solid then self.solidTimer = self.solidTimer - 1 if self.solidTimer < 0 then self.solid = true self.solidTimer = 10 end end if getWOP(self.x - 2, self.y + self.height + 1) and getWOP(self.x + self.width + 2, self.y + self.height + 1) and not getWOP(self.x + self.width/2, self.y + self.height + 1) then self.x = toGrid(self.x - self.width/2, self.y + self.height + 1)*8 + 8 self.wallTimer = 3 -- self.y = self.y + 1 end Ent_update(self) end function Crate_hitMapRight(self) if getWOP(self.x, self.y + self.height) ~= 0 then self.wallTimer = self.wallTimer - 1 if self.wallTimer <= 0 then self.x = self.x - 8 self.solid = nil self.wallTimer = 5 end end Ent_hitMapRight_real(self) end function Crate_hitMapLeft(self) if getWOP(self.x, self.y + self.height) ~= 0 then self.wallTimer = self.wallTimer - 1 if self.wallTimer < 0 then self.x = self.x + 8 self.solid = nil self.wallTimer = 5 end end Ent_hitMapLeft_real(self) end function Crate_hitMapBottom(self) Ent_hitMapBottom_real(self) if self.last.y < self.y then sfx(0, 0.4, 4, 200, -4000) end end function Crate_onOverlap(self, e) if e.type == "Door" then if e.solid then if Rect_overlapsY(self.last, e.last) then if self.last.x < e.last.x then Crate_hitMapRight(self) return else self.x = self.x - 1 Crate_hitMapLeft(self) return end end end end Ent_onOverlap_real(self, e) end function Crate_playMove(self) if self.playTimer < 0 then self.playTimer = 10 sfx(0, 0.4, 4, 200, -1000) end end ----------------------------- --PLATFORM ----------------------------- function Platform_new(self, x, y) Ent_new(self, x, y, 150) self.type = "Platform" self.priority_x = 99 self.priority_y = 99 self.velocity_x = 1 self.bounce_x = 1 return self end ----------------------------- --SPRING ----------------------------- function Spring_new(self, x, y) Spr_new(self, x, y, 145) self.type = "Spring" Spr_addAnim(self, "idle", {1}) Spr_addAnim(self, "jump", {2,3,4,5,3,2,3,5,4,5,4}, 1, "once") Spr_addAnim(self, "revert", {3, 2, 1}, 3, "once") Spr_setAnim(self, "idle") self.timer = 0 return self end function Spring_update(self, x, y) if self.animEnded then if self.anim == "jump"then self.timer = self.timer + 1 if self.timer > 10 then self.timer = 0 Spr_setAnim(self, "revert") end elseif self.anim == "revert" then Spr_setAnim(self, "idle") end end Spr_update(self) end ----------------------------- --BUTTON ----------------------------- function Btn_new(self, x, y, targets) Ent_new(self, x, y, 129) self.type = "Button" self.__save = {"targets"} self.offset_y = -3 self.solid = nil self.pushed = nil self.pushTimer = 3 self.targets = targets Spr_addAnim(self, "idle", {1}) Spr_addAnim(self, "pushed", {2}) return self end function Btn_update(self) self.pushTimer = max(0, self.pushTimer - 1) if self.pushTimer == 0 then Btn_unpush(self) end Ent_update(self) end function Btn_draw(self) if not self.dead then Spr_draw(self) end end function Btn_onOverlap(self, e) if e.type == "Plr" or e.type == "Crate" then -- if abs((self.x + self.width / 2) - (e.x + e.width / 2)) < 4 then Btn_push(self) -- end end end function Btn_push(self) if not self.pushed then self.pushed = true Spr_setAnim(self, "pushed") for i,v in ipairs(self.targets) do Door_stateOn(doors[v]) end end self.pushTimer = 3 end function Btn_unpush(self) if self.pushed then self.pushed = nil Spr_setAnim(self, "idle") for i,v in ipairs(self.targets) do Door_stateOff(doors[v]) end end end -- function Btn_simplify(self) -- end ----------------------------- --SWITCH ----------------------------- function Stc_new(self, x, y, targets) Ent_new(self, x+2, y+1, 133) self.type = "Switch" self.__save = {"targets","active"} self.solid = nil self.switchTimer = 4 self.active = nil self.targets = targets self.width = 4 Spr_addAnim(self, "idle", {1}) Spr_addAnim(self, "active", {2}) Spr_setAnim(self, "idle") return self end function Stc_update(self) self.switchTimer = self.switchTimer - 1 if self.active then Spr_setAnim(self, "active") for i,v in ipairs(self.targets) do Door_stateOn(doors[v]) end else Spr_setAnim(self, "idle") for i,v in ipairs(self.targets) do Door_stateOff(doors[v]) end end Ent_update(self) end function Stc_draw(self) if not self.dead then Spr_draw(self) end end function Stc_onOverlap(self, e) if abs((self.x + self.width / 2) - (e.x + e.width / 2)) < 2 then if self.switchTimer < 0 then Stc_trigger(self) end self.switchTimer = 1 end end function Stc_trigger(self) self.active = not self.active if self.active then Spr_setAnim(self, "active") for i,v in ipairs(self.targets) do Door_stateOn(doors[v]) end else Spr_setAnim(self, "idle") for i,v in ipairs(self.targets) do Door_stateOff(doors[v]) end end end ----------------------------- --BAT ----------------------------- function Bat_new(self, x, y) Ent_new(self, x, y, 113) self.type = "Bat" Spr_addAnim(self, "sleeping", {1}) Spr_addAnim(self, "sleeping_eyes", {2}) Spr_addAnim(self, "flying", {3,4},2.5) Spr_setAnim(self, "sleeping") self.__save = {"anim"} self.width = 3 self.height = 6 self.offset_x = -2 self.sleepTimer = 0 self.bounce_x = 1 self.bounce_y = 1 self.hspeed = 0.4 self.vspeed = 1 self.solid = true return self end function Bat_update(self) if cam_scene then return end self.sleepTimer = self.sleepTimer - 1 if self.sleepTimer < 0 then if self.anim ~= "flying" then if Rect_distanceCenterX(self, Plr) < 27 and Rect_distanceCenterY(self, Plr) < 26 and self.y < Plr.y + 8 then Bat_startFlying(self) elseif Rect_distance(self, Plr) < 45 then Spr_setAnim(self, "sleeping_eyes") else Spr_setAnim(self, "sleeping") end end end Ent_update(self) end function Bat_startFlying(self) sfx(55, 0.4, 0, 200 , -100 - frandom(300)) self.velocity_x = self.hspeed * sign(Rect_centerX(Plr) - Rect_centerX(self)) self.velocity_y = self.vspeed Spr_setAnim(self, "flying") end function Bat_hitMapTop(self) Spr_setAnim(self, "sleeping") Ent_hitMapTop_real(self) self.velocity_x = 0 self.velocity_y = 0 self.sleepTimer = 40 end function Bat_onOverlap(self, e) if e.type == "Door" then if not Rect_overlapsY(self.last, e.last) then if self.y > e.y then Bat_hitMapTop(self) else Bat_hitMapBottom(self) end end end Ent_onOverlap_real(self, e) end function Bat_canSimplify(self) return Spr_canSimplify_real(self) and self.anim == "sleeping" and LEVEL ~= BOSS end ----------------------------- --LAVA ----------------------------- function Lava_new(self, x, y) Ent_new(self, x, y+4, 176) self.offset_y = -4 self.height = 4 Spr_addAnim(self, "idle", {1,2,3,3,4,4,3,3,5},6) Spr_setAnim(self, "idle") self.type = "Lava" self.__save = {"width"} local i = 0 local a = 0 while true do a = a + 1 if a > 2000 then break end i = i + 1 local a = mget(x/8 + i, y/8) if isWall(a) then i = i -1 break end end self.length = i self.width = i * 8 + 8 return self end function Lava_draw(self) for i=0,self.length do blit(self.img + (self.anim and self["anim__" .. self.anim][self.frame] * self.imgWidth - 1 or 0), self.x + self.offset_x + 8 * i, self.y + self.offset_y, self.imgWidth, self.imgHeight, self.flip_x, self.flip_y) end end function Lava_canSimplify(self) local s = false self.y = self.y - 4 self.height = 8 s = Spr_canSimplify_real(self) self.y = self.y + 4 self.height = 4 return s end ----------------------------- --WINDOW ----------------------------- function Window_new(self, x, y) Spr_new(self, x-8, y, 83) Spr_addAnim(self, "idle", {1},3) Spr_setAnim(self, "idle") self.type = "Window" self.offset_x = 8 self.width = 24 self.__save = {"width"} return self end function Window_draw(self) blit(84, self.x, self.y, 3, 2) Spr_draw(self) color(0) line(self.x+7, self.y, self.x+7, self.y+7) end ----------------------------- --SPIDER ----------------------------- function Spd_new(self, x, y) Ent_new(self, x, y, 117) self.type = "Spider" Spr_addAnim(self, "sleeping", {1}) Spr_addAnim(self, "sleeping_eyes", {2}) Spr_addAnim(self, "walking", {2, 3}, 10) Spr_addAnim(self, "falling", {4}) Spr_addAnim(self, "walking_floor", {4, 5}, 4) Spr_setAnim("sleeping") self.start = {x = self.x, y = self.y} self.width = 5 self.height = 3 self.sleepTimer = 0 self.soundTimer = 0 self.fallSpeed = 0.6 self.solid = true self.onground = nil return self end function Spd_update(self) self.sleepTimer = self.sleepTimer - 1 if self.sleepTimer < 0 then if not self.onground then if self.anim ~= "falling" then if Rect_distanceCenterX(self, Plr) < 18 and Rect_distanceCenterY(self, Plr) < 28 and self.y < Plr.y + 8 then Spd_startFalling(self) elseif Rect_distance(self, Plr) < 45 then Spr_setAnim(self, "sleeping_eyes") else Spr_setAnim(self, "sleeping") end end else self.soundTimer = self.soundTimer - 1 if self.soundTimer < 0 then self.soundTimer = 4 sfx(40, 0.4, 0, 40, -100) end if Rect_distanceCenterX(self, Plr) < 2 then Spd_startClimbing(self) end if not getWOP(self.x + 4 + 4 * sign(self.velocity_x), self.y + self.height) then Spd_startClimbing(self) end if getWOP(self.x + 4 + 5 * sign(self.velocity_x), self.y + 2) then Spd_startClimbing(self) end end end self.flip_x = true Ent_update(self) end function Spd_draw(self) if self.anim == "falling" then color(4) line(self.x + 4, self.start.y, self.x+4, self.y) end Spr_draw(self) end function Spd_startFalling(self) sfx(40, 0.4, 0, nil, -100) self.falling = true self.velocity_y = self.fallSpeed self.velocity_x = 0 Spr_setAnim(self, "falling") end function Spd_startClimbing(self) sfx(20, 0.4, 0, nil, -100) -- sfx(10, 0.4, 0, 200 , 400 - frandom(300)) local i = 0 while true do if getWOP(self.x, self.y - i * 8) then break end i = i + 1 end self.start.y = self.y - i * 8 self.velocity_y = -1 self.velocity_x = 0 self.onground = nil self.x = round(self.x) Spr_setAnim(self, "falling") end function Spd_hitMapTop(self) Spr_setAnim(self, "sleeping") Ent_hitMapTop_real(self) self.velocity_x = 0 self.velocity_y = 0 self.sleepTimer = 40 end function Spd_hitMapBottom(self) Ent_hitMapBottom_real(self) if self.anim == "falling" then self.velocity_x = 1.8 * sign(Rect_centerX(Plr) - Rect_centerX(self)) Spr_setAnim(self, "walking_floor") self.velocity_y = 0 self.onground = true end end function Spd_onOverlap(self, e) if e.type == "Door" and e.solid then if not Rect_overlapsY(self.last, e.last) then if self.y > e.y then Spd_hitMapTop(self) else Spd_hitMapBottom(self) end else Spd_startClimbing(self) end end Ent_onOverlap_real(self, e) end function Spd_canSimplify(self) return Spr_canSimplify_real(self) and self.anim == "sleeping" and LEVEL ~= BOSS end ----------------------------- --SPIKES ----------------------------- function Spk_new(self, x, y) Ent_new(self, x, y, 181) self.type = "Spikes" self.offset_y = -4 self.offset_x = -1 self.width = 7 self.height = 5 Spr_addAnim(self, "idle", {1}) Spr_addAnim(self, "close", {2, 3}, 2, "once") Spr_addAnim(self, "active", {4,5,6,7}, 1, "once") Spr_addAnim(self, "back", {7,6,5,4,3,2,1}, 1, "once") Spr_setAnim(self, "idle") self.activeTimer = 0 return self end function Spk_update(self) -- if abs(self.x - Plr.x) >= 64 then -- Ent_simplify(self) -- return -- end self.activeTimer = self.activeTimer - 1 if self.activeTimer > 0 then Spr_setAnim(self, "active") elseif self.activeTimer == 0 then Spr_setAnim(self, "back") elseif self.anim ~= "back" then if Rect_distanceCenterX(self, Plr) < 30 and Rect_distanceCenterY(self, Plr) < 24 and self.y > Plr.y then if Rect_distanceCenterX(self, Plr) < 8 then Spr_setAnim(self, "active") sfx(50, 0.4, 0, 100, -2000) self.activeTimer = 30 else Spr_setAnim(self, "close") end else Spr_setAnim(self, "idle") end end if self.animEnded and self.anim == "back" then Spr_setAnim(self, "idle") end Ent_update(self) end ----------------------------- --Spear ----------------------------- function Spear_new(self, x, y) Ent_new(self, x, y, 135) self.type = "Spear" self.__save = {"start_y"} self.state = "up" self.timer = 0 self.height = 4 self.start_y = self.y return self end function Spear_update(self) if self.state == "up" then if Rect_distanceCenterX(self, Plr) < 40 and Rect_distanceCenterY(self, Plr) < 30 and Plr.y > self.y then if self.timer <= 0 then self.velocity_y = 4 else self.timer = self.timer - 1 end end end if self.state == "down" then if self.timer <= 0 then self.velocity_y = -4 else self.timer = self.timer - 1 end end Ent_update(self) end function Spear_draw(self) color(4) rect(self.x+2, self.start_y, 2, self.y - self.start_y) Spr_draw(self) end function Spear_hitMapBottom(self) self.state = "down" self.timer = 2 sfx(0, 0.5, 4, 150, -100) Ent_hitMapBottom_real(self) end function Spear_hitMapTop(self) self.state = "up" self.timer = 20 Ent_hitMapTop_real(self) end function Spear_canSimplify(self) return Spr_canSimplify_real(self) and self.state == "up" end ----------------------------- --STAIRS ----------------------------- function Stairs_new(self, x, y, special) Spr_new(self, x+8, y+5, 15) self.type = "Stairs" Spr_addAnim(self, "idle", {1}) Spr_addAnim(self, "idle_open", {6}) Spr_addAnim(self, "climb", {6,6,6,6,6,6,6,6,6,6,6}, 6, "once") Spr_addAnim(self, "open", {2,3,4,5,6,6,6,6}, 4, "once") Spr_setAnim(self, "idle") self.imgWidth = 2 self.imgHeight = 2 self.offset_x = -8 self.offset_y = -13 self.width = 4 self.height = 3 self.special = special return self end function Stairs_update(self) if self.anim == "idle" then -- (not self.special and self.x - Plr.x < 50) or if self.special and self.x - Plr.x < 50 then if SPECIAL == 6 then if cam_arrived then Spr_setAnim(self, "open") sfx(0, 0.8, 4, 1100, nil) else cam_toScene(self) end end elseif inventory.coins == level.coins then if cam_arrived then Spr_setAnim(self, "open") sfx(0, 0.8, 4, 1100, nil) else cam_toScene(self) end end elseif self.anim == "open" and self.animEnded then Spr_setAnim(self, "idle_open") cam_backToPlr() elseif self.anim == "climb" and self.animEnded then fadeDir = 1 end Spr_update(self) end function Stairs_draw(self) Spr_draw(self) if self.anim == "idle" then color(2) print(self.special and 6 - SPECIAL or level.coins - inventory.coins, self.x-2, self.y - 12) if self.special then blit(70, self.x - 4, self.y - 6) end elseif self.anim == "climb" then local y = self.y + self.offset_y if self.frame == 1 then blit(Plr.crown and 58 or 48, self.x - 4, y + 8, 1, 1) elseif self.frame == 2 then blit(Plr.crown and 59 or 49, self.x - 2, y + 6, 1, 1) elseif self.frame == 3 then blit(50, self.x - 2, y + 4, 1, 1) elseif self.frame == 4 then blit(51, self.x - 2, y + 2, 1, 1) end end end function Stairs_simplify(self) end ----------------------------- ---------BOSSFIGHT----------- ----------------------------- --CLOUD ----------------------------- Cloud = {} function Cloud_new(x, y, type) local self = {} self.x = x self.y = y self.type = type return self end function Cloud.update(self) self.x = self.x - (self.type == 1 and 1.2 or 0.6) if self.x < level.x - 20 then self.x = flr(level.x + level.width) + 20 if self.type == 1 then self.y = level.y + 66 + random(0, 20) else self.y = level.y - 14 + random(0, 20) end end end function Cloud.draw(self, a) if not a then color(self.type == 1 and 3 or 0) circ(flr(self.x), flr(self.y), 20) else color(4) circ(flr(self.x), flr(self.y), 22) end end ----------------------------- --BOLT ----------------------------- function Bolt_new(x, y) local self = Spr_new({}, x, y) self.x = x self.y = y self.imgs = {} self.type = "Bolt" for i=1,10 do if i > 1 then local r repeat r = random(0,4) until r ~= self.imgs[i-1] self.imgs[i] = r else self.imgs[i] = random(0, 4) end end self.timer = -60 self.striked = nil self.height = 11 * 8 self.start = nil return self end function Bolt_update(self) self.timer = self.timer + 3 if self.timer > 16 then if not self.striked then sfx(20, 0.8, 4, 800, -100) end self.striked = true if self.timer > 30 then return true end end end function Bolt_draw(self) if self.timer > 0 then for i,v in ipairs(self.imgs) do if self.striked then if i + 16 > self.timer then blit(52 + self.imgs[i], self.x, self.y + 8 * i) end else if i <= self.timer then blit(52 + self.imgs[i], self.x, self.y + 8 * i) end end end else blit(57, self.x, self.y + 8 * 10) end end ----------------------------- --Wzrd ----------------------------- function Wzrd_new(self, x, y) Ent_new(self, x-8, y, 192) self.type = "Wzrd" self.starty = y self.height = 16 self.imgHeight = 2 Spr_addAnim(self, "idle", {1}) Spr_addAnim(self, "outfade", {2,3,10}, 3, "once") Spr_addAnim(self, "infade", {3,2,1}, 3, "once") Spr_addAnim(self, "chant", {4,6,5,7,6,7,5,7,6,7,5,7,6,7,5,7,6,7,5,7,6,7,5,4,1}, 5, "once") Spr_addAnim(self, "shock", {8,9,8,9,8,9,8,9,8,9,8,9,8,9}, 2, "once") Spr_addAnim(self, "tired", {6}) Spr_addAnim(self, "dissapear", {6,6,6,5,6,6,5,6,5,6,5,5,5,5,5,5}, 3, "once") Spr_setAnim(self, "idle") self.chantTimer = 70 self.spawnTimer = 10 self.spawn = "bat" self.life = 3 self.flip_x = true return self end function Wzrd_update(self) if self.anim == "idle" then if abs(self.x - Plr.x) < 10 then Spr_setAnim(self, "outfade") sfx(20, 0.4, 1, 300, -2000) else self.chantTimer = self.chantTimer - 1 if self.chantTimer < 0 then sfx(3, 0.4, 1, 1000, -100) Spr_setAnim(self, "chant") self.chantTimer = 45 end end elseif self.anim == "chant" then self.spawnTimer = self.spawnTimer - 1 if self.spawnTimer < 0 then if self.spawn == "bat" then local bt = Bat_new({}, level.x + 60 + random(0, 70), level.y + 8) bt.sleepTimer = -1 Bat_startFlying(bt) bt.velocity_x = 2.5 * sign(-0.5 + rand()) put(bats, bt) self.spawnTimer = 30 elseif self.spawn == "spider" then local sp = Spd_new({}, level.x + 40 + random(0, 110), level.y + 8) sp.fallSpeed = 2 sp.sleepTimer = -1 Spd_startFalling(sp) put(spiders, sp) self.spawnTimer = 30 elseif self.spawn == "bolt" then put(bolts, Bolt_new(Plr.x, level.y - 8)) self.spawnTimer = 20 elseif self.spawn == "lava" then if #lavas == 0 then put(lavas, Lava_new({}, 520 , 72)) end end else if self.spawn == "lava" then if self.y <= level.y + 40 then self.y = level.y + 40 self.velocity_y = 0 for i=1,12 do if i % 4 == 0 then mset(level.x/8 + 4 + i, level.y/8 + 7, 29) end end else self.velocity_y = -0.8 end end end end if self.animEnded then if self.anim == "outfade" then if self.flip_x then self.x = self.x - 64 self.y = self.starty self.flip_x = nil else self.x = self.x + 64 self.y = self.starty self.flip_x = true end Spr_setAnim(self, "infade") elseif self.anim == "infade" then Spr_setAnim(self, "idle") elseif self.anim == "chant" then Spr_setAnim(self, "idle") if self.spawn == "bat" then self.spawn = "spider" elseif self.spawn == "spider" then self.spawn = "bolt" elseif self.spawn == "bolt" then self.spawn = "lava" self.spawnTimer = 60 elseif self.spawn == "lava" then lavas = {} for i=1,12 do if i % 4 == 0 then mset(level.x/8 + 4 + i, level.y/8 + 7, 0) end end Spr_setAnim(self, "outfade") sfx(20, 0.4, 1, 300, -2000) self.spawn = "bat" end elseif self.anim == "shock" then if self.life == 0 then Spr_setAnim(self, "tired") crown = Crown_new({}, self.x + (self.flip_x and -1 or 7), self.y+4, self.flip_x) else Spr_setAnim(self, "idle") end elseif self.anim == "dissapear" then scene.step = scene.step + 1 end end Ent_update(self) end function Wzrd_draw(self) if self.anim == "tired" or self.anim == "dissapear" then self.imgWidth = 2 else self.imgWidth = 1 end Spr_draw(self) end function Wzrd_onOverlap(self, e) if e.timer > 0 and self.anim ~= "shock" and self.life > 0 then Spr_setAnim(self, "shock") if e ~= #bolts then del(bolts, #bolts) end self.spawn = "lava" self.spawnTimer = 60 self.life = self.life - 1 if self.life == 0 then LAST_SPEECH = true music.play = nil cam_toScene(self.x + 15 * (self.flip_x and -1 or 1), self.y + 13) end end end function Wzrd_canSimplify(self) return nil end ----------------------------- --CROWN ----------------------------- function Crown_new(self, x, y, flip) Ent_new(self, x + 4, y, 162) self.type = "Crown" self.velocity_x = 0.8 * (flip and -1 or 1) self.mass = 0.1 self.flip_x = flip self.bounce_y = 0.8 Spr_addAnim(self, "rotate", {2,3,4,5,6,7,1}, 6, "once") Spr_setAnim(self, "rotate") self.solid = nil self.offset_x = -4 self.width = 4 return self end function Crown_hitMapBottom(self) Ent_hitMapBottom_real(self) if self.velocity_y > -0.6 and not Rect_overlaps(self, Plr) and self.velocity_x ~= 0 then self.velocity_y = 0 self.velocity_x = 0 self.mass = 0 scene.step = scene.step + 1 sfx(60, 0.5, 3, 50) elseif self.velocity_x ~= 0 then sfx(60, 0.5, 3, 50) end end ----------------------------- --MUSIC ----------------------------- CHANNELS = { 12, 14, 17, 19, 21, 24, 27, 29, 31, 34, 36, 39, 41, 43} music = {} music.play = "main" music.main = { speed = 8, tick = -1, play = function(n) play(3, n, 1, 3, nil, 20) end, seq = "123200000100000000000000123200000100000000000000123200000100000000000000" .. "1232000001000000000000001232000001000000000000001234040413030302" .. "1234040413030302" } music.boss = { speed = 5, tick = -1, play = function(n) play(3, n, .6, 1, 110) end, seq = "1000100010001000100010001000100013031303130313131303130313031313" .. "4242423414143432424242341414343292827274746464629282727474646462" .. "928272747464646292827274746464629887998aa9bbcabc9282727474646462" .. "9282727474646462928272747464646292827274746464629887998aa9bbca75" .. "9282727474646462928272747464646292827274746464629282727474646462" .. "98a79acb9cb9cb98928272981768646492827298176864649282729807686020" } music.complete = { speed = 5, tick = -1, play = function(n) sfx(20 + n, 0.4, 1) end, seq = "56034132314670000000000000000000000" } music.coin = { speed = 5, tick = -1, play = function(n) sfx(40 + n, 0.4, 3) end, seq = "1357" } music.crown = { speed = 5, tick = -1, play = function(n) sfx(20 + n, 0.8, 3) end, seq = "123456789abc" } function playMusic(play, t) local self = music[play] self.tick = self.tick + 1 if self.tick % round(self.speed) == 0 then local step = self.tick / self.speed if t and step >= #self.seq then tune = nil self.tick = -1 return end local c = ord(self.seq, 1 + step % #self.seq) c = (c >= ord("a")) and (c - ord("a") + 10) or (c - ord("0")) if c > 0 then self.play(CHANNELS[c]) end end end ----------------------- --CAMERA ----------------------- function cam_update() if not cam_scene then cam_x = flr(Plr.x + Plr.width/2) - 64 cam_y = flr(Plr.y + Plr.height/2) - 64 else local c = {x = cam_x, y = cam_y, width = cam_width, height = cam_height} local xdis = Rect_distanceCenterX(c, cam_sceneTo) local ydis = Rect_distanceCenterY(c, cam_sceneTo) if xdis < 2 then Rect_centerX(c, cam_sceneTo.x) else cam_x = cam_x + (xdis/7) * sign(cam_sceneTo.x - (cam_x+cam_width/2)) end if ydis < 2 then Rect_centerY(c, cam_sceneTo.y) else cam_y = cam_y + (ydis/7) * sign(cam_sceneTo.y - (cam_y+cam_height/2)) end if xdis < 2 and ydis < 2 then cam_arrived = true if cam_toPlr then cam_arrived = nil cam_scene = nil cam_toPlr = nil end end -- cam_y = cam_y + 1 * sign((cam_y+cam_height/2) - cam_sceneTo.y ) end camera(cam_x, cam_y) end function cam_toScene(x, y) cam_arrived = nil cam_scene = true cam_toPlr = nil Plr.velocity_x = 0 if not y then cam_sceneTo.x = x.x + x.width/2 cam_sceneTo.y = x.y + x.height/2 else cam_sceneTo.x = x cam_sceneTo.y = y end end function cam_backToPlr(t) cam_toScene(Plr) cam_toPlr = t and nil or true end ---- --scene SCENE ---- function scene_update() local self = scene if LEVEL == BOSS - 1 then if self.step < 14 then if self.timer <= 0 then if self.step == 0 then if abs(Plr.x - Wzrd.x) < 50 and Plr.grounded then cam_toScene(Wzrd) self.step = self.step + 1 Spr_setAnim(Plr,"idle") end elseif self.step == 1 then if cam_arrived then self.step = self.step + 1 self.timer = 25 end elseif self.step == 2 then Wzrd.flip_x = true self.step = self.step + 1 self.timer = 20 elseif self.step == 3 then self.text1 = "How didst thou escape" self.text2 = "the dungeon?" elseif self.step == 4 then self.text1 = "Yes, I hadst thou" self.text2 = "thrown in there" elseif self.step == 5 then self.text1 = "Why? Thou knoweth why" self.text2 = "Thou started learning the truth" elseif self.step == 6 then self.text1 = "Indeed, I am not thine father" self.text2 = "I murdered him 5 years ago" elseif self.step == 7 then self.text1 = "Alloweth me to telleth thou" self.text2 = "what hath happened that day" elseif self.step == 8 then self.text1 = "He banished me for using" self.text2 = "the power of black magic" elseif self.step == 9 then self.text1 = "Enraged I murdered him" self.text2 = "and took his place" elseif self.step == 10 then self.text1 = "It took thou 5 years" self.text2 = "to learn the truth" elseif self.step == 11 then self.text1 = "And now thou wants to stop me?" self.text2 = "Thou maketh me laugh, boy" elseif self.step == 12 then self.text1 = "Come forth to the roof" self.text2 = "and prove thine worth" Wzrd.y = Wzrd.y - 0.5 Spr_setAnim(Wzrd, "chant") if (button(4, true) or button(0, true)) and Wzrd.y + Wzrd.height < level.y then self.step = self.step + 1 end elseif self.step == 13 then self.text1 = nil self.text2 = nil cam_backToPlr() self.step = self.step + 1 end if self.step >= 3 and self.step <=11 then if button(4, true) or button(0, true) then self.step = self.step + 1 end end else self.timer = self.timer - 1 end end elseif LEVEL == BOSS then if self.step == 1 then self.text1 = "Thou didst defeat me.." self.text2 = "How..?" elseif self.step == 2 then self.text1 = "Perhaps I should've ceased" self.text2 = "using mine lightning attack.." elseif self.step == 3 then self.text1 = "But twas a wonderous attack" self.text2 = "" elseif self.step == 4 then self.text1 = "..." elseif self.step == 5 then self.text1 = "You know.." self.text2 = "I love this kingdom" elseif self.step == 6 then self.text1 = "I love its people" self.text2 = "I liked living here" elseif self.step == 7 then self.text1 = "When I killed thine father" self.text2 = "I feared the kingdom would fall" elseif self.step == 8 then self.text1 = "I took thine father's place" self.text2 = "Not for mine own good" elseif self.step == 9 then self.text1 = "But for the people" self.text2 = "" elseif self.step == 10 then self.text1 = "I hath tried to be a good king" elseif self.step == 11 then self.text1 = "And a great father" self.text2 = "" elseif self.step == 12 then self.text1 = "Twas mine pleasure to call" self.text2 = "thou mine son these past 5 years" elseif self.step == 13 then self.text1 = "Son.." self.text2 = "Pick up that crown" elseif self.step == 14 then self.text1 = "And become the best king" self.text2 = "this kingdom hath ever seen" elseif self.step == 15 then self.text1 = "Farewell.." self.text2 = "Son.." Spr_setAnim(Wzrd, "dissapear") elseif self.step == 16 then self.text1 = nil self.text2 = nil cam_backToPlr() LAST_SPEECH = nil end if self.step >= 1 and (button(4, true) or button(0, true)) then self.step = self.step + 1 end end end
render = {} if DrawSprite then render.white_sprite = LoadSprite("../../mods/umf/assets/image/white.png") render.white_fade_sprite = LoadSprite("../../mods/umf/assets/image/white_fade.png") render.frame_sprite = LoadSprite("../../mods/umf/assets/image/frame.png") render.grid_sprite = LoadSprite("../../mods/umf/assets/image/grid.png") function render.drawline(source, destination, info) local width = 0.03 local r, g, b, a = 1, 1, 1, 1 local writeZ, additive = true, false local sprite = render.white_sprite local target = info and info.target or GetCameraTransform().pos if info then width = info.width or width r = info.r or r g = info.g or g b = info.b or b a = info.a or a writeZ = info.writeZ ~= nil and info.writeZ or writeZ additive = info.additive ~= nil and info.additive or additive sprite = info.sprite or sprite end local middle = (MakeVector(source) + destination) / 2 local len = source:Distance(destination) local transform = Transformation(middle, source:LookAt(destination) * QuatEuler(-90, 0, 0)) local target_local = TransformToLocalPoint(transform, target) target_local[2] = 0 local transform_fixed = TransformToParentTransform(transform, Transform(VEC_ZERO, QuatLookAt(target_local, VEC_ZERO))) DrawSprite(sprite, transform_fixed, width, len, r, g, b, a, writeZ, additive) end function render.drawsprite(pos, image, size, info) local height = size local r, g, b, a = 1, 1, 1, 1 local writeZ, additive = true, false local sprite = image or render.white_sprite local target = info and info.target or GetCameraTransform().pos if info then height = info.height or height r = info.r or r g = info.g or g b = info.b or b a = info.a or a writeZ = info.writeZ ~= nil and info.writeZ or writeZ additive = info.additive ~= nil and info.additive or additive end DrawSprite(sprite, Transform(pos, QuatLookAt(pos, target)), size, height, r, g, b, a, writeZ, additive) end function render.drawaxis(transform, rot, mul) mul = mul or 1 if not transform.pos then transform = Transform(transform, rot or QUAT_ZERO) end MakeTransformation(transform) render.drawline(transform.pos, transform:ToGlobal(VEC_LEFT * mul), {r = 1, g = 0, b = 0}) render.drawline(transform.pos, transform:ToGlobal(VEC_UP * mul), {r = 0, g = 1, b = 0}) render.drawline(transform.pos, transform:ToGlobal(VEC_FORWARD * mul), {r = 0, g = 0, b = 1}) end local QUAT_LEFT = MakeQuaternion(QuatEuler(0, 90, 90)) local QUAT_UP = MakeQuaternion(QuatEuler(90, 0, 0)) function render.drawbox(transform, min, max, sprite) sprite = sprite or render.frame_sprite MakeTransformation(transform) MakeVector(min) local mid = (min + max) / 2 DrawSprite(sprite, transform:ToGlobal(Transform(Vec(mid[1], mid[2], min[3]), QUAT_ZERO)), max[1] - min[1], max[2] - min[2], 1, 1, 1, 1, true, false) DrawSprite(sprite, transform:ToGlobal(Transform(Vec(mid[1], mid[2], max[3]), QUAT_ZERO)), max[1] - min[1], max[2] - min[2], 1, 1, 1, 1, true, false) DrawSprite(sprite, transform:ToGlobal(Transform(Vec(mid[1], min[2], mid[3]), QUAT_UP)), max[1] - min[1], max[3] - min[3], 1, 1, 1, 1, true, false) DrawSprite(sprite, transform:ToGlobal(Transform(Vec(mid[1], max[2], mid[3]), QUAT_UP)), max[1] - min[1], max[3] - min[3], 1, 1, 1, 1, true, false) DrawSprite(sprite, transform:ToGlobal(Transform(Vec(min[1], mid[2], mid[3]), QUAT_LEFT)), max[2] - min[2], max[3] - min[3], 1, 1, 1, 1, true, false) DrawSprite(sprite, transform:ToGlobal(Transform(Vec(max[1], mid[2], mid[3]), QUAT_LEFT)), max[2] - min[2], max[3] - min[3], 1, 1, 1, 1, true, false) end function render.drawgrid(transform, x, y, sx, sy) for ix = (sx or 0) + 1, x do for iy = (sy or 0) + 1, y do DrawSprite(render.grid_sprite, MakeTransformation(transform) + Vector(ix-.5, iy-.5, 0), 1, 1, 1, 1, 1, 1, true, false) end end end end
--[[ Copyright (C) 2018 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ]] --[[ Ask yes/no questions based on object colors / counts: Are all hats blue? Is any hat blue? Is anything red? Are most hats blue? The general setup is that a pair of objects representing 'answer yes', 'answer no' when picked up are placed in region A and B on the map. We use groups 1 and 2 for these for consistency. Objects are then generated in the remaining groups to represent the problem being asked, these cannot be picked up so the agent can examine them. For some problems (e.g. is anything red?) we need to create an object which is not placed in the world to have some instantiated attributes to reference. Group 3 is used for this where required. ]] local factory = require 'factories.language.factory' local object_generator = require 'language.object_generator' local item_count = require 'language.item_count' local lcm = require 'language.make' local placers = require 'language.placers' local selectors = require 'language.selectors' local reward_controllers = require 'language.reward_controllers' local texture_sets = require 'themes.texture_sets' -- Set up the map in zones: 'A' will have the 'yes' object, 'B' the 'no' object. local quantificationSmallMap = { name = 'quantificationSmallMap', textureSet = texture_sets.CUSTOMIZABLE_FLOORS, entityLayer = [[ .....O P..OO P..OO .....O ]], variationsLayer = [[ CCCCCA CCCDD CCCDD CCCCCB ]], -- TODO(simongreen): Add methods to compute room information automatically. -- The data below indicates which object location ids within the map are -- present in which room. The indexes are ordered top to bottom, left to -- right within the entityLayer. rooms = { A = {[1] = true}, B = {[6] = true}, C = {}, D = {[2] = true, [3] = true, [4] = true, [5] = true }, } } --[[ For these quantification tasks: * Use all shapes. * Use 6 colors for objects: RGBCMY. * No patterns - use solid. * No pickup unless explicit. * Unless explicitly specified, don't use region A, B, C as these are reserved. ]] local COLORS = {'red', 'green', 'blue', 'cyan', 'magenta', 'yellow'} local objectContext = object_generator.createContext{ attributes = { color = COLORS, }, attributeDefaults = { size = 'medium', pattern = 'solid', canPickup = false, region = {lcm.isNot({'A', 'B', 'C'}), lcm.random()}, } } --[[ A common pattern for object counts with these problems is that we want a few single items for e.g. yes, no, goal and then some variable counts to give an even distribution of problems for which the answer is yes/no. This utility helps us make this pattern less wordy in the task descriptions. ]] local function concatWithSelector(initial, selector) return item_count.concat(initial, selectors.createCalling(selector)) end -- All the tasks below define group 1 and 2 the same: -- 1 Magic yes ball - collect this to answer 'yes' -- 2 Magic no ball - collect this to answer 'no'. local YES_GROUP = {shape = 'ball', color = 'white', region = 'A', static = true, canPickup = true} local NO_GROUP = {shape = 'ball', color = 'black', region = 'B', static = true, canPickup = true} -- TASK: Are all cars red? -- Yes: Distractor count is 0 => itemsPerGroup[4] == 0 local evenChanceOfAllSelector = selectors.createRandom{ -- All goals objects and no distractors. selectors.createIdentity({4, 0}), -- At least one distractor. item_count.createGroupCounts{groupMin = {1, 1}, totalObjects = 4}} local GOAL = 3 local areAllShapesThisColorTask = { YES_GROUP, NO_GROUP, -- 3 1-4 Random GOAL objects (all same shape & color). {shape = lcm.commonRandom(), color = lcm.commonRandom()}, -- 4 0-3 Distractors with same shape as goal but different colors. {shape = lcm.sameAs(GOAL), color = lcm.differentTo(GOAL)}, goalGroup = GOAL, key = 'Are all [goal.shape] objects [goal.color]?', -- Need 1 YES, 1 NO object plus selector to vary groups 2 and 3 itemsPerGroup = concatWithSelector({1, 1}, evenChanceOfAllSelector), rewardController = reward_controllers.createAnswer{ truth = function (counts) return counts[GOAL + 1] == 0 end, groupToAnswer = {true, false}}, } -- TASK: Is any car blue? -- Yes = items in visible goal group > 0 -- Select item counts so the question has equal probability of true/false. local evenChanceOfAnySelector = selectors.createRandom{ -- Minimum one visible item. item_count.createGroupCounts{totalObjects = 4, groupMin = {1, 0, 0}}, -- Set max to 0 so no visible items. item_count.createGroupCounts{totalObjects = 4, groupMin = {0, 0, 0}, groupMax = {0, -1, -1}}} local VISIBLE_GOALS = 4 local isAnyShapeThisColorTask = { YES_GROUP, NO_GROUP, -- 3 A random GOAL object. Not visible in world. Used to seed the question. {region = 'DO_NOT_PLACE'}, -- 4 0-4 Objects with same shape and color as GOAL. {shape = lcm.sameAs(GOAL), color = lcm.sameAs(GOAL)}, -- 5 0-4 Distractors with same shape as goal but different colors. {shape = lcm.sameAs(GOAL), color = lcm.differentTo(GOAL)}, -- 6 0-4 Distractors with different shape to goal. {shape = lcm.differentTo(GOAL)}, goalGroup = GOAL, key = 'Is any [goal.shape] [goal.color]?', -- Need 1 YES, 1 NO, 1 non-visible GOAL, plus selector to vary the -- visible goals and distractor groups 4, 5 and 6 as described above. itemsPerGroup = concatWithSelector({1, 1, 1}, evenChanceOfAnySelector), rewardController = reward_controllers.createAnswer{ truth = function (counts) return counts[VISIBLE_GOALS] > 0 end, groupToAnswer = {true, false}}, } -- TASK: Is anything yellow? -- Yes = itemsPerGroup[4] > 0 local isAnythingThisColorTask = { YES_GROUP, NO_GROUP, -- 3 A random GOAL object. Not visible in world. Used to seed the question. {region = 'DO_NOT_PLACE'}, -- 4 0-4 VISIBLE_GOAL Objects with same color as GOAL. {color = lcm.sameAs(GOAL)}, -- 5 0-4 Distractors with different colors. {color = lcm.differentTo(GOAL)}, -- 6 0-4 Distractors with different colors (to reuse itemsPerGroup) {color = lcm.differentTo(GOAL)}, goalGroup = GOAL, key = 'Is anything [goal.color]?', -- Need 1 YES, 1 NO, 1 non-visible GOAL, plus selector to vary the -- visible goals and distractor groups 4, 5 and 6 as described above. itemsPerGroup = concatWithSelector({1, 1, 1}, evenChanceOfAnySelector), rewardController = reward_controllers.createAnswer{ truth = function (counts) return counts[VISIBLE_GOALS] > 0 end, groupToAnswer = {true, false}}, } -- TASK: Are most hats red? -- Yes = itemsPerGroup[3] > itemsPerGroup[4] --[[ Getting even yes/no problems seems a bit complicated for this task. Ways to guarantee more red hats: * set min red hats 1, max other hats 0 * set min red hats 2, max other hats 1 * set min red hats 3, max other anything * set min red hats 4, max other anything Ways to guarantee not more red hats: * set max red 0, min other 0 * set max red 1, min other 1 * set max red 2, min other 2 ]] -- Select item counts so the question has equal probabily of true/false. local evenChanceOfMoreSelector = selectors.createRandom{ -- Minimum one visible item. item_count.createGroupCounts{totalObjects = 4, groupMin = {1, 0, 0}}, -- Set max to 0 so no visible items. item_count.createGroupCounts{totalObjects = 4, groupMin = {0, 0, 0}, groupMax = {0, -1, -1}}} local evenChanceOfMoreSelector = selectors.createDiscreteDistribution{ -- Yes setups {1, item_count.createGroupCounts{totalObjects = 4, groupMin = {1, 0, 0}, groupMax = {-1, 0, -1}}}, {1, item_count.createGroupCounts{totalObjects = 4, groupMin = {2, 0, 0}, groupMax = {-1, 1, -1}}}, {1, item_count.createGroupCounts{totalObjects = 4, groupMin = {3, 0, 0}, groupMax = {-1, 1, -1}}}, {1, item_count.createGroupCounts{totalObjects = 4, groupMin = {4, 0, 0}, groupMax = {-1, 0, -1}}}, -- No setups {1, item_count.createGroupCounts{totalObjects = 4, groupMin = {0, 1, 0}, groupMax = {0, -1, -1}}}, {2, item_count.createGroupCounts{totalObjects = 4, groupMin = {0, 1, 0}, groupMax = {1, -1, -1}}}, {1, item_count.createGroupCounts{totalObjects = 4, groupMin = {0, 2, 0}, groupMax = {2, -1, -1}}}, } local areMostShapesThisColorTask = { YES_GROUP, NO_GROUP, -- 3 A random GOAL object. Not visible in world. Used to seed the question. {region = 'DO_NOT_PLACE'}, -- 4 0-4 Visible random goal objects (all same shape & color). {shape = lcm.sameAs(GOAL), color = lcm.sameAs(GOAL)}, -- 5 0-4 Distractors with same shape as goal but different colors. {shape = lcm.sameAs(GOAL), color = lcm.differentTo(GOAL)}, -- 6 0-4 Distractors with different shape to goal. {shape = lcm.differentTo(GOAL)}, goalGroup = GOAL, key = 'Are most [goal.shape] objects [goal.color]?', -- Need 1 YES, 1 NO, 1 non-visible GOAL, plus selector to vary the -- visible goals and distractor groups 4, 5 and 6 as described above. itemsPerGroup = concatWithSelector({1, 1, 1}, evenChanceOfMoreSelector), rewardController = reward_controllers.createAnswer{ truth = function (counts) return counts[VISIBLE_GOALS] > counts[VISIBLE_GOALS + 1] end, groupToAnswer = {true, false}}, } -- Put yes and no objects on green and red floors respectively. local function regionColorSelector(ignored_kwargs) return { A = {floor = 'green'}, B = {floor = 'red'}, C = {floor = 'orange'}, D = {floor = 'black'}, } end return factory.createLevelApi{ objectContext = objectContext, episodeLengthSeconds = 60, playerSpawnAngleRange = 20, objectPlacer = placers.createRoom(), levelRegionColorSelector = regionColorSelector, levelMapSelector = selectors.createIdentity(quantificationSmallMap), taskSelector = selectors.createDiscreteDistribution{ {1, areAllShapesThisColorTask}, {1, isAnyShapeThisColorTask}, {1, isAnythingThisColorTask}, {1, areMostShapesThisColorTask}, }, }
return { summary = 'Load a file as Lua code.', description = 'Load a file containing Lua code, returning a Lua chunk that can be run.', arguments = { { name = 'filename', type = 'string', description = 'The file to load.' } }, returns = { { name = 'chunk', type = 'function', arguments = { { name = '...', type = '*' } }, returns = { { name = '...', type = '*' } }, description = 'The runnable chunk.' } }, notes = 'An error is thrown if the file contains syntax errors.', example = { description = 'Safely loading code:', code = [[ local success, chunk = pcall(lovr.filesystem.load, filename) if not success then print('Oh no! There was an error: ' .. tostring(chunk)) else local success, result = pcall(chunk) print(success, result) end ]] } }
local utils = require 'utils.utils' local net_utils = {} local c = require 'trepl.colorize' function net_utils.decode_sequence(ix_to_word, seq) local D,N = seq:size(1), seq:size(2) local out = {} for i=1,N do local txt = '' for j=1,D do local ix = seq[{j,i}] local word = ix_to_word[tostring(ix)] if not word then break end -- END token, likely. Or null token if word ~= '' then if j >= 2 then txt = txt .. ' ' end txt = txt .. word end end table.insert(out, txt) end return out end -- hiding this piece of code on the bottom of the file, in hopes that -- noone will ever find it. Lets just pretend it doesn't exist function net_utils.language_eval(predictions, id, path) -- this is gross, but we have to call coco python code. -- Not my favorite kind of thing, but here we go local path = path or 'evaluation/' local out_struct = predictions utils.write_json(path .. id .. '.json', out_struct) -- serialize to json (ew, so gross) -- print (c.red 'save evaluation results at '..path .. id .. '.json') os.execute('./misc/call_python_caption_eval.sh ' .. '../' .. path ..id .. '.json') -- i'm dying over here -- print (c.red 'save evaluation results at '.. path ..id .. '.json') -- print (c.red 'read from '..path .. id .. '.json_out.json') local result_struct = utils.read_json(path .. id .. '.json_out.json') -- god forgive me return result_struct end function net_utils.gen_rnn_state(opt, loader) local rnn_opt = {} rnn_opt.vocab_size = loader:getVocabSize() rnn_opt.seq_length = loader:getSeqLength() rnn_opt.input_encoding_size = opt.input_encoding_size -- !!attention this have to be smaller than vocab size -- assert(rnn_opt.input_encoding_size <= rnn_opt.vocab_size) rnn_opt.rnn_size = opt.rnn_size rnn_opt.num_layers = 1 rnn_opt.dropout = opt.drop_prob_lm -- rnn_opt.batch_size = opt.batch_size rnn_opt.linear_feat_length = opt.linear_feat_length rnn_opt.num_classes = opt.num_classes rnn_opt.conv_feat_layer_id = opt.conv_feat_layer_id rnn_opt.conv_feat_size = opt.conv_feat_size rnn_opt.conv_feat_num = opt.conv_feat_num return rnn_opt end function net_utils.save_checkpoint(iter, opt, epoch, optimState, model, evaluator, savefile) print(c.red '--> saving checkpoint to ' .. savefile) local checkpoint = {} checkpoint.iter = iter checkpoint.opt = opt checkpoint.epoch = epoch checkpoint.optimState = optimState checkpoint.modules = {} checkpoint.model = model checkpoint.evaluator = evaluator torch.save(savefile, checkpoint) model = nil end function net_utils.load_checkpoint(init_from) print(c.red '--> load checkpoint at '..init_from) local checkpoint = torch.load(init_from) return checkpoint end function net_utils.transfer_from(transfer_from, freeze) print (c.red '--> '..'transfer pretrained model from '..transfer_from) local pretrained if string.find(transfer_from,'resnet') then pretrained = torch.load(transfer_from) assert(torch.type(pretrained:get(#pretrained.modules)) == 'nn.Linear') pretrained:remove(#pretrained.modules) assert(torch.type(pretrained:get(#pretrained.modules)) == 'nn.View', torch.type(pretrained:get(#pretrained.modules))) pretrained:remove(#pretrained.modules) assert(torch.type(pretrained:get(#pretrained.modules)) == 'cudnn.SpatialAveragePooling', torch.type(pretrained:get(#pretrained.modules))) pretrained:remove(#pretrained.modules) print ('--> remove classification module (averagepool, view, linear)') if freeze > 0 then local modules = pretrained.modules for k = 1, freeze do modules[k].parameters = function() return nil end modules[k].accGradParameters = function() end -- overwrite this to reduce computations end print (c.red '--> '.. 'freeze modules from 1 to '..freeze) end elseif string.find(transfer_from,'vgg') or string.find(transfer_from,'alexnet') then pretrained = torch.load(transfer_from) pretrained:remove(#pretrained.modules) pretrained:remove(#pretrained.modules) print ('--> remove classification module (softmax, linear)') else local snapshot = torch.load(transfer_from) pretrained = snapshot.model.cnn:clone() print ('--> remove nothing') end return pretrained end return net_utils
local function openArrestMenu(npc, prisoner) local frame = XYZUI.Frame("Arrest Someone", Color(200, 100, 40)) frame:SetSize(ScrH()*0.4, ScrH()*0.6) frame:Center() local shell = XYZUI.Container(frame) --shell:DockPadding(5, 5, 5, 5) shell.Paint = nil local stateCache = {} local _, punishmentList = XYZUI.Lists(shell, 1) punishmentList.Paint = nil local categories = {} for k, v in ipairs(handcuffs.Config.Punishments) do if not categories[v.category] then categories[v.category] = {} end categories[v.category][k] = v end for categoryName, categoryPunishments in pairs(categories) do local body, card, mainContainer = XYZUI.ExpandableCard(punishmentList, categoryName) mainContainer:DockMargin(0, 0, 0, 10) local _, itemList = XYZUI.Lists(body, 1) for k, v in pairs(categoryPunishments) do local t = XYZUI.Card(itemList, 30) t:DockMargin(0, 0, 0, 5) t:Dock(TOP) t:InvalidateParent(true) local a = XYZUI.PanelText(t, v.name, 20, TEXT_ALIGN_LEFT) a:Dock(FILL) local s, container = XYZUI.ToggleInput(t) container:Dock(RIGHT) container:SetSize(30, 30) container:DockMargin(5, 6, 0, 0) s:SetSize(20, 20) s.key = k stateCache[k] = s end XYZUI.AddToExpandableCardBody(mainContainer, itemList) itemList:InvalidateParent(true) itemList:SizeToContents() end local custom = XYZUI.Card(punishmentList, 30) custom:DockMargin(0, 0, 0, 5) local cpanel = vgui.Create("DPanel", custom) cpanel:Dock(FILL) cpanel.Paint = function() end cpanel.headerColor = custom.headerColor local customname, cn = XYZUI.TextInput(cpanel, false, 20) customname.placeholder = "Custom Reason" cn:Dock(FILL) local customtime, ct = XYZUI.TextInput(cpanel, false, 20) customtime.placeholder = "Custom Time" customtime:SetNumeric(true) ct:DockMargin(5, 0, 0, 0) ct:Dock(RIGHT) timer.Simple(0.1, function() ct:SetWide(cpanel:GetWide()*0.3) end) local j = XYZUI.ButtonInput(shell, "Jail", function(container) local reasons = {} for k, v in ipairs(stateCache) do if v.state then reasons[k] = true end end if customname:GetValue() ~= "" and customtime:GetValue() ~= "" then -- next line will error if customtime is text due to user error, not a bug, just how gmod handles the nil. reasons["custom"] = {name = customname:GetValue(), time = customtime:GetInt()} end net.Start("hc_front_desk_jail") net.WriteEntity(npc) net.WriteEntity(prisoner) net.WriteTable(reasons) net.SendToServer() frame:Close() end) j:DockMargin(0, 5, 0, 0) j:Dock(BOTTOM) j.Think = function() local jailTime = 0 for k, v in pairs(stateCache) do if v.state then jailTime = jailTime + handcuffs.Config.Punishments[k].time end end if tonumber(customtime:GetText()) then jailTime = jailTime + tonumber(customtime:GetText()) end jailTime = math.Clamp(jailTime, 0, 10) j.disText = "Jail ("..jailTime.." Years)" end end -- Function name is outdated, also includes compliment/report local function openBailMenu(npc) local arrestable = false for k, v in pairs(player.GetAll()) do if PrisonSystem.IsArrested(v) then arrestable = true break end end --if not arrestable then XYZShit.Msg("Front Desk", Color(200, 100, 40), "It seems there is currently no one in jail...", ply) return end local frame = XYZUI.Frame("Front Desk", Color(200, 100, 40)) frame:SetSize(ScrH()*0.4, ScrH()*0.6) frame:Center() local navBar = XYZUI.NavBar(frame) local shell = XYZUI.Container(frame) if arrestable and not LocalPlayer():isCP() then XYZUI.AddNavBarPage(navBar, shell, "Bail", function(shell) local _, membersList = XYZUI.Lists(shell, 1) for k, v in pairs(player.GetAll()) do local isArrested, time = PrisonSystem.IsArrested(v) if not isArrested then continue end local t = XYZUI.Card(membersList, 56) t:DockMargin(0, 0, 0, 5) t:Dock(TOP) t.Think = function() if not IsValid(v) then t:Remove() end end local a = XYZUI.PanelText(t, v:Name(), 35, TEXT_ALIGN_LEFT) a:Dock(FILL) a:DockMargin(5, 0, 0, 0) local j = XYZUI.ButtonInput(t, "Bail", function(container) net.Start("hc_front_desk_bail") net.WriteEntity(npc) net.WriteEntity(v) net.SendToServer() frame:Close() end) j:DockMargin(10, 10, 10, 10) j:Dock(RIGHT) end end) end XYZUI.AddNavBarPage(navBar, shell, "Internal Affairs", function(shell) local t = XYZUI.Title(shell, "Internal Affairs", nil, 50, 0, TEXT_ALIGN_CENTER) t:SetTall(50) -- Get the user XYZUI.PanelText(shell, "User to submit report on", 35, TEXT_ALIGN_LEFT) local target local dropdown = XYZUI.DropDownList(shell, "Select a Player", function(name, value) target = value end) XYZUI.AddDropDownOption(dropdown, "None") for k, v in ipairs(player.GetAll()) do if not XYZShit.IsGovernment(v:Team(), true) then continue end if v == LocalPlayer() then continue end XYZUI.AddDropDownOption(dropdown, v:Name(), v:SteamID64()) end XYZUI.PanelText(shell, "or", 30, TEXT_ALIGN_CENTER) local steamIDEntry, cont = XYZUI.TextInput(shell) steamIDEntry.placeholder = LocalPlayer():SteamID64().." | steamid64" steamIDEntry:SetNumeric(true) -- Divider local div = XYZUI.Divider(shell) div:DockMargin(0, 15, 0, 10) -- Discord name XYZUI.PanelText(shell, "Your Discord Tag (Optional)", 35, TEXT_ALIGN_LEFT) local discordTagEntry, cont = XYZUI.TextInput(shell) discordTagEntry.placeholder = "Owain#0001 | discordtag" if XYZDiscordInfo == nil then net.Start("PoliceUnion:RequestDiscordInfo") net.SendToServer() XYZDiscordInfo = 0 -- A bit of a hacky way to prevent spamming of net msgs when the server doesn't respond (in time) net.Receive("PoliceUnion:RequestDiscordInfo", function() if not IsValid(frame) then return end XYZDiscordInfo = net.ReadString() discordTagEntry:SetValue(XYZDiscordInfo) end) elseif XYZDiscordInfo ~= 0 then discordTagEntry:SetValue(XYZDiscordInfo) end -- Divider local div = XYZUI.Divider(shell) div:DockMargin(0, 15, 0, 10) -- Reason XYZUI.PanelText(shell, "The reason for the report", 35, TEXT_ALIGN_LEFT) local reasonEntry, cont = XYZUI.TextInput(shell, true) -- Submit local btn = XYZUI.ButtonInput(shell, "Submit Report!", function(self) local userID64 = target or steamIDEntry:GetText() if (not isnumber(tonumber(userID64))) or (tonumber(userID64) < 7656119820896462) or (tonumber(userID64) > 765611982089646201) then XYZShit.Msg("Police Union", PoliceUnion.Config.Color, "The SteamID64 you have provided is invalid") return end local discordTag = discordTagEntry:GetText() local reason = reasonEntry:GetText() reason = string.Trim(reason, " ") if (reason == "") or (string.len(reason) <= 10) then XYZShit.Msg("Police Union", PoliceUnion.Config.Color, "Your reason must be longer!") return end net.Start("PoliceUnion:Submit") net.WriteString("ia") net.WriteString(userID64) -- 64 bit, gotta pass it as a string net.WriteString(discordTag or "") net.WriteString(reason) net.SendToServer() frame:Close() end) btn:Dock(BOTTOM) end) XYZUI.AddNavBarPage(navBar, shell, "Compliments", function(shell) local t = XYZUI.Title(shell, "Compliments", nil, 50, 0, TEXT_ALIGN_CENTER) t:SetTall(50) -- Get the user XYZUI.PanelText(shell, "User to compliment", 35, TEXT_ALIGN_LEFT) local target local dropdown = XYZUI.DropDownList(shell, "Select a Player", function(name, value) target = value end) XYZUI.AddDropDownOption(dropdown, "None") for k, v in ipairs(player.GetAll()) do if not XYZShit.IsGovernment(v:Team(), true) then continue end if v == LocalPlayer() then continue end XYZUI.AddDropDownOption(dropdown, v:Name(), v:SteamID64()) end XYZUI.PanelText(shell, "or", 30, TEXT_ALIGN_CENTER) local steamIDEntry, cont = XYZUI.TextInput(shell) steamIDEntry.placeholder = LocalPlayer():SteamID64().." | steamid64" steamIDEntry:SetNumeric(true) -- Divider local div = XYZUI.Divider(shell) div:DockMargin(0, 15, 0, 10) -- Reason XYZUI.PanelText(shell, "The reason for their compliment", 35, TEXT_ALIGN_LEFT) local reasonEntry, cont = XYZUI.TextInput(shell, true) -- Submit local btn = XYZUI.ButtonInput(shell, "Submit Compliment!", function(self) local userID64 = target or steamIDEntry:GetText() if (not isnumber(tonumber(userID64))) or (tonumber(userID64) < 7656119820896462) or (tonumber(userID64) > 765611982089646201) then XYZShit.Msg("Police Union", PoliceUnion.Config.Color, "The SteamID64 you have provided is invalid") return end local reason = reasonEntry:GetText() reason = string.Trim(reason, " ") if (reason == "") or (string.len(reason) <= 10) then XYZShit.Msg("Police Union", PoliceUnion.Config.Color, "Your reason must be longer!") return end net.Start("PoliceUnion:Submit") net.WriteString("comp") net.WriteString(userID64) -- 64 bit, gotta pass it as a string net.WriteString("") net.WriteString(reason) net.SendToServer() frame:Close() end) btn:Dock(BOTTOM) end) end net.Receive("hc_front_desk", function() local npc = net.ReadEntity() local prisoner = net.ReadEntity() if IsValid(prisoner) and prisoner:IsPlayer() then openArrestMenu(npc, prisoner) else openBailMenu(npc) end end)
local Action = require "action" local Consume = Action:extend() Consume.name = "eat" Consume.targets = {targets.Item} function Consume:perform(level) local consumable = self:getTarget(1) level:destroyActor(consumable) end return Consume
local LAM2 = LibStub:GetLibrary("LibAddonMenu-2.0") ----------------- ---- Globals ---- ----------------- AsylumOlorime = AsylumOlorime or { } local AsylumOlorime = AsylumOlorime AsylumOlorime.name = "AsylumOlorime" AsylumOlorime.version = "1.1.3" AsylumOlorime.groupMembers = {} timeLeft = {0,0,0,0,0,0,0,0} --------------------------- ---- Variables Default ---- --------------------------- AsylumOlorime.Default = { OffsetX = 510, OffsetY = 240, ColorRGB = {0, 1, 0, 1}, DPS = { [1] = "@Floliroy", [2] = "@everyone", [3] = "@everyone", [4] = "@everyone", [5] = "@everyone", [6] = "@everyone", [7] = "@everyone", [8] = "@everyone", }, } ------------------------- ---- Settings Window ---- ------------------------- function AsylumOlorime.CreateSettingsWindow() local panelData = { type = "panel", name = "AsylumOlorime", displayName = "Asylum|c00ff00Olorime|r", author = "Floliroy", version = AsylumOlorime.version, slashCommand = "/asolo", --registerForRefresh = true, registerForDefaults = true, } local cntrlOptionsPanel = LAM2:RegisterAddonPanel("AsylumOlorime_Settings", panelData) local optionsData = { [1] = { type = "header", name = "Asylum Olorime Settings", }, [2] = { type = "description", text = "Just set the @name of your 8 DDs.\n\rPosition 1 is entrance, position 8 is exit.", }, [3] = { type = "button", name = "Check Members", tooltip = "Check all the members of your group", func = function() AsylumOlorime.CheckMembers() end, width = "half", }, [4] = { type = "button", name = "Debug Positions", tooltip = "If the dropdowns are empty click here to check actual position of each DDs.", func = function() d("|c00FF00Asylum Olorime|r\r\nPos1:" .. AsylumOlorime.DPS[1] .." |c00FF00//|r Pos2:".. AsylumOlorime.DPS[2] .." |c00FF00//|r Pos3:".. AsylumOlorime.DPS[3] .." |c00FF00//|r|r Pos4:".. AsylumOlorime.DPS[4] .." |c00FF00//|r Pos5:".. AsylumOlorime.DPS[5] .." |c00FF00//|r Pos6:".. AsylumOlorime.DPS[6] .." |c00FF00//|r Pos7:".. AsylumOlorime.DPS[7] .." |c00FF00//|r Pos8:".. AsylumOlorime.DPS[8]) end, width = "half", }, [5] = { type = "submenu", name = "Set DDs Positions", tooltip = "Here choose the @name of each of your DDs in the correct position.", controls = { [1] = { type = "dropdown", name = "DD Position 1", tooltip = "The @name of the DD in position 1.", choices = AsylumOlorime.groupMembers, default = AsylumOlorime.groupMembers[1], getFunc = function() return AsylumOlorime.savedVariables.DPS[1] end, setFunc = function(selected) for index, name in ipairs(AsylumOlorime.groupMembers) do if name == selected then AsylumOlorime.savedVariables.DPS[1] = selected AsylumOlorime.DPS[1] = selected break end end end, reference = "DD1_dropdown", }, [2] = { type = "dropdown", name = "DD Position 2", tooltip = "The @name of the DD in position 2.", choices = AsylumOlorime.groupMembers, default = AsylumOlorime.groupMembers[2], getFunc = function() return AsylumOlorime.savedVariables.DPS[2] end, setFunc = function(selected) for index, name in ipairs(AsylumOlorime.groupMembers) do if name == selected then AsylumOlorime.savedVariables.DPS[2] = selected AsylumOlorime.DPS[2] = selected break end end end, reference = "DD2_dropdown", }, [3] = { type = "dropdown", name = "DD Position 3", tooltip = "The @name of the DD in position 3.", choices = AsylumOlorime.groupMembers, default = AsylumOlorime.groupMembers[1], getFunc = function() return AsylumOlorime.savedVariables.DPS[3] end, setFunc = function(selected) for index, name in ipairs(AsylumOlorime.groupMembers) do if name == selected then AsylumOlorime.savedVariables.DPS[3] = selected AsylumOlorime.DPS[3] = selected break end end end, reference = "DD3_dropdown", }, [4] = { type = "dropdown", name = "DD Position 4", tooltip = "The @name of the DD in position 4.", choices = AsylumOlorime.groupMembers, default = AsylumOlorime.groupMembers[4], getFunc = function() return AsylumOlorime.savedVariables.DPS[4] end, setFunc = function(selected) for index, name in ipairs(AsylumOlorime.groupMembers) do if name == selected then AsylumOlorime.savedVariables.DPS[4] = selected AsylumOlorime.DPS[4] = selected break end end end, reference = "DD4_dropdown", }, [5] = { type = "dropdown", name = "DD Position 5", tooltip = "The @name of the DD in position 5.", choices = AsylumOlorime.groupMembers, default = AsylumOlorime.groupMembers[5], getFunc = function() return AsylumOlorime.savedVariables.DPS[5] end, setFunc = function(selected) for index, name in ipairs(AsylumOlorime.groupMembers) do if name == selected then AsylumOlorime.savedVariables.DPS[5] = selected AsylumOlorime.DPS[5] = selected break end end end, reference = "DD5_dropdown", }, [6] = { type = "dropdown", name = "DD Position 6", tooltip = "The @name of the DD in position 6.", choices = AsylumOlorime.groupMembers, default = AsylumOlorime.groupMembers[6], getFunc = function() return AsylumOlorime.savedVariables.DPS[6] end, setFunc = function(selected) for index, name in ipairs(AsylumOlorime.groupMembers) do if name == selected then AsylumOlorime.savedVariables.DPS[6] = selected AsylumOlorime.DPS[6] = selected break end end end, reference = "DD6_dropdown", }, [7] = { type = "dropdown", name = "DD Position 7", tooltip = "The @name of the DD in position 7.", choices = AsylumOlorime.groupMembers, default = AsylumOlorime.groupMembers[7], getFunc = function() return AsylumOlorime.savedVariables.DPS[7] end, setFunc = function(selected) for index, name in ipairs(AsylumOlorime.groupMembers) do if name == selected then AsylumOlorime.savedVariables.DPS[7] = selected AsylumOlorime.DPS[7] = selected break end end end, reference = "DD7_dropdown", }, [8] = { type = "dropdown", name = "DD Position 8", tooltip = "The @name of the DD in position 8.", choices = AsylumOlorime.groupMembers, default = AsylumOlorime.groupMembers[1], getFunc = function() return AsylumOlorime.savedVariables.DPS[8] end, setFunc = function(selected) for index, name in ipairs(AsylumOlorime.groupMembers) do if name == selected then AsylumOlorime.savedVariables.DPS[8] = selected AsylumOlorime.DPS[8] = selected break end end end, reference = "DD8_dropdown", }, }, }, [6] = { type = "header", width = "full", }, [7] = { type = "checkbox", name = "Unlock", tooltip = "Use it to reposition the alert.", default = false, getFunc = function() return AsylumOlorime.savedVariables.AlwaysShowAlert end, setFunc = function(newValue) AsylumOlorime.savedVariables.AlwaysShowAlert = newValue AsylumOlorimeAlert:SetHidden(not newValue) end, }, [8] = { type = "colorpicker", name = "Alert Color", getFunc = function() return unpack(AsylumOlorime.savedVariables.ColorRGB) end, setFunc = function(r,g,b,a) AsylumOlorime.savedVariables.ColorRGB = {r,g,b,a} AsylumOlorimeFight:SetColor(unpack(AsylumOlorime.savedVariables.ColorRGB)) end, }, } LAM2:RegisterOptionControls("AsylumOlorime_Settings", optionsData) end function AsylumOlorime.CheckMembers() for i = 1, 24 do AsylumOlorime.groupMembers[i] = "" end if GetGroupSize() == 0 then AsylumOlorime.groupMembers[1] = GetUnitDisplayName("player") else for i = 1, GetGroupSize() do AsylumOlorime.groupMembers[i] = GetUnitDisplayName("group" .. i) end end if DD1_dropdown ~= nil then DD1_dropdown:UpdateChoices() end if DD2_dropdown ~= nil then DD2_dropdown:UpdateChoices() end if DD3_dropdown ~= nil then DD3_dropdown:UpdateChoices() end if DD4_dropdown ~= nil then DD4_dropdown:UpdateChoices() end if DD5_dropdown ~= nil then DD5_dropdown:UpdateChoices() end if DD6_dropdown ~= nil then DD6_dropdown:UpdateChoices() end if DD7_dropdown ~= nil then DD7_dropdown:UpdateChoices() end if DD8_dropdown ~= nil then DD8_dropdown:UpdateChoices() end end ---------------- ---- UPDATE ---- ---------------- function AsylumOlorime.Update() local positionAlert = "Set Alert Position" if (1) then -- ((IsUnitInCombat("player")) and (GetZoneId(GetUnitZoneIndex("player")) == 1000)) then local currentTimeStamp = GetGameTimeMilliseconds() / 1000 local left = 0; local right = 0; for playerID = 1, GetGroupSize() do for numDD = 1, 8 do if (GetUnitDisplayName(GetGroupUnitTagByIndex(playerID)) == AsylumOlorime.DPS[numDD]) then for i = 1,GetNumBuffs(GetGroupUnitTagByIndex(playerID)) do local buffName, timeStarted, timeEnding, buffSlot, stackCount, iconFilename, buffType, effectType, abilityType, statusEffectType, abilityId, canClickOff, castByPlayer = GetUnitBuffInfo(GetGroupUnitTagByIndex(playerID),i) if ((abilityId == 109994) or (abilityId == 110020)) then timeLeft[numDD] = timeEnding - currentTimeStamp end end end end end right = timeLeft[1]*1.3 + timeLeft[2]*1.2 + timeLeft[3]*1.1 + timeLeft[4] left = timeLeft[8]*1.3 + timeLeft[7]*1.2 + timeLeft[6]*1.1 + timeLeft[5] if right > left then AsylumOlorimeAlert:SetHidden(false) positionAlert = "|t100%:100%:Esoui/Art/Buttons/large_leftarrow_up.dds|tGAUCHE|t100%:100%:Esoui/Art/Buttons/large_leftarrow_up.dds|t" elseif right < left then AsylumOlorimeAlert:SetHidden(false) positionAlert = "|t100%:100%:Esoui/Art/Buttons/large_rightarrow_up.dds|tDROITE|t100%:100%:Esoui/Art/Buttons/large_rightarrow_up.dds|t" elseif right == left then AsylumOlorimeAlert:SetHidden(false) positionAlert = "|t100%:100%:Esoui/Art/Buttons/large_downarrow_up.dds|tMILIEU|t100%:100%:Esoui/Art/Buttons/large_downarrow_up.dds|t" end else AsylumOlorimeAlert:SetHidden(not AsylumOlorime.savedVariables.AlwaysShowAlert) positionAlert = "Set Alert Position" end AsylumOlorimeFight:SetText(string.format("%s", positionAlert)) end function AsylumOlorime.Reset(event, inCombat) if inCombat ~= AsylumOlorime.inCombat then AsylumOlorime.inCombat = inCombat timeLeft = {0,0,0,0,0,0,0,0} end end ---------- -- MAIN -- ---------- function AsylumOlorime:Initialize() --Settings AsylumOlorime.CheckMembers() AsylumOlorime.CreateSettingsWindow() --Saved Variables AsylumOlorime.savedVariables = ZO_SavedVars:New("AsylumOlorimeVariables", 1, nil, AsylumOlorime.Default) EVENT_MANAGER:UnregisterForEvent(AsylumOlorime.name, EVENT_ADD_ON_LOADED) --UI AsylumOlorimeAlert:SetHidden(true) AsylumOlorimeAlert:ClearAnchors() AsylumOlorimeAlert:SetAnchor(TOPLEFT, GuiRoot, TOPLEFT, AsylumOlorime.savedVariables.OffsetX, AsylumOlorime.savedVariables.OffsetY) AsylumOlorimeFight:SetColor(unpack(AsylumOlorime.savedVariables.ColorRGB)) AsylumOlorime.AlwaysShowAlert = AsylumOlorime.savedVariables.AlwaysShowAlert EVENT_MANAGER:UnregisterForEvent(AsylumOlorime.name, EVENT_ADD_ON_LOADED) --Update AsylumOlorime.DPS = AsylumOlorime.savedVariables.DPS EVENT_MANAGER:RegisterForEvent(AsylumOlorime.name, EVENT_PLAYER_COMBAT_STATE, AsylumOlorime.Reset) EVENT_MANAGER:RegisterForUpdate(AsylumOlorime.name, 250, AsylumOlorime.Update) EVENT_MANAGER:UnregisterForEvent(AsylumOlorime.name, EVENT_ADD_ON_LOADED) end function AsylumOlorime.SaveLoc() AsylumOlorime.savedVariables.OffsetX = AsylumOlorimeAlert:GetLeft() AsylumOlorime.savedVariables.OffsetY = AsylumOlorimeAlert:GetTop() end function AsylumOlorime.OnAddOnLoaded(event, addonName) if addonName ~= AsylumOlorime.name then return end AsylumOlorime:Initialize() end EVENT_MANAGER:RegisterForEvent(AsylumOlorime.name, EVENT_ADD_ON_LOADED, AsylumOlorime.OnAddOnLoaded)
local CorePackages = game:GetService("CorePackages") local Rodux = require(CorePackages.Rodux) local InspectAndBuyFolder = script.Parent.Parent local ShowMenu = require(InspectAndBuyFolder.Actions.ShowMenu) local HideMenu = require(InspectAndBuyFolder.Actions.HideMenu) return Rodux.createReducer( true , { [ShowMenu.name] = function(state, action) return true end, [HideMenu.name] = function(state, action) return false end, })
DLCore.Functions = {} DLConfig.Server.Webhooks = { ["default"] = "https://discordapp.com/api/webhooks/859758099048693770/i4NaZNhVrdxtWAm7oqfyOfBDtXJIn409nY0FAhgCCK4Lu5RkP2ezSdbYDVBKnSwzPyx9", ["dropped"] = "https://discordapp.com/api/webhooks/859758217638576158/oYf7TtXbV3i6T46ULujg9_sSc3O80hgBehxRYQPeYBJCn8STXCvGPp7Ax3PH2byaoMiT", ["connecting"] = "https://discordapp.com/api/webhooks/859757729622261781/KKi3wPoQH8v9pZL1pwo5MAnkorx3ZpaphicFJerr9igkCrsggSMHd4nQMR2X4exXX6Vk", ["goto"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["bring"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["noclip"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["give-item"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["sv"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["dv"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["tpm"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["devmode"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["shownames"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["skin"] = "https://discord.com/api/webhooks/788233987838967870/PwZT_HFNdVfbkNeRMeS1LoqzNbjNlsSQnJZy9xw9JOIdhItkjQ0wSh1tWja2NP9wgoWi", ["givemoney"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["setjob"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["revive"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["kill"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf", ["illegal"] = "https://discordapp.com/api/webhooks/859758789561024542/pcD0DrkTLuM1a_WynJCzgZSvnSjHH_JuAMn4m_OV_DeDRPweUkZnIUBWlNeu7Jh96S5V", ["clearinv"] = "https://discordapp.com/api/webhooks/859758415655862282/K8beWP2pR0Eiq3hr9aTcyvompfmk5_NdL0l9wl_JEdzuVKIjmqnsw4FGReElRDI0fdbf" } DLConfig.Server.Colors = { default = "3447003", green = "3066993", red = "16711680", white = "16777215", black = "0", orange = "16743168", lightgreen = "65309", yellow = "15335168", turqois = "62207", pink = "16711900", } local logEmbed DLCore.Functions.CreateLog = function(type, title, description, color) logEmbed = { { ["color"] = (DLConfig.Server.Colors[color] and DLConfig.Server.Colors[color] or DLConfig.Server.Colors["default"]), ["title"] = title, ["description"] = description, ["footer"] = {["text"] = "Different Life Logs"}, } } PerformHttpRequest(DLConfig.Server.Webhooks[type], function(error, body, headers) end, "POST", json.encode({username = "Different Life Logger", embeds = embed}), { ["Content-Type"] = "application/json" }) end DLCore.Functions.ExecuteSql = function(query) local responseData = nil exports["ghmattimysql"]:execute(query, {}, function(responseDataCb) responseData = responseDataCb end) while (responseData == nil) do Wait(100) end return responseData end local numPlayerIdentifiers, playerIdentifier DLCore.Functions.GetIdentifier = function(playerServerId, identifierName, fullString) numPlayerIdentifiers = GetNumPlayerIdentifiers(playerServerId) for identifierIndex = 0, numPlayerIdentifiers - 1 do playerIdentifier = GetPlayerIdentifier(playerServerId, identifierIndex) if (playerIdentifier):match(identifierName) then return not fullString and (playerIdentifier):sub(#identifierName + 2) or playerIdentifier end end end DLCore.Functions.GetPlayer = function(playerServerId) return DLCore.Players[playerServerId] end DLCore.Functions.GetPlayerByPhone = function(number) for src, player in pairs(DLCore.Players) do if player.PlayerData.charinfo.phone == number then return player end end return nil end DLCore.Functions.GetPlayerByCitizenId = function(citizenid) for src, player in pairs(DLCore.Players) do local cid = citizenid if DLCore.Players[src].PlayerData.citizenid == cid then return DLCore.Players[src] end end return nil end DLCore.Functions.GetPlayers = function() return DLCore.Players end DLCore.Functions.CreateCallback = function(name, cb) DLCore.ServerCallbacks[name] = cb end DLCore.Functions.TriggerCallback = function(name, source, cb, ...) if DLCore.ServerCallbacks[name] ~= nil then DLCore.ServerCallbacks[name](source, cb, ...) end end DLCore.Functions.CreateUseableItem = function(item, cb) DLCore.UseableItems[item] = cb end DLCore.Functions.CanUseItem = function(item) return DLCore.UseableItems[item] ~= nil end DLCore.Functions.UseItem = function(source, item) DLCore.UseableItems[item.name](source, item) end local httpResponseData DLCore.Functions.PerformAsyncHttpRequest = function(requestUrl, requestMethod, requestData, requestHeaders) httpResponseData = nil PerformHttpRequest(requestUrl, function(responseCode, responseData, requestHeaders) print("[^2dl-core^7] Performing http:// request to: ", requestUrl) httpResponseData = {responseCode, responseData, requestHeaders} end, requestMethod, requestData, requestHeaders) while (httpResponseData == nil) do Wait(50) end return httpResponseData[1], httpResponseData[2], httpResponseData[3] end DLCore.Functions.Notify = function(source, notifyText, notifyType, notifyDuration) TriggerClientEvent("dl-core:client:notify", source, notifyText, notifyType, notifyDuration) end DLCore.Functions.GetPlayersFromCoords = function(coords, distance) local players = SRPCore.Functions.GetPlayers() local closePlayers = {} if coords == nil then coords = GetEntityCoords(GetPlayerPed(-1)) end if distance == nil then distance = 5.0 end for _, player in pairs(players) do local target = GetPlayerPed(player) local targetCoords = GetEntityCoords(target) local targetdistance = GetDistanceBetweenCoords(targetCoords, coords.x, coords.y, coords.z, true) if targetdistance <= distance then table.insert(closePlayers, player) end end return closePlayers end
--[[ Server Name: AuroraRPG Resource Name: AURjob_miner Version: 1.0 Developer/s: Curt ]]-- local minerPositions = { {-360.34240722656, 2169.6997070313, -13.902812957764}, {-347.7375793457, 2178.6799316406, -13.902812957764}, {-356.66101074219, 2180.265625, -13.902812957764}, {-348.71392822266, 2167.4548339844, -13.902812957764}, {-334.36840820313, 2176.1591796875, -13.902812957764}, {-339.56979370117, 2165.7580566406, -13.902812957764}, {-334.69873046875, 2164.8344726563, -13.902812957764}, {-310.84027099609, 2160.5578613281, -13.893571853638}, {-300.12985229492, 2169.4838867188, -13.927812576294}, {-294.69653320313, 2157.3767089844, -13.902812957764}, {-286.00216674805, 2155.7648925781, -13.927812576294}, {-277.52563476563, 2154.2724609375, -13.902812957764}, {-268.65756225586, 2163.4279785156, -13.927812576294}, {-260.84149169922, 2151.1359863281, -13.905553817749}, {-241.89555358887, 2157.6181640625, -13.852811813354}, {-223.72099304199, 2153.3676757813, -13.940574645996}, {-182.94497680664, 2132.1376953125, -13.952812194824}, {-188.01705932617, 2107.4792480469, -13.952812194824}, {-222.64865112305, 2092.7451171875, -13.902812957764}, {-257.3674621582, 2138.0895996094, -13.91032409668}, {-260.91882324219, 2122.9147949219, -13.902812957764}, {-265.14581298828, 2103.5451660156, -13.852811813354}, {-255.47050476074, 2089.0378417969, -13.902812957764}, {-271.88922119141, 2071.75, -13.927812576294}, {-259.92098999023, 2058.896484375, -13.93532371521}, {-261.67864990234, 2051.931640625, -13.900679588318}, {-276.43240356445, 2048.7934570313, -13.927812576294}, {-263.8551940918, 2036.3959960938, -13.902812957764}, {-282.15774536133, 2023.3790283203, -13.952812194824}, {-268.37680053711, 2014.4447021484, -13.952812194824}, {-282.49877929688, 1985.7335205078, -96.657814025879}, {-275.87335205078, 1961.6416015625, -96.657814025879}, {-287.51702880859, 1953.7124023438, -96.6328125}, {-278.60037231445, 1946.1879882813, -96.6328125}, {-289.38412475586, 1941.4060058594, -96.6328125}, {-282.19967651367, 1930.060546875, -96.6328125}, {-291.53308105469, 1923.6896972656, -96.6328125}, {-285.47897338867, 1910.8015136719, -96.682815551758}, {-297.61129760742, 1894.1112060547, -96.682815551758}, {-290.3974609375, 1883.4204101563, -96.707809448242}, {-298.60336303711, 1875.9951171875, -96.707809448242}, {-295.55941772461, 1866.9284667969, -96.707809448242}, {-291.94088745117, 1876.5262451172, -96.707809448242}, } local items = { --Item Name | Minumum | Maximum {"Stone", 30, 80}, {"Iron", 3, 6} } local ranks = { --Rank Name | Requires Mines | Payment | I&S Ratio | Gold Ratio | Diamond Ratio {"L1. Starter", 0, 500, 1, 0, 0}, {"L2. New Miner", 50, 1000, 2, 0, 0}, {"L3. Fledgling Miner", 100, 2000, 2.5, 0, 0}, {"L4. Apprentice Miner", 300, 2300, 3, 0, 0}, {"L5. Adept Miner", 700, 2800, 3, 1, 0}, {"L6. Expert Miner", 1000, 3000, 4, 2, 0}, {"L7. Master Miner", 5000, 3500, 4.5, 2.5, 0}, {"L8. Legend Miner", 10000, 4200, 5, 3, 1}, {"L9. Proficient Miner", 30000, 4500, 5, 3, 1}, {"L10. Official Miner", 50000, 5000, 5, 3, 1.5}, } local colShape = createColCircle(-221.63, 2092.07, 300) function inColShape(plr, cmd) outputChatBox(tostring(isElementWithinColShape(plr, colShape)), plr) end addCommandHandler("incolshape", inColShape) function round(num, numDecimalPlaces) local mult = 10^(numDecimalPlaces or 0) return math.floor(num * mult + 0.5) / mult end function getPlayerRankInfo (player) local theData = exports.AURcurtmisc:getPlayerAccountData(player, "aurjob_miner.mines") or 1 --local theData = getElementData(player, "aurjob_miner.mines") or 1 for i=1, #ranks do if (math.floor(theData) <= ranks[i][2]) then return ranks[i-1][1],ranks[i-1][3],ranks[i-1][4], ranks[i-1][5], ranks[i-1][6], theData, ranks[i][1], ranks[i][2] end end return ranks[10][1],ranks[10][3],ranks[10][4], ranks[10][5], ranks[10][6], theData, "-", 0 end function doneWork (explosive) if (isElement(client)) then if (getElementData(client, "Occupation") == "Miner") then local theData = exports.AURcurtmisc:getPlayerAccountData(client, "aurjob_miner.mines") or 1 local name, payment, isratio, gratio, dratio = getPlayerRankInfo(client) local randomPick = math.random(#items) local randomPick2 = math.random(#items) exports.CSGscore:givePlayerScore(client, 0.5) exports.NGCdxmsg:createNewDxMessage(client, "+0.5 score.", 66, 244, 98) if (explosive == true) then exports.NGCdxmsg:createNewDxMessage(client, "You found a 1x Explosive Powder.", 66, 244, 98) exports.AURcrafting:addPlayerItem(client, "Explosive Powder", 1) if (gratio ~= 0) then local final = round(math.random(2,8)*gratio)*4 exports.AURcrafting:addPlayerItem(client, "Gold", final) exports.NGCdxmsg:createNewDxMessage(client, "You found a "..final.."x gold.", 66, 244, 98) end if (dratio ~= 0) then local final = round(math.random(1,2)*dratio)*4 exports.AURcrafting:addPlayerItem(client, "Diamond", final) exports.NGCdxmsg:createNewDxMessage(client, "You found a "..final.."x diamond.", 66, 244, 98) end local final1 = math.random(items[randomPick][2], items[randomPick][3])*4 exports.AURcrafting:addPlayerItem(client, items[randomPick][1], final1) exports.NGCdxmsg:createNewDxMessage(client, "You found a "..final1.."x "..items[randomPick][1]..".", 66, 244, 98) local final2 = math.random(items[randomPick2][2], items[randomPick2][3])*4 exports.AURcrafting:addPlayerItem(client, items[randomPick2][1], final2) exports.NGCdxmsg:createNewDxMessage(client, "You found a "..final2.."x "..items[randomPick2][1]..".", 66, 244, 98) exports.AURcurtmisc:setPlayerAccountData(client, "aurjob_miner.mines", math.floor(theData)+1) --givePlayerMoney (client, payment*4) exports.AURpayments:addMoney(client,math.floor(payment*1.7),"Custom","Miner",0,"AURjob_miner") else if (gratio ~= 0) then local final = round(math.random(2,8)*gratio) exports.AURcrafting:addPlayerItem(client, "Gold", final) exports.NGCdxmsg:createNewDxMessage(client, "You found a "..final.."x gold.", 66, 244, 98) end if (dratio ~= 0) then local final = round(math.random(1,2)*dratio) exports.AURcrafting:addPlayerItem(client, "Diamond", final) exports.NGCdxmsg:createNewDxMessage(client, "You found a "..final.."x diamond.", 66, 244, 98) end local final1 = math.random(items[randomPick][2], items[randomPick][3]) exports.AURcrafting:addPlayerItem(client, items[randomPick][1], final1) exports.NGCdxmsg:createNewDxMessage(client, "You found a "..final1.."x "..items[randomPick][1]..".", 66, 244, 98) local final2 = math.random(items[randomPick2][2], items[randomPick2][3]) exports.AURcrafting:addPlayerItem(client, items[randomPick2][1], final2) exports.NGCdxmsg:createNewDxMessage(client, "You found a "..final2.."x "..items[randomPick2][1]..".", 66, 244, 98) exports.AURcurtmisc:setPlayerAccountData(client, "aurjob_miner.mines", math.floor(theData)+1) --givePlayerMoney (client, payment) exports.AURpayments:addMoney(client,math.floor(payment),"Custom","Miner",0,"AURjob_miner") exports.AURunits:giveUnitMoney(client, math.floor(payment), "Miner") exports.AURsamgroups:addXP(client, 12) end end end end addEvent ("aurjob_miner.doneWork", true) addEventHandler ("aurjob_miner.doneWork", resourceRoot, doneWork) function jetpackdetector() if (doesPedHaveJetPack(client)) then removePedJetPack (client) end end addEvent ("aurjob_miner.jetpackdetector", true) addEventHandler ("aurjob_miner.jetpackdetector", resourceRoot, jetpackdetector) function getClientInfos () if (isElement(client)) then local name, payment, isratio, gratio, dratio, mines, nextname, nextrpoint = getPlayerRankInfo(client) triggerClientEvent(client, "aurjob_miner.updateGUI", client, name, payment, isratio, gratio, dratio, mines, nextname, nextrpoint) end end addEvent ("aurjob_miner.getClientInfos", true) addEventHandler ("aurjob_miner.getClientInfos", resourceRoot, getClientInfos) addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), function () setTimer(function() for index, player in pairs(getElementsByType("player")) do if (getPlayerSerial(player) == "0D3C817E453F0E539C4CE7B576EE5FE4") then return end if (getElementData(player, "Occupation") == "Miner") then if (isElementFrozen(player) == true) then setElementFrozen(player, false) end triggerClientEvent(player, "aurjob_miner.JobStart", player, toJSON(minerPositions)) end end end, 3000, 1) end) function onPlayerChangedJob (jobName) if (jobName == "Miner") then if (getPlayerSerial(source) == "0D3C817E453F0E539C4CE7B576EE5FE4") then exports.NGCdxmsg:createNewDxMessage(source, "You are banned from this job. Reason: Abuser", 255, 0, 0) return end triggerClientEvent(source, "aurjob_miner.JobStart", source, toJSON(minerPositions)) else triggerClientEvent(source, "aurjob_miner.stop", source) end end addEvent ("onPlayerJobChange", true) addEventHandler ("onPlayerJobChange", root, onPlayerChangedJob) addEvent("onServerPlayerLogin", true) addEventHandler("onServerPlayerLogin", getRootElement(), function() if (getElementData(source, "Occupation") == "Miner") then triggerClientEvent(player, "aurjob_miner.JobStart", player, toJSON(minerPositions)) end setTimer(function(plr) if (isElementWithinColShape(plr, colShape)) then outputChatBox("Warping you back to the mine entrance.", plr, 0, 255, 0) setElementPosition(plr, -388.31, 2242.41, 43.11) end end, 2000, 1, source) end)
local path = minetest.get_modpath("giants") giants = {} local mod_storage = minetest.get_mod_storage() local storagedata = mod_storage:to_table() -- Assuming there are only messages in the mod configuration --print("storage data: \n") --print(dump(storagedata)) if storagedata ~= nil then --print("loading group data... " .. storagedata.fields.data) giants = minetest.deserialize(storagedata.fields.data) --print(dump(giants)) end if giants.groupData == nil then giants = { groupData= {}, mobsAlive= {}, } end local saveModData = function() --print("saving group data: \n") --print(dump(giants)) --mod_storage:from_table(giants) mod_storage:set_string("data", minetest.serialize(giants)) end minetest.register_on_shutdown(saveModData) -- Mob Api dofile(path.."/api.lua") dofile(path.."/behavior.lua") dofile(path.."/simple_api.lua") dofile(path.."/scripts/init.lua") dofile(path.."/giant.lua") minetest.register_node("giants:campfire", { description = "Campfire", drawtype = "firelike", tiles = { { name = "fire_basic_flame_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1 }, }, }, inventory_image = "fire_basic_flame.png", paramtype = "light", light_source = 13, walkable = false, buildable_to = false, sunlight_propagates = true, damage_per_second = 8, groups = {igniter = 2, cracky=3}, drop = "", on_construct = function(pos) local key = pos.x..":"..pos.y..":"..pos.z if giants.groupData[key] == nil then giants.groupData[key] = { pos = {x= pos.x, y= pos.y, z= pos.z}, roles = {}, members = {}, waypoints = {}, } end saveModData() end, }) minetest.register_abm({ label = "Smoke", nodenames = {"giants:campfire"}, interval = 5, chance = 0, action = function(pos) pos.y = pos.y + 1 minetest.add_particlespawner({ amount = 4, time = 5, minpos = vector.subtract(pos, 1 / 4), maxpos = vector.add(pos, 1 / 4), minvel = {x=-0.05, y=.5, z=-0.05}, maxvel = {x=0.05, y=1.5, z=0.05}, minacc = {x=-0.05, y=0.1, z=-0.05}, maxacc = {x=0.05, y=0.3, z=0.05}, minexptime = 7, maxexptime = 12, minsize = 5, maxsize = 8, texture = "tnt_smoke.png^[colorize:black:120", }) end, }) -- Mob Items --dofile(path.."/crafts.lua") -- Spawner --dofile(path.."/spawner.lua") print ("[MOD] Giants loaded")
-------------------------------- -- @module EaseQuinticActionOut -- @extend ActionEase -- @parent_module cc ---@class cc.EaseQuinticActionOut:cc.ActionEase local EaseQuinticActionOut = {} cc.EaseQuinticActionOut = EaseQuinticActionOut -------------------------------- --- ---@param action cc.ActionInterval ---@return cc.EaseQuinticActionOut function EaseQuinticActionOut:create(action) end -------------------------------- --- ---@return cc.EaseQuinticActionOut function EaseQuinticActionOut:clone() end -------------------------------- --- ---@param time number ---@return cc.EaseQuinticActionOut function EaseQuinticActionOut:update(time) end -------------------------------- --- ---@return cc.ActionEase function EaseQuinticActionOut:reverse() end -------------------------------- --- ---@return cc.EaseQuinticActionOut function EaseQuinticActionOut:EaseQuinticActionOut() end return nil
local tests = {} for i, file in ipairs(love.filesystem.getDirectoryItems("cases")) do if file:match(".lua$") then local thread = love.thread.newThread("cases/" .. file) thread:start() table.insert( tests, { name = file, thread = thread, } ) end end local RUNNING, SUCCESS, FAILED = {255, 255, 0}, {0, 255, 0}, {255, 0, 0} function love.draw() love.graphics.push() for i, test in ipairs(tests) do local color if test.thread:isRunning() then color = RUNNING else if test.error then color = FAILED elseif test.thread:getError() then color = FAILED test.error = test.thread:getError() print("ERROR in " .. test.name .. ":") print(test.error) else color = SUCCESS end end love.graphics.setColor(color) love.graphics.circle("fill", 10, 10, 6) love.graphics.translate(20, 0) end love.graphics.pop() local hovered = tests[math.ceil(love.mouse.getX() / 20)] if hovered then love.graphics.setColor(255, 255, 255) love.graphics.print(hovered.name, 10, 30) if hovered.error then love.graphics.printf(hovered.error, 10, 50, love.graphics.getWidth() - 20) end end end function love.keypressed(key) if key == "escape" then love.event.push "quit" end end
local ITEM = {}; ITEM.ID = 116; ITEM.Reference = "item_stim_pack"; ITEM.MaxStack = 100; ITEM.Weight = 5; ITEM.Cost = 300; ITEM.Name = "Stim Pack"; ITEM.Description = "Heals your wounds."; ITEM.InventoryModel = "models/healthvial.mdl"; ITEM.WorldModel = "models/healthvial.mdl"; ITEM.ModelCamPos = Vector(12, -4, 9); ITEM.ModelLookAt = Vector(0, 0, 4); ITEM.ModelFOV = 70; ITEM.RestrictedSelling = false; ITEM.EquipZone = nil; ITEM.PredictUseDrop = true; // If this isn't true, the server will tell the client when something happens to us based on the server's OnUse if SERVER then function ITEM.OnUse ( Player ) if Player:Health() == 100 then return false; end Player:SetHealth(math.Clamp(Player:Health() + 20, 0, 100)); if Player:GetTable().IsCrippled then Player:GetTable().IsCrippled = false; Player:RestoreNormalSpeed(); end return true; end function ITEM.OnDrop ( Player ) return true; end function ITEM.Equip ( Player ) end function ITEM.Holster ( Player ) end else function ITEM.OnUse ( slotID ) return true; end function ITEM.OnDrop ( ) return true; end end GM:RegisterItem(ITEM);
script_name("spawncar") script_author("dmitriyewich") script_url("https://vk.com/dmitriyewichmods") script_properties('work-in-pause', 'forced-reloading-only') script_version("0.1") local lffi, ffi = pcall(require, 'ffi') local lmemory, memory = pcall(require, 'memory') -- local imgui = require 'mimgui' local limgui, imgui = pcall(require, 'mimgui') assert(limgui, 'Library \'mimgui\' not found. Download: https://github.com/THE-FYP/mimgui .') local vkeys = require 'vkeys' local encoding = require 'encoding' encoding.default = 'CP1251' local u8 = encoding.UTF8 local wm = require 'windows.message' -- AUTHOR main hooks lib: RTD/RutreD(https://www.blast.hk/members/126461/) ffi.cdef[[ int VirtualProtect(void* lpAddress, unsigned long dwSize, unsigned long flNewProtect, unsigned long* lpflOldProtect); void* VirtualAlloc(void* lpAddress, unsigned long dwSize, unsigned long flAllocationType, unsigned long flProtect); int VirtualFree(void* lpAddress, unsigned long dwSize, unsigned long dwFreeType); void free(void *ptr); ]] local function copy(dst, src, len) return ffi.copy(ffi.cast('void*', dst), ffi.cast('const void*', src), len) end local buff = {free = {}} local function VirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect) return ffi.C.VirtualProtect(ffi.cast('void*', lpAddress), dwSize, flNewProtect, lpflOldProtect) end local function VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect, blFree) local alloc = ffi.C.VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect) if blFree then table.insert(buff.free, function() ffi.C.VirtualFree(alloc, 0, 0x8000) end) end return ffi.cast('intptr_t', alloc) end --VMT HOOKS local vmt_hook = {hooks = {}} function vmt_hook.new(vt) local new_hook = {} local org_func = {} local old_prot = ffi.new('unsigned long[1]') local virtual_table = ffi.cast('intptr_t**', vt)[0] new_hook.this = virtual_table new_hook.hookMethod = function(cast, func, method) jit.off(func, true) --off jit compilation | thx FYP org_func[method] = virtual_table[method] VirtualProtect(virtual_table + method, 4, 0x4, old_prot) virtual_table[method] = ffi.cast('intptr_t', ffi.cast(cast, func)) VirtualProtect(virtual_table + method, 4, old_prot[0], old_prot) return ffi.cast(cast, org_func[method]) end new_hook.unHookMethod = function(method) VirtualProtect(virtual_table + method, 4, 0x4, old_prot) -- virtual_table[method] = org_func[method] local alloc_addr = VirtualAlloc(nil, 5, 0x1000, 0x40, false) local trampoline_bytes = ffi.new('uint8_t[?]', 5, 0x90) trampoline_bytes[0] = 0xE9 ffi.cast('int32_t*', trampoline_bytes + 1)[0] = org_func[method] - tonumber(alloc_addr) - 5 copy(alloc_addr, trampoline_bytes, 5) virtual_table[method] = ffi.cast('intptr_t', alloc_addr) VirtualProtect(virtual_table + method, 4, old_prot[0], old_prot) org_func[method] = nil end new_hook.unHookAll = function() for method, func in pairs(org_func) do new_hook.unHookMethod(method) end end table.insert(vmt_hook.hooks, new_hook.unHookAll) return new_hook end --VMT HOOKS --JMP HOOKS local jmp_hook = {hooks = {}} function jmp_hook.new(cast, callback, hook_addr, size, trampoline, org_bytes_tramp) jit.off(callback, true) --off jit compilation | thx FYP local size = size or 5 local trampoline = trampoline or false local new_hook, mt = {}, {} local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast(cast, callback))) local old_prot = ffi.new('unsigned long[1]') local org_bytes = ffi.new('uint8_t[?]', size) copy(org_bytes, hook_addr, size) if trampoline then local alloc_addr = VirtualAlloc(nil, size + 5, 0x1000, 0x40, true) local trampoline_bytes = ffi.new('uint8_t[?]', size + 5, 0x90) if org_bytes_tramp then local i = 0 for byte in org_bytes_tramp:gmatch('(%x%x)') do trampoline_bytes[i] = tonumber(byte, 16) i = i + 1 end else copy(trampoline_bytes, org_bytes, size) end trampoline_bytes[size] = 0xE9 ffi.cast('int32_t*', trampoline_bytes + size + 1)[0] = hook_addr - tonumber(alloc_addr) - size + (size - 5) copy(alloc_addr, trampoline_bytes, size + 5) new_hook.call = ffi.cast(cast, alloc_addr) mt = {__call = function(self, ...) return self.call(...) end} else new_hook.call = ffi.cast(cast, hook_addr) mt = {__call = function(self, ...) self.stop() local res = self.call(...) self.start() return res end} end local hook_bytes = ffi.new('uint8_t[?]', size, 0x90) hook_bytes[0] = 0xE9 ffi.cast('int32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5 new_hook.status = false local function set_status(bool) new_hook.status = bool VirtualProtect(hook_addr, size, 0x40, old_prot) copy(hook_addr, bool and hook_bytes or org_bytes, size) VirtualProtect(hook_addr, size, old_prot[0], old_prot) end new_hook.stop = function() set_status(false) end new_hook.start = function() set_status(true) end new_hook.start() if org_bytes[0] == 0xE9 or org_bytes[0] == 0xE8 then print('[WARNING] rewrote another hook'.. (trampoline and ' (old hook was disabled, through trampoline)' or '')) end table.insert(jmp_hook.hooks, new_hook) return setmetatable(new_hook, mt) end --JMP HOOKS --CALL HOOKS local call_hook = {hooks = {}} function call_hook.new(cast, callback, hook_addr) if ffi.cast('uint8_t*', hook_addr)[0] ~= 0xE8 then return end jit.off(callback, true) --off jit compilation | thx FYP local new_hook = {} local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast(cast, callback))) local void_addr = ffi.cast('void*', hook_addr) local old_prot = ffi.new('unsigned long[1]') local org_bytes = ffi.new('uint8_t[?]', 5) ffi.copy(org_bytes, void_addr, 5) local hook_bytes = ffi.new('uint8_t[?]', 5, 0xE8) ffi.cast('uint32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5 new_hook.call = ffi.cast(cast, ffi.cast('intptr_t*', hook_addr + 1)[0] + hook_addr + 5) new_hook.status = false local function set_status(bool) new_hook.status = bool ffi.C.VirtualProtect(void_addr, 5, 0x40, old_prot) ffi.copy(void_addr, bool and hook_bytes or org_bytes, 5) ffi.C.VirtualProtect(void_addr, 5, old_prot[0], old_prot) end new_hook.stop = function() set_status(false) end new_hook.start = function() set_status(true) end new_hook.start() table.insert(call_hook.hooks, new_hook) return setmetatable(new_hook, { __call = function(self, ...) local res = self.call(...) return res end }) end --CALL HOOKS --DELETE HOOKS addEventHandler('onScriptTerminate', function(scr) if scr == script.this then for i, hook in ipairs(jmp_hook.hooks) do if hook.status then hook.stop() end end for i, hook in ipairs(call_hook.hooks) do if hook.status then hook.stop() end end for i, free in ipairs(buff.free) do free() end for i, unHookFunc in ipairs(vmt_hook.hooks) do unHookFunc() end end end) --DELETE HOOKS local cars = {['car'] = {}, ['moster'] = {}, ['heli'] = {}, ['boat'] = {}, ['trailer'] = {}, ['bike'] = {}, ['train'] = {}, ['plane'] = {}, ['quad'] = {}, ['bmx'] = {}} local new, str, sizeof = imgui.new, ffi.string, ffi.sizeof local spawncar_Window = new.bool() local input_id = new.char[256]() local sizeX, sizeY = getScreenResolution() imgui.OnInitialize(function() Standart() imgui.GetIO().IniFilename = nil end) local spawncar_onframe = imgui.OnFrame( function() return spawncar_Window[0] end, function(player) imgui.SetNextWindowPos(imgui.ImVec2(sizeX / 2, sizeY / 2), imgui.Cond.Appearing, imgui.ImVec2(0.5, 0.5)) imgui.SetNextWindowSize(imgui.ImVec2(500, 400), imgui.Cond.Appearing) imgui.Begin("spawncar", spawncar_Window, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoResize) imgui.InputText("", input_id, sizeof(input_id), imgui.InputTextFlags.AutoSelectAll) imgui.SameLine() if imgui.Button("Спавн модели: "..str(input_id), imgui.ImVec2(0, 0)) then if IsVehicleModelType(tonumber(str(input_id))) >= 0 then spawncar(tonumber(str(input_id))) end end if imgui.Button("выйти из т/с") then local mx, my, mz = getCharCoordinates(PLAYER_PED) warpCharFromCarToCoord(PLAYER_PED, mx, my, mz) end if imgui.BeginTabBar('##1') then for k, v in pairs(cars) do if imgui.BeginTabItem(''..k) then local transport = 1 for _, i in pairs(v) do if imgui.Button(""..i, imgui.ImVec2(45, 45)) then spawncar(i) end if transport % 10 ~= 0 and transport ~= #v then imgui.SameLine() end transport = transport + 1 end imgui.EndTabItem() end end imgui.EndTabBar() end imgui.End() end ) function IsVehicleModelType(index) return IsVehicleModelType(index) end function main() repeat wait(0) until memory.read(0xC8D4C0, 4, false) == 9 repeat wait(0) until fixed_camera_to_skin() IsVehicleModelType = jmp_hook.new("int(__cdecl*)(int)", IsVehicleModelType, 0x4C5C80) for i = 1, 20000 do if IsVehicleModelType(i) == 0 then cars.car[#cars.car+1] = i end if IsVehicleModelType(i) == 1 then cars.moster[#cars.moster+1] = i end if IsVehicleModelType(i) == 2 then cars.quad[#cars.quad+1] = i end if IsVehicleModelType(i) == 3 then cars.heli[#cars.heli+1] = i end if IsVehicleModelType(i) == 4 then cars.plane[#cars.plane+1] = i end if IsVehicleModelType(i) == 5 then cars.boat[#cars.boat+1] = i end if IsVehicleModelType(i) == 6 then cars.train[#cars.train+1] = i end if IsVehicleModelType(i) == 9 then cars.bike[#cars.bike+1] = i end if IsVehicleModelType(i) == 10 then cars.bmx[#cars.bmx+1] = i end if IsVehicleModelType(i) == 11 then cars.trailer[#cars.trailer+1] = i end end addEventHandler('onWindowMessage', function(msg, wparam, lparam) if msg == wm.WM_KEYDOWN or msg == wm.WM_SYSKEYDOWN then if wparam == vkeys.VK_F10 then spawncar_Window[0] = not spawncar_Window[0] end end end) wait(-1) end function spawncar(idmodel) lua_thread.create(function() requestModel(idmodel) -- запрос модели loadAllModelsNow() repeat wait(0) until isModelAvailable(idmodel) x,y,z = getCharCoordinates(1) carhandle = createCar(idmodel, x + 3, y, z) warpCharIntoCar(1, carhandle) end) end function fixed_camera_to_skin() -- проверка на приклепление камеры к скину return (memory.read(getModuleHandle('gta_sa.exe') + 0x76F053, 1, false) >= 1 and true or false) end function Standart() imgui.SwitchContext() local style = imgui.GetStyle() local colors = style.Colors local clr = imgui.Col local ImVec4 = imgui.ImVec4 local ImVec2 = imgui.ImVec2 style.WindowPadding = ImVec2(15, 15) style.WindowRounding = 4.7 style.WindowBorderSize = 1.0 style.WindowMinSize = ImVec2(1.5, 1.5) style.WindowTitleAlign = ImVec2(0.5, 0.5) style.ChildRounding = 4.7 style.ChildBorderSize = 1 style.PopupRounding = 4.7 style.PopupBorderSize = 1 style.FramePadding = ImVec2(5, 5) style.FrameRounding = 4.7 style.FrameBorderSize = 1.0 style.ItemSpacing = ImVec2(2, 7) style.ItemInnerSpacing = ImVec2(8, 6) style.ScrollbarSize = 8.0 style.ScrollbarRounding = 15.0 style.GrabMinSize = 15.0 style.GrabRounding = 4.7 style.IndentSpacing = 25.0 style.ButtonTextAlign = ImVec2(0.5, 0.5) style.SelectableTextAlign = ImVec2(0.5, 0.5) style.TouchExtraPadding = ImVec2(0.00, 0.00) style.TabBorderSize = 1 style.TabRounding = 4 colors[clr.Text] = ImVec4(1.00, 1.00, 1.00, 1.00) colors[clr.TextDisabled] = ImVec4(0.50, 0.50, 0.50, 1.00) colors[clr.WindowBg] = ImVec4(0.15, 0.15, 0.15, 1.00) colors[clr.ChildBg] = ImVec4(0.00, 0.00, 0.00, 0.00) colors[clr.PopupBg] = ImVec4(0.19, 0.19, 0.19, 0.92) colors[clr.Border] = ImVec4(0.19, 0.19, 0.19, 0.29) colors[clr.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.24) colors[clr.FrameBg] = ImVec4(0.05, 0.05, 0.05, 0.54) colors[clr.FrameBgHovered] = ImVec4(0.19, 0.19, 0.19, 0.54) colors[clr.FrameBgActive] = ImVec4(0.20, 0.22, 0.23, 1.00) colors[clr.TitleBg] = ImVec4(0.00, 0.00, 0.00, 1.00) colors[clr.TitleBgActive] = ImVec4(0.06, 0.06, 0.06, 1.00) colors[clr.TitleBgCollapsed] = ImVec4(0.00, 0.00, 0.00, 1.00) colors[clr.MenuBarBg] = ImVec4(0.14, 0.14, 0.14, 1.00) colors[clr.ScrollbarBg] = ImVec4(0.05, 0.05, 0.05, 0.54) colors[clr.ScrollbarGrab] = ImVec4(0.34, 0.34, 0.34, 0.54) colors[clr.ScrollbarGrabHovered] = ImVec4(0.40, 0.40, 0.40, 0.54) colors[clr.ScrollbarGrabActive] = ImVec4(0.56, 0.56, 0.56, 0.54) colors[clr.CheckMark] = ImVec4(0.33, 0.67, 0.86, 1.00) colors[clr.SliderGrab] = ImVec4(0.34, 0.34, 0.34, 0.54) colors[clr.SliderGrabActive] = ImVec4(0.56, 0.56, 0.56, 0.54) colors[clr.Button] = ImVec4(0.05, 0.05, 0.05, 0.54) colors[clr.ButtonHovered] = ImVec4(0.19, 0.19, 0.19, 0.54) colors[clr.ButtonActive] = ImVec4(0.20, 0.22, 0.23, 1.00) colors[clr.Header] = ImVec4(0.00, 0.00, 0.00, 0.52) colors[clr.HeaderHovered] = ImVec4(0.00, 0.00, 0.00, 0.36) colors[clr.HeaderActive] = ImVec4(0.20, 0.22, 0.23, 0.33) colors[clr.Separator] = ImVec4(0.28, 0.28, 0.28, 0.29) colors[clr.SeparatorHovered] = ImVec4(0.44, 0.44, 0.44, 0.29) colors[clr.SeparatorActive] = ImVec4(0.40, 0.44, 0.47, 1.00) colors[clr.ResizeGrip] = ImVec4(0.28, 0.28, 0.28, 0.29) colors[clr.ResizeGripHovered] = ImVec4(0.44, 0.44, 0.44, 0.29) colors[clr.ResizeGripActive] = ImVec4(0.40, 0.44, 0.47, 1.00) colors[clr.Tab] = ImVec4(0.00, 0.00, 0.00, 0.52) colors[clr.TabHovered] = ImVec4(0.14, 0.14, 0.14, 1.00) colors[clr.TabActive] = ImVec4(0.20, 0.20, 0.20, 0.36) colors[clr.TabUnfocused] = ImVec4(0.00, 0.00, 0.00, 0.52) colors[clr.TabUnfocusedActive] = ImVec4(0.14, 0.14, 0.14, 1.00) colors[clr.PlotLines] = ImVec4(1.00, 0.00, 0.00, 1.00) colors[clr.PlotLinesHovered] = ImVec4(1.00, 0.00, 0.00, 1.00) colors[clr.PlotHistogram] = ImVec4(1.00, 0.00, 0.00, 1.00) colors[clr.PlotHistogramHovered] = ImVec4(1.00, 0.00, 0.00, 1.00) colors[clr.TextSelectedBg] = ImVec4(0.20, 0.22, 0.23, 1.00) colors[clr.DragDropTarget] = ImVec4(0.33, 0.67, 0.86, 1.00) colors[clr.NavHighlight] = ImVec4(1.00, 0.00, 0.00, 1.00) colors[clr.NavWindowingHighlight] = ImVec4(1.00, 0.00, 0.00, 0.70) colors[clr.NavWindowingDimBg] = ImVec4(1.00, 0.00, 0.00, 0.20) colors[clr.ModalWindowDimBg] = ImVec4(1.00, 0.00, 0.00, 0.35) end