content
stringlengths
5
1.05M
object_ship_jedi_starfighter_tier3 = object_ship_shared_jedi_starfighter_tier3:new { } ObjectTemplates:addTemplate(object_ship_jedi_starfighter_tier3, "object/ship/jedi_starfighter_tier3.iff")
client_scripts { 'config.lua', 'client.lua' } server_scripts { 'config.lua', 'server.lua' } export 'showAlert' ui_page 'html/index.html' files { 'html/index.html', 'html/main.js', 'html/main.css', 'html/images/job.png', 'html/images/society.svg', 'html/images/black_money.svg', 'html/images/bank.svg', 'html/images/money.svg', }
function love.load() button = {} button.x = 200 button.y = 200 button.size = 50 score = 0 timer = 10 gameState = 1 myFont = love.graphics.newFont(40) end function love.update(dt) if gameState == 2 then if timer > 0 then timer = timer - dt end if timer < 0 then timer = 0 gameState = 1 score = 0 end end end function love.draw() if gameState == 2 then love.graphics.setColor(255, 0, 0) love.graphics.circle("fill", button.x, button.y, button.size) end love.graphics.setFont(myFont) love.graphics.setColor(255, 255, 255) love.graphics.print("Score: " .. score) love.graphics.print("Time: " .. math.ceil(timer), 300, 0) if gameState == 1 then love.graphics.printf("Click anywhere to begin!", 0, love.graphics.getHeight()/2, love.graphics.getWidth(), "center") end end function love.mousepressed( x, y, b, istouch ) if b == 1 and gameState == 2 then if distanceBetween(button.x, button.y, love.mouse.getX(), love.mouse.getY()) < button.size then score = score + 1 button.x = math.random(button.size, love.graphics.getWidth() - button.size) button.y = math.random(button.size, love.graphics.getHeight() - button.size) end end if gameState == 1 then gameState = 2 timer = 10 end end function distanceBetween(x1, y1, x2, y2) return math.sqrt((y2 - y1)^2 + (x2 - x1)^2) end
gametable = { screenwidth = 640, screenheight = 480, state = 0, fieldmaxwidth = 384, fieldmaxheight = 448, fieldwidth = 32, fieldheight = 16 }
local class = require 'EasyLD.lib.middleclass' local Surface = class('Surface') Surface.table = {} function Surface.drawOnScreen() love.graphics.setCanvas(love.screen) end function Surface:initialize(w, h) self.w = w or EasyLD.window.w self.h = h or EasyLD.window.h self.s = love.graphics.newCanvas(self.w, self.h) EasyLD.surface.table[self.s] = self end function Surface:drawOn(clear) if clear then self:clear() end local s = love.graphics.getCanvas() love.graphics.setCanvas(self.s) if s == nil then return {drawOn = Surface.drawOnScreen} end return EasyLD.surface.table[s] end function Surface:draw(x, y, xs, ys, w, h, r) self.quad = love.graphics.newQuad(xs or 0, ys or 0, w or self.w, h or self.h, self.s:getWidth(), self.s:getHeight()) love.graphics.draw(self.s, self.quad, x, y) end function Surface:setFilter(type) self.s:setFilter(type) end function Surface:getPixel(x, y) return EasyLD.color:new() end function Surface:clear() self.s:clear(0,0,0,0) end return Surface
local m = {} local keys=require("api_keys") local hammerDir = hs.fs.currentDir() local iconsDir = (hammerDir .. '/hs-weather/icons/') local configFile = (hammerDir .. '/hs-weather/config.json') local urlBase = 'https://query.yahooapis.com/v1/public/yql?q=' local query = 'select item.title, item.condition from weather.forecast where \ woeid in (select woeid from geo.places(1) where text="' function curl_callback(exitCode, stdOut, stdErr) if exitCode == 0 then m.task = nil else print(stdOut, stdErr) end end date = os.date("*t", time) function m:wtInfo() local file = io.open( "hs-weather/query.txt", "r" ) wt_info = file:read() file:close() local decode_data_wt = hs.json.decode(wt_info) local temp = decode_data_wt.current_observation.condition.temperature local code = tonumber(decode_data_wt.current_observation.condition.code) local i=date.wday+1 local condition = decode_data_wt.current_observation.condition.text .. ' - Wind chill: ' .. decode_data_wt.current_observation.wind.chill .. "°C at " .. decode_data_wt.current_observation.wind.speed .. "km/h\nForecast: " .. decode_data_wt.forecasts[i].text .. " ; temp: " .. decode_data_wt.forecasts[i].low .. " to " .. decode_data_wt.forecasts[i].high.. "°C" local title = decode_data_wt.location.city .. ", " .. decode_data_wt.location.region .."\nSun is up from: " .. decode_data_wt.current_observation.astronomy.sunrise .. " to " .. decode_data_wt.current_observation.astronomy.sunset return temp, code, condition, title end function m:airInfo() local file = io.open( "hs-weather/air.txt", "r" ) air_info = file:read() file:close() local decode_data_air = hs.json.decode(air_info) local aqi=decode_data_air.data.aqi local station=decode_data_air.data.city.name local data="station: "..decode_data_air.data.city.name..'\nPression PM25: '..decode_data_air.data.iaqi.pm25.v..'\nUpdated:'..decode_data_air.data.time.s return aqi, data end --air_info=m.airInfo() --local decode_data_air = hs.json.decode(air_info) --local aqi=decode_data_air.data.aqi -- https://developer.yahoo.com/weather/archive.html#codes -- icons by RNS, Freepik, Vectors Market, Yannick at http://www.flaticon.com local weatherSymbols = { [0] = (iconsDir .. 'tornado.png'), -- tornado [1] = (iconsDir .. 'storm.png'), -- tropical storm [2] = (iconsDir .. 'tornado.png'), -- hurricane [3] = (iconsDir .. 'storm-5.png'), -- severe thunderstorms [4] = (iconsDir .. 'storm-4.png'), -- thunderstorms [5] = (iconsDir .. 'sleet.png'), -- mixed rain and snow [6] = (iconsDir .. 'sleet.png'), -- mixed rain and sleet [7] = (iconsDir .. 'sleet.png'), -- mixed snow and sleet [8] = (iconsDir .. 'drizzle.png'), -- freezing drizzle [9] = (iconsDir .. 'drizzle.png'), -- drizzle [10] = (iconsDir .. 'drizzle.png'), -- freezing rain [11] = (iconsDir .. 'rain-1.png'), -- showers [12] = (iconsDir .. 'rain-1.png'), -- showers [13] = (iconsDir .. 'snowflake.png'), -- snow flurries [14] = (iconsDir .. 'snowflake.png'), -- light snow showers [15] = (iconsDir .. 'snowflake.png'), -- blowing snow [16] = (iconsDir .. 'snowflake.png'), -- snow [17] = (iconsDir .. 'hail.png'), -- hail [18] = (iconsDir .. 'sleet.png'), -- sleet [19] = (iconsDir .. 'haze.png'), -- dust [20] = (iconsDir .. 'mist.png'), -- foggy [21] = (iconsDir .. 'haze.png'), -- haze [22] = (iconsDir .. 'mist.png'), -- smoky [23] = (iconsDir .. 'wind-1.png'), -- blustery [24] = (iconsDir .. 'windy-1.png'), -- windy [25] = (iconsDir .. 'cold.png'), -- cold [26] = (iconsDir .. 'clouds.png'), -- cloudy [27] = (iconsDir .. 'night.png'), -- mostly cloudy (night) [28] = (iconsDir .. 'cloudy.png'), -- mostly cloudy (day) [29] = (iconsDir .. 'cloudy-4.png'), -- partly cloudy (night) [30] = (iconsDir .. 'cloudy-5.png'), -- partly cloudy (day) [31] = (iconsDir .. 'moon-2.png'), -- clear (night) [32] = (iconsDir .. 'sun-1.png'), -- sunny [33] = (iconsDir .. 'night-2.png'), -- fair (night) [34] = (iconsDir .. 'cloudy-1.png'), -- fair (day) [35] = (iconsDir .. 'hail.png'), -- mixed rain and hail [36] = (iconsDir .. 'temperature.png'), -- hot [37] = (iconsDir .. 'storm-4.png'), -- isolated thunderstorms [38] = (iconsDir .. 'storm-2.png'), -- scattered thunderstorms [39] = (iconsDir .. 'rain-3.png'), -- scattered thunderstorms [40] = (iconsDir .. 'rain-6.png'), -- scattered showers [41] = (iconsDir .. 'snowflake.png'), -- heavy snow [42] = (iconsDir .. 'snowflake.png'), -- scattered snow showers [43] = (iconsDir .. 'snowflake.png'), -- heavy snow [44] = (iconsDir .. 'cloudy.png'), -- party cloudy [45] = (iconsDir .. 'storm.png'), -- thundershowers [46] = (iconsDir .. 'snowflake.png'), -- snow showers [47] = (iconsDir .. 'lightning.png'), -- isolated thundershowers [3200] = (iconsDir .. 'na.png'), [3201] = (iconsDir .. 'out.png') -- not available -- not available } function readConfig(file) local f = io.open(file, "rb") if not f then return {} end local content = f:read("*all") f:close() return hs.json.decode(content) end function setWeatherIcon(app, code) local iconPath = weatherSymbols[code] local size = {w=16,h=16} if iconPath ~= nil then app:setIcon(hs.image.imageFromPath(iconPath):setSize(size)) else app:setIcon(hs.image.imageFromPath(weatherSymbols[3200]):setSize(size)) end end function toCelsius(f) return (f - 32) * 5 / 9 end function setWeatherTitle(app, unitSys, temp, aqi) ok,appleScriptResult = hs.osascript.applescript([[ tell application "System Events" tell appearance preferences if (dark mode) then return true else return false end if end tell end tell ]]) if unitSys == 'C' then --local tempCelsius = toCelsius(temp) local tempCelsius = temp local tempRounded = math.floor(tempCelsius * 10 + 0.5) / 10 --app:setTitle(tempRounded .. '°C ') if tempRounded < 5 then color_temp = { red = 0, blue = 204/255, green = 0 } elseif tempRounded < 15 and tempRounded >= 5 then color_temp = { red = 0, blue = 153/255, green = 153/255 } elseif tempRounded >= 25 and tempRounded < 30 then color_temp = { red = 1, blue = 0, green = 128/255 } elseif tempRounded >= 35 then color_temp = { red = 1, blue = 51/255, green = 51/255 } elseif appleScriptResult ==true then color_temp = { red = 255, blue = 255, green = 255 } else color_temp = { red = 0, blue = 0, green = 0 } end if aqi < 50 then color_aqi = { red = 102/255, blue = 0, green = 204/255 } elseif aqi >= 50 and aqi < 100 then color_aqi = { red = 204/255, blue = 0, green = 204/255 } elseif aqi >= 100 and aqi < 150 then color_aqi = { red = 1, blue = 0, green = 128/255 } elseif aqi >= 105 and aqi <300 then color_aqi = { red = 153/255, blue = 153/255, green = 0} else color_aqi = { red = 1, blue = 0, green = 0 } end local cust_font={name = '.AppleSystemUIFont', size = 9 } text=tempRounded .. '°C\n' app:setTitle(hs.styledtext.new(text, { color = color_temp,font=cust_font})..hs.styledtext.new(aqi..' IQA', { color = color_aqi ,font=cust_font})) else app:setTitle(temp .. ' °F ') end end function urlencode(str) if (str) then str = string.gsub (str, "\n", "\r\n") str = string.gsub (str, "([^%w ])", function (c) return string.format ("%%%02X", string.byte(c)) end) str = string.gsub (str, " ", "+") end return str end --function getWeather(location) --- local weatherEndpoint = ( --- urlBase .. urlencode(query .. location .. '")') .. '&format=json') ---return hs.http.get(weatherEndpoint) --end function setWeatherForLocation(location, unitSys) lat=location:gsub('%(','') lat=lat:gsub(',.*','') long=location:gsub('.*,','') long=long:gsub('%)','') print(lat) print(long) str="hs-weather/query.js --lat " .. lat .. " --lon " .. long .. " -k " .. keys.weather_app .. " " .. keys.weather_user .. " " .. keys.weather_secret hs.execute(str,true) local url= 'http://api.waqi.info/feed/'..'geo:'..lat..';'..long..'/?token='.. keys.air print(url) local task = hs.task.new("/usr/bin/curl", curl_callback, {url, "-o", './hs-weather/air.txt'}) task:start() temp,code,condition,title=m.wtInfo() print(temp,code,condition,title) --local weatherEndpoint = ( -- urlBase .. urlencode(query .. location .. '")') .. '&format=json') -- hs.http.asyncGet(url, nil, -- function(code, body, table) -- if code ~= 200 then -- aqi,data_air=m.airInfo() -- setWeatherIcon(m.weatherApp, 3201) -- print('-- hs-weather: Could not get weather. Response code: ' .. code) -- else -- print('-- hs-weather: Weather for ' .. location .. ': ' .. body) -- local response = hs.json.decode(body) -- print(response) -- -- if response.query.results == nil then -- if m.weatherApp:title() == '' then -- setWeatherIcon(m.weatherApp, 3200) -- end -- else aqi,data_air=m.airInfo() temp,code,condition,title=m.wtInfo() setWeatherIcon(m.weatherApp, code) setWeatherTitle(m.weatherApp, unitSys, temp ,aqi) m.weatherApp:setTooltip((title .. '\n' .. condition.. '\nAir ' .. data_air)) -- end -- end -- end -- ) end loc = hs.location.get() print("ooooooook3") print(loc) -- Get weather for current location -- Hammerspoon needs access to OS location services function setWeatherForCurrentLocation(loc,unitSys) if hs.location.servicesEnabled() then --hs.location.start() hs.timer.doAfter(3, function () local loc = hs.location.get() --hs.location.stop() local lat_lon='(' .. loc.latitude .. ',' .. loc.longitude .. ')' setWeatherForLocation( lat_lon, unitSys) end) else print('\n-- Location services disabled!\n') end end function setWeather() if m.config.geolocation then setWeatherForCurrentLocation(loc,m.config.units) else setWeatherForLocation(m.config.location, m.config.units) end end m.start = function(cfg) m.config = cfg or readConfig(configFile) -- defaults if not set m.config.refresh = m.config.refresh or 300 m.config.units = m.config.units or 'C' m.config.location = m.config.location or 'Nice, FR' m.weatherApp = hs.menubar.new() setWeather() -- refresh on click m.weatherApp:setClickCallback(function () setWeather() end) m.timer = hs.timer.doEvery( m.config.refresh, function () setWeather() end) end m.stop = function() m.timer:stop() end return m --getAir(keys.air)
local KUI, E, L, V, P, G = unpack(select(2, ...)) local M = E:GetModule('Minimap') --local GetPlayerMapPosition = GetPlayerMapPosition local init = false local cluster, panel, location, xMap, yMap local inRestrictedArea = false local mapID = C_Map.GetBestMapForUnit("player") local SPACING = (E.PixelMode and 1 or 3) local digits ={ [0] = { .5, '%.0f' }, [1] = { .2, '%.1f' }, [2] = { .1, '%.2f' }, } local function setRestricted(zone) if zone then inRestrictedArea = true end xMap.text:SetText("-") yMap.text:SetText("-") return end local function getPos(zone) local mapID = C_Map.GetBestMapForUnit("player") if not mapID then setRestricted(zone) return end local pos = C_Map.GetPlayerMapPosition(mapID, "player") if not pos then setRestricted(zone) return end inRestrictedArea = false return pos end local function UpdateLocation(self, elapsed) if inRestrictedArea then return; end location.elapsed = (location.elapsed or 0) + elapsed if location.elapsed < digits[E.db.KlixUI.maps.minimap.topbar.locationdigits][1] then return end local pos = getPos() if not pos then return end xMap.pos, yMap.pos = pos:GetXY() xMap.text:SetFormattedText(digits[E.db.KlixUI.maps.minimap.topbar.locationdigits][2], xMap.pos * 100) yMap.text:SetFormattedText(digits[E.db.KlixUI.maps.minimap.topbar.locationdigits][2], yMap.pos * 100) location.elapsed = 0 end local function CreateKuiMaplocation() cluster = _G['MinimapCluster'] panel = CreateFrame('Frame', 'KuiLocationPanel', _G['MinimapCluster']) panel:SetFrameStrata("BACKGROUND") panel:Point("CENTER", E.UIParent, "CENTER", 0, 0) panel:Size(206, 22) xMap = CreateFrame('Frame', "MapCoordinatesX", panel) xMap:SetTemplate('Transparent') xMap:Point('LEFT', panel, 'LEFT', 2, 0) xMap:Size(38, 22) xMap:Styling() xMap.text = xMap:CreateFontString(nil, "OVERLAY") xMap.text:FontTemplate(E.media.font, 12, "OUTLINE") xMap.text:SetAllPoints(xMap) location = CreateFrame('Frame', "KuiLocationText", panel) location:SetTemplate('Transparent') location:Point('CENTER', panel, 'CENTER', 0, 0) location:Size(126, 22) location:Styling() location.text = location:CreateFontString(nil, "OVERLAY") location.text:FontTemplate(E.media.font, 12, "OUTLINE") location.text:SetAllPoints(location) yMap = CreateFrame('Frame', "MapCoordinatesY", panel) yMap:SetTemplate('Transparent') yMap:Point('RIGHT', panel, 'RIGHT', -2.5, 0) yMap:Size(38, 22) yMap:Styling() yMap.text = yMap:CreateFontString(nil, "OVERLAY") yMap.text:FontTemplate(E.media.font, 12, "OUTLINE") yMap.text:SetAllPoints(yMap) end hooksecurefunc(M, 'Update_ZoneText', function() if E.db.KlixUI.maps.minimap.topbar.locationtext == "LOCATION" then location.text:SetTextColor(M:GetLocTextColor()) location.text:SetText(strsub(GetMinimapZoneText(),1,25)) elseif E.db.KlixUI.maps.minimap.topbar.locationtext == "VERSION" then location.text:SetText(KUI.Title.. "v"..KUI.Version) end getPos(1) end) hooksecurefunc(M, 'UpdateSettings', function() if not E.private.general.minimap.enable then return end if not init then init = true CreateKuiMaplocation() end local holder = _G['MMHolder'] panel:SetPoint('BOTTOMLEFT', holder, 'TOPLEFT', -3, SPACING) panel:Size(holder:GetWidth() + (E.PixelMode and 5 or 7), 22) panel:Show() location:Width(holder:GetWidth() - 77) local point, relativeTo, relativePoint, xOfs, yOfs = holder:GetPoint() if E.db.general.minimap.locationText == "ABOVE" then holder:SetPoint(point, relativeTo, relativePoint, 0, -19) holder:Height(holder:GetHeight() + 22) panel:SetScript('OnUpdate', UpdateLocation) panel:Show() else holder:SetPoint(point, relativeTo, relativePoint, 0, 0) panel:SetScript('OnUpdate', nil) panel:Hide() end end)
dofile("test_setup.lua") local file1 = [=[ return { value = 5 } ]=] local file2 = [=[ return { value = 10 } ]=] local func = DoFileString(file1) func = nil collectgarbage() local cache = LuaReload.GetFileCache() local file = cache[ GetTestFilename() ] for k, v in pairs(file.returnValues) do error("return values are still present!") end
require(settings.get("ghu.base").."core/apis/ghu")local a=require("am.ui")local b=require("am.event")local c=require("am.log")local d=require("am.helpers")local e=require("am.progress.base")local f=e:extend("am.progress.CollectWrapper")function f:init(g,h,i,j)f.super.init(self,g,{[g.id]=h},i,j)self.src_map={[g.id]=g}self.position=nil;self.paused=false;self.names={[b.c.Event.Progress.collect]=true,[b.c.Event.Progress.tree]=true}return self end;function f:getEvent()local k=0;local l=nil;for m,n in pairs(self.progress)do k=k+1;l=n end;return l,k end;function f:isTree(l,k)if k==nil then l,k=self:getEvent()end;return k==1 and l~=nil and l.name==b.c.Event.Progress.tree end;function f:getTitle()local l,k=self:getEvent()if self:isTree(l,k)then local o=""if#l.trees>0 then o=string.format(" (%d)",#l.trees)end;return string.format("Tree%s",o)end;return"Collect"end;function f:getStatus()for m,l in pairs(self.progress)do return l.status end;return""end;function f:getItems()local p={}for m,l in pairs(self.progress)do for m,q in ipairs(l.rates)do if p[q.item.name]==nil then p[q.item.name]=q else local r=p[q.item.name]r.rate=r.rate+q.rate;p[q.item.name]=r end end end;local s={}for m,t in pairs(p)do s[#s+1]=t end;d.sortItemsByCount(s,false)local u={}for m,t in ipairs(s)do local q=d.metricString(t.rate)u[#u+1]=string.format("%5s %s/min",q,t.item.displayName)end;return u end;function f:createUI()local v=self:getBaseId()local w=self;local x=2;local y=a.Text(a.a.Top(),"",{id=v..".nameText"})local m,z=self.output.getSize()if z<=12 then x=1;y.visible=false end;if _G.PROGRESS_SHOW_CLOSE then local A=a.Button(a.a.TopRight(),"x",{id=v..".closeButton",fillColor=colors.red,border=0})A:addActivateHandler(function()_G.RUN_PROGRESS=false end)self.frame:add(A)end;self.frame:add(y)self.frame:add(a.Text(a.a.Center(x),"",{id=v..".titleText"}))self.frame:add(a.Text(a.a.Center(x+2),"",{id=v..".rateText"}))self.frame:add(a.Text(a.a.Center(x+4),"",{id=v..".statusText"}))local B=a.Button(a.a.Center(x+5,a.c.Offset.Left,1),"\x8f",{id=v..".haltButton",fillColor=colors.red})B:addActivateHandler(function()c.info(string.format("Halting %s...",self.src.label))b.TurtleRequestHaltEvent(self.src.id):send()end)self.frame:add(B)local C=a.Button(a.a.Center(x+5,a.c.Offset.Right,1),"\x95\x95",{id=v..".pauseButton",fillColor=colors.yellow})C:addActivateHandler(function()if w.paused then c.info(string.format("Continuing %s...",self.src.label))b.TurtleRequestContinueEvent(self.src.id):send()else c.info(string.format("Pausing %s...",self.src.label))b.TurtleRequestPauseEvent(self.src.id):send()end end)self.frame:add(C)self.frame:add(a.Text(a.a.Bottom(),"",{id=v..".posText"}))local l=self:getEvent()self:update(self.src,l)self:render()end;function f:update(g,l,D)if l~=nil then self.progress[g.id]=l end;if not self.frame.visible and not D then return end;local m,z=self.output.getSize()local v=self:getBaseId()self.src_map[g.id]=g;local y=self.frame:get(v..".nameText",self.output)local E=self.frame:get(v..".titleText",self.output)if self.src.label~=nil then local F=self.src.label;if b.online then F="info:"..F end;y:update(F)end;local x=1;if z<=12 then y.obj.visible=false else x=2;y.obj.visible=self.frame.visible end;E.obj.anchor.y=x;E:update(self:getTitle())local G=false;local H=self.frame:get(v..".rateText",self.output)local I=self.frame:get(v..".statusText",self.output)H.obj.anchor.y=x+2;local p=self:getItems()H:update(p)local J=#p;if J==0 then J=1 end;local K=x+J;if I.obj.anchor.y~=K+3 then G=true end;I.obj.anchor.y=K+3;I:update(self:getStatus())local B=self.frame:get(v..".haltButton",self.output)local C=self.frame:get(v..".pauseButton",self.output)B.obj.anchor.y=K+4;C.obj.anchor.y=K+4;local n,k=self:getEvent()if self:isTree(n,k)then self:updatePosition(g,n.pos)else self:updatePosition(g,nil)end;if G then self:render()end end;function e:updatePosition(g,L)self.position=L;local v=self:getBaseId()local M=self.frame:get(v..".posText",self.output)if L==nil then M.visible=false;M:update("")return end;local N,m=self.output.getSize()local O="pos (%d, %d) e: %d, d: %d"if N<30 then O="(%d,%d) e:%d, d:%d"end;M:update(string.format(O,L.v.x,L.v.z,L.v.y,L.dir))end;function f:updateStatus(g,P)local v=self:getBaseId()local I=self.frame:get(v..".statusText",self.output)I:update(P)end;function f:handle(g,l,Q)local v=self:getBaseId()local w=self;if l==b.c.Event.Progress.quarry then self:update(g,Q[1])else local B=self.frame:get(v..".haltButton",self.output)local C=self.frame:get(v..".pauseButton",self.output)if l==b.c.Event.Turtle.paused then self.paused=true;self.completed=false;C.obj.fillColor=colors.green;C:updateLabel("\x10")self:render()elseif l==b.c.Event.Turtle.started then self.paused=false;self.completed=false;B.obj.visible=w.frame.visible;B:updateLabel("\x8f")C.obj.visible=w.frame.visible;C.obj.fillColor=colors.yellow;C:updateLabel("\x95\x95")self:render()elseif l==b.c.Event.Turtle.exited then self.completed=true;self.paused=false;B.obj.visible=false;C.obj.visible=false;self:render()else self.frame:handle(self.output,{l,table.unpack(Q)})end end end;return f
--require("nn") local dbg = require("debugger") local THNN = require 'nn.THNN' local LookupTableWithNulls, parent = torch.class('LookupTableWithNulls', 'nn.Module') LookupTableWithNulls.__version = 1 function LookupTableWithNulls:__init(nIndex, nOutput) parent.__init(self) print('making a lookup table with nulls!') self.weight = torch.Tensor(nIndex + 1, nOutput) self.gradWeight = torch.Tensor(nIndex + 1, nOutput):zero() self:reset() self:resetNullWeight() end function LookupTableWithNulls:resetNullWeight() self.weight:select(1,1):zero() end function LookupTableWithNulls:backCompatibility() self._count = self._count or torch.IntTensor() self._input = self._input or torch.LongTensor() self._gradOutput = self._gradOutput or torch.CudaTensor() if self.shouldScaleGradByFreq == nil then self.shouldScaleGradByFreq = false end end function LookupTableWithNulls:accUpdateOnly() self.gradWeight = nil return self end function LookupTableWithNulls:scaleGradByFreq() self.shouldScaleGradByFreq = true return self end function LookupTableWithNulls:reset(stdv) stdv = stdv or 1 self.weight:normal(0, stdv) end function LookupTableWithNulls:makeInputContiguous(input) -- make sure input is a contiguous torch.LongTensor if (not input:isContiguous()) or torch.type(input) ~= torch.type(self._input) then self.copiedInput = true self._input:resize(input:size()):copy(input) return self._input end self.copiedInput = false return input end function LookupTableWithNulls:makeGradOutputContiguous(input) -- make sure input is a contiguous torch.LongTensor if (not input:isContiguous()) or torch.type(input) ~= torch.type(self._gradOutput) then self.copiedGradOutput = true self._gradOutput:resize(input:size()):copy(input) return self._gradOutput end self.copiedGradOutput = false return input end function LookupTableWithNulls:updateOutput(input) self:backCompatibility() input = self:makeInputContiguous(input) input:add(1) if input:dim() == 1 then self.output:index(self.weight, 1, input) elseif input:dim() == 2 then self.output:index(self.weight, 1, input:view(-1)) self.output = self.output:view(input:size(1), input:size(2), self.weight:size(2)) elseif input:dim() == 3 then self.output:index(self.weight, 1, input:view(-1)) self.output = self.output:view(input:size(1), input:size(2), input:size(3), self.weight:size(2)) else error("input must be a vector or matrix") end input:add(-1) return self.output end function LookupTableWithNulls:accGradParameters(input, gradOutput, scale) print("you are in lookuptableiwithnulls.lua at accGradParameters") dbg() self:backCompatibility() input = self.copiedInput and self._input or input if input:dim() == 2 then input = input:view(-1) elseif input:dim() == 3 then input = input:view(-1) elseif input:dim() ~= 1 then error("input must be a vector or matrix") end input:add(1) gradOutput = self:makeGradOutputContiguous(gradOutput) self.gradWeight.THNN.LookupTable_accGradParameters( input:cdata(), gradOutput:cdata(), self.gradWeight:cdata(), self._count:cdata(), THNN.optionalTensor(self._sorted), THNN.optionalTensor(self._indices), self.shouldScaleGradByFreq or false, self.paddingValue or 0, scale or 1 ) --self.gradWeight.nn.LookupTable_accGradParameters(self, input, gradOutput, scale) input:add(-1) end function LookupTableWithNulls:type(type, tensorCache) parent.type(self, type, tensorCache) if type == 'torch.CudaTensor' then -- CUDA uses _sorted and _indices temporary tensors self._sorted = self.weight.new() self._indices = self.weight.new() self._count = self.weight.new() self._input = self.weight.new() else -- self._count and self._input should only be converted if using Cuda self._count = torch.IntTensor() self._input = torch.LongTensor() end return self end -- we do not need to accumulate parameters when sharing LookupTableWithNulls.sharedAccUpdateGradParameters = LookupTableWithNulls.accUpdateGradParameters
local PLUGIN = PLUGIN; local Clockwork = Clockwork; local COMMAND = Clockwork.command:New("ItemSpawnerCount"); COMMAND.tip = "Counts the amount of spawned items on the map."; COMMAND.flags = CMD_DEFAULT; COMMAND.access = "s"; COMMAND.arguments = 0; -- Called when the command has been run. function COMMAND:OnRun(player, arguments) Clockwork.player:Notify(player, "There are a total of "..PLUGIN:GetSpawnedItemsCount().." spawned items on the map."); end; COMMAND:Register();
--[[ Forward and backward combined. ]]-- require 'nn' require 'nnx' require 'cunn' require 'cudnn' require 'cutorch' paths.dofile('para_model.lua') local ParallelNet_Mod,ParallelNet = torch.class("nn.ParallelNet_Mod",'nn.ParallelNet') function ParallelNet_Mod:__init(config, layer) print("Parallel Model (Combination) Initialization.") ParallelNet.__init(self, config, layer) end function ParallelNet_Mod:change_Activation(new_activation) self.new_act.modules[#self.new_act] = new_activation():cuda() local para = self.new_act.modules[1] table.remove(para.modules[1].modules,#para.modules[1]) table.insert(para.modules[2].modules,#para.modules[2]+1,new_activation():cuda()) print(para) for i=1,2 do para.modules[i].modules[#para.modules[i]] = new_activation():cuda() end print("Now : ", self.new_act) end function ParallelNet_Mod:make_NewActivation(activation) print("ParallelNet_Comb Activation Building...") activation = activation or cudnn.Tanh print("Using activation : ") print(activation()) self.new_act = nn.Sequential() local input_layer = nn.ParallelTable() local net_input = nn.Sequential() local net_rele = nn.Sequential() net_input:add(nn.SpatialSymmetricPadding(1,1,1,1)) net_input:add(cudnn.SpatialConvolution(self.from_nfeat,self.from_nfeat/2,3,3,1,1)) net_input:add(activation()) net_rele :add(nn.SpatialSymmetricPadding(1,1,1,1)) net_rele :add(cudnn.SpatialConvolution(self.from_nfeat,self.from_nfeat/2,3,3,1,1)) net_rele :add(activation()) input_layer:add(net_input):add(net_rele) self.new_act:add(input_layer):add(nn.JoinTable(2)) -- join at (batch,x,256,256) self.new_act:add(nn.SpatialSymmetricPadding(1,1,1,1)) self.new_act:add(cudnn.SpatialConvolution(self.from_nfeat,self.from_nfeat,3,3,1,1)) self.new_act:add(activation()) self.new_act = self.new_act:cuda() end return nn.ParallelNet_Mod
require "zip" local zfile, err = zip.open('build-vs13.zip') -- print the filenames of the files inside the zip for file in zfile:files() do print(file.filename) end zfile:close()
surface.CreateFont("consolas", { font = "Consolas", size = 16, weight = 0, blursize = 0, scanlines = 0, antialias = false, underline = false, shadow = true, }) local col_green = Color(0, 255, 0) local title = "Terminal debug system [v 0.3 - NS]" local _n = "\n----------------------\n" local X_SIZE, Y_SIZE = 800, 400 function debug_menu() local _FRAME = vgui.Create("DFrame") local _SHEET = _FRAME:Add("DColumnSheet") _SHEET:Dock( FILL ) _FRAME:SetPos(ScrW() / 5, ScrH() / 3.2) _FRAME:SetSize(X_SIZE, Y_SIZE) _FRAME:SetTitle(title) _FRAME:MakePopup() local _PANEL2 = _SHEET:Add("DPanel") _PANEL2:Dock( FILL ) _PANEL2.Paint = function( self, w, h ) draw.RoundedBox( 4, 0, 0, w, h, Color( 0, 0, 0 ) ) end local _FPS = _PANEL2:Add("DLabel") _FPS:SetFont("consolas") _FPS:Dock(BOTTOM) _FPS:SetTextColor(col_green) _FPS:SetText(" ") _FPS.Think = function(this) if ((this.nextTime or 0) < CurTime()) then this:SetText( "; FPS: "..math.Round( 1/RealFrameTime() ).. "\n; PING: "..LocalPlayer():Ping().. "\n; PACKET LOOSE: "..LocalPlayer():PacketLoss() ) this.nextTime = CurTime() + 0.02 _FPS:SizeToContents() end end local _NUT_ALLENTS = _PANEL2:Add("DLabel") _NUT_ALLENTS:SetFont("consolas") _NUT_ALLENTS:Dock(TOP) _NUT_ALLENTS:SetTextColor(col_green) _NUT_ALLENTS:SetText(" ") local nuts = {} for k, v in pairs(ents.FindByClass("nut_*")) do nuts[v:GetClass()] = (nuts[v:GetClass()] or 0) + 1 end PrintTable(nuts) local _PL = player.GetAll() _NUT_ALLENTS.Think = function(this) if ((this.nextTime or 0) < CurTime()) then this:SetText( "; _SERVER ; "..GetHostName().. _n.."; _ALL_ENTS ; "..#ents.GetAll().. "\n; _ALL_NUT_ENTS ; "..#ents.FindByClass("nut_*").. _n.."; _NUT_ITEMS ; "..#ents.FindByClass("nut_item").. "\n; _NUT_ITEM_INSTANCE ; "..tostring(nut.item.instances).. _n.."; _PL ; "..#_PL ) this.nextTime = CurTime() + 0.02 _NUT_ALLENTS:SizeToContents() end end _SHEET:AddSheet( "NUT graph", _PANEL2, "icon16/application_xp_terminal.png" ) end concommand.Add("debug.menu", debug_menu) function SCHEMA:PrePlayerDraw(player) local pos = player:GetPos() local dist = LocalPlayer():GetPos():Distance(pos) if dist > 4000 then return true end end local color = {} color["$pp_colour_addr"] = 0 color["$pp_colour_addg"] = 0 color["$pp_colour_addb"] = 0 color["$pp_colour_brightness"] = -0.01 color["$pp_colour_contrast"] = 1 color["$pp_colour_colour"] = 1.2 color["$pp_colour_mulr"] = 0 color["$pp_colour_mulg"] = 0 color["$pp_colour_mulb"] = 0 function SCHEMA:RenderScreenspaceEffects() DrawColorModify(color) end function SCHEMA:GetColorModify() return color end netstream.Hook("plyData", function(...) vgui.Create("nutData"):setData(...) end) netstream.Hook("voicePlay", function(sounds, volume, index) if (index) then local client = Entity(index) if (IsValid(client)) then nut.util.emitQueuedSounds(client, sounds, nil, nil, volume) end else nut.util.emitQueuedSounds(LocalPlayer(), sounds, nil, nil, volume) end end) function SCHEMA:SetupQuickMenu(menu) menu:addButton("Настройка музыки", function() if (nut.gui.nmconfig and nut.gui.nmconfig:IsVisible()) then nut.gui.nmconfig:Close() nut.gui.nmconfig = nil end nut.gui.nmconfig = vgui.Create("nutNMConfig") end) menu:addButton("Шрифты", function() if (nut.gui.fontsel and nut.gui.fontsel:IsVisible()) then nut.gui.fontsel:Close() nut.gui.fontsel = nil end nut.gui.fontsel = vgui.Create("nutFontSel") end) end local PANEL = {} function PANEL:Init() self:SetTitle("Настройка громкости музыки") self:SetSize(300, 100) self:Center() self:MakePopup() self.list = self:Add("DPanel") self.list:Dock(FILL) self.list:DockMargin(0, 0, 0, 0) local cfg = self.list:Add("DNumSlider") cfg:Dock(TOP) cfg:SetText("Громкость") // Set the text above the slider cfg:SetMin(0) // Set the minimum number you can slide to cfg:SetMax(100) // Set the maximum number you can slide to cfg:SetDecimals(0) // Decimal places - zero for whole number cfg:SetConVar("nombat_volume") // Changes the ConVar when you slide cfg:DockMargin(10, 0, 0, 5) local change = self.list:Add("DButton") change:Dock(TOP) change:SetText("Сменить композицию") change:SetConsoleCommand("nombat_debug_switch_both") end vgui.Register("nutNMConfig", PANEL, "DFrame") NUT_CVAR_FONT = CreateClientConVar("nut_font", "Ведьмак", true) local PANEL = {} function PANEL:Init() self:SetTitle("Настройка шрифтов") self:SetSize(300, 60) self:Center() self:MakePopup() self.list = self:Add("DPanel") self.list:Dock(FILL) self.list:DockMargin(0, 0, 0, 0) local cfg = self.list:Add("DComboBox") cfg:Dock(TOP) cfg:AddChoice("Ведьмак") cfg:AddChoice("Стандартный") cfg:SetValue(NUT_CVAR_FONT:GetString()) function cfg:OnSelect( index, value, data ) if index == 1 then RunConsoleCommand("nut_font", "Ведьмак") elseif index == 2 then RunConsoleCommand("nut_font", "Стандартный") end timer.Simple(0, function() hook.Run("LoadFonts", "") end) end end vgui.Register("nutFontSel", PANEL, "DFrame")
--[[-------------------------------------------------------------------- optlex.lua: does lexer-based optimizations This file is part of LuaSrcDiet. Copyright (c) 2008 Kein-Hong Man <[email protected]> The COPYRIGHT file describes the conditions under which this software may be distributed. See the ChangeLog for more information. ----------------------------------------------------------------------]] --[[-------------------------------------------------------------------- -- NOTES: -- * For more lexer-based optimization ideas, see the TODO items or -- look at technotes.txt. -- * TODO: general string delimiter conversion optimizer -- * TODO: (numbers) warn if overly significant digit ----------------------------------------------------------------------]] local base = _G local string = require "string" module "optlex" local match = string.match local sub = string.sub local find = string.find local rep = string.rep local print ------------------------------------------------------------------------ -- variables and data structures ------------------------------------------------------------------------ -- error function, can override by setting own function into module error = base.error warn = {} -- table for warning flags local stoks, sinfos, stoklns -- source lists local is_realtoken = { -- significant (grammar) tokens TK_KEYWORD = true, TK_NAME = true, TK_NUMBER = true, TK_STRING = true, TK_LSTRING = true, TK_OP = true, TK_EOS = true, } local is_faketoken = { -- whitespace (non-grammar) tokens TK_COMMENT = true, TK_LCOMMENT = true, TK_EOL = true, TK_SPACE = true, } local opt_details -- for extra information ------------------------------------------------------------------------ -- true if current token is at the start of a line -- * skips over deleted tokens via recursion ------------------------------------------------------------------------ local function atlinestart(i) local tok = stoks[i - 1] if i <= 1 or tok == "TK_EOL" then return true elseif tok == "" then return atlinestart(i - 1) end return false end ------------------------------------------------------------------------ -- true if current token is at the end of a line -- * skips over deleted tokens via recursion ------------------------------------------------------------------------ local function atlineend(i) local tok = stoks[i + 1] if i >= #stoks or tok == "TK_EOL" or tok == "TK_EOS" then return true elseif tok == "" then return atlineend(i + 1) end return false end ------------------------------------------------------------------------ -- counts comment EOLs inside a long comment -- * in order to keep line numbering, EOLs need to be reinserted ------------------------------------------------------------------------ local function commenteols(lcomment) local sep = #match(lcomment, "^%-%-%[=*%[") local z = sub(lcomment, sep + 1, -(sep - 1)) -- remove delims local i, c = 1, 0 while true do local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i) if not p then break end -- if no matches, done i = p + 1 c = c + 1 if #s > 0 and r ~= s then -- skip CRLF or LFCR i = i + 1 end end return c end ------------------------------------------------------------------------ -- compares two tokens (i, j) and returns the whitespace required -- * important! see technotes.txt for more information -- * only two grammar/real tokens are being considered -- * if "", no separation is needed -- * if " ", then at least one whitespace (or EOL) is required ------------------------------------------------------------------------ local function checkpair(i, j) local match = match local t1, t2 = stoks[i], stoks[j] -------------------------------------------------------------------- if t1 == "TK_STRING" or t1 == "TK_LSTRING" or t2 == "TK_STRING" or t2 == "TK_LSTRING" then return "" -------------------------------------------------------------------- elseif t1 == "TK_OP" or t2 == "TK_OP" then if (t1 == "TK_OP" and (t2 == "TK_KEYWORD" or t2 == "TK_NAME")) or (t2 == "TK_OP" and (t1 == "TK_KEYWORD" or t1 == "TK_NAME")) then return "" end if t1 == "TK_OP" and t2 == "TK_OP" then -- for TK_OP/TK_OP pairs, see notes in technotes.txt local op, op2 = sinfos[i], sinfos[j] if (match(op, "^%.%.?$") and match(op2, "^%.")) or (match(op, "^[~=<>]$") and op2 == "=") or (op == "[" and (op2 == "[" or op2 == "=")) then return " " end return "" end -- "TK_OP" + "TK_NUMBER" case local op = sinfos[i] if t2 == "TK_OP" then op = sinfos[j] end if match(op, "^%.%.?%.?$") then return " " end return "" -------------------------------------------------------------------- else-- "TK_KEYWORD" | "TK_NAME" | "TK_NUMBER" then return " " -------------------------------------------------------------------- end end ------------------------------------------------------------------------ -- repack tokens, removing deletions caused by optimization process ------------------------------------------------------------------------ local function repack_tokens() local dtoks, dinfos, dtoklns = {}, {}, {} local j = 1 for i = 1, #stoks do local tok = stoks[i] if tok ~= "" then dtoks[j], dinfos[j], dtoklns[j] = tok, sinfos[i], stoklns[i] j = j + 1 end end stoks, sinfos, stoklns = dtoks, dinfos, dtoklns end ------------------------------------------------------------------------ -- number optimization -- * optimization using string formatting functions is one way of doing -- this, but here, we consider all cases and handle them separately -- (possibly an idiotic approach...) -- * scientific notation being generated is not in canonical form, this -- may or may not be a bad thing, feedback welcome -- * note: intermediate portions need to fit into a normal number range -- * optimizations can be divided based on number patterns: -- * hexadecimal: -- (1) no need to remove leading zeros, just skip to (2) -- (2) convert to integer if size equal or smaller -- * change if equal size -> lose the 'x' to reduce entropy -- (3) number is then processed as an integer -- (4) note: does not make 0[xX] consistent -- * integer: -- (1) note: includes anything with trailing ".", ".0", ... -- (2) remove useless fractional part, if present, e.g. 123.000 -- (3) remove leading zeros, e.g. 000123 -- (4) switch to scientific if shorter, e.g. 123000 -> 123e3 -- * with fraction: -- (1) split into digits dot digits -- (2) if no integer portion, take as zero (can omit later) -- (3) handle degenerate .000 case, after which the fractional part -- must be non-zero (if zero, it's matched as an integer) -- (4) remove trailing zeros for fractional portion -- (5) p.q where p > 0 and q > 0 cannot be shortened any more -- (6) otherwise p == 0 and the form is .q, e.g. .000123 -- (7) if scientific shorter, convert, e.g. .000123 -> 123e-6 -- * scientific: -- (1) split into (digits dot digits) [eE] ([+-] digits) -- (2) if significand has ".", shift it out so it becomes an integer -- (3) if significand is zero, just use zero -- (4) remove leading zeros for significand -- (5) shift out trailing zeros for significand -- (6) examine exponent and determine which format is best: -- integer, with fraction, scientific ------------------------------------------------------------------------ local function do_number(i) local before = sinfos[i] -- 'before' local z = before -- working representation local y -- 'after', if better -------------------------------------------------------------------- if match(z, "^0[xX]") then -- hexadecimal number local v = base.tostring(base.tonumber(z)) if #v <= #z then z = v -- change to integer, AND continue else return -- no change; stick to hex end end -------------------------------------------------------------------- if match(z, "^%d+%.?0*$") then -- integer or has useless frac z = match(z, "^(%d+)%.?0*$") -- int portion only if z + 0 > 0 then z = match(z, "^0*([1-9]%d*)$") -- remove leading zeros local v = #match(z, "0*$") local nv = base.tostring(v) if v > #nv + 1 then -- scientific is shorter z = sub(z, 1, #z - v).."e"..nv end y = z else y = "0" -- basic zero end -------------------------------------------------------------------- elseif not match(z, "[eE]") then -- number with fraction part local p, q = match(z, "^(%d*)%.(%d+)$") -- split if p == "" then p = 0 end -- int part zero if q + 0 == 0 and p == 0 then y = "0" -- degenerate .000 case else -- now, q > 0 holds and p is a number local v = #match(q, "0*$") -- remove trailing zeros if v > 0 then q = sub(q, 1, #q - v) end -- if p > 0, nothing else we can do to simplify p.q case if p + 0 > 0 then y = p.."."..q else y = "."..q -- tentative, e.g. .000123 local v = #match(q, "^0*") -- # leading spaces local w = #q - v -- # significant digits local nv = base.tostring(#q) -- e.g. compare 123e-6 versus .000123 if w + 2 + #nv < 1 + #q then y = sub(q, -w).."e-"..nv end end end -------------------------------------------------------------------- else -- scientific number local sig, ex = match(z, "^([^eE]+)[eE]([%+%-]?%d+)$") ex = base.tonumber(ex) -- if got ".", shift out fractional portion of significand local p, q = match(sig, "^(%d*)%.(%d*)$") if p then ex = ex - #q sig = p..q end if sig + 0 == 0 then y = "0" -- basic zero else local v = #match(sig, "^0*") -- remove leading zeros sig = sub(sig, v + 1) v = #match(sig, "0*$") -- shift out trailing zeros if v > 0 then sig = sub(sig, 1, #sig - v) ex = ex + v end -- examine exponent and determine which format is best local nex = base.tostring(ex) if ex == 0 then -- it's just an integer y = sig elseif ex > 0 and (ex <= 1 + #nex) then -- a number y = sig..rep("0", ex) elseif ex < 0 and (ex >= -#sig) then -- fraction, e.g. .123 v = #sig + ex y = sub(sig, 1, v).."."..sub(sig, v + 1) elseif ex < 0 and (#nex >= -ex - #sig) then -- e.g. compare 1234e-5 versus .01234 -- gives: #sig + 1 + #nex >= 1 + (-ex - #sig) + #sig -- -> #nex >= -ex - #sig v = -ex - #sig y = "."..rep("0", v)..sig else -- non-canonical scientific representation y = sig.."e"..ex end end--if sig end -------------------------------------------------------------------- if y and y ~= sinfos[i] then if opt_details then print("<number> (line "..stoklns[i]..") "..sinfos[i].." -> "..y) opt_details = opt_details + 1 end sinfos[i] = y end end ------------------------------------------------------------------------ -- string optimization -- * note: works on well-formed strings only! -- * optimizations on characters can be summarized as follows: -- \a\b\f\n\r\t\v -- no change -- \\ -- no change -- \"\' -- depends on delim, other can remove \ -- \[\] -- remove \ -- \<char> -- general escape, remove \ -- \<eol> -- normalize the EOL only -- \ddd -- if \a\b\f\n\r\t\v, change to latter -- if other < ascii 32, keep ddd but zap leading zeros -- if >= ascii 32, translate it into the literal, then also -- do escapes for \\,\",\' cases -- <other> -- no change -- * switch delimiters if string becomes shorter ------------------------------------------------------------------------ local function do_string(I) local info = sinfos[I] local delim = sub(info, 1, 1) -- delimiter used local ndelim = (delim == "'") and '"' or "'" -- opposite " <-> ' local z = sub(info, 2, -2) -- actual string local i = 1 local c_delim, c_ndelim = 0, 0 -- "/' counts -------------------------------------------------------------------- while i <= #z do local c = sub(z, i, i) ---------------------------------------------------------------- if c == "\\" then -- escaped stuff local j = i + 1 local d = sub(z, j, j) local p = find("abfnrtv\\\n\r\"\'0123456789", d, 1, true) ------------------------------------------------------------ if not p then -- \<char> -- remove \ z = sub(z, 1, i - 1)..sub(z, j) i = i + 1 ------------------------------------------------------------ elseif p <= 8 then -- \a\b\f\n\r\t\v\\ i = i + 2 -- no change ------------------------------------------------------------ elseif p <= 10 then -- \<eol> -- normalize EOL local eol = sub(z, j, j + 1) if eol == "\r\n" or eol == "\n\r" then z = sub(z, 1, i).."\n"..sub(z, j + 2) elseif p == 10 then -- \r case z = sub(z, 1, i).."\n"..sub(z, j + 1) end i = i + 2 ------------------------------------------------------------ elseif p <= 12 then -- \"\' -- remove \ for ndelim if d == delim then c_delim = c_delim + 1 i = i + 2 else c_ndelim = c_ndelim + 1 z = sub(z, 1, i - 1)..sub(z, j) i = i + 1 end ------------------------------------------------------------ else -- \ddd -- various steps local s = match(z, "^(%d%d?%d?)", j) j = i + 1 + #s -- skip to location local cv = s + 0 local cc = string.char(cv) local p = find("\a\b\f\n\r\t\v", cc, 1, true) if p then -- special escapes s = "\\"..sub("abfnrtv", p, p) elseif cv < 32 then -- normalized \ddd s = "\\"..cv elseif cc == delim then -- \<delim> s = "\\"..cc c_delim = c_delim + 1 elseif cc == "\\" then -- \\ s = "\\\\" else -- literal character s = cc if cc == ndelim then c_ndelim = c_ndelim + 1 end end z = sub(z, 1, i - 1)..s..sub(z, j) i = i + #s ------------------------------------------------------------ end--if p ---------------------------------------------------------------- else-- c ~= "\\" -- <other> -- no change i = i + 1 if c == ndelim then -- count ndelim, for switching delimiters c_ndelim = c_ndelim + 1 end ---------------------------------------------------------------- end--if c end--while -------------------------------------------------------------------- -- switching delimiters, a long-winded derivation: -- (1) delim takes 2+2*c_delim bytes, ndelim takes c_ndelim bytes -- (2) delim becomes c_delim bytes, ndelim becomes 2+2*c_ndelim bytes -- simplifying the condition (1)>(2) --> c_delim > c_ndelim if c_delim > c_ndelim then i = 1 while i <= #z do local p, q, r = find(z, "([\'\"])", i) if not p then break end if r == delim then -- \<delim> -> <delim> z = sub(z, 1, p - 2)..sub(z, p) i = p else-- r == ndelim -- <ndelim> -> \<ndelim> z = sub(z, 1, p - 1).."\\"..sub(z, p) i = p + 2 end end--while delim = ndelim -- actually change delimiters end -------------------------------------------------------------------- z = delim..z..delim if z ~= sinfos[I] then if opt_details then print("<string> (line "..stoklns[I]..") "..sinfos[I].." -> "..z) opt_details = opt_details + 1 end sinfos[I] = z end end ------------------------------------------------------------------------ -- long string optimization -- * note: warning flagged if trailing whitespace found, not trimmed -- * remove first optional newline -- * normalize embedded newlines -- * reduce '=' separators in delimiters if possible ------------------------------------------------------------------------ local function do_lstring(I) local info = sinfos[I] local delim1 = match(info, "^%[=*%[") -- cut out delimiters local sep = #delim1 local delim2 = sub(info, -sep, -1) local z = sub(info, sep + 1, -(sep + 1)) -- lstring without delims local y = "" local i = 1 -------------------------------------------------------------------- while true do local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i) -- deal with a single line local ln if not p then ln = sub(z, i) elseif p >= i then ln = sub(z, i, p - 1) end if ln ~= "" then -- flag a warning if there are trailing spaces, won't optimize! if match(ln, "%s+$") then warn.lstring = "trailing whitespace in long string near line "..stoklns[I] end y = y..ln end if not p then -- done if no more EOLs break end -- deal with line endings, normalize them i = p + 1 if p then if #s > 0 and r ~= s then -- skip CRLF or LFCR i = i + 1 end -- skip first newline, which can be safely deleted if not(i == 1 and i == p) then y = y.."\n" end end end--while -------------------------------------------------------------------- -- handle possible deletion of one or more '=' separators if sep >= 3 then local chk, okay = sep - 1 -- loop to test ending delimiter with less of '=' down to zero while chk >= 2 do local delim = "%]"..rep("=", chk - 2).."%]" if not match(y, delim) then okay = chk end chk = chk - 1 end if okay then -- change delimiters sep = rep("=", okay - 2) delim1, delim2 = "["..sep.."[", "]"..sep.."]" end end -------------------------------------------------------------------- sinfos[I] = delim1..y..delim2 end ------------------------------------------------------------------------ -- long comment optimization -- * note: does not remove first optional newline -- * trim trailing whitespace -- * normalize embedded newlines -- * reduce '=' separators in delimiters if possible ------------------------------------------------------------------------ local function do_lcomment(I) local info = sinfos[I] local delim1 = match(info, "^%-%-%[=*%[") -- cut out delimiters local sep = #delim1 local delim2 = sub(info, -sep, -1) local z = sub(info, sep + 1, -(sep - 1)) -- comment without delims local y = "" local i = 1 -------------------------------------------------------------------- while true do local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i) -- deal with a single line, extract and check trailing whitespace local ln if not p then ln = sub(z, i) elseif p >= i then ln = sub(z, i, p - 1) end if ln ~= "" then -- trim trailing whitespace if non-empty line local ws = match(ln, "%s*$") if #ws > 0 then ln = sub(ln, 1, -(ws + 1)) end y = y..ln end if not p then -- done if no more EOLs break end -- deal with line endings, normalize them i = p + 1 if p then if #s > 0 and r ~= s then -- skip CRLF or LFCR i = i + 1 end y = y.."\n" end end--while -------------------------------------------------------------------- -- handle possible deletion of one or more '=' separators sep = sep - 2 if sep >= 3 then local chk, okay = sep - 1 -- loop to test ending delimiter with less of '=' down to zero while chk >= 2 do local delim = "%]"..rep("=", chk - 2).."%]" if not match(y, delim) then okay = chk end chk = chk - 1 end if okay then -- change delimiters sep = rep("=", okay - 2) delim1, delim2 = "--["..sep.."[", "]"..sep.."]" end end -------------------------------------------------------------------- sinfos[I] = delim1..y..delim2 end ------------------------------------------------------------------------ -- short comment optimization -- * trim trailing whitespace ------------------------------------------------------------------------ local function do_comment(i) local info = sinfos[i] local ws = match(info, "%s*$") -- just look from end of string if #ws > 0 then info = sub(info, 1, -(ws + 1)) -- trim trailing whitespace end sinfos[i] = info end ------------------------------------------------------------------------ -- returns true if string found in long comment -- * this is a feature to keep copyright or license texts ------------------------------------------------------------------------ local function keep_lcomment(opt_keep, info) if not opt_keep then return false end -- option not set local delim1 = match(info, "^%-%-%[=*%[") -- cut out delimiters local sep = #delim1 local delim2 = sub(info, -sep, -1) local z = sub(info, sep + 1, -(sep - 1)) -- comment without delims if find(z, opt_keep, 1, true) then -- try to match return true end end ------------------------------------------------------------------------ -- main entry point -- * currently, lexer processing has 2 passes -- * processing is done on a line-oriented basis, which is easier to -- grok due to the next point... -- * since there are various options that can be enabled or disabled, -- processing is a little messy or convoluted ------------------------------------------------------------------------ function optimize(option, toklist, semlist, toklnlist) -------------------------------------------------------------------- -- set option flags -------------------------------------------------------------------- local opt_comments = option["opt-comments"] local opt_whitespace = option["opt-whitespace"] local opt_emptylines = option["opt-emptylines"] local opt_eols = option["opt-eols"] local opt_strings = option["opt-strings"] local opt_numbers = option["opt-numbers"] local opt_keep = option.KEEP opt_details = option.DETAILS and 0 -- upvalues for details display print = print or base.print if opt_eols then -- forced settings, otherwise won't work properly opt_comments = true opt_whitespace = true opt_emptylines = true end -------------------------------------------------------------------- -- variable initialization -------------------------------------------------------------------- stoks, sinfos, stoklns -- set source lists = toklist, semlist, toklnlist local i = 1 -- token position local tok, info -- current token local prev -- position of last grammar token -- on same line (for TK_SPACE stuff) -------------------------------------------------------------------- -- changes a token, info pair -------------------------------------------------------------------- local function settoken(tok, info, I) I = I or i stoks[I] = tok or "" sinfos[I] = info or "" end -------------------------------------------------------------------- -- processing loop (PASS 1) -------------------------------------------------------------------- while true do tok, info = stoks[i], sinfos[i] ---------------------------------------------------------------- local atstart = atlinestart(i) -- set line begin flag if atstart then prev = nil end ---------------------------------------------------------------- if tok == "TK_EOS" then -- end of stream/pass break ---------------------------------------------------------------- elseif tok == "TK_KEYWORD" or -- keywords, identifiers, tok == "TK_NAME" or -- operators tok == "TK_OP" then -- TK_KEYWORD and TK_OP can't be optimized without a big -- optimization framework; it would be more of an optimizing -- compiler, not a source code compressor -- TK_NAME that are locals needs parser to analyze/optimize prev = i ---------------------------------------------------------------- elseif tok == "TK_NUMBER" then -- numbers if opt_numbers then do_number(i) -- optimize end prev = i ---------------------------------------------------------------- elseif tok == "TK_STRING" or -- strings, long strings tok == "TK_LSTRING" then if opt_strings then if tok == "TK_STRING" then do_string(i) -- optimize else do_lstring(i) -- optimize end end prev = i ---------------------------------------------------------------- elseif tok == "TK_COMMENT" then -- short comments if opt_comments then if i == 1 and sub(info, 1, 1) == "#" then -- keep shbang comment, trim whitespace do_comment(i) else -- safe to delete, as a TK_EOL (or TK_EOS) always follows settoken() -- remove entirely end elseif opt_whitespace then -- trim whitespace only do_comment(i) end ---------------------------------------------------------------- elseif tok == "TK_LCOMMENT" then -- long comments if keep_lcomment(opt_keep, info) then ------------------------------------------------------------ -- if --keep, we keep a long comment if <msg> is found; -- this is a feature to keep copyright or license texts if opt_whitespace then -- trim whitespace only do_lcomment(i) end prev = i elseif opt_comments then local eols = commenteols(info) ------------------------------------------------------------ -- prepare opt_emptylines case first, if a disposable token -- follows, current one is safe to dump, else keep a space; -- it is implied that the operation is safe for '-', because -- current is a TK_LCOMMENT, and must be separate from a '-' if is_faketoken[stoks[i + 1]] then settoken() -- remove entirely tok = "" else settoken("TK_SPACE", " ") end ------------------------------------------------------------ -- if there are embedded EOLs to keep and opt_emptylines is -- disabled, then switch the token into one or more EOLs if not opt_emptylines and eols > 0 then settoken("TK_EOL", rep("\n", eols)) end ------------------------------------------------------------ -- if optimizing whitespaces, force reinterpretation of the -- token to give a chance for the space to be optimized away if opt_whitespace and tok ~= "" then i = i - 1 -- to reinterpret end ------------------------------------------------------------ else -- disabled case if opt_whitespace then -- trim whitespace only do_lcomment(i) end prev = i end ---------------------------------------------------------------- elseif tok == "TK_EOL" then -- line endings if atstart and opt_emptylines then settoken() -- remove entirely elseif info == "\r\n" or info == "\n\r" then -- normalize the rest of the EOLs for CRLF/LFCR only -- (note that TK_LCOMMENT can change into several EOLs) settoken("TK_EOL", "\n") end ---------------------------------------------------------------- elseif tok == "TK_SPACE" then -- whitespace if opt_whitespace then if atstart or atlineend(i) then -- delete leading and trailing whitespace settoken() -- remove entirely else ------------------------------------------------------------ -- at this point, since leading whitespace have been removed, -- there should be a either a real token or a TK_LCOMMENT -- prior to hitting this whitespace; the TK_LCOMMENT case -- only happens if opt_comments is disabled; so prev ~= nil local ptok = stoks[prev] if ptok == "TK_LCOMMENT" then -- previous TK_LCOMMENT can abut with anything settoken() -- remove entirely else -- prev must be a grammar token; consecutive TK_SPACE -- tokens is impossible when optimizing whitespace local ntok = stoks[i + 1] if is_faketoken[ntok] then -- handle special case where a '-' cannot abut with -- either a short comment or a long comment if (ntok == "TK_COMMENT" or ntok == "TK_LCOMMENT") and ptok == "TK_OP" and sinfos[prev] == "-" then -- keep token else settoken() -- remove entirely end else--is_realtoken -- check a pair of grammar tokens, if can abut, then -- delete space token entirely, otherwise keep one space local s = checkpair(prev, i + 1) if s == "" then settoken() -- remove entirely else settoken("TK_SPACE", " ") end end end ------------------------------------------------------------ end end ---------------------------------------------------------------- else error("unidentified token encountered") end ---------------------------------------------------------------- i = i + 1 end--while repack_tokens() -------------------------------------------------------------------- -- processing loop (PASS 2) -------------------------------------------------------------------- if opt_eols then i = 1 -- aggressive EOL removal only works with most non-grammar tokens -- optimized away because it is a rather simple scheme -- basically -- it just checks 'real' token pairs around EOLs if stoks[1] == "TK_COMMENT" then -- first comment still existing must be shbang, skip whole line i = 3 end while true do tok, info = stoks[i], sinfos[i] -------------------------------------------------------------- if tok == "TK_EOS" then -- end of stream/pass break -------------------------------------------------------------- elseif tok == "TK_EOL" then -- consider each TK_EOL local t1, t2 = stoks[i - 1], stoks[i + 1] if is_realtoken[t1] and is_realtoken[t2] then -- sanity check local s = checkpair(i - 1, i + 1) if s == "" then settoken() -- remove entirely end end end--if tok -------------------------------------------------------------- i = i + 1 end--while repack_tokens() end -------------------------------------------------------------------- if opt_details and opt_details > 0 then print() end -- spacing return stoks, sinfos, stoklns end
----------------------------------------- -- Spell: Stonega II -- Deals earth damage to enemies within area of effect. ----------------------------------------- require("scripts/globals/status") require("scripts/globals/magic") ----------------------------------------- function onMagicCastingCheck(caster, target, spell) return 0 end function onSpellCast(caster, target, spell) local spellParams = {} spellParams.hasMultipleTargetReduction = true spellParams.resistBonus = 1.0 spellParams.V = 201 spellParams.V0 = 250 spellParams.V50 = 450 spellParams.V100 = 600 spellParams.V200 = 800 spellParams.M = 1 spellParams.M0 = 4 spellParams.M50 = 3 spellParams.M100 = 2 spellParams.M200 = 1 spellParams.I = 232 return doElementalNuke(caster, spell, target, spellParams) end
--[[ Copyright (c) 2016 by Marco Lizza ([email protected]) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ]]-- -- MODULE INCLUSIONS ----------------------------------------------------------- local config = require('game.config') local constants = require('game.constants') local Foe = require('game.foe') local graphics = require('lib.graphics') local utils = require('lib.utils') -- MODULE DECLARATION ---------------------------------------------------------- local Entities = { world = nil, avatar = nil, door = nil, keys = { }, foes = {}, flares = {} } -- MODULE OBJECT CONSTRUCTOR --------------------------------------------------- Entities.__index = Entities function Entities.new() local self = setmetatable({}, Entities) return self end -- LOCAL FUNCTIONS ------------------------------------------------------------- -- FIXME: return a table, not a pair. local function randomize_position() return love.math.random(constants.MAZE_WIDTH), love.math.random(constants.MAZE_HEIGHT) end local function overlap(x, y, table) for _, entry in pairs(table) do local position = entry.position if x == position.x and y == position.y then return true end end return false end -- MODULE FUNCTIONS ------------------------------------------------------------ function Entities:initialize(world) self.world = world end function Entities:generate(level) local world = self.world local maze = world.maze -- We are cyclically incrementing the foes count and restart (and increase) the -- number of keys to be found. We also decrement the foes' period (i.e. we speed -- them up). local keys = level % 5 local foes = level / 3 local period = math.max(0.2, 0.5 - (level / 5) * 0.1) -- The avatar is placed on a fixed position at a different corner each level. -- Please note that we are safe in assuming that the corner position is always -- walkable. local avatar = { position = nil, health = 10, keys = 0, flares = 3, duration = 60 } self.avatar = avatar local turn = level % 4 if turn == 0 then avatar.position = { x = 2, y = 2 } elseif turn == 1 then avatar.position = { x = maze.width - 1, y = 2 } elseif turn == 2 then avatar.position = { x = maze.width - 1, y = maze.height - 1 } else avatar.position = { x = 2, y = maze.height - 1 } end -- Generate the keys. Each key need to be "far enough" from the avatar, so -- we are cycling util we find some reasonable positions. We also check for -- overlapping keys. self.keys = {} while #self.keys < keys do local x, y = randomize_position() local distance = utils.distance(avatar.position.x, avatar.position.y, x, y) if maze:is_walkable(x, y) and not overlap(x, y, self.keys) and distance >= 20 then local key = { position = { x = x, y = y }, visible = true } self.keys[#self.keys + 1] = key end end -- Pick a random position for the door. The door can be everywhere, -- since the player will move from the starting point, but we do like it not -- be place on top a key. while true do local x, y = randomize_position() if maze:is_walkable(x, y) and not overlap(x, y, self.keys) then local door = { position = { x = x, y = y }, visible = false, unlocked = false } self.door = door break end end -- Foes are randomly scatterd around the center of the maze. We make sure they -- won't overlap each other. self.foes = {} while #self.foes < foes do local x, y = randomize_position() local distance = utils.distance(math.floor(maze.width / 2), math.floor(maze.height / 2), x, y) if maze:is_walkable(x, y) and not overlap(x, y, self.foes) and distance < 7 then local foe = Foe.new() foe:initialize(self.world, x, y, period) self.foes[#self.foes + 1] = foe end end -- Empty the flares list. self.flares = {} end function Entities:input(keys) local dx, dy = 0, 0 -- find the delta movement local drop_flare = false if keys.pressed['up'] then dy = dy - 1 end if keys.pressed['down'] then dy = dy + 1 end if keys.pressed['left'] then dx = dx - 1 end if keys.pressed['right'] then dx = dx + 1 end if keys.pressed['x'] then drop_flare = true end -- local avatar = self.avatar -- Compute the new position by checking the map walkability. Note that we -- don't need to check the boundaries since the map features a non-walkable -- border that force the player *inside* the map itself. local position = avatar.position local _ = self.world:move(position, dx, dy) -- If the player requested a flare drop, leave it at the current player -- position -- -- TODO: we should synch flares and emitters outside this module. Note -- that flare entities are not removed when the emitter is finished. if drop_flare and avatar.flares > 0 then local flare_id = string.format('flare-%d', avatar.flares) local flare = { position = { x = position.x, y = position.y } } self.flares[flare_id] = flare self.world.maze:spawn_emitter(flare_id, position.x, position.y, 7, 3, 30) avatar.flares = avatar.flares - 1 end end function Entities:update(dt) -- Update and advance the foes. for _, foe in pairs(self.foes) do foe:update(dt) end -- Check for player collision (i.e. fetch) of a key. It all the keys -- have been fetched, we check for door collision. local avatar = self.avatar if avatar.keys < #self.keys then for _, key in ipairs(self.keys) do if key.visible and utils.overlap(avatar.position, key.position) then avatar.keys = avatar.keys + 1 key.visible = false end end else local door = self.door door.visible = true if utils.overlap(avatar.position, door.position) then door.visible = false door.unlocked = true end end -- The player duration decreases during the normal gameplay by a constant rate. -- This rate is higher when a foe is colliding with the player. local decay = 0.10 if self:is_avatar_hit() then decay = 10 if avatar.health > 0 then avatar.health = avatar.health - 2 * dt end end avatar.duration = avatar.duration - (decay * dt) end function Entities:draw() local world = self.world local maze = world.maze local avatar = self.avatar -- Flares dim according to their energy value. The will become invisible -- even if globally illuminated. for flare_id, flare in pairs(self.flares) do local x, y = flare.position.x, flare.position.y local emitter = maze:get_emitter(flare_id) local energy = emitter:energy_at(x, y) local alpha = math.min(math.floor(255 * energy), 255) graphics.square(x, y, 'yellow', alpha) end -- Keys are visible according to the global energy level on their spot. for _, key in pairs(self.keys) do if key.visible then local x, y = key.position.x, key.position.y local energy = maze:energy_at(x, y) local alpha = config.debug.cheat and 255 or math.min(math.floor(255 * energy), 255) graphics.square(x, y, 'teal', alpha) end end -- The avatar is always visible. It need to be visible over flares and keys. local x, y = avatar.position.x, avatar.position.y graphics.square(x, y, 'cyan') -- Display the door, if visible (e.g. the player has fetched all the keys). local door = self.door if door.visible then local x, y = door.position.x, door.position.y local energy = maze:energy_at(x, y) local alpha = config.debug.cheat and 255 or math.min(math.floor(255 * energy), 255) graphics.square(x, y, 'green', alpha) end for _, foe in pairs(self.foes) do foe:draw() end end function Entities:is_avatar_hit() local avatar = self.avatar local position = avatar.position return overlap(position.x, position.y, self.foes) end function Entities:danger_level() local avatar = self.avatar local min_distance = math.huge for _, foe in pairs(self.foes) do local distance = utils.distance(avatar.position, foe.position) if min_distance > distance then min_distance = distance end end min_distance = math.min(10, min_distance) return 1 - (min_distance / 10) end -- END OF MODULE --------------------------------------------------------------- return Entities -- END OF FILE -----------------------------------------------------------------
function convert._from_human_to_timestamp(str) return atom.timestamp:load(str) end
---===================================== ---luastg 基础用户接口 ---lstg 库 ---作者:Xiliusha ---邮箱:[email protected] ---===================================== ---@class lstg @lstg库 local m = {} ---@type lstg lstg = m ---------------------------------------- ---游戏循环流程 --[[ 1 > 初始化游戏框架,启动lua虚拟机 2 > 加载launch初始化脚本(可选),此时游戏引擎还没有初始化完成 3 > 完成游戏引擎初始化 4 > 加载core.lua核心脚本,也就是游戏的入口点文件 5 > 执行GameInit,然后开始游戏循环 6 > 按照FrameFunc->RenderFunc->FrameFunc->...的顺序进行游戏循环 7 > 结束游戏循环,然后执行GameExit 8 > 卸载所有资源,关闭游戏引擎,关闭lua虚拟机,销毁游戏框架 --]] ---------------------------------------- ---全局回调函数 ---游戏循环开始前调用一次 function GameInit() end ---游戏循环中每帧调用一次,在RenderFunc之前 ---@return boolean @返回true时结束游戏循环 function FrameFunc() return false end ---游戏循环中每帧调用一次,在FrameFunc之后 function RenderFunc() end ---游戏循环结束后,退出前调用一次 function GameExit() end ---窗口失去焦点的时候被调用 function FocusLoseFunc() end ---窗口获得焦点的时候被调用 function FocusGainFunc() end
local core = require("apisix.core") local ngx_re = require("ngx.re") local tab_concat = table.concat local http = require("resty.http") local string = string local io_open = io.open local io_close = io.close local ngx = ngx local ipairs = ipairs local pairs = pairs local tonumber = tonumber local _M = {} local tmp = {} function _M.generate_complex_value(data, ctx) core.table.clear(tmp) core.log.info("proxy-cache complex value: ", core.json.delay_encode(data)) for i, value in ipairs(data) do core.log.info("proxy-cache complex value index-", i, ": ", value) if string.byte(value, 1, 1) == string.byte('$') then tmp[i] = ctx.var[string.sub(value, 2)] else tmp[i] = value end end return tab_concat(tmp, "") end -- check whether the request method match the user defined. function _M.match_method(conf, ctx) for _, method in ipairs(conf.cache_method) do if method == ctx.var.request_method then return true end end return false end -- check whether the response status match the user defined. function _M.match_status(conf, ctx) for _, status in ipairs(conf.cache_http_status) do if status == ngx.status then return true end end return false end -- check whether the request method and response status -- match the user defined. function _M.match_method_and_status(conf, ctx) local match_method = _M.match_method(conf, ctx) local match_status = _M.match_status(conf, ctx) if match_method and match_status then return true end return false end function _M.file_exists(name) local f = io_open(name, "r") if f ~= nil then io_close(f) return true end return false end function _M.generate_cache_filename(cache_path, cache_levels, cache_key) local md5sum = ngx.md5(cache_key) local levels = ngx_re.split(cache_levels, ":") local filename = "" local index = #md5sum for k, v in pairs(levels) do local length = tonumber(v) index = index - length filename = filename .. md5sum:sub(index + 1, index + length) .. "/" end if cache_path:sub(-1) ~= "/" then cache_path = cache_path .. "/" end filename = cache_path .. filename .. md5sum return md5sum end function _M.cache_purge(conf, ctx) local cache_zone_info = ngx_re.split(ctx.var.upstream_cache_zone_info, ",") local filename = _M.generate_cache_filename(cache_zone_info[1], cache_zone_info[2], ctx.var.upstream_cache_key) if _M.file_exists(filename) then os.remove(filename) return nil end return "Not found" end function _M.generate_cache_key(cache_path, cache_levels, cache_key) -- Todo: Parse header and get content local md5sum = ngx.md5(cache_key) return md5sum end function _M.new_headers() local t = {} local lt = {} local _mt = { __index = function(t, k) return rawget(lt, string.lower(k)) end, __newindex = function(t, k, v) rawset(t, k, v) rawset(lt, string.lower(k), v) end } return setmetatable(t, _mt) end function _M.http_req(method, uri, body, myheaders, timeout) if myheaders == nil then myheaders = _M.new_headers() end local httpc = http.new() if timeout then httpc:set_timeout(timeout) end local params = { method = method, headers = myheaders, body = body, ssl_verify = false } local res, err = httpc:request_uri(uri, params) if err then core.log.error("FAIL REQUEST [ ", core.json.delay_encode({ method = method, uri = uri, body = body, headers = myheaders }), " ] failed! res is nil, err:", err) return nil, err end return res end function _M.http_get(uri, myheaders, timeout) return _M.http_req("GET", uri, nil, myheaders, timeout) end return _M
local test_env = require("spec.util.test_env") local lfs = require("lfs") local get_tmp_path = test_env.get_tmp_path local run = test_env.run local testing_paths = test_env.testing_paths local write_file = test_env.write_file local git_repo = require("spec.util.git_repo") test_env.unload_luarocks() local cfg = require("luarocks.core.cfg") local fs = require("luarocks.fs") local extra_rocks = { "/lmathx-20120430.51-1.src.rock", "/lmathx-20120430.51-1.rockspec", "/lmathx-20120430.52-1.src.rock", "/lmathx-20120430.52-1.rockspec", "/lmathx-20150505-1.src.rock", "/lmathx-20150505-1.rockspec", "/lpeg-1.0.0-1.rockspec", "/lpeg-1.0.0-1.src.rock", "/luafilesystem-1.6.3-1.src.rock", "/luasec-0.6-1.rockspec", "/luasocket-3.0rc1-2.src.rock", "/luasocket-3.0rc1-2.rockspec", "/stdlib-41.0.0-1.src.rock", "/validate-args-1.5.4-1.rockspec" } local c_module_source = [[ #include <lua.h> #include <lauxlib.h> int luaopen_c_module(lua_State* L) { lua_newtable(L); lua_pushinteger(L, 1); lua_setfield(L, -2, "c_module"); return 1; } ]] describe("LuaRocks build #integration", function() lazy_setup(function() cfg.init() fs.init() end) before_each(function() test_env.setup_specs(extra_rocks) end) describe("basic testing set", function() it("invalid", function() assert.is_false(run.luarocks_bool("build invalid")) end) it("with no arguments behaves as luarocks make", function() test_env.run_in_tmp(function(tmpdir) write_file("c_module-1.0-1.rockspec", [[ package = "c_module" version = "1.0-1" source = { url = "http://example.com/c_module" } build = { type = "builtin", modules = { c_module = { "c_module.c" } } } ]], finally) write_file("c_module.c", c_module_source, finally) assert.is_true(run.luarocks_bool("build")) assert.truthy(lfs.attributes(tmpdir .. "/c_module." .. test_env.lib_extension)) end, finally) end) end) describe("building with flags", function() it("fails if it doesn't have the permissions to access the specified tree #unix", function() assert.is_false(run.luarocks_bool("build --tree=/usr " .. testing_paths.fixtures_dir .. "/a_rock-1.0.1-rockspec")) assert.falsy(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/1.0-1/a_rock-1.0-1.rockspec")) end) it("fails if it doesn't have the permissions to access the specified tree's parent #unix", function() assert.is_false(run.luarocks_bool("build --tree=/usr/invalid " .. testing_paths.fixtures_dir .. "/a_rock-1.0-1.rockspec")) assert.falsy(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/1.0-1/a_rock-1.0-1.rockspec")) end) it("verbose", function() test_env.run_in_tmp(function(tmpdir) write_file("test-1.0-1.rockspec", [[ package = "test" version = "1.0-1" source = { url = "file://]] .. tmpdir:gsub("\\", "/") .. [[/test.lua" } build = { type = "builtin", modules = { test = "test.lua" } } ]], finally) write_file("test.lua", "return {}", finally) assert.is_true(run.luarocks_bool("build --verbose test-1.0-1.rockspec")) assert.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/test/1.0-1/test-1.0-1.rockspec")) end, finally) end) it("fails if the deps-mode argument is invalid", function() assert.is_false(run.luarocks_bool("build --deps-mode=123 " .. testing_paths.fixtures_dir .. "/a_rock-1.0-1.rockspec")) assert.falsy(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/1.0-1/a_rock-1.0-1.rockspec")) end) it("with --only-sources", function() assert.is_true(run.luarocks_bool("download --server=" .. testing_paths.fixtures_dir .. "/a_repo --rockspec a_rock 1.0")) assert.is_false(run.luarocks_bool("build --only-sources=\"http://example.com\" a_rock-1.0-1.rockspec")) assert.is.falsy(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/1.0-1/a_rock-1.0-1.rockspec")) assert.is_true(run.luarocks_bool("download --server=" .. testing_paths.fixtures_dir .. "/a_repo --source a_rock 1.0")) assert.is_true(run.luarocks_bool("build --only-sources=\"http://example.com\" a_rock-1.0-1.src.rock")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/1.0-1/a_rock-1.0-1.rockspec")) assert.is_true(os.remove("a_rock-1.0-1.rockspec")) assert.is_true(os.remove("a_rock-1.0-1.src.rock")) end) it("fails if an empty tree is given", function() assert.is_false(run.luarocks_bool("build --tree=\"\" " .. testing_paths.fixtures_dir .. "/a_rock-1.0-1.rockspec")) assert.falsy(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/1.0-1/a_rock-1.0-1.rockspec")) end) end) describe("basic builds", function() it("luacov diff version", function() assert.is_true(run.luarocks_bool("build luacov 0.13.0-1")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/luacov/0.13.0-1/luacov-0.13.0-1.rockspec")) end) it("command stdlib", function() assert.is_true(run.luarocks_bool("build stdlib")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/stdlib/41.0.0-1/stdlib-41.0.0-1.rockspec")) end) it("fails if the current platform is not supported", function() test_env.run_in_tmp(function(tmpdir) write_file("test-1.0-1.rockspec", [[ package = "test" version = "1.0-1" source = { url = "file://]] .. tmpdir:gsub("\\", "/") .. [[/test.lua" } supported_platforms = { "unix", "macosx" } build = { type = "builtin", modules = { test = "test.lua" } } ]], finally) write_file("test.lua", "return {}", finally) if test_env.TEST_TARGET_OS == "windows" then assert.is_false(run.luarocks_bool("build test-1.0-1.rockspec")) -- Error: This rockspec does not support windows platforms assert.is.falsy(lfs.attributes(testing_paths.testing_sys_rocks .. "/test/1.0-1/test-1.0-1.rockspec")) else assert.is_true(run.luarocks_bool("build test-1.0-1.rockspec")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/test/1.0-1/test-1.0-1.rockspec")) end end, finally) end) it("with skipping dependency checks", function() test_env.run_in_tmp(function(tmpdir) write_file("test-1.0-1.rockspec", [[ package = "test" version = "1.0-1" source = { url = "file://]] .. tmpdir:gsub("\\", "/") .. [[/test.lua" } dependencies = { "a_rock 1.0" } build = { type = "builtin", modules = { test = "test.lua" } } ]], finally) write_file("test.lua", "return {}", finally) assert.is_true(run.luarocks_bool("build test-1.0-1.rockspec --deps-mode=none")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/test/1.0-1/test-1.0-1.rockspec")) end) end) it("supports --pin #pinning", function() test_env.run_in_tmp(function(tmpdir) write_file("test-1.0-1.rockspec", [[ package = "test" version = "1.0-1" source = { url = "file://]] .. tmpdir:gsub("\\", "/") .. [[/test.lua" } dependencies = { "a_rock >= 0.8" } build = { type = "builtin", modules = { test = "test.lua" } } ]], finally) write_file("test.lua", "return {}", finally) assert.is_true(run.luarocks_bool("build --server=" .. testing_paths.fixtures_dir .. "/a_repo test-1.0-1.rockspec --pin --tree=lua_modules")) assert.is.truthy(lfs.attributes("./lua_modules/lib/luarocks/rocks-" .. test_env.lua_version .. "/test/1.0-1/test-1.0-1.rockspec")) assert.is.truthy(lfs.attributes("./lua_modules/lib/luarocks/rocks-" .. test_env.lua_version .. "/a_rock/2.0-1/a_rock-2.0-1.rockspec")) local lockfilename = "./lua_modules/lib/luarocks/rocks-" .. test_env.lua_version .. "/test/1.0-1/luarocks.lock" assert.is.truthy(lfs.attributes(lockfilename)) local lockdata = loadfile(lockfilename)() assert.same({ dependencies = { ["a_rock"] = "2.0-1", ["lua"] = test_env.lua_version .. "-1", } }, lockdata) end) end) it("lmathx deps partial match", function() assert.is_true(run.luarocks_bool("build lmathx")) if test_env.LUA_V == "5.1" or test_env.LUAJIT_V then assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/lmathx/20120430.51-1/lmathx-20120430.51-1.rockspec")) elseif test_env.LUA_V == "5.2" then assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/lmathx/20120430.52-1/lmathx-20120430.52-1.rockspec")) elseif test_env.LUA_V == "5.3" then assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/lmathx/20150505-1/lmathx-20150505-1.rockspec")) end end) end) describe("#namespaces", function() it("builds a namespaced package from the command-line", function() assert(run.luarocks_bool("build a_user/a_rock --server=" .. testing_paths.fixtures_dir .. "/a_repo" )) assert.is_false(run.luarocks_bool("show a_rock 1.0")) assert(run.luarocks_bool("show a_rock 2.0")) assert(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/2.0-1/rock_namespace")) end) it("builds a package with a namespaced dependency", function() assert(run.luarocks_bool("build has_namespaced_dep --server=" .. testing_paths.fixtures_dir .. "/a_repo" )) assert(run.luarocks_bool("show has_namespaced_dep")) assert.is_false(run.luarocks_bool("show a_rock 1.0")) assert(run.luarocks_bool("show a_rock 2.0")) end) it("builds a package reusing a namespaced dependency", function() assert(run.luarocks_bool("build a_user/a_rock --server=" .. testing_paths.fixtures_dir .. "/a_repo" )) assert(run.luarocks_bool("show a_rock 2.0")) assert(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/2.0-1/rock_namespace")) local output = run.luarocks("build has_namespaced_dep --server=" .. testing_paths.fixtures_dir .. "/a_repo" ) assert.has.no.match("Missing dependencies", output) end) it("builds a package considering namespace of locally installed package", function() assert(run.luarocks_bool("build a_user/a_rock --server=" .. testing_paths.fixtures_dir .. "/a_repo" )) assert(run.luarocks_bool("show a_rock 2.0")) assert(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/2.0-1/rock_namespace")) local output = run.luarocks("build has_another_namespaced_dep --server=" .. testing_paths.fixtures_dir .. "/a_repo" ) assert.has.match("Missing dependencies", output) print(output) assert(run.luarocks_bool("show a_rock 3.0")) end) end) describe("more complex tests", function() if test_env.TYPE_TEST_ENV == "full" then it("luacheck show downloads test_config", function() local output = run.luarocks("build luacheck", { LUAROCKS_CONFIG = testing_paths.testrun_dir .. "/testing_config_show_downloads.lua"} ) assert.is.truthy(output:match("%.%.%.")) end) end it("luasec only deps", function() assert.is_true(run.luarocks_bool("build luasec " .. test_env.openssl_dirs .. " --only-deps")) assert.is_false(run.luarocks_bool("show luasec")) assert.is.falsy(lfs.attributes(testing_paths.testing_sys_rocks .. "/luasec/0.6-1/luasec-0.6-1.rockspec")) end) it("only deps of a given rockspec", function() test_env.run_in_tmp(function(tmpdir) write_file("test-1.0-1.rockspec", [[ package = "test" version = "1.0-1" source = { url = "file://]] .. tmpdir:gsub("\\", "/") .. [[/test.lua" } dependencies = { "a_rock 1.0" } build = { type = "builtin", modules = { test = "test.lua" } } ]], finally) write_file("test.lua", "return {}", finally) assert.is.truthy(run.luarocks_bool("build --server=" .. testing_paths.fixtures_dir .. "/a_repo test-1.0-1.rockspec --only-deps")) assert.is.falsy(lfs.attributes(testing_paths.testing_sys_rocks .. "/test/1.0-1/test-1.0-1.rockspec")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/1.0-1/a_rock-1.0-1.rockspec")) end, finally) end) it("only deps of a given rock", function() test_env.run_in_tmp(function(tmpdir) write_file("test-1.0-1.rockspec", [[ package = "test" version = "1.0-1" source = { url = "file://]] .. tmpdir:gsub("\\", "/") .. [[/test.lua" } dependencies = { "a_rock 1.0" } build = { type = "builtin", modules = { test = "test.lua" } } ]], finally) write_file("test.lua", "return {}", finally) assert.is.truthy(run.luarocks_bool("pack test-1.0-1.rockspec")) assert.is.truthy(lfs.attributes("test-1.0-1.src.rock")) assert.is.truthy(run.luarocks_bool("build --server=" .. testing_paths.fixtures_dir .. "/a_repo test-1.0-1.src.rock --only-deps")) assert.is.falsy(lfs.attributes(testing_paths.testing_sys_rocks .. "/test/1.0-1/test-1.0-1.rockspec")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/a_rock/1.0-1/a_rock-1.0-1.rockspec")) end, finally) end) it("with https", function() assert.is_true(run.luarocks_bool("download --rockspec validate-args 1.5.4-1")) assert.is_true(run.luarocks_bool("install luasec " .. test_env.openssl_dirs)) assert.is_true(run.luarocks_bool("build validate-args-1.5.4-1.rockspec")) assert.is.truthy(run.luarocks("show validate-args")) assert.is.truthy(lfs.attributes(testing_paths.testing_sys_rocks .. "/validate-args/1.5.4-1/validate-args-1.5.4-1.rockspec")) assert.is_true(os.remove("validate-args-1.5.4-1.rockspec")) end) it("fails if given an argument with an invalid patch", function() assert.is_false(run.luarocks_bool("build " .. testing_paths.fixtures_dir .. "/invalid_patch-0.1-1.rockspec")) end) end) describe("rockspec format 3.0 #rs3", function() local tmpdir local olddir before_each(function() tmpdir = get_tmp_path() olddir = lfs.currentdir() lfs.mkdir(tmpdir) lfs.chdir(tmpdir) lfs.mkdir("autodetect") write_file("autodetect/bla.lua", "return {}", finally) write_file("c_module.c", c_module_source, finally) end) after_each(function() if olddir then lfs.chdir(olddir) if tmpdir then lfs.rmdir("autodetect") lfs.rmdir(tmpdir) end end end) it("defaults to build.type == 'builtin'", function() local rockspec = "a_rock-1.0-1.rockspec" test_env.write_file(rockspec, [[ rockspec_format = "3.0" package = "a_rock" version = "1.0-1" source = { url = "file://]] .. testing_paths.fixtures_dir .. [[/a_rock.lua" } description = { summary = "An example rockspec", } dependencies = { "lua >= 5.1" } build = { modules = { build = "a_rock.lua" }, } ]], finally) assert.truthy(run.luarocks_bool("build " .. rockspec)) assert.is.truthy(run.luarocks("show a_rock")) end) it("'builtin' detects lua files if build is not given", function() local rockspec = "autodetect-1.0-1.rockspec" test_env.write_file(rockspec, [[ rockspec_format = "3.0" package = "autodetect" version = "1.0-1" source = { url = "file://autodetect/bla.lua" } description = { summary = "An example rockspec", } dependencies = { "lua >= 5.1" } ]], finally) assert.truthy(run.luarocks_bool("build " .. rockspec)) assert.match("bla.lua", run.luarocks("show autodetect")) end) it("'builtin' synthesizes external_dependencies if not given but a library is given in build", function() local rockspec = "autodetect-1.0-1.rockspec" test_env.write_file(rockspec, [[ rockspec_format = "3.0" package = "autodetect" version = "1.0-1" source = { url = "file://c_module.c" } description = { summary = "An example rockspec", } dependencies = { "lua >= 5.1" } build = { modules = { c_module = { sources = "c_module.c", libraries = "inexistent_library", } } } ]], finally) assert.match("INEXISTENT_LIBRARY_DIR", run.luarocks("build " .. rockspec)) end) end) describe("#mock external dependencies", function() lazy_setup(function() test_env.mock_server_init() end) lazy_teardown(function() test_env.mock_server_done() end) it("fails when missing external dependency", function() test_env.run_in_tmp(function(tmpdir) write_file("missing_external-0.1-1.rockspec", [[ package = "missing_external" version = "0.1-1" source = { url = "https://example.com/build.lua" } external_dependencies = { INEXISTENT = { library = "inexistentlib*", header = "inexistentheader*.h", } } dependencies = { "lua >= 5.1" } build = { type = "builtin", modules = { build = "build.lua" } } ]], finally) assert.is_false(run.luarocks_bool("build missing_external-0.1-1.rockspec INEXISTENT_INCDIR=\"/invalid/dir\"")) end, finally) end) it("builds with external dependency", function() local rockspec = testing_paths.fixtures_dir .. "/with_external_dep-0.1-1.rockspec" local foo_incdir = testing_paths.fixtures_dir .. "/with_external_dep" assert.is_truthy(run.luarocks_bool("build " .. rockspec .. " FOO_INCDIR=\"" .. foo_incdir .. "\"")) assert.is.truthy(run.luarocks("show with_external_dep")) end) end) describe("#build_dependencies", function() it("builds with a build dependency", function() assert(run.luarocks_bool("build has_build_dep --server=" .. testing_paths.fixtures_dir .. "/a_repo" )) assert(run.luarocks_bool("show has_build_dep 1.0")) assert(run.luarocks_bool("show a_build_dep 1.0")) end) end) end) test_env.unload_luarocks() test_env.setup_specs() local cfg = require("luarocks.core.cfg") local deps = require("luarocks.deps") local fs = require("luarocks.fs") local path = require("luarocks.path") local rockspecs = require("luarocks.rockspecs") local build_builtin = require("luarocks.build.builtin") describe("LuaRocks build #unit", function() local runner lazy_setup(function() runner = require("luacov.runner") runner.init(testing_paths.testrun_dir .. "/luacov.config") runner.tick = true cfg.init() fs.init() deps.check_lua_incdir(cfg.variables) deps.check_lua_libdir(cfg.variables) end) lazy_teardown(function() runner.shutdown() end) describe("build.builtin", function() describe("builtin.autodetect_external_dependencies", function() it("returns false if the given build table has no external dependencies", function() local build_table = { type = "builtin" } assert.falsy(build_builtin.autodetect_external_dependencies(build_table)) end) it("returns a table of the external dependencies found in the given build table", function() local build_table = { type = "builtin", modules = { module1 = { libraries = { "foo1", "foo2" }, }, module2 = { libraries = "foo3" }, } } local extdeps = build_builtin.autodetect_external_dependencies(build_table) assert.same(extdeps["FOO1"], { library = "foo1" }) assert.same(extdeps["FOO2"], { library = "foo2" }) assert.same(extdeps["FOO3"], { library = "foo3" }) end) it("adds proper include and library dirs to the given build table", function() local build_table build_table = { type = "builtin", modules = { module1 = { libraries = "foo" } } } build_builtin.autodetect_external_dependencies(build_table) assert.same(build_table, { type = "builtin", modules = { module1 = { libraries = "foo", incdirs = { "$(FOO_INCDIR)" }, libdirs = { "$(FOO_LIBDIR)" } } } }) build_table = { type = "builtin", modules = { module1 = { libraries = "foo", incdirs = { "INCDIRS" } } } } build_builtin.autodetect_external_dependencies(build_table) assert.same(build_table, { type = "builtin", modules = { module1 = { libraries = "foo", incdirs = { "INCDIRS" }, libdirs = { "$(FOO_LIBDIR)" } } } }) build_table = { type = "builtin", modules = { module1 = { libraries = "foo", libdirs = { "LIBDIRS" } } } } build_builtin.autodetect_external_dependencies(build_table) assert.same(build_table, { type = "builtin", modules = { module1 = { libraries = "foo", incdirs = { "$(FOO_INCDIR)" }, libdirs = { "LIBDIRS" } } } }) build_table = { type = "builtin", modules = { module1 = { libraries = "foo", incdirs = { "INCDIRS" }, libdirs = { "LIBDIRS" } } } } build_builtin.autodetect_external_dependencies(build_table) assert.same(build_table, { type = "builtin", modules = { module1 = { libraries = "foo", incdirs = { "INCDIRS" }, libdirs = { "LIBDIRS" } } } }) end) end) describe("builtin.autodetect_modules", function() local tmpdir local olddir before_each(function() tmpdir = get_tmp_path() olddir = lfs.currentdir() lfs.mkdir(tmpdir) lfs.chdir(tmpdir) fs.change_dir(tmpdir) end) after_each(function() if olddir then lfs.chdir(olddir) fs.change_dir(olddir) if tmpdir then lfs.rmdir(tmpdir) end end end) local libs = { "foo1", "foo2" } local incdirs = { "$(FOO1_INCDIR)", "$(FOO2_INCDIR)" } local libdirs = { "$(FOO1_LIBDIR)", "$(FOO2_LIBDIR)" } it("returns a table of the modules having as location the current directory", function() write_file("module1.lua", "", finally) write_file("module2.c", "", finally) write_file("module3.c", "int luaopen_my_module()", finally) write_file("test.lua", "", finally) write_file("tests.lua", "", finally) local modules = build_builtin.autodetect_modules(libs, incdirs, libdirs) assert.same(modules, { module1 = "module1.lua", module2 = { sources = "module2.c", libraries = libs, incdirs = incdirs, libdirs = libdirs }, my_module = { sources = "module3.c", libraries = libs, incdirs = incdirs, libdirs = libdirs } }) end) local test_with_location = function(location) lfs.mkdir(location) lfs.mkdir(location .. "/dir1") lfs.mkdir(location .. "/dir1/dir2") write_file(location .. "/module1.lua", "", finally) write_file(location .. "/dir1/module2.c", "", finally) write_file(location .. "/dir1/dir2/module3.c", "int luaopen_my_module()", finally) write_file(location .. "/test.lua", "", finally) write_file(location .. "/tests.lua", "", finally) local modules = build_builtin.autodetect_modules(libs, incdirs, libdirs) assert.same(modules, { module1 = location .. "/module1.lua", ["dir1.module2"] = { sources = location .. "/dir1/module2.c", libraries = libs, incdirs = incdirs, libdirs = libdirs }, my_module = { sources = location .. "/dir1/dir2/module3.c", libraries = libs, incdirs = incdirs, libdirs = libdirs } }) lfs.rmdir(location .. "/dir1/dir2") lfs.rmdir(location .. "/dir1") lfs.rmdir(location) end it("returns a table of the modules having as location the src directory", function() test_with_location("src") end) it("returns a table of the modules having as location the lua directory", function() test_with_location("lua") end) it("returns as second and third argument tables of the bin files and copy directories", function() lfs.mkdir("doc") lfs.mkdir("docs") lfs.mkdir("samples") lfs.mkdir("tests") lfs.mkdir("bin") write_file("bin/binfile", "", finally) local _, install, copy_directories = build_builtin.autodetect_modules({}, {}, {}) assert.same(install, { bin = { "bin/binfile" } }) assert.same(copy_directories, { "doc", "docs", "samples", "tests" }) lfs.rmdir("doc") lfs.rmdir("docs") lfs.rmdir("samples") lfs.rmdir("tests") lfs.rmdir("bin") end) end) describe("builtin.run", function() local tmpdir local olddir before_each(function() tmpdir = get_tmp_path() olddir = lfs.currentdir() lfs.mkdir(tmpdir) lfs.chdir(tmpdir) fs.change_dir(tmpdir) path.use_tree(lfs.currentdir()) end) after_each(function() if olddir then lfs.chdir(olddir) fs.change_dir(olddir) if tmpdir then lfs.rmdir(tmpdir) end end end) it("returns false if the rockspec has no build modules and its format does not support autoextraction", function() local rockspec = { package = "test", version = "1.0-1", source = { url = "http://example.com/test" }, build = {} } rockspecs.from_persisted_table("test-1.0-1.rockspec", rockspec) assert.falsy(build_builtin.run(rockspec)) rockspec.rockspec_format = "1.0" assert.falsy(build_builtin.run(rockspec)) end) it("returns false if lua.h could not be found", function() local rockspec = { package = "c_module", version = "1.0-1", source = { url = "http://example.com/c_module" }, build = { type = "builtin", modules = { c_module = "c_module.c" } } } write_file("c_module.c", c_module_source, finally) rockspecs.from_persisted_table("c_module-1.0-1.rockspec", rockspec) rockspec.variables = { LUA_INCDIR = "invalid" } assert.falsy(build_builtin.run(rockspec)) end) it("returns false if the build fails", function() local rockspec = { package = "c_module", version = "1.0-1", source = { url = "http://example.com/c_module" }, build = { type = "builtin", modules = { c_module = "c_module.c" } } } write_file("c_module.c", c_module_source .. "invalid", finally) rockspecs.from_persisted_table("c_module-1.0-1.rockspec", rockspec) assert.falsy(build_builtin.run(rockspec)) end) it("returns true if the build succeeds with C module", function() local rockspec = { package = "c_module", version = "1.0-1", source = { url = "http://example.com/c_module" }, build = { type = "builtin", modules = { c_module = "c_module.c" } } } write_file("c_module.c", c_module_source, finally) rockspecs.from_persisted_table("c_module-1.0-1.rockspec", rockspec) assert.truthy(build_builtin.run(rockspec)) assert.truthy(lfs.attributes("lib/luarocks/rocks-" .. test_env.lua_version .. "/c_module/1.0-1/lib/c_module." .. test_env.lib_extension)) end) it("returns true if the build succeeds with Lua module", function() local rockspec = { rockspec_format = "1.0", package = "test", version = "1.0-1", source = { url = "http://example.com/test" }, build = { type = "builtin", modules = { test = "test.lua" } } } write_file("test.lua", "return {}", finally) rockspecs.from_persisted_table("test-1.0-1.rockspec", rockspec) assert.truthy(build_builtin.run(rockspec)) assert.truthy(lfs.attributes("lib/luarocks/rocks-" .. test_env.lua_version .. "/test/1.0-1/lua/test.lua")) end) it("automatically extracts the modules and libraries if they are not given and builds against any external dependencies", function() local ssllib = "ssl" if test_env.TEST_TARGET_OS == "windows" then if test_env.MINGW then ssllib = "eay32" else ssllib = "ssleay32" end end local rockspec = { rockspec_format = "3.0", package = "c_module", version = "1.0-1", source = { url = "http://example.com/c_module" }, external_dependencies = { OPENSSL = { library = ssllib -- Use OpenSSL since it is available on all testing platforms } }, build = { type = "builtin" } } write_file("c_module.c", c_module_source, finally) rockspecs.from_persisted_table("c_module-1.0-1.rockspec", rockspec) rockspec.variables["OPENSSL_INCDIR"] = test_env.OPENSSL_INCDIR rockspec.variables["OPENSSL_LIBDIR"] = test_env.OPENSSL_LIBDIR assert.truthy(build_builtin.run(rockspec)) end) it("returns false if any external dependency is missing", function() local rockspec = { rockspec_format = "3.0", package = "c_module", version = "1.0-1", source = { url = "https://example.com/c_module" }, external_dependencies = { EXTDEP = { library = "missing" } }, build = { type = "builtin" } } write_file("c_module.c", c_module_source, finally) rockspecs.from_persisted_table("c_module-1.0-1.rockspec", rockspec) rockspec.variables["EXTDEP_INCDIR"] = lfs.currentdir() rockspec.variables["EXTDEP_LIBDIR"] = lfs.currentdir() assert.falsy(build_builtin.run(rockspec)) end) end) end) describe("#unix build from #git", function() local git lazy_setup(function() git = git_repo.start() end) lazy_teardown(function() if git then git:stop() end end) it("using --branch", function() write_file("my_branch-1.0-1.rockspec", [[ rockspec_format = "3.0" package = "my_branch" version = "1.0-1" source = { url = "git://localhost/testrock" } ]], finally) assert.is_false(run.luarocks_bool("build --branch unknown-branch ./my_branch-1.0-1.rockspec")) assert.is_true(run.luarocks_bool("build --branch test-branch ./my_branch-1.0-1.rockspec")) end) end) end)
local require = GLOBAL.require require("extended")
--[[ Copyright (C) 2017-2020 The DMLab2D Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] local io = require 'io' local paths = {} local function _join(base, path) if path:sub(1, 1) == '/' then return path elseif base:sub(#base) == '/' then return base .. path else return base .. '/' .. path end end --[[ Joins a path with a base directory. (Honours leading slash to ignore base directory) * paths.join('base', 'path') => 'base/path' * paths.join('base/', 'path') => 'base/path' * paths.join('base', '/path') => '/path' * paths.join('base/', '/path') => '/path' * paths.join('a', 'b', 'c', 'd') => 'a/b/c/d' ]] function paths.join(base, ...) for i = 1, select('#', ...) do base = _join(base, select(i, ...)) end return base end --[[ Returns directory name of path including trailing slash. * paths.dirname('file') => '' * paths.dirname('/path2') => '/' * paths.dirname('path1/path2') => 'path1/' * paths.dirname('path1/path2/') => 'path1/path2/' * paths.dirname('/path1/path2') => '/path1/' * paths.dirname('/path1/path2/') => '/path1/path2/' * paths.dirname('~/path1/path2/') => '~/path1/path2/' * paths.dirname('~/path1/path2') => '~/path1/' ]] function paths.dirname(path) return path:match(".-/.-") and path:gsub("(.*/)(.*)", "%1") or '' end -- Returns whether a file exists. (Must be readable.) function paths.fileExists(path) local file = io.open(path, "r") if file ~= nil then io.close(file) return true else return false end end return paths
--[[ Copyright (c) 2019 igor725, scaledteam released under The MIT license http://opensource.org/licenses/MIT ]] return function(player, x, y, z, mode, id) local world = getWorld(player) local cblock = world:getBlock(x, y, z) if mode == 0x00 then id = 0 end local cantPlace = not player.isSpawned if world:isReadOnly()then player:sendMessage(WORLD_RO, MT_ANNOUNCE) cantPlace = true end if not cantPlace and cblock == -1 then cblock = 1 cantPlace = true end if not cantPlace then cantPlace = not isValidBlockID(id) end if not cantPlace then cantPlace = hooks:call('prePlayerPlaceBlock', player, x, y, z, id) end if not cantPlace and player.onPlaceBlock then cantPlace = player.onPlaceBlock(x, y, z, id) end if not cantPlace then if world:setBlock(x, y, z, id, player)then hooks:call('postPlayerPlaceBlock', player, x, y, z, id, cblock) else cantPlace = true end end if cantPlace then cblock = cblock or 1 player:sendPacket(false, 0x06, x, y, z, cblock) end end
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") ENT.SeizeReward = LCD.Config.SeizeReward local PreMoney function ENT:Initialize() self.PrinterStoredMoney = LCD.Config.StartingStoredMoney self:SetNWInt( "StoredMoney", PrinterStoredMoney ) self.PrinterTemperature = LCD.Config.StartingTemperature self:SetNWInt( "StoredTemp", PrinterTemperature ) self.PrinterExplosion = 0 self:SetNWInt( "StoredExpl", PrinterExplosion ) self.PrinterCoolant = LCD.Config.StartingCoolant self:SetNWInt( "StoredCool", PrinterCoolant ) self.PrinterFan = LCD.Config.StartingFan self:SetNWBool( "StoredFan", PrinterFan ) self.PrinterScreen = LCD.Config.StartingScreen self:SetNWBool( "StoredScreen", PrinterScreen ) self.PrinterStorage = LCD.Config.StartingStorage self:SetNWBool( "StoredStorage", PrinterStorage ) self.PrinterArmor = LCD.Config.StartingArmor self:SetNWBool( "StoredArmor", PrinterArmor ) self.PrinterMode = 0 self.id = self:GetCreationID() self:SetModel("models/props_c17/consolebox01a.mdl") self:SetUseType(SIMPLE_USE) self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) local phys = self:GetPhysicsObject() phys:Wake() self.sparking = false if self.PrinterArmor == false then self.damage = LCD.Config.HitPoints else self.damage = LCD.Config.ArmorHitPoints end self.IsMoneyPrinter = true timer.Create( "PrinterCountdown1-" .. self.id, math.random(LCD.Config.PrintTimer1,LCD.Config.PrintTimer2), 1, function() PreMoney(self) end) self.sound = CreateSound(self, Sound("ambient/levels/labs/equipment_printer_loop1.wav")) self.sound:SetSoundLevel(52) self.sound:PlayEx(1, 100) end function ENT:OnTakeDamage(dmg) if self.burningup then return end self.damage = (self.damage or 100) - dmg:GetDamage() if self.damage <= 0 then local rnd = math.random(1, 10) if rnd < 3 then self:BurstIntoFlames() else self:Destruct() self:Remove() end end end -- the explosion stuff function ENT:Destruct() local vPoint = self:GetPos() local effectdata = EffectData() effectdata:SetStart(vPoint) effectdata:SetOrigin(vPoint) effectdata:SetScale(1) util.Effect("Explosion", effectdata) DarkRP.notify(self:Getowning_ent(), 1, 4, DarkRP.getPhrase("money_printer_exploded")) end function ENT:BurstIntoFlames() DarkRP.notify(self:Getowning_ent(), 0, 4, DarkRP.getPhrase("money_printer_overheating")) self.burningup = true local burntime = math.random(8, 18) self:Ignite(burntime, 0) timer.Simple(burntime, function() if not IsValid(self) then return end self:Fireball() end) end function ENT:Fireball() if not self:IsOnFire() then self.burningup = false return end local dist = math.random(20, 280) -- Explosion radius self:Destruct() for k, v in pairs(ents.FindInSphere(self:GetPos(), dist)) do if not v:IsPlayer() and not v:IsWeapon() and v:GetClass() ~= "predicted_viewmodel" and not v.IsMoneyPrinter then v:Ignite(math.random(5, 22), 0) elseif v:IsPlayer() then local distance = v:GetPos():Distance(self:GetPos()) v:TakeDamage(distance / dist * 100, self, self) end end self:Remove() end function ENT:TestExplosion() if not IsValid(self) or self:IsOnFire() then return end self.explchance = math.random(1,100) if self.explchance <= self.PrinterExplosion then self:BurstIntoFlames() else DarkRP.notify(self:Getowning_ent(), 0, 4, "Your printer is in danger of exploding!") end end -- the money stuff PreMoney = function(ent) if not IsValid(ent) then return end ent.sparking = true ent:EmitSound("buttons/button6.wav") timer.Simple(3, function() if not IsValid(ent) then return end ent:AddMoney() end) end function ENT:AddMoney() if not IsValid(self) or self:IsOnFire() then return end if self.PrinterExplosion > 0 then self:TestExplosion() end if self.PrinterStorage == true then self.effectivestorage = LCD.Config.UpgradeMaximum else self.effectivestorage = LCD.Config.PrintMaximum end if self.PrinterStoredMoney < self.effectivestorage then if self.PrinterMode == 1 then self.PrinterStoredMoney = self.PrinterStoredMoney + math.random(LCD.Config.OverclockerPrintAmount1, LCD.Config.OverclockerPrintAmount2) else self.PrinterStoredMoney = self.PrinterStoredMoney + math.random(LCD.Config.PrintAmount1, LCD.Config.PrintAmount2) end self:SetNWInt( "StoredMoney", self.PrinterStoredMoney ) self:EmitSound("buttons/button4.wav") if self.PrinterMode == 1 then if self.PrinterFan == false then self.PrinterTemperature = self.PrinterTemperature + math.random(LCD.Config.OverclockerHeatNoFan1, LCD.Config.OverclockerHeatNoFan2) else self.PrinterTemperature = self.PrinterTemperature + math.random(LCD.Config.OverclockerHeatFan1, LCD.Config.OverclockerHeatFan2) end else if self.PrinterFan == false then self.PrinterTemperature = self.PrinterTemperature + math.random(LCD.Config.HeatNoFan1, LCD.Config.HeatNoFan2) else self.PrinterTemperature = self.PrinterTemperature + math.random(LCD.Config.HeatFan1, LCD.Config.HeatFan2) end end self:SetNWInt( "StoredTemp", self.PrinterTemperature ) else self:EmitSound("buttons/button8.wav") DarkRP.notify(self:Getowning_ent(), 0, 4, "Your money printer is full!") if self.PrinterFan == false then self.PrinterTemperature = self.PrinterTemperature + math.random(LCD.Config.HeatNoFanFull1, LCD.Config.HeatNoFanFull2) else self.PrinterTemperature = self.PrinterTemperature + math.random(LCD.Config.HeatFanFull1, LCD.Config.HeatFanFull2) end self:SetNWInt( "StoredTemp", self.PrinterTemperature ) end self.sparking = false if self.PrinterMode == 1 then timer.Create( "PrinterCountdown2-" .. self.id, math.random(LCD.Config.OverclockerPrintTimer1,LCD.Config.OverclockerPrintTimer2), 1, function() PreMoney(self) end) else timer.Create( "PrinterCountdown2-" .. self.id, math.random(LCD.Config.PrintTimer1,LCD.Config.PrintTimer2), 1, function() PreMoney(self) end) end end function ENT:CreateMoneybag( ply ) if not IsValid(self) or self:IsOnFire() then return end local MoneyPos = self:GetPos() ply:addMoney(self.PrinterStoredMoney) DarkRP.notify(ply, 0, 4, "Withdrew $" .. self.PrinterStoredMoney) self.PrinterStoredMoney = 0 self:SetNWInt( "StoredMoney", self.PrinterStoredMoney ) self:EmitSound("ambient/tones/equip3.wav") end -- the misc stuff function ENT:CoolOff() if self.PrinterCoolant > 0 and self.PrinterTemperature > LCD.Config.CoolingMinTemperature then self.PrinterCoolant = self.PrinterCoolant - LCD.Config.CoolingCoolant self:SetNWInt( "StoredCool", self.PrinterCoolant ) self.PrinterTemperature = self.PrinterTemperature - LCD.Config.CoolingTemp self:SetNWInt( "StoredTemp", self.PrinterTemperature ) end end function ENT:Use( ply ) if self.PrinterStoredMoney > 0 then self:CreateMoneybag( ply ) end end function ENT:Think() self:CoolOff() self.TempIncreaseChance = math.random(1,100) if self.PrinterMode == 1 then if self.PrinterFan == false then if self.TempIncreaseChance > LCD.Config.HeatChanceNoFan then self.PrinterTemperature = self.PrinterTemperature + math.random(LCD.Config.OverclockerHeatAddedFan1, LCD.Config.OverclockerHeatAddedFan2) self:SetNWInt( "StoredTemp", self.PrinterTemperature ) end else if self.TempIncreaseChance > LCD.Config.HeatChanceFan then self.PrinterTemperature = self.PrinterTemperature + math.random(LCD.Config.OverclockerHeatAddedNoFan1, LCD.Config.OverclockerHeatAddedNoFan2) self:SetNWInt( "StoredTemp", self.PrinterTemperature ) end end else if self.PrinterFan == false then if self.TempIncreaseChance > LCD.Config.HeatChanceNoFan then self.PrinterTemperature = self.PrinterTemperature + math.random(LCD.Config.HeatAddedFan1, LCD.Config.HeatAddedFan2) self:SetNWInt( "StoredTemp", self.PrinterTemperature ) end else if self.TempIncreaseChance > LCD.Config.HeatChanceFan then self.PrinterTemperature = self.PrinterTemperature + math.random(LCD.Config.HeatAddedNoFan1, LCD.Config.HeatAddedNoFan2) self:SetNWInt( "StoredTemp", self.PrinterTemperature ) end end end if self.PrinterTemperature >= 65 then self.PrinterExplosion = math.floor(((self.PrinterTemperature-65)/3.5)^2) self:SetNWInt( "StoredExpl", self.PrinterExplosion ) else self.PrinterExplosion = 0 self:SetNWInt( "StoredExpl", self.PrinterExplosion ) end if self:WaterLevel() > 0 then self:Destruct() self:Remove() return end if (timer.Exists( "PrinterCountdown1-" .. self.id )) then local count1 = math.floor(timer.TimeLeft( "PrinterCountdown1-" .. self.id )) if count1 <= 9999 then self:SetNWInt( "StoredCount", count1 ) else self:SetNWInt( "StoredCount", 0 ) end else local count2 = math.floor(timer.TimeLeft( "PrinterCountdown2-" .. self.id )) if count2 <= 9999 then self:SetNWInt( "StoredCount", count2 ) else self:SetNWInt( "StoredCount", 0 ) end end if not self.sparking then return end local effectdata = EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetMagnitude(1) effectdata:SetScale(1) effectdata:SetRadius(2) util.Effect("Sparks", effectdata) end function ENT:PhysicsCollide(data, phys) if self.PrinterFan == false then if (data.HitEntity:GetClass() == "lcd_fan") then timer.Simple(0, function() if (IsValid(self)) then data.HitEntity:Remove() end end) self.PrinterFan = true self:SetNWBool( "StoredFan", self.PrinterFan ) self:EmitSound("buttons/lever8.wav") self.soundfan = CreateSound(self, Sound("ambient/tones/fan2_loop.wav")) self.soundfan:SetSoundLevel(52) self.soundfan:PlayEx(1, 100) end end if self.PrinterScreen == false then if (data.HitEntity:GetClass() == "lcd_screen") then timer.Simple(0, function() if (IsValid(self)) then timer.Simple(0, function() data.HitEntity:Remove() end) end end) self.PrinterScreen = true self:SetNWBool( "StoredScreen", self.PrinterScreen ) self:EmitSound("buttons/lever8.wav") end end if self.PrinterStorage == false then if (data.HitEntity:GetClass() == "lcd_storage") then timer.Simple(0, function() if (IsValid(self)) then data.HitEntity:Remove() end end) self.PrinterStorage = true self:SetNWBool( "StoredStorage", self.PrinterStorage ) self:EmitSound("buttons/lever8.wav") end end if self.PrinterArmor == false then if (data.HitEntity:GetClass() == "lcd_armor") then timer.Simple(0, function() if (IsValid(self)) then data.HitEntity:Remove() end end) self.PrinterArmor = true self:SetNWBool( "StoredArmor", self.PrinterArmor ) self:EmitSound("buttons/lever8.wav") self.damage = LCD.Config.ArmorHitPoints end end if (data.HitEntity:GetClass() == "lcd_coolant") and self.PrinterCoolant <= LCD.Config.CoolantAdded then timer.Simple(0, function() if (IsValid(self)) then data.HitEntity:Remove() end end) self.PrinterCoolant = self.PrinterCoolant + LCD.Config.CoolantAdded self:SetNWInt( "StoredCool", self.PrinterCoolant ) elseif (data.HitEntity:GetClass() == "lcd_coolant") and self.PrinterCoolant > 20 - LCD.Config.CoolantAdded and self.PrinterCoolant < 20 then timer.Simple(0, function() if (IsValid(self)) then data.HitEntity:Remove() end end) self.PrinterCoolant = self.PrinterCoolant + (20 - self.PrinterCoolant) self:SetNWInt( "StoredCool", self.PrinterCoolant ) end if self.PrinterMode == 0 then if (data.HitEntity:GetClass() == "lcd_overclocker") then timer.Simple(0, function() if (IsValid(self)) then data.HitEntity:Remove() end end) self.PrinterMode = 1 self:SetNWInt( "StoredMode", self.PrinterMode ) self:EmitSound("buttons/lever8.wav") end end end function ENT:OnRemove() if self.sound then self.sound:Stop() end if self.soundfan then self.soundfan:Stop() end end
mapFields = require "lib/mapFields" mapQuests = require "lib/mapQuests" quest = target.get_quest(mapQuests.getID("KiddnapingOfCamila")) -- Evan only target.field = mapFields.getID("GolemsTempleEntrance") if quest.state == mapQuests.getState("Perform") then quest.complete() -- pi.playerMessage(5, "Camila rescued!"); target.sp = target.sp + 1 end
-- define standart values number_of_leds = 95; -- set number of leds in strip normal_brightness=150; -- set normal brightness from 0 to 255 max_brightness=255; -- set max brightness from 0 to 255 -- --------------------------------------------------------- -- Wifi settings static_ip=true; -- allows to use static ip; set it to false if you don't want to use static ip ssid = 'SweetHome' -- name of the acces point password = 'eltechsux'-- password -- static ip parameters ip_config = { ip = "192.168.0.120", netmask = "255.255.255.0", gateway = "192.168.0.1" } -- initial values speed = 150; color = 100; saturation=255; brightness = 100; mode = 0; channel_average=1; mode_11_max_brightness=max_brightness;
Ambi.General.Utility = Ambi.General.Utility or {} setmetatable( Ambi.General.Utility, { __index = util } ) -- ------------------------------------------------------------------------------------- local A = Ambi.General local player, string, ipairs, table, tostring, os, isstring = player, string, ipairs, table, tostring, os, isstring local surface, IsValid, tonumber = surface, IsValid, tonumber local math, ents, bit, Vector = math, ents, bit, Vector -- ------------------------------------------------------------------------------------- function util.FindPlayer( sArg, fData, bOnlyHumans ) if not fData then A.Error( 'Ambition.Utility', 'Not specified fData' ) return false end sArg = sArg or '' sArs = string.lower( sArgs ) local tab, players = bOnlyHumans and player.GetHumans() or player.GetAll(), {} for _, ply in ipairs( tab ) do local data = string.lower( tostring( fData( ply ) ) ) if string.find( data, sArg ) then table.insert( players, ply ) end if ( data == sArg ) then return ply end end if ( #players == 0 ) or ( #players > 1 ) then return false end return players[ 1 ] end function util.GetRussianDate( nDate ) return os.date( '%d.%m.%Y', nDate ) end function util.GetTextSizeX( sText, sFont ) if not CLIENT then return end surface.SetFont( sFont ) local x, _ = surface.GetTextSize( sText ) return x end function util.GetTextSizeY( sText, sFont ) if not CLIENT then return end surface.SetFont( sFont ) local _, y = surface.GetTextSize( sText ) return y end function util.GetFrontPos( eObj, nMultiply ) if not IsValid( eObj ) then return end -- TODO: fix pos, then Entity spawned with nMultiply to Wall or behind Wall local shoot_pos = eObj:GetShootPos() local aim_pos = eObj:GetAimVector() return shoot_pos + ( aim_pos * ( nMultiply or 70 ) ) end function util.GetFrontPosNew( ePly, eObj, nMultiply ) if not IsValid( eObj ) then return end if not IsValid( ePly ) then return end local tr = ePly:GetEyeTrace() local hitpos = tr.HitPos local pos = ePly:GetPos() local dis = hitpos - pos return hitpos - ( dis ) + Vector( ePly:GetAimVector().x, ePly:GetAimVector().y, 0 ) * ( eObj:BoundingRadius() * 1.5 ) end function util.UnpackColor( cColor ) return cColor.r, cColor.g, cColor.b, cColor.a end -- ------------------------------------------------------------------------------------- -- by Odic-Force function util.ClassIsNearby( vPos, sClass, nRange ) -- Source: https://github.com/Odic-Force/GMStranded/blob/master/gamemodes/GMStranded/gamemode/init.lua#L603 -- Refactored this code if not sClass or not isstring( sClass ) then return end nRange = nRange or 1 vPos = vPos or Vector( 0, 0, 0 ) for k, v in pairs( ents.FindInSphere( vPos, nRange ) ) do if ( v:GetClass() == sClass ) then local dist = v:GetPos():Distance( vPos ) if ( dist <= nRange ) then return true end end end return false end -- by Odic-Force local VECTOR = Vector( 0, 0, 1 ) -- constant for IsInWater function util.IsInWater( vPos ) -- Source: https://github.com/Odic-Force/GMStranded/blob/master/gamemodes/GMStranded/gamemode/init.lua#L614 vPos = vPos or Vector( 0, 0, 0 ) local trace = {} trace.start = vPos trace.endpos = vPos + VECTOR trace.mask = bit.bor( MASK_WATER, MASK_SOLID ) return util.TraceLine( trace ).Hit end -- ------------------------------------------------------------------------------------- -- by SuperiorServers -- Source: https://github.com/SuperiorServers/dash/blob/master/lua/dash/extensions/util.lua -- Tracer flags TRACER_FLAG_WHIZ = 0x0001 TRACER_FLAG_USEATTACHMENT = 0x0002 TRACER_DONT_USE_ATTACHMENT = -1 function util.Tracer( vStart, vEnd, eObj, nAttachment, nVel, bWhiz, sCustomTracerName, nParticleID ) -- https://github.com/SuperiorServers/dash/blob/master/lua/dash/extensions/util.lua#L11 vStart, vEnd = vStart or Vector( 0, 0, 0 ), vEnd or Vector( 0, 0, 0 ) local data = EffectData() data:SetStart( vStart ) data:SetOrigin( vEnd ) data:SetEntity( eObj ) data:SetScale( nVel ) if ( nParticleID ~= nil ) then data:SetHitBox( nParticleID ) end local fFlags = data:GetFlags() if bWhiz then fFlags = bit.bor( fFlags, TRACER_FLAG_WHIZ ) end if ( nAttachment ~= TRACER_DONT_USE_ATTACHMENT ) then fFlags = bit.bor( fFlags, TRACER_FLAG_USEATTACHMENT ) data:SetAttachment( nAttachment ) end data:SetFlags(fFlags) -- Fire it off if pCustomTracerName then util.Effect( sCustomTracerName, data) else util.Effect( 'Tracer', data ) end end function util.FindHullIntersection( tTab, tTrace ) -- https://github.com/SuperiorServers/dash/blob/master/lua/dash/extensions/util.lua#L45 if not tTab or not istable( tTab ) then A.Error( 'Ambition.Utility', 'FindHullIntersection | tTab is not selected!' ) return end if not tTrace or not istable( tTab ) then A.Error( 'Ambition.Utility', 'FindHullIntersection | tTrace is not selected!' ) return end local iDist = 1e12 tTab.output = nil local vSrc = tTab.start local vHullEnd = vSrc + ( tTrace.HitPos - vSrc ) * 2 tTab.endpos = vHullEnd local tBounds = { tTab.mins, tTab.maxs } local trTemp = util.TraceLine( tTab ) if (trTemp.Fraction ~= 1) then table.CopyFromTo( trTemp, tTrace ) return tTrace end local trOutput for i = 1, 2 do for j = 1, 2 do for k = 1, 2 do tTab.endpos = Vector( vHullEnd.x + tBounds[i].x, vHullEnd.y + tBounds[j].y, vHullEnd.z + tBounds[k].z ) local trTemp = util.TraceLine( tTab ) if ( trTemp.Fraction ~= 1 ) then local iHitDistSqr = ( trTemp.HitPos - vSrc ):LengthSqr() if ( iHitDistSqr < iDist ) then trOutput = trTemp iDist = iHitDistSqr end end end end end if trOutput then table.CopyFromTo( trOutput, tTrace ) end return tTrace end local ents_FindInSphere = ents.FindInSphere local util_PointContents = util.PointContents local BADPOINTS = { [CONTENTS_SOLID] = true, [CONTENTS_MOVEABLE] = true, [CONTENTS_LADDER] = true, [CONTENTS_PLAYERCLIP] = true, [CONTENTS_MONSTERCLIP] = true, } local function isempty( vPos, nRange ) if BADPOINTS[ util_PointContents( vPos ) ] then return false end local entities = ents_FindInSphere( vPos or Vector( 0, 0, 0 ), nRange or 1 ) for i = 1, #entities do if ( entities[ i ]:GetClass() == 'prop_physics' ) or ( entities[ i ]:IsPlayer() and entities[ i ]:Alive() ) then return false end end return true end function util.FindEmptyPos( vPos, nRange, nSteps ) -- https://github.com/SuperiorServers/dash/blob/master/lua/dash/extensions/util.lua#L117 vPos = vPos or Vector( 0, 0, 0 ) nRange = nRange or 0 nSteps = nSteps or 1 if isempty( vPos, nRange ) then return vPos end for i = 1, nSteps do local step = ( i * 50 ) if isempty( Vector( vPos.x + step, vPos.y, vPos.z ), nRange ) then vPos.x = vPos.x + step return vPos elseif isempty( Vector( vPos.x, vPos.y + step, vPos.z ), nRange ) then vPos.y = vPos.y + step return vPos elseif isempty( Vector( vPos.x, vPos.y, vPos.z + step ), nRange ) then vPos.z = vPos.z + step return vPos end end return vPos end -- ------------------------------------------------------------------------------------- if CLIENT then -- Source: https://github.com/SuperiorServers/dash/blob/master/lua/dash/extensions/client/util.lua local Material = Material local name = GetConVar( 'sv_skyname' ):GetString() local AREAS = { 'lf', 'ft', 'rt', 'bk', 'dn', 'up' } local TEXTURES = { Material( 'skybox/'.. name .. 'lf' ), Material( 'skybox/'.. name .. 'ft' ), Material( 'skybox/'.. name .. 'rt' ), Material( 'skybox/'.. name .. 'bk' ), Material( 'skybox/'.. name .. 'dn' ), Material( 'skybox/'.. name .. 'up' ), } function util.SetSkybox( sSkybox ) -- Thanks someone from some fp post I cant find sSkybox = sSkybox or 'painted' for i = 1, 6 do TEXTURES[ i ]:SetTexture( '$basetexture', Material( 'skybox/' .. sSkybox .. AREAS[ i ] ):GetTexture( '$basetexture' ) ) end end end
--globals PYRITION.MediaCommands = {} --local functions local function execute_media(command_data, ply, arguments, arguments_string) hook.Call("PyritionConsoleRunMediatedCommand", PYRITION, ply, command_data.Command, arguments, arguments_string) end local function has_flag(flags, flag) return bit.band(flags, flag) == flag end local function read_media_command() local command = net.ReadString() local command_data if net.ReadBool() then command_data = {net.ReadBool()} repeat local sub_command, sub_command_data = read_media_command() command_data[sub_command] = sub_command_data until not net.ReadBool() else command_data = true end return command, command_data end --pyrition functions function PYRITION:PyritionConsoleCompleteCommand(command, arguments) local arguments = arguments and string.Split(string.TrimLeft(arguments), " ") or false local partial = arguments[1] or "" local root_command = PYRITION.Commands[partial] or false if istable(root_command) and root_command.Tree then local completes = {} local current = root_command.Tree partial = "" local prefix = "pyrition " .. table.remove(arguments, 1) for index, branch in ipairs(arguments) do local tree = current[branch] if istable(tree) then current = tree prefix = prefix .. " " .. branch else partial = branch break end end for branch, branch_data in pairs(current) do if branch == 1 then if isfunction(branch_data) then table.insert(completes, prefix) end elseif string.StartWith(branch, partial) then table.insert(completes, prefix .. " " .. branch) end end return completes else local completes = {} for root_command, command_data in pairs(PYRITION.Commands) do if string.StartWith(root_command, partial) then table.insert(completes, "pyrition " .. root_command) end end return completes end return self:PyritionLanguageFormat("pyrition.insults.autocomplete") end function PYRITION:PyritionConsoleExecuteCommand(ply, command_data, command, arguments, arguments_string) print(ply, command_data, command, arguments, arguments_string) if isbool(command_data) then hook.Call("PyritionConsoleRunMediatedCommand", PYRITION, ply, command, arguments, arguments_string) else command_data:Execute(ply, arguments, arguments_string) end end function PYRITION:PyritionConsoleInitializeCommand(file_path, command, command_data) return has_flag(command_data.Realm, PYRITION_CLIENT) end function PYRITION:PyritionConsoleRunMediatedCommand(ply, command, arguments, arguments_string) net.Start("pyrition_console") net.WriteString(command) if #arguments > 0 then local passed = false net.WriteBool(true) net.WriteString(arguments_string) for index, argument in ipairs(arguments) do if passed then net.WriteBool(true) else passed = true end net.WriteString(argument) end net.WriteBool(false) else net.WriteBool(false) end net.SendToServer() end --commands concommand.Add("pyrition", function(...) --more? hook.Call("PyritionConsoleRunCommand", PYRITION, ...) end, function(...) --more return hook.Call("PyritionConsoleCompleteCommand", PYRITION, ...) end, hook.Call(PyritionLanguageFormat, PYRITION, "pyrition.commands")) --net net.Receive("pyrition_console", function(length) repeat local command, command_data = read_media_command(command_data) if istable(command_data) then local has_root_function = command_data[1] if has_root_function then PYRITION.Commands[command] = { true, Command = command, Execute = execute_media, Tree = command_data } else PYRITION.Commands[command] = { Command = command, Execute = execute_media, Tree = command_data } end else PYRITION.Commands[command] = command_data end PYRITION.MediaCommands[command] = command_data until not net.ReadBool() end) --post hook.Call("PyritionConsoleLoadCommands", PYRITION, "pyrition/console/commands/") --debug --[[ local function debug_detour(library, key) local old_function = library[key .. "X_Pyrition"] or library[key] library[key .. "X_Pyrition"] = old_function library[key] = function(...) local returns = {old_function(...)} print("debug " .. key, unpack(returns)) return unpack(returns) end end debug_detour(net, "ReadBool") debug_detour(net, "ReadString") debug_detour(net, "ReadUInt") --]]
-- we need to require these before fire.save_the_world(), to prevent crashes require "cpml" require "iqm" require "love3d".import(false) local anchor = require "anchor" local fire = require "fire" fire.save_the_world() _G.EVENT = require "talkback".new() _G.SCENE = require "gamestate" function love.load(args) for _, v in pairs(args) do if v == "--debug" then _G.FLAGS.debug_mode = true end if v == "--hud" then _G.FLAGS.show_perfhud = true end end anchor:set_overscan(0.1) anchor:update() _G.SCENE.registerEvents { "update", "keypressed", "mousepressed", "mousereleased", "mousemoved", "wheelmoved", "touchpressed", "touchreleased", "touchmoved" } _G.DEFAULT_PREFERENCES = { fullscreen = false, master_volume = 0.50, bgm_volume = 0.40, sfx_volume = 0.90, language = "en" } _G.PREFERENCES = {} -- Load preferences if love.filesystem.isFile("preferences.json") then local json = require "dkjson" local file = love.filesystem.read("preferences.json") local decode = json.decode(file) for k, v in pairs(decode) do _G.PREFERENCES[k] = v end else for k, v in pairs(_G.DEFAULT_PREFERENCES) do _G.PREFERENCES[k] = v end end love.window.setFullscreen(_G.PREFERENCES.fullscreen) _G.SCENE.switch(require("scenes.splash")()) end function love.update(dt) anchor:update() end local function draw_overscan() love.graphics.setColor(180, 180, 180, 200) love.graphics.setLineStyle("rough") love.graphics.line(anchor:left(), anchor:center_y(), anchor:right(), anchor:center_y()) love.graphics.line(anchor:center_x(), anchor:top(), anchor:center_x(), anchor:bottom()) love.graphics.setColor(255, 255, 255, 255) love.graphics.rectangle("line", anchor:bounds()) end function love.draw() local top = _G.SCENE.current() if not top.draw then fire.print("no draw function on the top screen.", 0, 0, "red") else top:draw() end if _G.FLAGS.show_overscan then draw_overscan() end end
local Ans = select(2, ...); local AuctionList = {}; AuctionList.__index = AuctionList; Ans.AuctionList = AuctionList; local Recycler = AnsCore.API.GroupRecycler; local Utils = AnsCore.API.Utils; AuctionList.selectedEntry = -1; AuctionList.items = {}; AuctionList.rows = {}; AuctionList.style = { rowHeight = 16 }; AuctionList.isBuying = false; AuctionList.isPurchaseReady = false; AuctionList.commodity = nil; local stepTime = 1; local clickTime = time(); local clickCount = 0; local purchaseQueue = {}; function AuctionList:OnLoad(parent) self.parent = parent; self.frame = _G[parent:GetName().."ResultsItems"]; self.commodityConfirm = _G[parent:GetName().."ResultsCommodityConfirm"]; -- get scroll child and set it's size -- since we are using a faux scrollframe -- it does not need to be the size of the total items self.childFrame = _G[self.frame:GetName().."ScrollChildFrame"]; self.childFrame:SetSize(self.frame:GetWidth(), self.frame:GetHeight()); self.style.totalRows = math.floor(self.frame:GetHeight() / self.style.rowHeight); self:RegisterEvents(); self:CreateRows(); end function AuctionList:RegisterEvents() local d = self; if (self.frame) then self.frame:SetScript("OnVerticalScroll", function(f, offset) FauxScrollFrame_OnVerticalScroll(f, offset, d.style.rowHeight, function() d:Refresh() end); end); end end function AuctionList:Buy(index) if (self.frame and #self.items > 0 and index > 0 and index <= #self.items) then local block = self.items[index]; if (block and not self.isBuying and self.commodity == nil) then if (self.isPurchaseReady) then self.isBuying = true; local success, isCommodity = self:Purchase(block); if (not isCommodity and success and block.count <= 0) then Recycler:Recycle(table.remove(self.items, index)); if (self.selectedEntry == index) then self.selectedEntry = -1; end end if (not isCommodity or not success) then self.isBuying = false; end self:Refresh(); end end end end function AuctionList:BuyFirst() if (self.frame and #self.items > 0) then self:Buy(1); end end function AuctionList:BuySelected() if (self.frame and #self.items > 0 and self.selectedEntry > 0) then self:Buy(self.selectedEntry); end end function AuctionList:ItemsExist() return #self.items > 0; end function AuctionList:AddItems(items) for i,v in ipairs(items) do tinsert(self.items, v:Clone()); end table.sort(self.items, function(a,b) return a.percent < b.percent; end); self:Refresh(); end function AuctionList:SetItems(items) wipe(self.items); for i,v in ipairs(items) do tinsert(self.items, v:Clone()); end table.sort(self.items, function(a,b) return a.percent < b.percent; end) self:Refresh(); end function AuctionList:Purchase(block) if (self.commodity ~= nil) then return false, false; end if (block.auctionId ~= nil and not block.isCommodity) then if (GetMoney() >= block.buyoutPrice) then C_AuctionHouse.PlaceBid(block.auctionId, block.buyoutPrice); block.count = block.count - 1; return true, false; end elseif (block.auctionId == nil and block.isCommodity) then if (ANS_GLOBAL_SETTINGS.useCommodityConfirm) then self.commodity = block:Clone(); self.commodityConfirm:Show(); return true, true; elseif (GetMoney() >= block.buyoutPrice) then self.commodity = block:Clone(); self:PurchaseCommodity(self.commodity.count); return true, true; end end return false, false; end function AuctionList:PurchaseCommodity(total) if (self.commodity == nil or total < 1) then return false; end self.commodity.toPurchase = total; if (self.commodity.toPurchase * self.commodity.ppu > GetMoney()) then print("AnS: Not enough gold to purchase "..total.." of "..self.commodity.name); return false; end C_AuctionHouse.StartCommoditiesPurchase(self.commodity.id, self.commodity.toPurchase, self.commodity.ppu); return true; end function AuctionList:ConfirmCommoditiesPurchase(ppu, total) if (self.commodity == nil) then return false; end if (total > self.commodity.ppu * self.commodity.toPurchase) then print("AnS: Updated total price of commodities is higher than original total purchase price."); self:CancelCommoditiesPurchase(true); return false; elseif (ppu * self.commodity.toPurchase > GetMoney()) then print("AnS: You do not have enough gold to purchase everything at the updated price per unit!"); self:CancelCommoditiesPurchase(false); return false; end C_AuctionHouse.ConfirmCommoditiesPurchase(self.commodity.id, self.commodity.toPurchase); return true; end function AuctionList:OnCommondityPurchased(failed) if (self.commodity == nil) then return; end self.isBuying = false; if (not failed) then self:RemoveAuctionAmount(self.commodity, self.commodity.toPurchase); else print("AnS: Failed to buy "..self.commodity.toPurchase.." of "..self.commodity.name); end self.commodity = nil; end function AuctionList:CancelCommoditiesPurchase(remove) if (self.commodity == nil) then return; end self.isBuying = false; C_AuctionHouse.CancelCommoditiesPurchase(); if (remove) then self:RemoveAuction(self.commodity); end self.commodity = nil; end function AuctionList:RemoveAuctionAmount(block, count) for i = 1, #self.items do local item = self.items[i]; if (item.id == block.id and item.link == block.link and item.name == block.name and item.ppu == block.ppu and item.buyoutPrice == block.buyoutPrice and item.count == block.count) then block.count = block.count - count; item.count = item.count - count; if (item.count <= 0) then Recycler:Recycle(table.remove(self.items, i)); if (self.selectedEntry == i) then self.selectedEntry = -1; end end self:Refresh(); return; end end end function AuctionList:RemoveAuction(block) for i = 1, #self.items do local item = self.items[i]; if (item.id == block.id and item.link == block.link and item.name == block.name and item.ppu == block.ppu and item.buyoutPrice == block.buyoutPrice and item.count == block.count) then Recycler:Recycle(table.remove(self.items, i)); if (self.selectedEntry == i) then self.selectedEntry = -1; end self:Refresh(); return; end end end function AuctionList:Click(row, button, down) local id = row:GetID(); if (time() - clickTime > 1) then clickCount = 0; end if (self.selectedEntry ~= id) then clickCount = 0; end self.selectedEntry = id; clickCount = clickCount + 1; local fps = math.floor(GetFramerate()); if (clickCount == 1 and IsControlKeyDown()) then local block = self.items[id]; if (block) then ANS_GLOBAL_SETTINGS.itemBlacklist[block.tsmId] = true; Recycler:Recycle(table.remove(self.items, id)); end self.selectedEntry = -1; clickCount = 0; end if (clickCount == 1 and ANS_GLOBAL_SETTINGS.showDressing) then local block = self.items[id]; if (block) then local itemLink = block.link; if (not block.isCommodity and not block.isPet) then DressUpItemLink(itemLink) end end end if (clickCount == 2) then self:Buy(id); clickCount = 0; end self:Refresh(); clickTime = time(); end function AuctionList:ShowTip(item) local index = item:GetID(); if (self.items[index]) then local auction = self.items[index]; if (auction ~= nil) then local itemLink = auction.link; local count = auction.count; if (itemLink ~= nil) then Utils:ShowTooltip(item, itemLink, count); end end end end function AuctionList:UpdateRow(offset, row) if (offset <= #self.items) then if (not self.items[offset]) then row:Hide(); return; end row:SetID(offset); local auction = self.items[offset]; local itemKey = auction.itemKey; local ppu = auction.ppu; local itemID = auction.id; local ilevel = auction.iLevel; local percent = auction.percent; local count = auction.count; local texture = auction.texture; local quality = auction.quality; local name = auction.name; local itemPrice = _G[row:GetName().."PPU"]; local itemName = _G[row:GetName().."NameText"]; local itemStack = _G[row:GetName().."StackPrice"]; local itemPercent = _G[row:GetName().."Percent"]; local itemIcon = _G[row:GetName().."ItemIcon"]; local itemLevel = _G[row:GetName().."ILevel"]; local color = ITEM_QUALITY_COLORS[quality]; if (color) then itemName:SetText("stack of "..count.." "..color.hex..name); else itemName:SetText("stack of "..count.." "..name); end itemLevel:SetText(ilevel); itemPrice:SetText(Utils:PriceToString(ppu)); itemPercent:SetText(auction.percent.."%"); if (percent >= 100) then itemPercent:SetTextColor(1,0,0); elseif (percent >= 75) then itemPercent:SetTextColor(1,1,1); elseif (percent >= 50) then itemPercent:SetTextColor(0,1,0); elseif (percent < 0) then itemPercent:SetTextColor(0.5,0.5,0.5); else itemPercent:SetTextColor(0,0.5,1); end if (texture ~= nil) then itemIcon:SetTexture(texture); itemIcon:Show(); else itemIcon:Hide(); end if (offset == self.selectedEntry) then row:SetButtonState("PUSHED", true); else row:SetButtonState("NORMAL", false); end row:Show(); else row:Hide(); end end function AuctionList:CreateRows() local d = self; local i; for i = 1, self.style.totalRows do local f = CreateFrame("BUTTON", self.frame:GetName().."ItemRow"..i, self.frame:GetParent(), "AnsAuctionRowTemplate"); f:SetScript("OnClick", function(r,button,down) d:Click(r,button,down) end); f:SetScript("OnLeave", Utils.HideTooltip); f:SetScript("OnEnter", function(r) d:ShowTip(r) end); f:SetPoint("TOPLEFT", self.frame, "TOPLEFT", 0, (i - 1) * -self.style.rowHeight); tinsert(self.rows, f); end end function AuctionList:Clear() if (_G["AnsSnipeMainPanel"]:IsShown()) then local i; for i = 1, self.style.totalRows do self.rows[i]:Hide(); end end end function AuctionList:Refresh() self:Clear(); local i; local doffset; local offset = FauxScrollFrame_GetOffset(self.frame); for i = 1, self.style.totalRows do doffset = i + offset; local row = self.rows[i]; self:UpdateRow(doffset, row); end FauxScrollFrame_Update(self.frame, #self.items, self.style.totalRows, self.style.rowHeight); end
object_tangible_quest_story_loot_som_kenobi_historian_data_disk = object_tangible_quest_story_loot_shared_som_kenobi_historian_data_disk:new { } ObjectTemplates:addTemplate(object_tangible_quest_story_loot_som_kenobi_historian_data_disk, "object/tangible/quest/story_loot/som_kenobi_historian_data_disk.iff")
function onStepIn(creature, item, position, fromPosition) local player = creature:getPlayer() if not player then return true end if player:getStorageValue(Storage.TheApeCity.Questline) >= 17 then player:teleportTo({x = 32749, y = 32536, z = 10}) else player:teleportTo(fromPosition) player:sendTextMessage(MESSAGE_STATUS_SMALL, 'You don\'t have access to this area.') end position:sendMagicEffect(CONST_ME_TELEPORT) player:getPosition():sendMagicEffect(CONST_ME_TELEPORT) return true end
for i,v in ipairs(TeamInfo.kRelevantTechIdsMarine) do if v == kTechId.AdvancedArmoryUpgrade then table.insert(TeamInfo.kRelevantTechIdsMarine, i + 1, kTechId.HeavyMachineGunTech) end end
require "behaviours/wander" require "behaviours/doaction" require "behaviours/chaseandattack" require "behaviours/standstill" local STOP_RUN_DIST = 10 local SEE_PLAYER_DIST = 5 local MAX_WANDER_DIST = 20 local SEE_TARGET_DIST = 6 local MAX_CHASE_DIST = 7 local MAX_CHASE_TIME = 8 local function GoHomeAction(inst) if inst.components.homeseeker and inst.components.homeseeker.home and inst.components.homeseeker.home:IsValid() then return BufferedAction(inst, inst.components.homeseeker.home, ACTIONS.GOHOME) end end local function ShouldGoHome(inst) return not GetClock():IsDay() or GetSeasonManager():IsWinter() end local FrogBrain = Class(Brain, function(self, inst) Brain._ctor(self, inst) end) function FrogBrain:OnStart() local clock = GetClock() local root = PriorityNode( { ChaseAndAttack(self.inst, MAX_CHASE_TIME), WhileNode(function() return ShouldGoHome(self.inst) end, "ShouldGoHome", DoAction(self.inst, function() return GoHomeAction(self.inst) end, "go home", true )), WhileNode(function() return clock and not clock:IsNight() end, "IsNotNight", Wander(self.inst, function() return self.inst.components.knownlocations:GetLocation("home") end, MAX_WANDER_DIST)), StandStill(self.inst, function() return self.inst.sg:HasStateTag("idle") end, nil), }, .25) self.bt = BT(self.inst, root) end return FrogBrain
-- Local Variables: -- lua-indent-close-paren-align: nil -- lua-indent-only-use-last-opener: t -- End: -- XFAIL: one param, nested table on same line as opener foobar({ a, b, c }) -- XFAIL: two params, nested table on same line as opener foobar(a, { b, c }) foobar({}, { b, c }) -- XFAIL: two aligned params, nested table on next line foobar({}, {1, 2, 3}) -- XFAIL: two aligned table params, first has nested tables foobar({{}, {1, 2, 3}}, { 4,5,6 }) foobar({{}, {1, 2, 3}}, { 4,5,6 } ) -- XFAIL: one nested table containing another table foobar({ {4, 5, 6} }) -- XFAIL: nested table with indentation: nested table on separate line foobar( a, { b, c }) foobar( a, { b, c } ) -- XFAIL: nested table with alignment: nested table on separate line foobar(a, { b, c }) foobar(a, { b, c } ) -- nested table with indentation: params after nested table foobar( { a, b }, c, d) foobar( { a, b }, c, d )
local mod = get_mod("GiveWeapon") local pl = require'pl.import_into'() local tablex = require'pl.tablex' local stringx = require'pl.stringx' mod.simple_ui = get_mod("SimpleUI") mod.more_items_library = get_mod("MoreItemsLibrary") mod.properties = {} mod.traits = {} fassert(mod.simple_ui, "GiveWeapon must be lower than SimpleUI in your launcher's load order.") fassert(mod.more_items_library, "GiveWeapon must be lower than MoreItemsLibrary in your launcher's load order.") mod.pos_y = -35 mod.create_skins_dropdown = function(item_type, window_size) mod:pcall(function() local all_skins = pl.List(mod.get_skins(item_type)) mod.skin_names = tablex.pairmap(function(_, skin) return skin, Localize(WeaponSkins.skins[skin].display_name) end, all_skins) mod.sorted_skin_names = all_skins:map(function(skin) return Localize(WeaponSkins.skins[skin].display_name) end) -- it used to be each skin had an unique localized name, but not anymore -- so we have to do something about duplicates for localized_skin_name, skin_data in pairs(mod.skin_names) do if type(skin_data) == "table" then mod.skin_names[localized_skin_name] = skin_data[1] end end mod.sorted_skin_names = pl.Map.keys(pl.Set(mod.sorted_skin_names)) table.sort(mod.sorted_skin_names, function(skin_name_first, skin_name_second) local skin_key_first = mod.skin_names[skin_name_first] local skin_key_second = mod.skin_names[skin_name_second] if pl.stringx.lfind(skin_key_first, "_runed") and pl.stringx.lfind(skin_key_second, "_runed") then if pl.stringx.lfind(skin_key_first, "_runed_02") and pl.stringx.lfind(skin_key_second, "_runed_02") then return skin_name_first < skin_name_second end if pl.stringx.lfind(skin_key_first, "_runed_02") then return true end if pl.stringx.lfind(skin_key_second, "_runed_02") then return false end return skin_name_first < skin_name_second end if pl.stringx.lfind(skin_key_first, "_runed") then return true elseif pl.stringx.lfind(skin_key_second, "_runed") then return false else return skin_name_first < skin_name_second end end) local skin_options = tablex.index_map(mod.sorted_skin_names) if mod.skins_dropdown then mod.skins_dropdown.visible = false end mod.skins_dropdown = mod.main_window:create_dropdown("skins_dropdown", {5+180+180+5+5+260+5+260+5, mod.pos_y+window_size[2]-35}, {200, 30}, nil, skin_options, "skins_dropdown", 1) mod.skins_dropdown:select_index(1) end) end mod.get_skins = function(item_type) local current_career_names = mod.current_careers:map(function(career) return career.name end) for _, item in pairs( ItemMasterList ) do if item.item_type == item_type and item.template and item.can_wield and pl.List(item.can_wield) -- check if the item is valid career-wise :map(function(career_name) return current_career_names:contains(career_name) end) :reduce('or') then if item.skin_combination_table or pl.List{"necklace", "ring", "trinket"}:contains(item_type) then if item.skin_combination_table then local all_skins = pl.List() tablex.foreach(WeaponSkins.skin_combinations[item.skin_combination_table], function(value) all_skins:extend(pl.List(value)) end) return pl.Map.keys(pl.Set(all_skins)) end end end end end mod:hook(table, "clone", function(func, t, skip_metatable) return func(t, true) end) mod.create_weapon = function(item_type, give_random_skin, rarity, no_skin) if not mod.current_careers then local player = Managers.player:local_player() local profile_index = player:profile_index() mod.current_careers = pl.List(SPProfiles[profile_index].careers) end local current_career_names = mod.current_careers:map(function(career) return career.name end) for item_key, item in pairs( ItemMasterList ) do if item.item_type == item_type and item.template and item.can_wield and pl.List(item.can_wield) -- check if the item is valid career-wise :map(function(career_name) return current_career_names:contains(career_name) end) :reduce('or') then if item.skin_combination_table or pl.List{"necklace", "ring", "trinket"}:contains(item_type) then local skin if item.skin_combination_table and mod.skin_names then skin = mod.skin_names[mod.sorted_skin_names[mod.skins_dropdown.index]] end if mod:get(mod.SETTING_NAMES.NO_SKINS) then skin = nil end if give_random_skin then local skins = mod.get_skins(item_type) skin = skins[math.random(#skins)] end local custom_properties = "{" for _, prop_name in ipairs( mod.properties ) do custom_properties = custom_properties..'\"'..prop_name..'\":1,' end custom_properties = custom_properties.."}" local properties = {} for _, prop_name in ipairs( mod.properties ) do properties[prop_name] = 1 end local custom_traits = "[" for _, trait_name in ipairs( mod.traits ) do custom_traits = custom_traits..'\"'..trait_name..'\",' end custom_traits = custom_traits.."]" local rnd = math.random(1000000) -- uhh yeah local new_backend_id = tostring(item_key) .. "_" .. rnd .. "_from_GiveWeapon" local entry = table.clone(ItemMasterList[item_key], true) entry.mod_data = { backend_id = new_backend_id, ItemInstanceId = new_backend_id, CustomData = { -- traits = "[\"melee_attack_speed_on_crit\", \"melee_timed_block_cost\"]", traits = custom_traits, power_level = "300", properties = custom_properties, rarity = "exotic", }, rarity = "exotic", -- traits = { "melee_timed_block_cost", "melee_attack_speed_on_crit" }, traits = table.clone(mod.traits, true), power_level = 300, properties = properties, } if skin then entry.mod_data.CustomData.skin = skin entry.mod_data.skin = skin entry.mod_data.inventory_icon = WeaponSkins.skins[skin].inventory_icon end entry.rarity = "exotic" entry.rarity = "default" entry.mod_data.rarity = "default" entry.mod_data.CustomData.rarity = "default" mod.more_items_library:add_mod_items_to_local_backend({entry}, "GiveWeapon") mod:echo("Spawned "..item_key) Managers.backend:get_interface("items"):_refresh() ItemHelper.mark_backend_id_as_new(new_backend_id) local backend_items = Managers.backend:get_interface("items") local new_item = backend_items:get_item_from_id(new_backend_id) if rarity then new_item.rarity = rarity new_item.data.rarity = rarity new_item.CustomData.rarity = rarity end if no_skin then new_item.skin = nil end mod.properties = {} mod.traits = {} return new_backend_id end end end end mod.hero_options = {} for i, profile in ipairs(pl.List(SPProfiles):slice(1, 5)) do mod.hero_options[Localize(profile.ingame_display_name)] = i end mod.create_item_types_dropdown = function(profile_index, window_size) mod.current_careers = pl.List(SPProfiles[profile_index].careers) local item_master_list = ItemMasterList local any_weapon = get_mod("AnyWeapon") if any_weapon then local cached_item_master_list = any_weapon:persistent_table("cache").ItemMasterList if cached_item_master_list then item_master_list = cached_item_master_list end end local career_item_types = {} for _, item in pairs( item_master_list ) do for _, career in ipairs( mod.current_careers ) do if table.contains(item.can_wield, career.name) and (item.slot_type == "melee" or item.slot_type == "ranged") then career_item_types[item.item_type] = true break end end end mod.career_item_types = tablex.keys(career_item_types) mod.career_item_types:extend({"necklace", "ring", "trinket"}) career_item_types = mod.career_item_types:map(Localize) local item_types_options = tablex.index_map(career_item_types) if mod.item_types_dropdown then mod.item_types_dropdown.visible = false end mod.item_types_dropdown = mod.main_window:create_dropdown("item_types_dropdown", {5+180+5, mod.pos_y+window_size[2]-35}, {180, 30}, nil, item_types_options, "item_types_dropdown", 1) mod.item_types_dropdown.on_index_changed = function(dropdown) local item_type = mod.career_item_types[dropdown.index] mod.create_skins_dropdown(item_type, window_size) end mod.item_types_dropdown:select_index(1) end mod.on_create_weapon_click = function(button) -- luacheck: ignore button mod:pcall(function() local item_type = mod.career_item_types[mod.item_types_dropdown.index] if not item_type then return end local trait_name = mod.trait_names[mod.sorted_trait_names[mod.traits_dropdown.index]] if trait_name then table.insert(mod.traits, trait_name) end local rarity = mod:get(mod.SETTING_NAMES.NO_SKINS) and "default" or "exotic" local no_skin = mod:get(mod.SETTING_NAMES.NO_SKINS) local backend_id = mod.create_weapon(item_type, false, rarity, no_skin) local backend_items = Managers.backend:get_interface("items") if mod.loadout_inv_view then backend_items:_refresh() local inv_item_grid = mod.loadout_inv_view._item_grid inv_item_grid:change_item_filter(mod.item_filter, false) inv_item_grid:repopulate_current_inventory_page() end end) end mod.create_window = function(self, profile_index, loadout_inv_view) mod.loadout_inv_view = loadout_inv_view local scale = UIResolutionScale_pow2() local screen_width, screen_height = UIResolution() -- luacheck: ignore screen_width local window_size = {905+190+15, 80+32} local window_position = {850-160, screen_height - window_size[2] - 5} self.main_window = mod.simple_ui:create_window("give_weapon", window_position, window_size) mod.main_window:create_title("give_weapon_title", "Give Weapon", 35) self.main_window.position = {screen_width - (905+190+15)*scale - 150, screen_height - window_size[2]*scale - 5} local pos_x = 5 local pos_y = mod.pos_y mod.create_weapon_button = self.main_window:create_button("create_weapon_button", {pos_x+90, pos_y+window_size[2]-35-35}, {200, 30}, nil, ">Create Weapon<", nil) mod.create_weapon_button.on_click = mod.on_create_weapon_click mod.heroes_dropdown = self.main_window:create_dropdown("heroes_dropdown", {pos_x, pos_y+window_size[2]-35}, {180, 30}, nil, mod.hero_options, nil, 1) mod.heroes_dropdown.on_index_changed = function(dropdown) mod.create_item_types_dropdown(dropdown.index, window_size) end if profile_index then mod.heroes_dropdown:select_index(profile_index) end mod.add_property_button = self.main_window:create_button("add_property_button", {pos_x+180+180+5+5+260+5+40, pos_y+window_size[2]-70}, {180, 30}, nil, "Add Property", nil) mod.add_property_button.on_click = function(button) -- luacheck: ignore button local property_name = mod.property_names[mod.sorted_property_names[mod.properties_dropdown.index]] if property_name then table.insert(mod.properties, property_name) end end -- mod.add_trait_button = self.main_window:create_button("add_trait_button", {pos_x+180+180+50+5, pos_y+window_size[2]-70}, {180, 30}, nil, "Add Trait", nil) -- mod.add_trait_button.on_click = function(button) -- local trait_name = mod.trait_names[mod.traits_dropdown.index] -- if trait_name then -- table.insert(mod.traits, trait_name) -- end -- end mod.property_names = tablex.pairmap( function(property_key, _) local full_prop_description = UIUtils.get_property_description(property_key, 0) local _, _, prop_description = stringx.partition(full_prop_description, " ") prop_description = stringx.replace(prop_description, "Damage", "Dmg") if property_key == "deus_power_vs_chaos" then prop_description = prop_description.." (CW)" end return property_key, prop_description end, WeaponProperties.properties ) mod.sorted_property_names = tablex.pairmap( function(property_key, _) local full_prop_description = UIUtils.get_property_description(property_key, 0) local _, _, prop_description = stringx.partition(full_prop_description, " ") prop_description = stringx.replace(prop_description, "Damage", "Dmg") if property_key == "deus_power_vs_chaos" then prop_description = prop_description.." (CW)" end return prop_description end, WeaponProperties.properties ) table.sort(mod.sorted_property_names) local properties_options = tablex.index_map(mod.sorted_property_names) mod.properties_dropdown = self.main_window:create_dropdown("properties_dropdown", {pos_x+180+180+5+5+260+5, pos_y+window_size[2]-35}, {260, 30}, nil, properties_options, nil, 1) mod.trait_names = tablex.pairmap(function(trait_key, trait) return trait_key, Localize(trait.display_name) end, WeaponTraits.traits) mod.sorted_trait_names = tablex.pairmap(function(trait_key, trait) -- luacheck: ignore trait_key return Localize(trait.display_name) end, WeaponTraits.traits) table.sort(mod.sorted_trait_names) local traits_options = tablex.index_map(mod.sorted_trait_names) mod.traits_dropdown = self.main_window:create_dropdown("traits_dropdown", {pos_x+180+180+5+5, pos_y+window_size[2]-35}, {260, 30}, nil, traits_options, nil, 1) self.main_window.on_hover_enter = function(window) window:focus() end self.main_window:init() end -- # Track item_grid's last used item_filter mod:hook_safe(ItemGridUI, "change_item_filter", function(self, item_filter, change_page) mod.item_filter = item_filter end) --- Create window when opening hero view. mod:hook_safe(HeroWindowLoadoutInventory, "on_enter", function(self) local player = Managers.player:local_player() local profile_index = player:profile_index() mod:reload_windows(profile_index, self) end) mod.reload_windows = function(self, profile_index, loadout_inv_view) self:destroy_windows() self:create_window(profile_index, loadout_inv_view) end mod.destroy_windows = function(self) if self.main_window then self.main_window:destroy() self.main_window = nil end end mod:hook(HeroWindowLoadoutInventory, "on_exit", function(func, self) func(self) mod:destroy_windows() end) mod:dofile("scripts/mods/"..mod:get_name().."/wooden_2h_hammer")
--[[- A basic logging library. This writes messages to a log file (.artist.d/log), rotating the file when it gets too large (more than 64KiB). ]] local select, os, fs = select, os, fs local expect = require "cc.expect".expect local path = ".artist.d/log" local old_path = ".artist.d/log.1" fs.delete(path) local size, max_size = 0, 64 * 1024 --[[- Log a message. @tparam string tag A tag for this log message, typically the module it came from. @tparam string msg The message to log. When additional arguments (`...`) are given, msg is treated as a format string. @param ... Additional arguments to pass to @{string.format} when `msg` is a format string. ]] local function log(tag, msg, ...) expect(1, tag, "string") expect(2, msg, "string") if size > max_size then -- Rotate old files size = 0 fs.delete(old_path) fs.move(path, old_path) end if select('#', ...) > 0 then msg = msg:format(...) end local now = os.epoch("utc") local date = os.date("%Y-%m-%d %H:%M:%S", now * 1e-3) local ms = ("%.2f"):format(now % 1000 * 1e-3):sub(2) local message = ("[%s%s] %s: %s\n"):format(date, ms, tag, msg) local handle = fs.open(path, "a") handle.write(message) handle.close() size = size + #message end --[[- Create a logging function for a given tag. @tparam string tag A tag for this logger. @treturn function(msg: string, ...: any):nil The logger function. ]] local function get_logger(tag) expect(1, tag, "string") return function(...) return log(tag, ...) end end return { log = log, get_logger = get_logger, }
local composer = require( "composer" ) local scene = composer.newScene() -- ----------------------------------------------------------------------------------- -- Code outside of the scene event functions below will only be executed ONCE unless -- the scene is removed entirely (not recycled) via "composer.removeScene()" -- ----------------------------------------------------------------------------------- -- ----------------------------------------------------------------------------------- -- Scene event functions -- ----------------------------------------------------------------------------------- local resume_btn_overlay local pause_overlay_background local pause_overlay_text -- create() function scene:create( event ) local sceneGroup = self.view -- Code here runs when the scene is first created but has not yet appeared on screen -- overlay background pause_overlay_background = display.newImageRect(sceneGroup, "images/paused_background.png", display.contentWidth, display.contentHeight); pause_overlay_background.x = display.contentCenterX pause_overlay_background.y = display.contentCenterY pause_overlay_background.alpha=0.7 -- overlay text pause_overlay_text = display.newImageRect(sceneGroup, "images/paused_text.png", 300, 100); pause_overlay_text.x = display.contentCenterX pause_overlay_text.y = display.contentCenterY pause_overlay_text.alpha=1 -- fade in resume button resume_btn = display.newImageRect(sceneGroup, "images/resume_btn.png", 230, 70) resume_btn.x=132 resume_btn.y=150 resume_btn.alpha=0 transition.fadeIn(resume_btn, {time=1000} ) end -- show() function scene:show( event ) local sceneGroup = self.view local phase = event.phase local parent = event.parent -- important!!! if ( phase == "will" ) then -- Code here runs when the scene is still off screen (but is about to come on screen) elseif ( phase == "did" ) then -- Code here runs when the scene is entirely on screen -- resume game function local function resume_game(event) parent:resumeGame() end resume_btn:addEventListener("tap", resume_game) end end -- hide() function scene:hide( event ) local sceneGroup = self.view local phase = event.phase local parent = event.parent if ( phase == "will" ) then -- Code here runs when the scene is on screen (but is about to go off screen) elseif ( phase == "did" ) then -- Code here runs immediately after the scene goes entirely off screen end end -- destroy() function scene:destroy( event ) local sceneGroup = self.view -- Code here runs prior to the removal of scene's view end -- ----------------------------------------------------------------------------------- -- Scene event function listeners -- ----------------------------------------------------------------------------------- scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) -- ----------------------------------------------------------------------------------- return scene
if not wac then return end ENT.Base = "wac_hc_base" ENT.Type = "anim" ENT.Author = "Chippy" ENT.Category = wac.aircraft.spawnCategoryC ENT.Spawnable = true ENT.AdminSpawnable = true ENT.PrintName = "AH-1W Super Cobra" ENT.Model = "models/chippy/ah1w/body.mdl" ENT.SmokePos = Vector(-177,0,28) ENT.FirePos = Vector(-177,-12,28) ENT.TopRotor = { dir = -1, pos = Vector(-29,2,65), model = "models/chippy/ah1w/mainrotor.mdl" } ENT.BackRotor = { dir = -1, pos = Vector(-432.5,-11.06,63), model = "models/chippy/ah1w/tailrotor.mdl" } ENT.thirdPerson={ distance = 700, position = Vector(0,0,50) } ENT.Seats = { { pos=Vector(39, 1.2, -1.3), exit=Vector(72,70,0), weapons = {"Hydra 70"}, }, { pos=Vector(100, 1, -10), exit=Vector(120,70,0), weapons = {"Hellfire", "M197"}, }, } ENT.Weapons = { ["Hydra 70"] = { class = "wac_pod_hydra", info = { Sequential = true, Pods = { Vector(35, 45, -20), Vector(35, -45, -20) } } }, ["Hellfire"] = { class = "wac_pod_hellfire", info = { Pods = { Vector(50, 60, -20), Vector(50, -60, -20), } } }, ["M197"] = { class = "wac_pod_aimedgun", info = { ShootPos = Vector(110, 2, -33), ShootOffset = Vector(60, 0, 0), } }, } ENT.WeaponAttachments={ gunMount1 = { model = "models/BF2/helicopters/AH-1 Cobra/ah1z_g1.mdl", pos = Vector(107.5,0,-30.5), restrictPitch=true, }, gunMount2 = { model = "models/BF2/helicopters/AH-1 Cobra/ah1z_g2.mdl", pos = Vector(111,0,-37), localTo = "gunMount1", }, gun = { model = "models/BF2/helicopters/AH-1 Cobra/ah1z_g.mdl", pos = Vector(111,0,-37), localTo = "gunMount2", }, radar1 = { model = "models/chippy/ah1w/tgp.mdl", pos = Vector(160,0,-15), restrictPitch=true }, } ENT.Camera = { model = "models/props_junk/popcan01a.mdl", pos = Vector(160,0,-15), offset = Vector(-1,0,0), viewPos = Vector(10, 0, 0), maxAng = Angle(45, 90, 0), minAng = Angle(-2, -90, 0), seat = 2 } ENT.Sounds={ Start="wac/ah1w/startup.wav", Blades="wac/ah1w/external.wav", Engine="wac/ah1w/internal.wav", MissileAlert="HelicopterVehicle/MissileNearby.mp3", MissileShoot="HelicopterVehicle/MissileShoot.mp3", MinorAlarm="wac/ah1w/lowhealth.wav", LowHealth="wac/ah1w/lowhealth.wav", CrashAlarm="wac/ah1w/explode.wav" } function ENT:DrawWeaponSelection() end
-- the primary "known good" list is handled a little differently than the rest, so... local primaryTable = {} for k, v in hs.fnutils.sortByKeys(hs.image.systemImageNames) do table.insert(primaryTable, v) end local sources = { { "hs.image.systemImageNames", primaryTable }, } for k,v in hs.fnutils.sortByKeys(hs.image.additionalImageNames) do table.insert(sources, { "hs.image.additionalImageNames." .. k, v }) end local position = 1 local currentOffset = 0 local maxCols = 14 local maxRows = 5 local maxPerPage = maxCols * maxRows local drawBlock drawBlock = function() local imageSource = sources[position][2] local a = { hs.drawing.rectangle{x=10, y=40, w=1420, h=740} :setRoundedRectRadii(20,20):setStroke(true):setStrokeWidth(10) :setFill(true):setFillColor{red=1, blue=1, green = 1, alpha = 1}:show() } local pos = 0 local c = 0 for i,v in ipairs(imageSource) do pos = pos + 1 if pos >= currentOffset then c = c + 1 table.insert(a, hs.drawing.text({ x=20, y=45, h=30, w=1380}, sources[position][1]) :setTextSize(20):setTextColor{red = 0, blue = 0, green = 0, alpha=1} :setTextFont("Menlo"):show()) local picture = hs.image.imageFromName(v) if picture then table.insert(a, hs.drawing.image({ x=20 + ((c - 1) % 14) * 100, y=75 + math.floor((c-1)/14) * 140, h=100, w=100}, picture):show()) end table.insert(a, hs.drawing.text({ x=20 + ((c - 1) % 14) * 100, y=175 + math.floor((c-1)/14) * 140, h=50, w=100}, v) :setTextSize(10):setTextColor{red = 0, blue = 0, green = 0, alpha=1} :setTextFont("Menlo"):show()) end if c == maxPerPage then break end end esc = function() hs.fnutils.map(a, function(a) a:delete() end) end if position < #sources or pos < #imageSource then nextPage = hs.hotkey.bind({},"right", function() esc() end, function() if xyzzy then xyzzy:disable() ; xyzzy = nil end if nextPage then nextPage:disable() ; nextPage = nil end if prevPage then prevPage:disable() ; prevPage = nil end if pos < #imageSource then currentOffset = currentOffset + maxPerPage else currentOffset = 0 position = position + 1 end drawBlock() end ) end if position > 1 then prevPage = hs.hotkey.bind({}, "left", function() esc() end, function() if xyzzy then xyzzy:disable() ; xyzzy = nil end if nextPage then nextPage:disable() ; nextPage = nil end if prevPage then prevPage:disable() ; prevPage = nil end if currentOffset == 0 then position = position - 1 else currentOffset = currentOffset - maxPerPage end drawBlock() end ) end xyzzy = hs.hotkey.bind({},"escape", function() esc() end, function() if xyzzy then xyzzy:disable() ; xyzzy = nil end if nextPage then nextPage:disable() ; nextPage = nil end if prevPage then prevPage:disable() ; prevPage = nil end end ) end drawBlock()
return { summary = 'An offscreen render target.', description = [[ A Canvas is also known as a framebuffer or render-to-texture. It allows you to render to a texture instead of directly to the screen. This lets you postprocess or transform the results later before finally rendering them to the screen. After creating a Canvas, you can attach Textures to it using `Canvas:setTexture`. ]], constructors = { 'lovr.graphics.newCanvas' }, notes = [[ Up to four textures can be attached to a Canvas and anything rendered to the Canvas will be broadcast to all attached Textures. If you want to do render different things to different textures, use the `multicanvas` shader flag when creating your shader and implement the `void colors` function instead of the usual `vec4 color` function. You can then assign different output colors to `lovrCanvas[0]`, `lovrCanvas[1]`, etc. instead of returning a single color. Each color written to the array will end up in the corresponding texture attached to the Canvas. ]], example = { description = 'Apply a postprocessing effect (wave) using a Canvas and a fragment shader.', code = [=[ function lovr.load() lovr.graphics.setBackgroundColor(.1, .1, .1) canvas = lovr.graphics.newCanvas(lovr.headset.getDisplayDimensions()) wave = lovr.graphics.newShader([[ vec4 lovrMain() { return lovrRVertex; } ]], [[ uniform float time; vec4 lovrMain() { uv.x += sin(uv.y * 10 + time * 4) * .01; uv.y += cos(uv.x * 10 + time * 4) * .01; return lovrGraphicsColor * lovrDiffuseColor * lovrVertexColor * texture(lovrDiffuseTexture, lovrTexCoord); } ]]) end function lovr.update(dt) wave:send('time', lovr.timer.getTime()) end function lovr.draw() -- Render the scene to the canvas instead of the headset. canvas:renderTo(function() lovr.graphics.clear() local size = 5 for i = 1, size do for j = 1, size do for k = 1, size do lovr.graphics.setColor(i / size, j / size, k / size) local x, y, z = i - size / 2, j - size / 2, k - size / 2 lovr.graphics.cube('fill', x, y, z, .5) end end end end) -- Render the canvas to the headset using a shader. lovr.graphics.setColor(1, 1, 1) lovr.graphics.setShader(wave) lovr.graphics.fill(canvas:getTexture()) lovr.graphics.setShader() end ]=] } }
-- Based on https://github.com/streetturtle/awesome-wm-widgets/blob/master/volume-widget/volume.lua local awful = require("awful") local gears = require("gears") local watch = require("awful.widget.watch") local spawn = require("awful.spawn") local icons = require("theme.icons") local iconContainer = require("widgets.general.icon-container") local GET_VOLUME_CMD = "amixer sget Master" local INC_VOLUME_CMD = "amixer sset Master 5%+" local DEC_VOLUME_CMD = "amixer sset Master 5%-" local TOG_VOLUME_CMD = "amixer sset Master toggle" -- Create icon container local volumeIcon = iconContainer(icons.volumeMedium, 5, false, true) -- Function for updating widgets icon local function updateIcon(_, stdout) local mute = string.match(stdout, "%[(o%D%D?)%]") local volume = string.match(stdout, "(%d?%d?%d)%%") volume = tonumber(string.format("% 3d", volume)) if mute == "off" then volumeIcon:change_icon(icons.volumeMuted) elseif (volume >= 0 and volume < 25) then volumeIcon:change_icon(icons.volumeLow) elseif (volume < 50) then volumeIcon:change_icon(icons.volumeMedium) elseif (volume < 75) then volumeIcon:change_icon(icons.volumeHigh) elseif (volume <= 100) then volumeIcon:change_icon(icons.volumeFull) end end -- Create widget click events volumeIcon:buttons( gears.table.join( awful.button( {}, 0, nil, function() spawn.easy_async( GET_VOLUME_CMD, function(stdout) updateIcon(_, stdout) end ) end ), awful.button( {}, 1, nil, function() awful.spawn(TOG_VOLUME_CMD, false) end ), awful.button( {}, 4, nil, function() awful.spawn(INC_VOLUME_CMD, false) end ), awful.button( {}, 5, nil, function() awful.spawn(DEC_VOLUME_CMD, false) end ) ) ) -- Watcher on changing volume watch(GET_VOLUME_CMD, 1, updateIcon, volumeIcon) return volumeIcon
local path = (...) local sub1 = path:match("(.-)%.[^%.]+$") local sub2 = sub1:match("(.-)%.[^%.]+$") local sub3 = sub2:match("(.-)%.[^%.]+$") local sub4 = sub3:match("(.-)%.[^%.]+$") local roboto = require (sub1..".roboto") local smooth_rectangle = require (sub2..".utils.smooth_rectangle") local guilt = require (sub3) local font_writer = require (sub3..".font_writer") local pleasure = require (sub3..".pleasure") local NOP = require (sub3..".pleasure.NOP") local rgb = require (sub4..".color.rgb") local rgba = require (sub4..".color.rgba") local namespace = guilt.namespace("material-design") local Button = namespace:template("Button"):needs{ text = pleasure.need.string; } Button.back_color_normal = rgb( 56, 158, 255) Button.back_color_hover = rgb( 42, 147, 247) Button.back_color_pressed = rgb( 0, 116, 225) Button.text_color = rgb(255, 255, 255) local min_width = 64 local preferred_height = 36 local x_pad = 16 function Button:init() self.preferred_width = math.max(min_width, roboto.button:getWidth(self.text) + 2*x_pad) self.preferred_height = preferred_height end function Button:draw () if self.pressed then self:draw_pressed() elseif self.hovered then self:draw_hover() else self:draw_normal() end end function Button:draw_normal() local x, y, width, height = self:bounds() local cx, cy = x + width/2, y + height/2 local back_color = self.back_color_normal local text_color = self.text_color -- drop shadow smooth_rectangle(x, y, width, height, 2, rgba(0,0,0,0.62)) -- button smooth_rectangle(x, y-1, width, height, 2, back_color) love.graphics.setColor(text_color) font_writer.print_aligned(roboto.button, self.text:upper(), cx, cy, "middle", "center") end function Button:draw_hover () local x, y, width, height = self:bounds() local cx, cy = x + width/2, y + height/2 local back_color = self.back_color_hover local text_color = self.text_color_hover or self.text_color -- drop shadow smooth_rectangle(x, y, width, height, 2, rgba(0,0,0,0.62)) -- button smooth_rectangle(x, y-1, width, height, 2, back_color) love.graphics.setColor(text_color) font_writer.print_aligned(roboto.button, self.text:upper(), cx, cy, "middle", "center") end function Button:draw_pressed () local x, y, width, height = self:bounds() local cx, cy = x + width/2, y + height/2 local back_color = self.back_color_pressed local text_color = self.text_color_pressed or self.text_color smooth_rectangle(x, y, width, height, 2, back_color) love.graphics.setColor(text_color) font_writer.print_aligned(roboto.button, self.text:upper(), cx, cy, "middle", "center") end Button.mousepressed = NOP Button.mousereleased = NOP Button.mouseclicked = NOP namespace:finalize_template(Button)
local serializers = { ['none'] = require('colyseus.serialization.none'), ['fossil-delta'] = require('colyseus.serialization.fossil_delta'), ['schema'] = require('colyseus.serialization.schema'), } local exports = {} exports.register_serializer = function(id, handler) serializers[id] = handler end exports.get_serializer = function(id) return serializers[id] end return exports
local t = Def.ActorFrame{ OnCommand=function(self) if LoadModule("Characters.AnyoneHasChar.lua")() then if SCREENMAN:GetTopScreen():GetChild("SongBackground") then local SBG_sc = SCREENMAN:GetTopScreen():GetChild("SongBackground"):GetChild("") local BGBrightness = SBG_sc:GetChild("")[5]:GetChild("BrightnessOverlay") for i=1,3 do BGBrightness[i]:zoom(0) end SCREENMAN:GetTopScreen():GetChild("SongBackground"):visible(false) end end; end }; t[#t+1] = LoadActor("ScreenFilter"); for ip, pn in ipairs(GAMESTATE:GetEnabledPlayers()) do if LoadModule("Config.Load.lua")("MeasureCounter",CheckIfUserOrMachineProfile(string.sub(pn,-1)-1).."/OutFoxPrefs.ini") then t[#t+1] = LoadActor("MeasureCount", pn) end end if GAMESTATE:IsHumanPlayer(PLAYER_1) then if not LoadModule("Config.Load.lua")("ToastiesDraw",CheckIfUserOrMachineProfile(0).."/OutFoxPrefs.ini") then t[#t+1] = LoadModule("Options.SmartToastieActors.lua")(1) end end if GAMESTATE:IsHumanPlayer(PLAYER_2) then if not LoadModule("Config.Load.lua")("ToastiesDraw",CheckIfUserOrMachineProfile(1).."/OutFoxPrefs.ini") then t[#t+1] = LoadModule("Options.SmartToastieActors.lua")(2) end end return t;
local type = type local string_format = string.format local string_find = string.find local string_lower = string.lower local ngx_re_find = ngx.re.find local resty_cookie=require("gateway.lib.cookie") local stringy = require("gateway.utils.stringy") local function assert_condition(real, operator, expected) if not real then ngx.log(ngx.ERR, string_format("assert_condition error: %s %s %s", real, operator, expected)) return false end if operator == 'match' then if ngx_re_find(real, expected, 'isjo') ~= nil then return true end elseif operator == 'not_match' then if ngx_re_find(real, expected, 'isjo') == nil then return true end elseif operator == "=" then if real == expected then return true end elseif operator == "!=" then if real ~= expected then return true end elseif operator == '>' then if real ~= nil and expected ~= nil then expected = tonumber(expected) real = tonumber(real) if real and expected and real > expected then return true end end elseif operator == '>=' then if real ~= nil and expected ~= nil then expected = tonumber(expected) real = tonumber(real) if real and expected and real >= expected then return true end end elseif operator == '<' then if real ~= nil and expected ~= nil then expected = tonumber(expected) real = tonumber(real) if real and expected and real < expected then return true end end elseif operator == '<=' then if real ~= nil and expected ~= nil then expected = tonumber(expected) real = tonumber(real) if real and expected and real <= expected then return true end end --匹配in elseif operator =='in' then ngx.log(ngx.INFO, "execute in ", operator,real,expected) if real ~= nil and expected ~= nil then return string_find(expected,real) end end return false end local _M = {} function _M.judge(condition) local condition_type = condition and condition.type if not condition_type then return false end ngx.log(ngx.INFO, " condition_type==================================", condition_type) local operator = condition.operator local expected = condition.value if not operator or not expected then return false end local real if condition_type == "URI" then real = ngx.var.uri elseif condition_type == "Query" then local query = ngx.req.get_uri_args() real = query[condition.name] elseif condition_type == "Header" then local headers = ngx.req.get_headers() real = headers[condition.name] elseif condition_type == "IP" then real = ngx.var.remote_addr elseif condition_type == "UserAgent" then real = ngx.var.http_user_agent elseif condition_type == "Method" then local method = ngx.req.get_method() method = string_lower(method) if not expected or type(expected) ~= "string" then expected = "" end expected = string_lower(expected) real = method elseif condition_type == "PostParams" then local headers = ngx.req.get_headers() local header = headers['Content-Type'] if header then local is_multipart = string_find(header, "multipart") if is_multipart and is_multipart > 0 then return false end end ngx.req.read_body() local post_params, err = ngx.req.get_post_args() if not post_params or err then ngx.log(ngx.ERR, "[Condition Judge]failed to get post args: ", err) return false end real = post_params[condition.name] elseif condition_type == "Referer" then real = ngx.var.http_referer elseif condition_type == "Host" then real = ngx.var.host --类型时cookie时 elseif condition_type == "Cookie" then ngx.log(ngx.INFO, " Cookie==================================", condition.name) local cookies = resty_cookie:new() -- local cookies,err = cookieUtil:get_all() if cookies then ngx.log(ngx.INFO, " cookiename==================================", condition.name) real = cookies:get(condition.name) ngx.log(ngx.INFO, " real=========================================", real) end end return assert_condition(real, operator, expected) end return _M
local ID = require("scripts/zones/Mog_Garden/IDs"); require("scripts/globals/moghouse") require("scripts/globals/shop"); ----------------------------------- local BRONZE_PIECE_ITEMID = 2184; function onTrade(player, npc, trade) moogleTrade(player, npc, trade) end; function onTrigger(player, npc) player:startEvent(1016); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player, csid, option) if (csid == 1016 and option == 0xFFF00FF) then -- Show the Mog House menu.. -- Print the expire time for mog locker if exists.. local lockerLease = getMogLockerExpiryTimestamp(player); if (lockerLease ~= nil) then if (lockerLease == -1) then -- Lease expired.. player:messageSpecial(ID.text.MOGLOCKER_MESSAGE_OFFSET + 2, BRONZE_PIECE_ITEMID); else player:messageSpecial(ID.text.MOGLOCKER_MESSAGE_OFFSET + 1, lockerLease); end end -- Show the mog house menu.. player:sendMenu(1); elseif (csid == 1016 and option == 0xFFE00FF) then -- Buy/Sell Things local stock = { 573, 280, -- Vegetable Seeds 574, 320, -- Fruit Seeds 575, 280, -- Grain Seeds 572, 280, -- Herb Seeds 1236, 1685, -- Cactus Stems 2235, 320, -- Wildgrass Seeds 3986, 1111, -- Chestnut Tree Sap (11th Anniversary Campaign) 3985, 1111, -- Monarch Beetle Saliva (11th Anniversary Campaign) 3984, 1111, -- Golden Seed Pouch (11th Anniversary Campaign) }; tpz.shop.general(player, stock); elseif (csid == 1016 and option == 0xFFB00FF) then -- Leave this Mog Garden -> Whence I Came player:warp(); -- Ghetto for now, the last zone seems to get messed up due to mog house issues. end end;
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file api.lua -- -- imports import("core.project.option") -- add c function function _api_add_cfunc(interp, module, alias, links, includes, checkinfo) -- parse the check code local checkname, checkcode = option.checkinfo(checkinfo) -- make the option name local name = nil if module ~= nil then name = format("__%s_%s", module, checkname) else name = format("__%s", checkname) end -- uses the alias name if alias ~= nil then checkname = alias end -- make the option define local define = nil if module ~= nil then define = format("$(prefix)_%s_HAVE_%s", module:upper(), checkname:upper()) else define = format("$(prefix)_HAVE_%s", checkname:upper()) end -- save the current scope local scope = interp:scope_save() -- check option interp:api_call("option", name) interp:api_call("set_category", "cfuncs") interp:api_call("add_cfuncs", checkinfo) if links then interp:api_call("add_links", links) end if includes then interp:api_call("add_cincludes", includes) end interp:api_call("add_defines_h_if_ok", define) -- restore the current scope interp:scope_restore(scope) -- add this option interp:api_call("add_options", name) end -- add c functions function _api_add_cfuncs(interp, module, links, includes, ...) -- done for _, checkinfo in ipairs({...}) do _api_add_cfunc(interp, module, nil, links, includes, checkinfo) end end -- add c++ function function _api_add_cxxfunc(interp, module, alias, links, includes, checkinfo) -- parse the check code local checkname, checkcode = option.checkinfo(checkinfo) -- make the option name local name = nil if module ~= nil then name = format("__%s_%s", module, checkname) else name = format("__%s", checkname) end -- uses the alias name if alias ~= nil then checkname = alias end -- make the option define local define = nil if module ~= nil then define = format("$(prefix)_%s_HAVE_%s", module:upper(), checkname:upper()) else define = format("$(prefix)_HAVE_%s", checkname:upper()) end -- save the current scope local scope = interp:scope_save() -- check option interp:api_call("option", name) interp:api_call("set_category", "cxxfuncs") interp:api_call("add_cxxfuncs", checkinfo) if links then interp:api_call("add_links", links) end if includes then interp:api_call("add_cxxincludes", includes) end interp:api_call("add_defines_h_if_ok", define) -- restore the current scope interp:scope_restore(scope) -- add this option interp:api_call("add_options", name) end -- add c++ functions function _api_add_cxxfuncs(interp, module, links, includes, ...) -- done for _, checkinfo in ipairs({...}) do _api_add_cxxfunc(interp, module, nil, links, includes, checkinfo) end end -- get apis function apis() -- init apis _g.values = { -- target.set_xxx "target.set_config_h_prefix" -- target.add_xxx , "target.add_links" , "target.add_cflags" , "target.add_cxflags" , "target.add_cxxflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_defines" , "target.add_undefines" , "target.add_defines_h" , "target.add_undefines_h" -- option.add_xxx , "option.add_cincludes" , "option.add_cxxincludes" , "option.add_cfuncs" , "option.add_cxxfuncs" , "option.add_ctypes" , "option.add_cxxtypes" , "option.add_links" , "option.add_cflags" , "option.add_cxflags" , "option.add_cxxflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_defines" , "option.add_defines_if_ok" , "option.add_defines_h_if_ok" , "option.add_undefines" , "option.add_undefines_if_ok" , "option.add_undefines_h_if_ok" } _g.pathes = { -- target.set_xxx "target.set_headerdir" , "target.set_config_h" -- target.add_xxx , "target.add_headers" , "target.add_linkdirs" , "target.add_includedirs" -- option.add_xxx , "option.add_linkdirs" , "option.add_includedirs" } _g.custom = { -- target.add_xxx {"target.add_cfunc", _api_add_cfunc } , {"target.add_cfuncs", _api_add_cfuncs } , {"target.add_cxxfunc", _api_add_cxxfunc } , {"target.add_cxxfuncs", _api_add_cxxfuncs } } -- ok return _g end
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local voices = { {text = 'Feel the wind in your hair during one of my carpet rides!'} } npcHandler:addModule(VoiceModule:new(voices)) keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = "I am known as Uzon Ibn Kalith."}) keywordHandler:addKeyword({'passage'}, StdModule.say, {npcHandler = npcHandler, text = "You'll have to leave this unholy place first!"}) keywordHandler:addKeyword({'transport'}, StdModule.say, {npcHandler = npcHandler, text = "You'll have to leave this unholy place first!"}) keywordHandler:addKeyword({'ride'}, StdModule.say, {npcHandler = npcHandler, text = "You'll have to leave this unholy place first!"}) keywordHandler:addKeyword({'trip'}, StdModule.say, {npcHandler = npcHandler, text = "You'll have to leave this unholy place first!"}) local function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end if isInArray({"back", "leave", "passage"}, msg) then npcHandler:say('Do you really want to leave this unholy place?', cid) npcHandler.topic[cid] = 1 elseif(msgcontains(msg, "yes")) then if(npcHandler.topic[cid] == 1) then local player, destination = Player(cid), Position(32535, 31837, 4) player:getPosition():sendMagicEffect(CONST_ME_TELEPORT) player:teleportTo(destination) destination:sendMagicEffect(CONST_ME_TELEPORT) npcHandler:say('So be it!', cid) npcHandler.topic[cid] = 0 end end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:setMessage(MESSAGE_GREET, "Daraman's blessings, traveller |PLAYERNAME|.") npcHandler:setMessage(MESSAGE_FAREWELL, "Daraman's blessings") npcHandler:setMessage(MESSAGE_WALKAWAY, "Daraman's blessings") npcHandler:addModule(FocusModule:new())
package.path = package.path .. ";../lib/?.lua;../lib/?/init.lua" local ffi = require "ffi" local nn = require "nanomsg" local sdl = require "sdl2" ffi.cdef[[ int aacircleRGBA( SDL_Renderer *renderer, Sint16 x, Sint16 y, Sint16 rad, Uint8 r, Uint8 g, Uint8 b, Uint8 a ); int filledCircleRGBA( SDL_Renderer *renderer, Sint16 x, Sint16 y, Sint16 rad, Uint8 r, Uint8 g, Uint8 b, Uint8 a ); int filledTrigonRGBA( SDL_Renderer *renderer, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3, Uint8 r, Uint8 g, Uint8 b, Uint8 a ); int filledPieRGBA( SDL_Renderer *renderer, Sint16 x, Sint16 y, Sint16 rad, Sint16 start, Sint16 end, Uint8 r, Uint8 g, Uint8 b, Uint8 a ); typedef struct { Uint32 framecount; float rateticks; Uint32 baseticks; Uint32 lastticks; Uint32 rate; } FPSmanager; void SDL_initFramerate(FPSmanager *manager); int SDL_setFramerate(FPSmanager *manager, Uint32 rate); int SDL_getFramecount(FPSmanager *manager); Uint32 SDL_framerateDelay(FPSmanager *manager); ]] local gfx = ffi.load("SDL2_gfx") local initFramerate = gfx.SDL_initFramerate local setFramerate = gfx.SDL_setFramerate local getFramecount = gfx.SDL_getFramecount local framerateDelay = gfx.SDL_framerateDelay local function Rect(x, y, w, h) return ffi.new("SDL_Rect", {x, y, w, h}) end local TITLE = "nanobattle" local WIN_WIDTH, WIN_HEIGHT local BOT_RADIUS local BULLET_RADIUS local RADAR_AREA local COLORS = { {255, 0, 0}, {0, 255, 0}, {0, 0, 255}, {226, 214, 0}, {0, 255, 255}, {255, 0, 255}, {255, 255, 255}, {0, 0, 0} } local len = 256 local buf = ffi.new("char[?]", len) local function bot2color(id) local n = #COLORS local idx = id - 1 local a = idx % n local b = (a + (math.floor(idx / n)) + 1) % n return a+1, b+1 end local function recv(sock) size, err = sock:recv(buf, len) assert(size ~= nil, nn.strerror(err)) return ffi.string(buf, size) end local function init(ip, port) local err, sock, rc, size local url = "tcp://"..ip..":"..tostring(port) sock, err = nn.socket(nn.SUB) assert(sock, nn.strerror(err)) rc, err = sock:setsockopt(nn.SUB, nn.SUB_SUBSCRIBE, "", 0) assert(rc == 0, nn.strerror(err)) rc, err = sock:connect(url) assert(rc ~= nil, nn.strerror(err)) return sock end local function set_radar_radius(bot, radius) bot.rad_radius = radius bot.rad_angle = 2*RADAR_AREA/(radius*radius) end local function clear(renderer, r, g, b) sdl.renderClear(renderer) sdl.setRenderDrawColor(renderer, r, g, b, 255) sdl.renderFillRect(renderer, Rect(0, 0, WIN_WIDTH, WIN_HEIGHT)) end local function draw_bot_body(renderer, bot) gfx.filledCircleRGBA( renderer, bot.cx, bot.cy, BOT_RADIUS, bot.color_a[1], bot.color_a[2], bot.color_a[3], 255 ) local a = bot.dir local b = bot.dir + 2 * math.pi / 3 local c = bot.dir - 2 * math.pi / 3 local cosa, sina = math.cos(a), math.sin(a) local cosb, sinb = math.cos(b), math.sin(b) local cosc, sinc = math.cos(c), math.sin(c) gfx.filledTrigonRGBA( renderer, bot.cx, bot.cy, bot.cx + cosa * BOT_RADIUS, bot.cy + sina * BOT_RADIUS, bot.cx + cosb * BOT_RADIUS, bot.cy + sinb * BOT_RADIUS, bot.color_b[1], bot.color_b[2], bot.color_b[3], 255 ) gfx.filledTrigonRGBA( renderer, bot.cx, bot.cy, bot.cx + cosa * BOT_RADIUS, bot.cy + sina * BOT_RADIUS, bot.cx + cosc * BOT_RADIUS, bot.cy + sinc * BOT_RADIUS, bot.color_b[1], bot.color_b[2], bot.color_b[3], 255 ) end local function draw_bot_gun(renderer, bot) local o = math.pi / 20 local s if bot.shield == 0 then s = 1.3 - bot.wait * 0.8 / 50 else s = 0.5 end local cosa, sina = math.cos(bot.gun_dir), math.sin(bot.gun_dir) local cosb, sinb = math.cos(bot.gun_dir-o), math.sin(bot.gun_dir-o) local cosc, sinc = math.cos(bot.gun_dir+o), math.sin(bot.gun_dir+o) gfx.filledTrigonRGBA( renderer, bot.cx - cosa * BOT_RADIUS/2, bot.cy - sina * BOT_RADIUS/2, bot.cx + cosb * BOT_RADIUS*s, bot.cy + sinb * BOT_RADIUS*s, bot.cx + cosc * BOT_RADIUS*s, bot.cy + sinc * BOT_RADIUS*s, 0, 0, 0, 255 ) end local function draw_bot_shield(renderer, bot) if bot.shield == 1 then local a1 = bot.rad_dir - bot.rad_angle/2 local a2 = bot.rad_dir + bot.rad_angle/2 local s = 1 + bot.wait * 0.3 / 50 gfx.filledPieRGBA( renderer, bot.cx, bot.cy, BOT_RADIUS*s, math.deg(a1), math.deg(a2), 255, 255, 255, 255 ) end end local function draw_bot_radar(renderer, bot) local a1 = bot.rad_dir - bot.rad_angle/2 local a2 = bot.rad_dir + bot.rad_angle/2 local r, g, b if bot.visible == 0 then r, g, b = 255, 255, 255 else r, g, b = 255, 0, 0 end gfx.filledPieRGBA( renderer, bot.cx, bot.cy, bot.rad_radius, math.deg(a1), math.deg(a2), r, g, b, 96 ) end local function draw_bot_energy(renderer, bot) local e = bot.energy local r = BOT_RADIUS local dy = bot.cy < BOT_RADIUS+10 and r+5 or -r-10 local rect = Rect(bot.cx-r, bot.cy+dy, 2*r, 5) sdl.setRenderDrawColor(renderer, 0, 0, 0, 255) sdl.renderFillRect(renderer, rect) sdl.setRenderDrawColor(renderer, (100-e/2)*255/100, e*255/100, 0, 255) rect.w = rect.w * e / 100 sdl.renderFillRect(renderer, rect) end local function draw_bullet(renderer, bullet) gfx.filledCircleRGBA( renderer, bullet.x, bullet.y, BULLET_RADIUS, 255, 102, 0, 255 ) gfx.aacircleRGBA( renderer, bullet.x, bullet.y, BULLET_RADIUS, 255, 255, 255, 255 ) end local sock = init("127.0.0.1", 1800) local num = "(-?%d+)" local pattern = "! "..string.rep(num.." ", 6)..num local str while true do str = recv(sock) if string.sub(str, 1, 1) == "!" then break end end local w, h, br, fr, ra, n, m = string.match(str, pattern) for i = 1, n+m do recv(sock) end WIN_WIDTH, WIN_HEIGHT = tonumber(w), tonumber(h) BOT_RADIUS = tonumber(br) BULLET_RADIUS = tonumber(fr) RADAR_AREA = tonumber(ra) sdl.init(sdl.INIT_VIDEO) local win = sdl.createWindow( TITLE, sdl.WINDOWPOS_CENTERED, sdl.WINDOWPOS_CENTERED, WIN_WIDTH, WIN_HEIGHT, 0 ) local rdr = sdl.createRenderer(win, -1, sdl.RENDERER_ACCELERATED) local pb = string.rep(num.." ", 10)..num local pc = num.." "..num local pevent = ffi.new("SDL_Event[1]") local running = true local fps_res = 50 local t1, t2 t1 = sdl.getTicks() local frame = 0 local fps = 0 while running do while sdl.pollEvent(pevent) == 1 do local event = pevent[0] if event.type == sdl.KEYDOWN and event.key.keysym.sym == sdl.K_q then running = false end end w, h, br, fr, ra, n, m = string.match(recv(sock), pattern) local bots = {} local vis = 0 for i = 1, n do local id, bx, by, bd, gd, gw, s, rd, rr, rv, e = string.match(recv(sock), pb) id = tonumber(id) local id_a, id_b = bot2color(id) local color_a, color_b = COLORS[id_a], COLORS[id_b] local bot = { cx = tonumber(bx), cy = tonumber(by), dir = math.rad(tonumber(bd)), color_a = color_a, color_b = color_b, gun_dir = math.rad(tonumber(gd)), rad_dir = math.rad(tonumber(rd)), wait = tonumber(gw), shield = tonumber(s), visible = tonumber(rv), energy = tonumber(e) } set_radar_radius(bot, tonumber(rr)) vis = vis + bot.visible bots[i] = bot end local bullets = {} for i = 1, m do local x, y = string.match(recv(sock), pc) bullets[i] = {x = tonumber(x), y = tonumber(y)} end clear(rdr, 130, 130, 150) local layers = { draw_bot_shield, draw_bot_body, draw_bot_gun, draw_bot_radar, draw_bot_energy } for i = 1, #layers do local layer = layers[i] for j = 1, n do layer(rdr, bots[j]) end end for i = 1, m do draw_bullet(rdr, bullets[i]) end sdl.renderPresent(rdr) local title = string.format( "%s: %2d bots, %2d visible, %2d bullets (%d fps)", TITLE, n, vis, m, fps ) sdl.setWindowTitle(win, title) sdl.delay(1) frame = frame + 1 if frame == fps_res then frame = 0 t2 = sdl.getTicks() fps = fps_res * 1000 / (t2-t1) t1 = t2 end end sdl.destroyRenderer(rdr) sdl.destroyWindow(win) sdl.quit()
--[[ Polish translation by Veran120 (http://steamcommunity.com//id/Veran120) --]] NAME = "Polski" LANGUAGE = { loading = "Ładowanie", dbError = "Połączenie z bazą danych nie powiodło się", unknown = "Nieznane", noDesc = "Rysopis niedostępny", create = "Stwórz", createTip = "Stwórz nową postać aby nią zagrać.", load = "Załaduj", loadTip = "Załaduj uprzednio stworzoną postać aby nią zagrać.", leave = "Wyjdź", leaveTip = "Opuść serwer.", ["return"] = "Powrót", returnTip = "Powrót do poprzedniego menu.", name = "Imię i nazwisko", desc = "Rysopis", model = "Model", attribs = "Atrybuty", charCreateTip = "Wypełnij pola poniżej i klinij 'Zakończ' aby stworzyć swoją postać.", invalid = "Podałeś niewłaściwe(ą) %s", descMinLen = "Rysopis musi zawierać minimum %d znak(ów).", model = "Model", player = "Gracz", finish = "Zakończ", finishTip = "Zakończ tworzenie postaci.", needModel = "Musisz wybrać prawidłowy model", creating = "Twoja postać jest aktualnie tworzona...", unknownError = "Wystąpił nieznany błąd", delConfirm = "Czy jesteś pewien, że chcesz PERMANENTNIE skasować %s?", no = "Nie", yes = "Tak", itemInfo = "Imię i nazwisko %s\nRysopis: %s", cloud_no_repo = "Repozytorium, które zostało podane nie jest prawidłowe.", cloud_no_plugin = "Podany plugin nie jest prawidłowy.", inv = "Ekwipunek", plugins = "Pluginy", author = "Autor", version = "Wersja", characters = "Postacie", business = "Biznes", settings = "Ustawienia", config = "Konfiguracja", chat = "Czat", appearance = "Wygląd", misc = "Różne", oocDelay = "Musisz poczekać %s sekund przed ponownym użyciem OOC.", loocDelay = "Musisz poczekać %s sekund przed ponownym użyciem LOOC.", usingChar = "Aktualnie już używasz tej postaci.", notAllowed = "Przepraszamy, nie masz uprawnień do zrobienia tego.", itemNoExist = "Przepraszamy, przedmiot o który prosiłeś nie istnieje.", cmdNoExist = "Przepraszamy, ta komenda nie istnieje.", plyNoExist = "Przerpaszamy, nie znaleziono pasującego gracza.", cfgSet = "%s ustawił \"%s\" na %s.", drop = "Upuść", dropTip = "Upuszcza ten przedmiot z Twojego ekwipunku.", take = "Weź", takeTip = "Weź ten przedmiot i umieść go w swoim ekwipunku.", dTitle = "Drzwi możliwe do wykupienia", dTitleOwned = "Wykupione Drzwi", dIsNotOwnable = "Tych drzwi nie można kupić.", dIsOwnable = "Możesz kupić te drzwi naciskając F2.", dMadeUnownable = "Uczyniłeś te drzwi niemożliwymi do kupienia.", dMadeOwnable = "Uczyniłeś te drzwi możliwymi do kupienia.", dNotAllowedToOwn = "Nie możesz kupić tych drzwi.", dSetDisabled = "Wyłączyłeś te drzwi z użytku.", dSetNotDisabled = "Ponownie można używać tych drzwi.", dSetParentDoor = "Uczyniłeś te drzwi swoimi drzwiami nadrzędnymi.", dCanNotSetAsChild = "Nie możesz ustawi aby drzwi nadrzędne były drzwiami podrzędnymi.", dAddChildDoor = "Dodałeś te drzwi jako drzwi podrzędne.", dRemoveChildren = "Usunąłeś wszystkie drzwi podrzędne należące do tych drzwi.", dRemoveChildDoor = "Te drzwi już nie są drzwiami podrzędnymi.", dNoParentDoor = "Nie masz ustawionych drzwi nadrzędnych.", dOwnedBy = "Te drzwi należą do %s.", dConfigName = "Drzwi", dSetFaction = "Te drzwi należą teraz do frakcji %s.", dRemoveFaction = "Te drzwi już nie należą do żadnej frakcji.", dNotValid = "Nie patrzysz na prawidłowe drzwi.", canNotAfford = "Nie stać Cię na kupienie tego.", dPurchased = "Kupiłeś te drzwi za %s.", dSold = "Sprzedałeś te drzwi za %s.", notOwner = "Nie jesteś właścicielem tego.", invalidArg = "Podałeś niepoprawną wartość dla argumentu #%s.", invalidFaction = "Frakcja, którą podałeś nie mogła zostać znaleziona.", flagGive = "%s dał %s następujące flagi: '%s'.", flagGiveTitle = "Daj Flagi", flagGiveDesc = "Daj następujące flagi graczowi.", flagTake = "%s zabrał od %s następujące flagi: '%s'.", flagTakeTitle = "Zabierz Flagi", flagTakeDesc = "Zabierz następujące flagi od gracza.", flagNoMatch = "Musisz posiadać flagę(i) \"%s\" aby wykonać tą czynność.", textAdded = "Dodałeś tekst.", textRemoved = "Usunąłeś %s tekst(y).", moneyTaken = "Znalazłeś %s.", businessPurchase = "Kupiłeś %s za %s.", businessSell = "Sprzedałeś %s za %s.", cChangeModel = "%s zmienił model gracza %s na %s.", cChangeName = "%s zmienił imię gracza %s na %s.", playerCharBelonging = "Ten przedmiot należy do innej postaci należącej do Ciebie.", business = "Biznes", invalidFaction = "Wprowadziłeś niewłaściwą frakcję.", spawnAdd = "Dodaj punkt odradzania się (Spawn) dla %s.", spawnDeleted = "Usunąłeś %s punktów odradzania się (spawn'u).", someone = "Ktoś", rgnLookingAt = "Pozwól osobie na którą patrzysz aby Cię rozpoznawała.", rgnWhisper = "Pozwól tym, którzy są w zasięgu Twoich szeptów aby Cię rozpoznawali.", rgnTalk = "Pozwól tym, którzy są w zasięgu normalnych rozmów aby Cię rozpoznawali.", rgnYell = "Pozwól tym, którzy są w zasięgu Twoich krzyków aby Cię rozpoznawali.", icFormat = "%s mówi: \"%s\"", rollFormat = "%s wylosował %s rzucając kośćmi.", wFormat = "%s szepcze: \"%s\"", yFormat = "%s krzyczy: \"%s\"", sbOptions = "Kliknij aby zobaczyć opcje dla %s.", spawnAdded = "Dodałeś punkt odradzania się (Spawn) dla %s.", whitelist = "%s dodał %s na białą listę frakcji %s.", unwhitelist = "%s usunął %s z białej listy frakcji %s.", gettingUp = "Podnosisz się...", wakingUp = "Wraca Ci świadomość...", Weapons = "Broń", checkout = "Idź do kasy (%s)", purchase = "Kup", purchasing = "Kupuję...", success = "Sukces", buyFailed = "Zakupy nie powiodły się.", buyGood = "Zakupy udane!", shipment = "Dostawa", shipmentDesc = "Ta dostawa należy do %s.", class = "Klasa", classes = "Klasy", illegalAccess = "Nielegalny Dostęp.", becomeClassFail = "Nie udało Ci się zostać %s.", becomeClass = "Zostałeś %s.", attribSet = "Postać %s ma teraz %s ustawioną na %s.", attribUpdate = "Postać %s ma teraz %s podwyższoną o %s.", noFit = "Ten przedmiot nie mieści się w Twoim ekwipunku.", help = "Pomoc", commands = "Komendy", helpDefault = "Wybierz kateogrię", doorSettings = "Ustawienia drzwi", sell = "Sprzedaj", access = "Dostęp", locking = "Zamykanie tego przedmiotu...", unlocking = "Otwieranie tego przedmiotu...", modelNoSeq = "Twój model nie obsługuje tej animacji.", notNow = "Nie możesz tego aktualnie zrobić.", faceWall = "Musisz patrzeć na ścianę aby to wykonać.", faceWallBack = "Musisz stać tyłem do ściany aby to wykonać.", descChanged = "Zmieniłeś rysopis swojej postaci.", charMoney = "Aktualnie posiadasz %s.", charFaction = "Jesteś członkiem frakcji %s.", charClass = "Piastujesz stanowisko %s we frakcji.", noSpace = "Ekwipunek jest pełny.", noOwner = "Nieprawidłowy właściciel.", notAllowed = "Ta akcja jest niedozowolna.", invalidIndex = "Index przedmiotu jest nieprawidłowy.", invalidItem = "Obiekt przedmiotu jest nieprawidłowy.", invalidInventory = "Obiekt ekwipunku jest nieprawidłowy.", home = "Strona główna", charKick = "%s wyrzucił %s.", charBan = "%s zbanował postać %s.", charBanned = "Ta postać jest niedostępna.", setMoney = "Ustawiłem ilość pieniędzy %s na %s.", itemPriceInfo = "Możesz kupić ten przedmiot za %s.\nMożesz sprzedać ten przedmiot za %s", free = "Darmowe", vendorNoSellItems = "Nie ma przedmiotów do sprzedania.", vendorNoBuyItems = "Nie ma przedmiotów do kupienia.", vendorSettings = "Ustawienia sprzedawców", vendorUseMoney = "Czy sprzedawcy powinni używać pieniędzy?", vendorNoBubble = "Ukryć dymek sprzedawcy?", mode = "Tryb", price = "Cena", stock = "Zasób", none = "Nic", vendorBoth = "Kupowanie i Sprzedawanie", vendorBuy = "Tylko kupowanie", vendorSell = "Tylko sprzedawanie", maxStock = "Maksymalny zasób", vendorFaction = "Edytor frakcji", buy = "Kup", vendorWelcome = "Witaj w moim sklepie, czy mogę Ci coś podać?", vendorBye = "Przyjdź niedługo z powrotem!", charSearching = "Aktualnie szukasz już innej postaci, proszę poczekać.", charUnBan = "%s odbanował postać %s.", charNotBanned = "Ta postać nie jest zbanowana.", storPass = "Ustawiłeś hasło tego pojemnika na %s.", storPassRmv = "Usunąłeś hasło z tego pojemnika.", storPassWrite = "Wprowadź hasło.", wrongPassword = "Wprowadziłeś złe hasło.", cheapBlur = "Wyłączyć rozmazywanie? (Podnosi FPSy)", quickSettings = "Szybkie Ustawienia", vmSet = "Ustawiłeś swoją automatyczną sekretarkę.", vmRem = "Usunąłeś swoją automatyczną sekretarkę.", altLower = "Ukryć dłonie kiedy są opuszczone?", noPerm = "Nie wolno Ci tego zrobić.", youreDead = "Jesteś martwy.", injMajor = "Widoczne krytyczne obrażenia.", injLittle = "Widoczne obrażenia.", toggleESP = "Włącz/Wyłącz Admiński wallhack.", chgName = "Zmień imię i nazwisko.", chgNameDesc = "Wprowadź nowę imię i nazwisko postaci poniżej.", thirdpersonToggle = "Przełącz widok z trzeciej osoby", thirdpersonClassic = "Używaj klasycznego widoku z trzeciej osoby", equippedBag = "Torba którą przesunąłeś posiada przedmiot(y).", useTip = "Używa przedmiotu.", equipTip = "Zakłada przedmiot.", unequipTip = "Zdejmuje przedmiot.", consumables = "Towary konsumpcyjne.", plyNotValid = "Nie patrzysz na prawidłowego gracza.", restricted = "Zostałeś związany.", viewProfile = "Obejrzyj profil Steam." }
-- Various torch additions, should move to torch itself torch.select = function (A, dim, index) return A:select(dim, index) end torch.index = function (A, dim, index) return A:index(dim, index) end torch.narrow = function(A, dim, index, size) return A:narrow(dim, index, size) end torch.clone = function(A) local B = A.new(A:size()) return B:copy(A) end torch.contiguous = function(A) return A:contiguous() end torch.copy = function(A,B) local o = A:copy(B) return o end torch.size = function(A, dim) return A:size(dim) end torch.nDimension = function(A) return A:nDimension() end torch.nElement = function(A) return A:nElement() end torch.isSameSizeAs = function(A, B) return A:isSameSizeAs(B) end torch.transpose = function(A, d1, d2) return A:transpose(d1,d2) end torch.t = function(A) return A:t() end torch.long = function(A) return A:long() end torch.narrow = function(A, dim, index, size) return A:narrow(dim, index, size) end torch.typeAs = function(A, B) return A:type(B:type()) end local numberMetatable = { __add = function(a,b) if type(a) == "number" then return b + a else error("attempt to perform arithmetic on a " .. type(a) .. " value", 2) end end, __sub = function(a,b) if type(a) == "number" then return -b + a else error("attempt to perform arithmetic on a " .. type(a) .. " value", 2) end end, __mul = function(a,b) if type(a) == "number" then return b * a else error("attempt to perform arithmetic on a " .. type(a) .. " value", 2) end end } debug.setmetatable(1.0, numberMetatable)
require'nvim-treesitter.configs'.setup { ensure_installed = "all", ignore_install = { "haskell" }, highlight = { enable = true, additional_vim_regex_highlighting = false, }, indent = { enable = true, }, matchup = { enable = true, }, }
local functions = {} function functions.quitGame() -- cleans up before quiting the game if ENET_IS_CONNECTED then -- test if pressing ESC on main screen (i.e. quiting) if #CURRENT_SCREEN == 1 then if IS_A_CLIENT then EnetHandler.disconnectClient(LANDERS[1].connectionID) elseif IS_A_HOST then EnetHandler.disconnectHost() else error("Error 10 occured while player disconnected.") end end end love.event.quit() end function functions.AddScreen(strNewScreen) table.insert(CURRENT_SCREEN, strNewScreen) end function functions.RemoveScreen() if #CURRENT_SCREEN == 1 then functions.quitGame() end table.remove(CURRENT_SCREEN) end function functions.CurrentScreenName() -- returns the current active screen return CURRENT_SCREEN[#CURRENT_SCREEN] end function functions.SwapScreen(newscreen) -- swaps screens so that the old screen is removed from the stack -- this adds the new screen then removes the 2nd last screen. Fun.AddScreen(newscreen) table.remove(CURRENT_SCREEN, #CURRENT_SCREEN - 1) end function functions.SaveGameSettings() -- save game settings so they can be autoloaded next session local savefile local serialisedString local success, message local savedir = love.filesystem.getSource() savefile = savedir .. "/" .. "settings.dat" serialisedString = Bitser.dumps(GAME_SETTINGS) success, message = Nativefs.write(savefile, serialisedString ) end function functions.LoadGameSettings() local savedir = love.filesystem.getSource() love.filesystem.setIdentity( savedir ) local savefile, contents savefile = savedir .. "/" .. "settings.dat" contents, _ = Nativefs.read(savefile) local success success, GAME_SETTINGS = pcall(Bitser.loads, contents) --! should do pcall on all the "load" functions if success == false then GAME_SETTINGS = {} end --[[ FIXME: -- This is horrible bugfix and needs refactoring. If a player doesn't have -- a settings.dat already then all the values in GAME_SETTINGS table are -- nil. This sets some reasonable defaults to stop nil value crashes. ]]-- if GAME_SETTINGS.PlayerName == nil then GAME_SETTINGS.PlayerName = DEFAULT_PLAYER_NAME end if GAME_SETTINGS.hostIP == nil then GAME_SETTINGS.hostIP = HOST_IP_ADDRESS end if GAME_SETTINGS.hostPort == nil then GAME_SETTINGS.hostPort = "22122" end if GAME_SETTINGS.FullScreen == nil then GAME_SETTINGS.FullScreen = false end if GAME_SETTINGS.HighScore == nil then GAME_SETTINGS.HighScore = 0 end -- Set the gloal player name to the new value CURRENT_PLAYER_NAME = GAME_SETTINGS.PlayerName end function functions.SaveGame() -- uses the globals because too hard to pass params --! for some reason bitser throws runtime error when serialising true / false values. local savefile local contents local success, message local savedir = love.filesystem.getSource() savefile = savedir .. "/" .. "landers.dat" serialisedString = Bitser.dumps(LANDERS) success, message = Nativefs.write(savefile, serialisedString ) savefile = savedir .. "/" .. "ground.dat" serialisedString = Bitser.dumps(GROUND) success, message = Nativefs.write(savefile, serialisedString ) savefile = savedir .. "/" .. "objects.dat" serialisedString = Bitser.dumps(OBJECTS) success, message = Nativefs.write(savefile, serialisedString ) LovelyToasts.show("Game saved",3, "middle") end function functions.LoadGame() local savedir = love.filesystem.getSource() love.filesystem.setIdentity( savedir ) local savefile local contents local size local error = false savefile = savedir .. "/" .. "ground.dat" if Nativefs.getInfo(savefile) then contents, size = Nativefs.read(savefile) GROUND = bitser.loads(contents) else error = true end savefile = savedir .. "/" .. "objects.dat" if Nativefs.getInfo(savefile) then contents, size = Nativefs.read(savefile) OBJECTS = bitser.loads(contents) else error = true end savefile = savedir .. "/" .. "landers.dat" if Nativefs.getInfo(savefile) then contents, size = Nativefs.read(savefile) LANDERS = bitser.loads(contents) else error = true end if error then -- a file is missing, so display a popup on a new game Fun.ResetGame() LovelyToasts.show("ERROR: Unable to load game!", 3, "middle") end end function functions.CalculateScore() local score = LANDERS[1].x - ORIGIN_X if score > GAME_SETTINGS.HighScore then GAME_SETTINGS.HighScore = score Fun.SaveGameSettings() -- this needs to be refactored somehow, not save every change end return score end function functions.GetDistanceToClosestBase(xvalue, intBaseType) -- returns two values: the distance to the closest base, and the object/table item for that base -- if there are no bases (impossible) then the distance value returned will be -1 -- note: if distance is a negative value then the Lander has not yet passed the base local closestdistance = -1 local closestbase = {} local absdist local dist local realdist for k,v in pairs(OBJECTS) do if v.objecttype == intBaseType then -- the + bit is an offset to calculate the landing pad and not the image absdist = math.abs(xvalue - (v.x + 85)) -- same but without the math.abs) dist = (xvalue - (v.x + 85)) if closestdistance == -1 or absdist <= closestdistance then closestdistance = absdist closestbase = v end end end -- now we have the closest base, work out the distance to the landing pad for that base if closestbase then -- the + bit is an offset to calculate the landing pad and not the image realdist = xvalue - (closestbase.x + 85) end return realdist, closestbase end function functions.ResetGame() -- this resets the game for all landers - including multiplayer landers GROUND = {} OBJECTS = {} -- TODO: don't reset whole table but instead reset status, fuel amounts etc. Smoke.destroy() -- ensure Terrain.init appears before Lander.create Terrain.init() -- TODO: mplayer needs to reset without wiping LANDERS -- or to wipe LANDERS and recreate each client if not ENET_IS_CONNECTED then LANDERS = {} table.insert(LANDERS, Lander.create()) end end return functions
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2012-2014 Kenny Shields -- --]]------------------------------------------------ -- get the current require path local path = string.sub(..., 1, string.len(...) - string.len(".objects.tree")) local loveframes = require(path .. ".libraries.common") -- button object local newobject = loveframes.NewObject("tree", "loveframes_object_tree", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize() self.type = "tree" self.width = 200 self.height = 200 self.offsetx = 0 self.offsety = 0 self.itemwidth = 0 self.itemheight = 0 self.extrawidth = 0 self.extraheight = 0 self.buttonscrollamount = 0.10 self.vbar = false self.hbar = false self.internal = false self.selectednode = false self.OnSelectNode = nil self.children = {} self.internals = {} end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the object --]]--------------------------------------------------------- function newobject:update(dt) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end self:CheckHover() local parent = self.parent local base = loveframes.base local update = self.Update -- move to parent if there is a parent if parent ~= base then self.x = self.parent.x + self.staticx self.y = self.parent.y + self.staticy end self.itemwidth = 0 self.itemheight = 0 for k, v in ipairs(self.children) do v.x = (v.parent.x + v.staticx) - self.offsetx v.y = (self.y + self.itemheight) - self.offsety if v.width > self.itemwidth then self.itemwidth = v.width end self.itemheight = self.itemheight + v.height v:update(dt) end if self.vbar then self.itemwidth = self.itemwidth + 16 + 5 end self.extrawidth = self.itemwidth - self.width self.extraheight = self.itemheight - self.height if self.itemheight > self.height then if not self.vbar then local scrollbody = loveframes.objects["scrollbody"]:new(self, "vertical") table.insert(self.internals, scrollbody) self.vbar = true if self.hbar then local vbody = self:GetVerticalScrollBody() local vbodyheight = vbody:GetHeight() - 15 local hbody = self:GetHorizontalScrollBody() local hbodywidth = hbody:GetWidth() - 15 vbody:SetHeight(vbodyheight) hbody:SetWidth(hbodywidth) end end else if self.vbar then self:GetVerticalScrollBody():Remove() self.vbar = false self.offsety = 0 if self.hbar then local hbody = self:GetHorizontalScrollBody() local hbodywidth = hbody:GetWidth() - 15 hbody:SetWidth(hbodywidth) end end end if self.itemwidth > self.width then if not self.hbar then local scrollbody = loveframes.objects["scrollbody"]:new(self, "horizontal") table.insert(self.internals, scrollbody) self.hbar = true if self.vbar then local vbody = self:GetVerticalScrollBody() local hbody = self:GetHorizontalScrollBody() vbody:SetHeight(vbody:GetHeight() - 15) hbody:SetWidth(hbody:GetWidth() - 15) end end else if self.hbar then self:GetHorizontalScrollBody():Remove() self.hbar = false self.offsetx = 0 if self.vbar then local vbody = self:GetVerticalScrollBody() if vbody then vbody:SetHeight(vbody:GetHeight() + 15) end end end end for k, v in ipairs(self.internals) do v:update(dt) end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] local drawfunc = skin.DrawTree or skins[defaultskin].DrawTree local draw = self.Draw local drawcount = loveframes.drawcount -- set the object's draw order self:SetDrawOrder() if self.vbar and not self.hbar then love.graphics.setScissor(self.x, self.y, self.width - 16, self.height) elseif self.hbar and not self.vbar then love.graphics.setScissor(self.x, self.y, self.width, self.height - 16) elseif self.vbar and self.hbar then love.graphics.setScissor(self.x, self.y, self.width - 16, self.height - 16) end if draw then draw(self) else drawfunc(self) end for k, v in ipairs(self.children) do v:draw() end love.graphics.setScissor() for k, v in ipairs(self.internals) do v:draw() end end --[[--------------------------------------------------------- - func: mousepressed(x, y, button) - desc: called when the player presses a mouse button --]]--------------------------------------------------------- function newobject:mousepressed(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end for k, v in ipairs(self.internals) do v:mousepressed(x, y, button) end for k, v in ipairs(self.children) do v:mousepressed(x, y, button) end end --[[--------------------------------------------------------- - func: mousereleased(x, y, button) - desc: called when the player releases a mouse button --]]--------------------------------------------------------- function newobject:mousereleased(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end for k, v in ipairs(self.internals) do v:mousereleased(x, y, button) end for k, v in ipairs(self.children) do v:mousereleased(x, y, button) end end --[[--------------------------------------------------------- - func: AddNode(text) - desc: adds a node to the object --]]--------------------------------------------------------- function newobject:AddNode(text) local node = loveframes.objects["treenode"]:new() node.parent = self node.tree = self node.text = text node.staticx = 0 node.staticy = self.itemheight table.insert(self.children, node) return node end --[[--------------------------------------------------------- - func: RemoveNode(id) - desc: removes a node from the object --]]--------------------------------------------------------- function newobject:RemoveNode(id) for k, v in ipairs(self.children) do if k == id then v:Remove() break end end end --[[--------------------------------------------------------- - func: GetVerticalScrollBody() - desc: gets the object's vertical scroll body --]]--------------------------------------------------------- function newobject:GetVerticalScrollBody() local vbar = self.vbar local internals = self.internals local item = false if vbar then for k, v in ipairs(internals) do if v.type == "scrollbody" and v.bartype == "vertical" then item = v end end end return item end --[[--------------------------------------------------------- - func: GetHorizontalScrollBody() - desc: gets the object's horizontal scroll body --]]--------------------------------------------------------- function newobject:GetHorizontalScrollBody() local hbar = self.hbar local internals = self.internals local item = false if hbar then for k, v in ipairs(internals) do if v.type == "scrollbody" and v.bartype == "horizontal" then item = v end end end return item end
return { name = "Русский [Built-in]", description = "Перевод на русский язык.", api_version = 4, -- please use ISO 639-1 plus country code if required language_code = "ru" }
Weapon.PrettyName = "M24" Weapon.WeaponID = "m9k_m24" Weapon.DamageMultiplier = 2.2 Weapon.WeaponType = WEAPON_PRIMARY
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB local S = E:GetModule('Skins') --Cache global variables --Lua functions local _G = _G local select, unpack = select, unpack --WoW API / Variables --Global variables that we don't cache, list them here for mikk's FindGlobals script -- GLOBALS: local function LoadSkin() if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.help ~= true then return end local frames = { "HelpFrameLeftInset", "HelpFrameMainInset", "HelpFrameKnowledgebase", "HelpFrameKnowledgebaseErrorFrame", } local buttons = { "HelpFrameAccountSecurityOpenTicket", "HelpFrameOpenTicketHelpOpenTicket", "HelpFrameKnowledgebaseSearchButton", "HelpFrameKnowledgebaseNavBarHomeButton", "HelpFrameCharacterStuckStuck", "HelpFrameButton16", "HelpFrameSubmitSuggestionSubmit", "HelpFrameReportBugSubmit", } for i = 1, #frames do _G[frames[i]]:StripTextures(true) _G[frames[i]]:CreateBackdrop("Transparent") end HelpFrameHeader:StripTextures(true) HelpFrameHeader:CreateBackdrop("Default", true) HelpFrameHeader:SetFrameLevel(HelpFrameHeader:GetFrameLevel() + 2) HelpFrameKnowledgebaseErrorFrame:SetFrameLevel(HelpFrameKnowledgebaseErrorFrame:GetFrameLevel() + 2) HelpFrameReportBugScrollFrame:StripTextures() HelpFrameReportBugScrollFrame:CreateBackdrop("Transparent") HelpFrameReportBugScrollFrame.backdrop:Point("TOPLEFT", -4, 4) HelpFrameReportBugScrollFrame.backdrop:Point("BOTTOMRIGHT", 6, -4) for i = 1, HelpFrameReportBug:GetNumChildren() do local child = select(i, HelpFrameReportBug:GetChildren()) if not child:GetName() then child:StripTextures() end end S:HandleScrollBar(HelpFrameReportBugScrollFrameScrollBar) HelpFrameSubmitSuggestionScrollFrame:StripTextures() HelpFrameSubmitSuggestionScrollFrame:CreateBackdrop("Transparent") HelpFrameSubmitSuggestionScrollFrame.backdrop:Point("TOPLEFT", -4, 4) HelpFrameSubmitSuggestionScrollFrame.backdrop:Point("BOTTOMRIGHT", 6, -4) for i=1, HelpFrameSubmitSuggestion:GetNumChildren() do local child = select(i, HelpFrameSubmitSuggestion:GetChildren()) if not child:GetName() then child:StripTextures() end end S:HandleScrollBar(HelpFrameSubmitSuggestionScrollFrameScrollBar) S:HandleScrollBar(HelpFrameKnowledgebaseScrollFrame2ScrollBar) -- skin sub buttons for i = 1, #buttons do _G[buttons[i]]:StripTextures(true) S:HandleButton(_G[buttons[i]], true) if _G[buttons[i]].text then _G[buttons[i]].text:ClearAllPoints() _G[buttons[i]].text:Point("CENTER") _G[buttons[i]].text:SetJustifyH("CENTER") end end -- skin main buttons for i = 1, 6 do local b = _G["HelpFrameButton"..i] S:HandleButton(b, true) b.text:ClearAllPoints() b.text:Point("CENTER") b.text:SetJustifyH("CENTER") end -- skin table options for i = 1, HelpFrameKnowledgebaseScrollFrameScrollChild:GetNumChildren() do local b = _G["HelpFrameKnowledgebaseScrollFrameButton"..i] b:StripTextures(true) S:HandleButton(b, true) end --Navigation buttons S:HandleButton(HelpBrowserNavHome) HelpBrowserNavHome:Size(26) HelpBrowserNavHome:ClearAllPoints() HelpBrowserNavHome:SetPoint("BOTTOMLEFT", HelpBrowser, "TOPLEFT", -5, 9) S:HandleNextPrevButton(HelpBrowserNavBack) HelpBrowserNavBack:Size(26) S:HandleNextPrevButton(HelpBrowserNavForward) HelpBrowserNavForward:Size(26) S:HandleButton(HelpBrowserNavReload) HelpBrowserNavReload:Size(26) S:HandleButton(HelpBrowserNavStop) HelpBrowserNavStop:Size(26) S:HandleButton(HelpBrowserBrowserSettings) HelpBrowserBrowserSettings:Size(26) HelpBrowserBrowserSettings:ClearAllPoints() HelpBrowserBrowserSettings:SetPoint("TOPRIGHT", HelpFrameCloseButton, "TOPLEFT", -3, -8) -- skin misc items HelpFrameKnowledgebaseSearchBox:ClearAllPoints() HelpFrameKnowledgebaseSearchBox:Point("TOPLEFT", HelpFrameMainInset, "TOPLEFT", 13, -10) HelpFrameKnowledgebaseNavBar:StripTextures() local HelpFrame = _G["HelpFrame"] HelpFrame:StripTextures(true) HelpFrame:CreateBackdrop("Transparent") S:HandleEditBox(HelpFrameKnowledgebaseSearchBox) S:HandleScrollBar(HelpFrameKnowledgebaseScrollFrameScrollBar, 5) S:HandleCloseButton(HelpFrameCloseButton, HelpFrame.backdrop) S:HandleCloseButton(HelpFrameKnowledgebaseErrorFrameCloseButton, HelpFrameKnowledgebaseErrorFrame.backdrop) --Hearth Stone Button HelpFrameCharacterStuckHearthstone:StyleButton() HelpFrameCharacterStuckHearthstone:SetTemplate("Default", true) HelpFrameCharacterStuckHearthstone.IconTexture:SetInside() HelpFrameCharacterStuckHearthstone.IconTexture:SetTexCoord(unpack(E.TexCoords)) S:HandleButton(HelpFrameGM_ResponseNeedMoreHelp) S:HandleButton(HelpFrameGM_ResponseCancel) for i=1, HelpFrameGM_Response:GetNumChildren() do local child = select(i, HelpFrameGM_Response:GetChildren()) if child and child:GetObjectType() == "Frame" and not child:GetName() then child:SetTemplate("Default") end end end S:AddCallback("Help", LoadSkin)
-- Plane of Fire function events.AfterLoadMap() Party.QBits[931] = true -- DDMapBuff, changed for rev4 for merge end
buffer = "" function readint() if buffer == "" then buffer = io.read("*line") end local num, buffer0 = string.match(buffer, '^([%-%d]*)(.*)') buffer = buffer0 return tonumber(num) end function stdinsep() if buffer == "" then buffer = io.read("*line") end if buffer ~= nil then buffer = string.gsub(buffer, '^%s*', "") end end function copytab (tab, len) local o = {} for i = 0, len - 1 do o[i + 1] = tab[i + 1] end return o end function bubblesort (tab, len) for i = 0, len - 1 do for j = i + 1, len - 1 do if tab[i + 1] > tab[j + 1] then local tmp = tab[i + 1] tab[i + 1] = tab[j + 1] tab[j + 1] = tmp end end end end function qsort0 (tab, len, i, j) if i < j then local i0 = i local j0 = j --[[ pivot : tab[0] --]] while i ~= j do if tab[i + 1] > tab[j + 1] then if i == j - 1 then --[[ on inverse simplement--]] local tmp = tab[i + 1] tab[i + 1] = tab[j + 1] tab[j + 1] = tmp i = i + 1 else --[[ on place tab[i+1] à la place de tab[j], tab[j] à la place de tab[i] et tab[i] à la place de tab[i+1] --]] local tmp = tab[i + 1] tab[i + 1] = tab[j + 1] tab[j + 1] = tab[i + 2] tab[i + 2] = tmp i = i + 1 end else j = j - 1 end end qsort0(tab, len, i0, i - 1) qsort0(tab, len, i + 1, j0) end end local len = 2 len = readint() stdinsep() local tab = {} for i_ = 0, len - 1 do local tmp = 0 tmp = readint() stdinsep() tab[i_ + 1] = tmp end local tab2 = copytab(tab, len) bubblesort(tab2, len) for i = 0, len - 1 do io.write(string.format("%d ", tab2[i + 1])) end io.write("\n") local tab3 = copytab(tab, len) qsort0(tab3, len, 0, len - 1) for i = 0, len - 1 do io.write(string.format("%d ", tab3[i + 1])) end io.write("\n")
local ui = {} local Style = getClass 'wyx.ui.Style' local command = require 'wyx.ui.command' local colors = colors local floor = math.floor local yOffset = 40 local panelWidth = 0.6 * WIDTH local panelHeight = 0.75 * HEIGHT local titleFont = GameFont.bighuge local titleFontH = titleFont:getHeight() local titleMargin = 48 ui.title = { x = 0, y = 0, w = WIDTH, h = titleFontH + titleMargin*2, margin = titleMargin, text = '@ Game Menu @', normalStyle = Style({ font = titleFont, fontcolor = colors.LIGHTORANGE, }) } ui.keysID = 'PlayMenu' ui.keys = { O = command('MENU_OPTIONS'), H = command('MENU_HELP'), A = command('DELETE_GAME'), S = command('MENU_SAVE_GAME'), M = command('MENU_MAIN'), escape = command('EXIT_MENU'), } ui.screenStyle = Style({ bgcolor = colors.GREY20, }) ui.panel = { x = floor(WIDTH/2) - floor(panelWidth/2), y = HEIGHT - (panelHeight + yOffset), w = panelWidth, h = panelHeight, normalStyle = Style({ bordersize = 4, borderinset = 4, bordercolor = colors.GREY30, bgcolor = colors.GREY10, }), } -- positions are relative to parent (panel) local INNERMARGIN = 24 ui.innerpanel = { x = INNERMARGIN, y = INNERMARGIN, w = ui.panel.w - INNERMARGIN*2, h = ui.panel.h - INNERMARGIN*2, hmargin = 8, -- horizontal space bewteen child elements vmargin = 2, -- vertical space bewteen child elements } local font = GameFont.big local fontH = font:getHeight() ui.button = { w = ui.innerpanel.w, h = fontH * 2.5, normalStyle = Style({ bordersize = 4, borderinset = 4, bordercolor = colors.GREY50, bgcolor = colors.GREY30, fontcolor = colors.GREY80, font = font, }), } ui.button.hoverStyle = ui.button.normalStyle:clone({ fontcolor = colors.ORANGE, bordercolor = colors.LIGHTORANGE, }) ui.button.activeStyle = ui.button.hoverStyle:clone({ bgcolor = colors.DARKORANGE, }) ui.buttons = { {'Options', command('MENU_OPTIONS')}, {'Help', command('MENU_HELP')}, {'Abandon Game', command('DELETE_GAME')}, {'Save and Continue', command('MENU_SAVE_GAME')}, {'Save and Quit', command('MENU_MAIN')}, } return ui
--define the class ACF_defineGunClass("MO", { spread = 0.64, name = "Mortar", desc = "Mortars are able to fire shells with usefull payloads from a light weight gun, at the price of limited velocities.", muzzleflash = "mortar_muzzleflash_noscale", rofmod = 2.5, sound = "weapons/ACF_Gun/mortar_new.mp3", soundDistance = "Mortar.Fire", soundNormal = " " }) --add a gun to the class --id ACF_defineGun("60mmM", { name = "60mm Mortar", desc = "The 60mm is a common light infantry support weapon, with a high rate of fire but a puny payload.", model = "models/mortar/mortar_60mm.mdl", gunclass = "MO", caliber = 6.0, weight = 60, rofmod = 1.25, year = 1930, round = { maxlength = 20, propweight = 0.037 } }) ACF_defineGun("80mmM", { name = "80mm Mortar", desc = "The 80mm is a common infantry support weapon, with a good bit more boom than its little cousin.", model = "models/mortar/mortar_80mm.mdl", gunclass = "MO", caliber = 8.0, weight = 120, year = 1930, round = { maxlength = 28, propweight = 0.055 } }) ACF_defineGun("120mmM", { name = "120mm Mortar", desc = "The versatile 120 is sometimes vehicle-mounted to provide quick boomsplat to support the infantry. Carries more boom in its boomsplat, has good HEAT performance, and is more accurate in high-angle firing.", model = "models/mortar/mortar_120mm.mdl", gunclass = "MO", caliber = 12.0, weight = 640, year = 1935, round = { maxlength = 45, propweight = 0.175 } }) ACF_defineGun("150mmM", { name = "150mm Mortar", desc = "The perfect balance between the 120mm and the 200mm. Can prove a worthy main gun weapon, as well as a mighty good mortar emplacement", model = "models/mortar/mortar_150mm.mdl", gunclass = "MO", caliber = 15.0, weight = 1255, year = 1945, round = { maxlength = 58, propweight = 0.235 } }) ACF_defineGun("200mmM", { name = "200mm Mortar", desc = "The 200mm is a beast, often used against fortifications. Though enormously powerful, feel free to take a nap while it reloads", model = "models/mortar/mortar_200mm.mdl", gunclass = "MO", caliber = 20.0, weight = 2850, year = 1940, round = { maxlength = 80, propweight = 0.330 } }) --[[ ACF_defineGun("280mmM", { name = "280mm Mortar", desc = "Massive payload, with a reload time to match. Found in rare WW2 siege artillery pieces. It's the perfect size for a jeep.", model = "models/mortar/mortar_280mm.mdl", gunclass = "MO", caliber = 28.0, weight = 9035, year = 1945, round = { maxlength = 138, propweight = 0.462 } } ) ]] --
QBCore = nil notLoaded, currentStreetName, intersectStreetName, lastStreet, speedlimit, nearbyPeds, isPlayerWhitelisted, playerPed, playerCoords, job, rank, firstname, lastname, phone = true playerIsDead = false Citizen.CreateThread(function() while QBCore == nil do TriggerEvent('QBCore:GetObject', function(obj) QBCore = obj end) Citizen.Wait(10) end while QBCore.Functions.GetPlayerData().job == nil do Citizen.Wait(10) end GetPlayerInfo() end) RegisterNetEvent('QBCore:Client:OnPlayerLoaded') AddEventHandler('QBCore:Client:OnPlayerLoaded', function() GetPlayerInfo() end) RegisterNetEvent('QBCore:Client:OnJobUpdate') AddEventHandler('QBCore:Client:OnJobUpdate', function(job) QBCore.PlayerData = QBCore.Functions.GetPlayerData() job = QBCore.PlayerData.job.name rank = QBCore.PlayerData.job.grade.name isPlayerWhitelisted = refreshPlayerWhitelisted() end) function GetPlayerInfo() local playerData = QBCore.Functions.GetPlayerData() firstname = playerData.charinfo.firstname lastname = playerData.charinfo.lastname phone = playerData.charinfo.phone job = playerData.job.name rank = playerData.job.grade.label isPlayerWhitelisted = refreshPlayerWhitelisted() end AddEventHandler('onPlayerDied', function(data) playerIsDead = true end) AddEventHandler('playerSpawned', function(data) playerIsDead = false end)
test = require 'u-test' common = require 'common' function GetUserProfiles_Handler() print("GetUserProfiles_Handler") XblProfileGetUserProfilesAsync() end function OnXblProfileGetUserProfilesAsync() print("OnXblProfileGetUserProfilesAsync") test.stopTest(); end test.GetUserProfiles = function() common.init(GetUserProfiles_Handler) end
local serialize = require 'src/serialize' local oop = require 'src/oop' local folder = oop.class() function folder:init(name) self.temp_count = nil self.name = name -- local path = 'folders/' .. name .. '.lua' -- Look first in save dir, then in game folders. -- if love.filesystem.getInfo(path) then -- self.data = love.filesystem.load()() -- else self.data = love.filesystem.load('folders/' .. name .. '.lua')() -- end end function folder:save(name) if name then self.name = name end local outdir = 'folders/' love.filesystem.createDirectory(outdir) serialize.to_config( love.filesystem.getSaveDirectory() .. '/' .. outdir .. self.name, self.data) end -- Sort a folder using a specific method. -- @method: How to sort. If the specified method doesn't work, uses a priority -- list. -- @reverse: If true, switch the default sort upside down. function folder:sort(method, reverse) local fetch_functions = { letter = function (chip) return chip.letter end, name = function (chip) return chip.name end, amount = function (chip) return -chip.amount end, element = function (chip) return GAME.chipdb[chip.name].element end, } local method_priority_lists = { letter = {'letter', 'name'}, name = {'name', 'letter'}, amount = {'amount', 'letter', 'name'}, element = {'element', 'letter', 'name'}, } local priority_list = method_priority_lists[method] local sort_function = function (a,b) for _,method in ipairs(priority_list) do local fetch = fetch_functions[method] local a_val,b_val = fetch(a), fetch(b) if a_val < b_val then return not reverse end if a_val > b_val then return reverse end end return not reverse end table.sort(self.data, sort_function) end function folder:condense() for i,a in ipairs(self.data) do for j = i+1,#self.data do local b = self.data[j] if a.name == b.name and a.letter == b.letter then a.amount = a.amount + b.amount b.amount = 0 end end end for _,v in ipairs(self.data) do if v.amount == 0 then table.remove(self.data, v) end end end function folder:find(entry) for i=1,#self.data do if self.data[i].name == entry.name and self.data[i].letter == entry.letter then return i end end end function folder:insert(entry) self.temp_count = nil local i = self:find(entry) if i then self.data[i].amount = self.data[i].amount + 1 else entry.amount = 1 table.insert(self.data, entry) end end function folder:remove(index) self.temp_count = nil index = index or love.math.random(#self.data) local entry = self.data[index] if not entry then print('tried to remove nonexistant index:', index) return end if not GAME.debug.endless_folder then entry.amount = entry.amount - 1 end if entry.amount==0 then table.remove(self.data, index) end return {name = entry.name, letter = entry.letter} end function folder:count() if not self.temp_count then self.temp_count = 0 for _,v in ipairs(self.data) do self.temp_count = self.temp_count + v.amount end end return self.temp_count end -- Draw a folder, optionally fill a palette function folder:draw(num, pal) pal = pal or {} for i=1,num do if not pal[i] then pal[i] = self:remove() end end return pal end return folder
-- --------------------------------------------- -- png.lua 2014/06/05 -- Copyright (c) 2013-2014 Jun Mizutani, -- released under the MIT open source license. -- --------------------------------------------- local ffi = require("ffi") local libpng = ffi.load("libpng12.so.0") ffi.cdef[[ typedef struct _IO_FILE FILE; typedef char charf; typedef struct z_stream_s z_stream; typedef long int __jmp_buf[8]; typedef struct { unsigned long int __val[(1024 / (8 * sizeof (unsigned long int)))]; } __sigset_t; typedef __sigset_t sigset_t; struct __jmp_buf_tag { __jmp_buf __jmpbuf; int __mask_was_saved; __sigset_t __saved_mask; }; typedef struct __jmp_buf_tag jmp_buf[1]; typedef const char * png_const_charp; typedef struct png_struct_def png_struct; typedef png_struct * png_structp; typedef png_struct * * png_structpp; typedef unsigned long png_uint_32; typedef long png_int_32; typedef unsigned short png_uint_16; typedef short png_int_16; typedef unsigned char png_byte; typedef size_t png_size_t; typedef png_int_32 png_fixed_point; typedef void * png_voidp; typedef png_byte * png_bytep; typedef png_uint_32 * png_uint_32p; typedef png_int_32 * png_int_32p; typedef png_uint_16 * png_uint_16p; typedef png_int_16 * png_int_16p; typedef const char * png_const_charp; typedef char * png_charp; typedef png_fixed_point * png_fixed_point_p; typedef FILE * png_FILE_p; typedef double * png_doublep; typedef png_byte ** png_bytepp; typedef png_uint_32 ** png_uint_32pp; typedef png_int_32 ** png_int_32pp; typedef png_uint_16 ** png_uint_16pp; typedef png_int_16 ** png_int_16pp; typedef const char ** png_const_charpp; typedef char ** png_charpp; typedef png_fixed_point * * png_fixed_point_pp; typedef double ** png_doublepp; typedef char * * * png_charppp; typedef charf * png_zcharp; typedef charf * * png_zcharpp; typedef z_stream * png_zstreamp; extern const char png_libpng_ver[18]; extern const int png_pass_start[7]; extern const int png_pass_inc[7]; extern const int png_pass_ystart[7]; extern const int png_pass_yinc[7]; extern const int png_pass_mask[7]; extern const int png_pass_dsp_mask[7]; typedef struct png_color_struct { png_byte red; png_byte green; png_byte blue; } png_color; typedef png_color * png_colorp; typedef png_color * * png_colorpp; typedef struct png_color_16_struct { png_byte index; png_uint_16 red; png_uint_16 green; png_uint_16 blue; png_uint_16 gray; } png_color_16; typedef png_color_16 * png_color_16p; typedef png_color_16 * * png_color_16pp; typedef struct png_color_8_struct { png_byte red; png_byte green; png_byte blue; png_byte gray; png_byte alpha; } png_color_8; typedef png_color_8 * png_color_8p; typedef png_color_8 * * png_color_8pp; typedef struct png_sPLT_entry_struct { png_uint_16 red; png_uint_16 green; png_uint_16 blue; png_uint_16 alpha; png_uint_16 frequency; } png_sPLT_entry; typedef png_sPLT_entry * png_sPLT_entryp; typedef png_sPLT_entry * * png_sPLT_entrypp; typedef struct png_sPLT_struct { png_charp name; png_byte depth; png_sPLT_entryp entries; png_int_32 nentries; } png_sPLT_t; typedef png_sPLT_t * png_sPLT_tp; typedef png_sPLT_t * * png_sPLT_tpp; typedef struct png_text_struct { int compression; png_charp key; png_charp text; png_size_t text_length; } png_text; typedef png_text * png_textp; typedef png_text * * png_textpp; typedef struct png_time_struct { png_uint_16 year; png_byte month; png_byte day; png_byte hour; png_byte minute; png_byte second; } png_time; typedef png_time * png_timep; typedef png_time * * png_timepp; typedef struct png_unknown_chunk_t { png_byte name[5]; png_byte *data; png_size_t size; png_byte location; } png_unknown_chunk; typedef png_unknown_chunk * png_unknown_chunkp; typedef png_unknown_chunk * * png_unknown_chunkpp; typedef struct png_info_struct { png_uint_32 width ; png_uint_32 height ; png_uint_32 valid ; png_uint_32 rowbytes ; png_colorp palette ; png_uint_16 num_palette ; png_uint_16 num_trans ; png_byte bit_depth ; png_byte color_type ; png_byte compression_type ; png_byte filter_type ; png_byte interlace_type ; png_byte channels ; png_byte pixel_depth ; png_byte spare_byte ; png_byte signature[8] ; float gamma ; png_byte srgb_intent ; int num_text ; int max_text ; png_textp text ; png_time mod_time ; png_color_8 sig_bit ; png_bytep trans ; png_color_16 trans_values ; png_color_16 background ; png_int_32 x_offset ; png_int_32 y_offset ; png_byte offset_unit_type ; png_uint_32 x_pixels_per_unit ; png_uint_32 y_pixels_per_unit ; png_byte phys_unit_type ; png_uint_16p hist ; float x_white ; float y_white ; float x_red ; float y_red ; float x_green ; float y_green ; float x_blue ; float y_blue ; png_charp pcal_purpose ; png_int_32 pcal_X0 ; png_int_32 pcal_X1 ; png_charp pcal_units ; png_charpp pcal_params ; png_byte pcal_type ; png_byte pcal_nparams ; png_uint_32 free_me ; png_unknown_chunkp unknown_chunks ; png_size_t unknown_chunks_num ; png_charp iccp_name ; png_charp iccp_profile ; png_uint_32 iccp_proflen ; png_byte iccp_compression ; png_sPLT_tp splt_palettes ; png_uint_32 splt_palettes_num ; png_byte scal_unit ; double scal_pixel_width ; double scal_pixel_height ; png_charp scal_s_width ; png_charp scal_s_height ; png_bytepp row_pointers ; png_fixed_point int_gamma ; png_fixed_point int_x_white ; png_fixed_point int_y_white ; png_fixed_point int_x_red ; png_fixed_point int_y_red ; png_fixed_point int_x_green ; png_fixed_point int_y_green ; png_fixed_point int_x_blue ; png_fixed_point int_y_blue ; } png_info; typedef png_info * png_infop; typedef png_info * * png_infopp; typedef struct png_row_info_struct { png_uint_32 width; png_uint_32 rowbytes; png_byte color_type; png_byte bit_depth; png_byte channels; png_byte pixel_depth; } png_row_info; typedef png_row_info * png_row_infop; typedef png_row_info * * png_row_infopp; typedef void ( *png_error_ptr) (png_structp, png_const_charp); extern png_structp png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn); extern png_infop png_create_info_struct(png_structp png_ptr); extern void png_init_io(png_structp png_ptr, png_FILE_p fp); extern void png_read_info(png_structp png_ptr, png_infop info_ptr); extern png_uint_32 png_get_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 *width, png_uint_32 *height, int *bit_depth, int *color_type, int *interlace_method, int *compression_method, int *filter_method); extern void png_set_filler(png_structp png_ptr, png_uint_32 filler, int flags); extern png_voidp png_malloc(png_structp png_ptr, png_uint_32 size); extern void png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers); extern void png_read_image(png_structp png_ptr, png_bytepp image); extern void png_destroy_read_struct (png_structpp png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr); extern png_structp png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn); extern void png_write_info(png_structp png_ptr, png_infop info_ptr); extern void png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr); extern void png_write_png (png_structp png_ptr, png_infop info_ptr, int transforms, png_voidp params); ]] local png = { PNG_LIBPNG_VER_STRING = "1.2.49", PNG_COLOR_MASK_COLOR = 2, PNG_COLOR_MASK_ALPHA = 4, PNG_COLOR_TYPE_RGB_ALPHA = 6, PNG_COLOR_TYPE_RGB = 2, PNG_COLOR_TYPE_RGBA = 6, PNG_FILLER_AFTER = 1, PNG_INTERLACE_NONE = 0, PNG_FILTER_TYPE_BASE = 0, PNG_FILTER_TYPE_DEFAULT = 0, PNG_COMPRESSION_TYPE_BASE = 0, PNG_COMPRESSION_TYPE_DEFAULT = 0, PNG_TRANSFORM_IDENTITY = 0x0000, PNG_TRANSFORM_STRIP_16 = 0x0001, PNG_TRANSFORM_STRIP_ALPHA = 0x0002, PNG_TRANSFORM_PACKING = 0x0004, PNG_TRANSFORM_PACKSWAP = 0x0008, PNG_TRANSFORM_EXPAND = 0x0010, PNG_TRANSFORM_INVERT_MONO = 0x0020, PNG_TRANSFORM_SHIFT = 0x0040, PNG_TRANSFORM_BGR = 0x0080, PNG_TRANSFORM_SWAP_ALPHA = 0x0100, PNG_TRANSFORM_SWAP_ENDIAN = 0x0200, PNG_TRANSFORM_INVERT_ALPHA = 0x0400, PNG_TRANSFORM_STRIP_FILLER = 0x0800, PNG_TRANSFORM_STRIP_FILLER_BEFORE = 0x0800, PNG_TRANSFORM_STRIP_FILLER_AFTER = 0x1000, PNG_TRANSFORM_GRAY_TO_RGB = 0x2000, png_create_read_struct = libpng.png_create_read_struct, png_create_info_struct = libpng.png_create_info_struct, png_init_io = libpng.png_init_io, png_read_info = libpng.png_read_info, png_get_IHDR = libpng.png_get_IHDR, png_set_filler = libpng.png_set_filler, png_malloc = libpng.png_malloc, png_set_rows = libpng.png_set_rows, png_read_image = libpng.png_read_image, png_destroy_read_struct = libpng.png_destroy_read_struct, png_create_write_struct = libpng.png_create_write_struct, png_write_info = libpng.png_write_info, png_destroy_write_struct = libpng.png_destroy_write_struct, png_write_png = libpng.png_write_png } -- --------------------------------------------------------------------- -- Read image from PNG file. -- image, bytes, width, height, bpp, ncol = readPNG(filename, fill) -- --------------------------------------------------------------------- function png.readPNG(filename, fill) local ncol = 4 local width = ffi.new("uint32_t[1]") local height = ffi.new("uint32_t[1]") --local width = ffi.new("uint64_t[1]") --local height = ffi.new("uint64_t[1]") local bpp = ffi.new("uint32_t[1]") local color_type = ffi.new("uint32_t[1]") local interlace_type = ffi.new("uint32_t[1]") local fh, err = io.open(filename, "rb") if fh == nil then print(err) return nil end local png_ptr = libpng.png_create_read_struct( png.PNG_LIBPNG_VER_STRING, nil, nil, nil) local info_ptr = libpng.png_create_info_struct(png_ptr) libpng.png_init_io(png_ptr, fh) libpng.png_read_info(png_ptr, info_ptr) libpng.png_get_IHDR(png_ptr, info_ptr, width, height, bpp, color_type, interlace_type, nil, nil) if (color_type[0] == png.PNG_COLOR_TYPE_RGB) then if fill ~= 0 then libpng.png_set_filler(png_ptr, 255, png.PNG_FILLER_AFTER) else ncol = 3 end end local row_pointers = ffi.new('png_bytep[?]', height[0]) local buflen = width[0] * height[0] * (bpp[0]/8 * ncol) local image = ffi.new("unsigned char[?]", buflen) for i = 0, tonumber(height[0] - 1) do row_pointers[i] = ffi.cast('png_bytep', image + (i * width[0] * (bpp[0] / 8 * ncol))) end libpng.png_set_rows(png_ptr, info_ptr, row_pointers) libpng.png_read_image(png_ptr, row_pointers) local end_info if png_ptr ~= nil then libpng.png_destroy_read_struct(ffi.new('png_structp[1]', png_ptr), ffi.new('png_infop[1]', info_ptr), ffi.new('png_infop[1]', end_info)) end fh:close() return image, buflen, width[0], height[0], bpp[0], ncol end -- --------------------------------------------------------------------- -- Write image into PNG file. -- writePNG(filename, image, width, height, bpp, ncol) -- if ncol == 3 then RGB else RGBA -- --------------------------------------------------------------------- function png.writePNG(filename, image, width, height, bpp, ncol) local fh = io.open(filename, "wb") local png_ptr = libpng.png_create_write_struct( png.PNG_LIBPNG_VER_STRING, nil, nil, nil) local info_ptr = libpng.png_create_info_struct(png_ptr) if ncol ~= 3 then ncol = 4 end libpng.png_init_io(png_ptr, fh) info_ptr.width = width info_ptr.height = height info_ptr.bit_depth = bpp if ncol == 3 then info_ptr.color_type = png.PNG_COLOR_TYPE_RGB else info_ptr.color_type = png.PNG_COLOR_TYPE_RGBA end info_ptr.interlace_type = png.PNG_INTERLACE_NONE info_ptr.compression_type = png.PNG_COMPRESSION_TYPE_DEFAULT info_ptr.filter_type = png.PNG_FILTER_TYPE_DEFAULT local row_pointers = ffi.new('png_bytep[?]', height) for i=0, height-1 do row_pointers[i] = ffi.cast('png_bytep', image + (i*width*(bpp/8*ncol))) end libpng.png_set_rows(png_ptr, info_ptr, row_pointers); libpng.png_write_png(png_ptr, info_ptr, png.PNG_TRANSFORM_IDENTITY, nil) libpng.png_destroy_write_struct(ffi.new('png_structp[1]', png_ptr), ffi.new('png_infop[1]', info_ptr)) end function png.flipImage(image, width, height, ncol) local n = math.floor((height - 1) / 2) for y = 0, n do local bottom = height - 1 - y for x = 0, width - 1 do local m = (y * width + x) * ncol local k = (bottom * width + x) * ncol image[m ], image[k ] = image[k ], image[m ] image[m+1], image[k+1] = image[k+1], image[m+1] image[m+2], image[k+2] = image[k+2], image[m+2] if ncol == 4 then image[m+3], image[k+3] = image[k+3], image[m+3] end end end end return png
AddCSLuaFile() ENT.Type = "anim" ENT.Base = "ttt_basegrenade_proj" ENT.Model = Model("models/weapons/w_eq_fraggrenade.mdl") AccessorFunc( ENT, "radius", "Radius", FORCE_NUMBER ) function ENT:Initialize() self.Hit = false self.CurrentPitch = 100 self:SetMaterial( "models/alyx/emptool_glow" ) -- self:SetModelScale(self:GetModelScale()*0.75,0) if SERVER then util.SpriteTrail(self, 0, Color(0,100,255), false, 32, 1, 0.3, 0.01, "trails/plasma.vmt") end self.WhirrSound = CreateSound(self, "ambient/energy/force_field_loop1.wav") self.WhirrSound:Play() if not self:GetRadius() then self:SetRadius(20) end return self.BaseClass.Initialize(self) end if CLIENT then function ENT:CreateSmoke(center) local em = ParticleEmitter(center) for i=1,24 do local smoke = em.Add("particle/particle_smokegrenade", vOrig) if (smoke) then smoke:SetColor(25, 125, 200) smoke:SetVelocity(VectorRand():GetNormal()*math.random(100, 300)) smoke:SetRoll(math.Rand(0, 360)) smoke:SetRollDelta(math.Rand(-2, 2)) smoke:SetDieTime(1) smoke:SetLifeTime(0) smoke:SetStartSize(50) smoke:SetStartAlpha(255) smoke:SetEndSize(100) smoke:SetEndAlpha(0) smoke:SetGravity(Vector(0,0,0)) end local smoke2 = em.Add("particle/particle_smokegrenade", vOrig) if (smoke2) then smoke2:SetColor(25, 125, 200) smoke2:SetVelocity(VectorRand():GetNormal()*math.random(50, 100)) smoke2:SetRoll(math.Rand(0, 360)) smoke2:SetRollDelta(math.Rand(-2, 2)) smoke2:SetDieTime(5) smoke2:SetLifeTime(0) smoke2:SetStartSize(50) smoke2:SetStartAlpha(255) smoke2:SetEndSize(100) smoke2:SetEndAlpha(0) smoke2:SetGravity(Vector(0,0,0)) end local smoke3 = em.Add("particle/particle_smokegrenade", vOrig+Vector(math.random(-150,150),math.random(-150,150),0)) if (smoke3) then smoke3:SetColor(0, 25, 50) smoke3:SetVelocity(VectorRand():GetNormal()*math.random(50, 100)) smoke3:SetRoll(math.Rand(0, 360)) smoke3:SetRollDelta(math.Rand(-2, 2)) smoke3:SetDieTime(5) smoke3:SetLifeTime(0) smoke3:SetStartSize(50) smoke3:SetStartAlpha(255) smoke3:SetEndSize(100) smoke3:SetEndAlpha(0) smoke3:SetGravity(Vector(0,0,0)) end local heat = em.Add("sprites/heatwave", vOrig+Vector(math.random(-150,150),math.random(-150,150),0)) if (heat) then heat:SetColor(0, 25, 50) heat:SetVelocity(VectorRand():GetNormal()*math.random(50, 100)) heat:SetRoll(math.Rand(0, 360)) heat:SetRollDelta(math.Rand(-2, 2)) heat:SetDieTime(3) heat:SetLifeTime(0) heat:SetStartSize(100) heat:SetStartAlpha(255) heat:SetEndSize(0) heat:SetEndAlpha(0) heat:SetGravity(Vector(0,0,0)) end end for i=1,72 do local sparks = em.Add("effects/spark", vOrig) if (sparks) then sparks:SetColor(0, 200, 255) sparks:SetVelocity(VectorRand():GetNormal()*math.random(300, 500)) sparks:SetRoll(math.Rand(0, 360)) sparks:SetRollDelta(math.Rand(-2, 2)) sparks:SetDieTime(2) sparks:SetLifeTime(0) sparks:SetStartSize(3) sparks:SetStartAlpha(255) sparks:SetStartLength(15) sparks:SetEndLength(3) sparks:SetEndSize(3) sparks:SetEndAlpha(255) sparks:SetGravity(Vector(0,0,-800)) end local sparks2 = em.Add("effects/spark", vOrig) if (sparks2) then sparks2:SetColor(0, 200, 255) sparks2:SetVelocity(VectorRand():GetNormal()*math.random(400, 800)) sparks2:SetRoll(math.Rand(0, 360)) sparks2:SetRollDelta(math.Rand(-2, 2)) sparks2:SetDieTime(0.4) sparks2:SetLifeTime(0) sparks2:SetStartSize(5) sparks2:SetStartAlpha(255) sparks2:SetStartLength(80) sparks2:SetEndLength(0) sparks2:SetEndSize(5) sparks2:SetEndAlpha(0) sparks2:SetGravity(Vector(0,0,0)) end end for i=1,8 do local flash = em.Add("effects/combinemuzzle2_dark", vOrig) if (flash) then flash:SetColor(255, 255, 255) flash:SetVelocity(VectorRand():GetNormal()*math.random(10, 30)) flash:SetRoll(math.Rand(0, 360)) flash:SetDieTime(0.10) flash:SetLifeTime(0) flash:SetStartSize(150) flash:SetStartAlpha(255) flash:SetEndSize(240) flash:SetEndAlpha(0) flash:SetGravity(Vector(0,0,0)) end local quake = em.Add("effects/splashwake3", vOrig) if (quake) then quake:SetColor(0, 175, 255) quake:SetVelocity(VectorRand():GetNormal()*math.random(10, 30)) quake:SetRoll(math.Rand(0, 360)) quake:SetDieTime(0.10) quake:SetLifeTime(0) quake:SetStartSize(160) quake:SetStartAlpha(200) quake:SetEndSize(270) quake:SetEndAlpha(0) quake:SetGravity(Vector(0,0,0)) end local wave = em.Add("sprites/heatwave", vOrig) if (wave) then wave:SetColor(0, 175, 255) wave:SetVelocity(VectorRand():GetNormal()*math.random(10, 30)) wave:SetRoll(math.Rand(0, 360)) wave:SetDieTime(0.25) wave:SetLifeTime(0) wave:SetStartSize(160) wave:SetStartAlpha(255) wave:SetEndSize(270) wave:SetEndAlpha(0) wave:SetGravity(Vector(0,0,0)) end end em:Finish() end end function ENT:Explode(tr) if SERVER then self:SetNoDraw(true) self:SetSolid(SOLID_NONE) -- pull out of the surface if tr.Fraction != 1.0 then self:SetPos(tr.HitPos + tr.HitNormal * 0.6) end local pos = self:GetPos() self:Remove() else local spos = self:GetPos() local trs = util.TraceLine({start=spos + Vector(0,0,64), endpos=spos + Vector(0,0,-128), filter=self}) util.Decal("SmallScorch", trs.HitPos + trs.HitNormal, trs.HitPos - trs.HitNormal) self:SetDetonateExact(0) if tr.Fraction != 1.0 then spos = tr.HitPos + tr.HitNormal * 0.6 end -- Smoke particles can't get cleaned up when a round restarts, so prevent -- them from existing post-round. if GetRoundState() == ROUND_POST then return end self:CreateSmoke(spos) end end function ENT:Think() if self.Hit then self.CurrentPitch = self.CurrentPitch + 5 if self.WhirrSound then self.WhirrSound:ChangePitch(math.Clamp(self.CurrentPitch,100,255),0) end end if self.Hit && self.Splodetimer && self.Splodetimer < CurTime() then util.ScreenShake( self:GetPos(), 50, 50, 1, 250 ) if IsValid(self.Owner) then if IsValid(self.Inflictor) then util.BlastDamage(self.Inflictor, self.Owner, self:GetPos(), 150, 88) else util.BlastDamage(self, self.Owner, self:GetPos(), 150, 88) end end local fx = EffectData() fx:SetOrigin(self:GetPos()) util.Effect("plasmasplode", fx) self:EmitSound("ambient/energy/zap"..math.random(1,9)..".wav",90,100) self:EmitSound("ambient/explosions/explode_"..math.random(7,9)..".wav",90,100) self:EmitSound("weapons/explode"..math.random(3,5)..".wav",90,85) self:Remove() end end function ENT:Touch(ent) if IsValid(ent) && !self.Stuck then if ent:IsNPC() || (ent:IsPlayer() && ent != self:GetOwner()) || (ent == self:GetOwner() && self.SpawnDelay < CurTime() ) || ent:IsVehicle() then self:SetSolid(SOLID_NONE) self:SetMoveType(MOVETYPE_NONE) self:SetParent(ent) if !self.Splodetimer then self.Splodetimer = CurTime() + 2 end self.Stuck = true self.Hit = true end end end function ENT:PhysicsCollide(data,phys) if self:IsValid() && !self.Hit then self:SetCollisionGroup(COLLISION_GROUP_DEBRIS) if !self.Splodetimer then self.Splodetimer = CurTime() + 2 end self.Hit = true end end function ENT:OnRemove() if self.WhirrSound then self.WhirrSound:Stop() end if IsValid(self.Fear) then self.Fear:Fire("kill") end return self.BaseClass.OnRemove(self) end
return LoadFont("_miso")..{ InitCommand=function(self) self:xy(IsUsingWideScreen() and 50, _screen.cy-24):zoom(0.8):diffusealpha(0) end, OnCommand=function(self) self:diffusealpha(0):settext(THEME:GetString("ScreenSelectMusic", "FooterTextSongs")):linear(0.15):diffusealpha(1) end, }
----------------------------------- -- Area: Port Windurst -- NPC: Degong -- Type: Fishing Synthesis Image Support -- !pos -178.400 -3.835 60.480 240 ----------------------------------- require("scripts/globals/status") require("scripts/globals/crafting") local ID = require("scripts/zones/Port_Windurst/IDs") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) local guildMember = isGuildMember(player, 5) local SkillCap = getCraftSkillCap(player, tpz.skill.FISHING) local SkillLevel = player:getSkillLevel(tpz.skill.FISHING) if (guildMember == 1) then if (player:hasStatusEffect(tpz.effect.FISHING_IMAGERY) == false) then player:startEvent(10013, SkillCap, SkillLevel, 2, 239, player:getGil(), 0, 30, 0) -- p1 = skill level else player:startEvent(10013, SkillCap, SkillLevel, 2, 239, player:getGil(), 19293, 30, 0) end else player:startEvent(10013) -- Standard Dialogue end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 10013 and option == 1) then player:messageSpecial(ID.text.FISHING_SUPPORT, 0, 0, 2) player:addStatusEffect(tpz.effect.FISHING_IMAGERY, 1, 0, 3600) end end
--get the addon namespace local addon, ns = ... --get oUF namespace (just in case needed) local oUF = ns.oUF or oUF --get the config local cfg = ns.cfg --get the functions local func = ns.func --get the unit container local unit = ns.unit --------------------------------------------- -- UNIT SPECIFIC FUNCTIONS --------------------------------------------- --init parameters local initUnitParameters = function(self) self:SetFrameStrata("BACKGROUND") self:SetFrameLevel(1) self:SetSize(self.cfg.width, self.cfg.height) self:SetScale(self.cfg.scale) self:SetPoint(self.cfg.pos.a1,self.cfg.pos.af,self.cfg.pos.a2,self.cfg.pos.x,self.cfg.pos.y) self:RegisterForClicks("AnyDown") self:SetScript("OnEnter", UnitFrame_OnEnter) self:SetScript("OnLeave", UnitFrame_OnLeave) func.applyDragFunctionality(self) end --actionbar background local createArtwork = function(self) local t = self:CreateTexture(nil,"BACKGROUND",nil,-8) t:SetAllPoints(self) t:SetTexture("Interface\\AddOns\\oUF_Diablo\\media\\targettarget") end --create health frames local createHealthFrame = function(self) local cfg = self.cfg.health --health local h = CreateFrame("StatusBar", nil, self) h:SetPoint("TOP",0,-21.9) h:SetPoint("LEFT",24.5,0) h:SetPoint("RIGHT",-24.5,0) h:SetPoint("BOTTOM",0,28.7) h:SetStatusBarTexture(cfg.texture) h.bg = h:CreateTexture(nil,"BACKGROUND",nil,-6) h.bg:SetTexture(cfg.texture) h.bg:SetAllPoints(h) h.glow = h:CreateTexture(nil,"OVERLAY",nil,-5) h.glow:SetTexture("Interface\\AddOns\\oUF_Diablo\\media\\targettarget_hpglow") h.glow:SetAllPoints(self) h.glow:SetVertexColor(0,0,0,1) h.highlight = h:CreateTexture(nil,"OVERLAY",nil,-4) h.highlight:SetTexture("Interface\\AddOns\\oUF_Diablo\\media\\targettarget_highlight") h.highlight:SetAllPoints(self) self.Health = h self.Health.Smooth = true end --create power frames local createPowerFrame = function(self) local cfg = self.cfg.power --power local h = CreateFrame("StatusBar", nil, self) h:SetPoint("TOP",0,-38.5) h:SetPoint("LEFT",24.5,0) h:SetPoint("RIGHT",-24.5,0) h:SetPoint("BOTTOM",0,21.9) h:SetStatusBarTexture(cfg.texture) h.bg = h:CreateTexture(nil,"BACKGROUND",nil,-6) h.bg:SetTexture(cfg.texture) h.bg:SetAllPoints(h) h.glow = h:CreateTexture(nil,"OVERLAY",nil,-5) h.glow:SetTexture("Interface\\AddOns\\oUF_Diablo\\media\\targettarget_ppglow") h.glow:SetAllPoints(self) h.glow:SetVertexColor(0,0,0,1) self.Power = h self.Power.Smooth = true end --create health power strings local createHealthPowerStrings = function(self) local name = func.createFontString(self, cfg.font, 14, "THINOUTLINE") name:SetPoint("BOTTOM", self, "TOP", 0, -13) name:SetPoint("LEFT", self.Health, 0, 0) name:SetPoint("RIGHT", self.Health, 0, 0) self.Name = name local hpval = func.createFontString(self.Health, cfg.font, 11, "THINOUTLINE") hpval:SetPoint("RIGHT", -2,0) self:Tag(name, "[diablo:name]") self:Tag(hpval, self.cfg.health.tag or "") end --------------------------------------------- -- PET STYLE FUNC --------------------------------------------- local function createStyle(self) --apply config to self self.cfg = cfg.units.pet self.cfg.style = "pet" self.cfg.width = 128 self.cfg.height = 64 --init initUnitParameters(self) --create the art createArtwork(self) --createhealthPower createHealthFrame(self) createPowerFrame(self) --health power strings createHealthPowerStrings(self) --health power update self.Health.PostUpdate = func.updateHealth self.Power.PostUpdate = func.updatePower --create portrait if self.cfg.portrait.show then func.createPortrait(self) self:SetHitRectInsets(0, 0, -100, 0); end --castbar if self.cfg.castbar.show then func.createCastbar(self) elseif self.cfg.castbar.hideDefault then --do not show the default castbar PetCastingBarFrame:UnregisterAllEvents() PetCastingBarFrame.Show = PetCastingBarFrame.Hide PetCastingBarFrame:Hide() end --auras if self.cfg.auras.show then func.createDebuffs(self) self.Debuffs.PostCreateIcon = func.createAuraIcon end --debuffglow func.createDebuffGlow(self) --make alternative power bar movable (vehicle) if self.cfg.altpower.show then func.createAltPowerBar(self,"oUF_AltPowerPet") end --threat self:RegisterEvent("UNIT_THREAT_SITUATION_UPDATE", func.checkThreat) --icons self.RaidIcon = func.createIcon(self,"BACKGROUND",18,self.Name,"BOTTOM","TOP",0,0,-1) --add heal prediction func.healPrediction(self) --add total absorb func.totalAbsorb(self) --add self to unit container (maybe access to that unit is needed in another style) unit.pet = self end --------------------------------------------- -- SPAWN PET UNIT --------------------------------------------- if cfg.units.pet.show then oUF:RegisterStyle("diablo:pet", createStyle) oUF:SetActiveStyle("diablo:pet") oUF:Spawn("pet", "oUF_DiabloPetFrame") end
local libcore = require "core.libcore" -- The Class module implements basic OOP functionality local Class = require "Base.Class" -- The base class for all units local Unit = require "Unit" -- A graphical control for the unit menu local OptionControl = require "Unit.MenuControl.OptionControl" -- A graphical control for comparator objects on the unit input local InputGate = require "Unit.ViewControl.InputGate" -- A graphical control for gainbias objects local GainBias = require "Unit.ViewControl.GainBias" -- A graphical control for comparator objects local Gate = require "Unit.ViewControl.Gate" -- Needed to get access to the pre-defined encoder maps local Encoder = require "Encoder" -- Create an empty class definition for the Countdown unit local Countdown = Class {} -- Use inclusion to effectively inherit from the Unit class Countdown:include(Unit) -- The constructor function Countdown:init(args) -- This is the default title shown in the unit header. args.title = "Count- down" -- This is the 2 letter abbreviation for this unit. args.mnemonic = "Cd" -- Optionally, set a version number unique to this unit. args.version = 1 -- Make sure to call the parent class constructor also. Unit.init(self, args) end -- This method will be called during unit instantiation. Create the DSP graph here. -- pUnit : an object containing the unit's input and output ports. -- channelCount: used to determine if we are building a mono or stereo version of this unit. function Countdown:onLoadGraph(channelCount) -- The addObject method is used to instantiate and name DSP objects. -- Create a Gate object for digitizing the incoming signal into triggers. local input = self:addObject("input", app.Comparator()) -- A comparator has trigger, gate and toggle output modes. Configure the comparator to output triggers. input:setTriggerMode() -- Create a Counter object, turn off wrapping and set its initial parameter values. local counter = self:addObject("counter", libcore.Counter()) counter:setOptionValue("Wrap", app.CHOICE_NO) counter:hardSet("Gain", 1) counter:hardSet("Step Size", -1) counter:hardSet("Start", 0) -- Here we connect the output of the 'input' comparator to the input of the 'counter' object. connect(input, "Out", counter, "In") -- Since a comparator only fires when the threshold is exceeded from below, let's negate the output of the counter. local negate = self:addObject("negate", app.ConstantGain()) negate:hardSet("Gain", -1) connect(counter, "Out", negate, "In") -- Create another Gate object for the output. local output = self:addObject("output", app.Comparator()) output:setTriggerMode() output:hardSet("Threshold", -0.5) connect(negate, "Out", output, "In") -- And yet another Gate object for the reset control. local reset = self:addObject("reset", app.Comparator()) reset:setTriggerMode() connect(reset, "Out", counter, "Reset") -- We need an external control for setting what value to start counting from. local start = self:addObject("start", app.ParameterAdapter()) -- Give it an initial value, otherwise it will be zero. start:hardSet("Bias", 4) -- Unlike audio-rate signals, parameters are tied together like this slave parameter to master parameter. Think of it as an assignment. -- Note: We need to use the counter's Finish parameter because our step size is negative. tie(counter, "Finish", start, "Out") -- Register sub-chains (internally called branches) for modulation. self:addMonoBranch("start", start, "In", start, "Out") self:addMonoBranch("reset", reset, "In", reset, "Out") -- Finally, connect the output of the 'output' Gate to the unit output(s). connect(output, "Out", self, "Out1") if channelCount > 1 then connect(output, "Out", self, "Out2") end -- Force a reset to occur, so that the counter is ready to go. reset:simulateRisingEdge() reset:simulateFallingEdge() end -- Describe the layout of the menu in terms of its controls. local menu = { "wrap", "processingRate" } -- Here we create each control for the menu. function Countdown:onShowMenu(objects, branches) local controls = {} controls.wrap = OptionControl { description = "Wrap?", option = objects.counter:getOption("Wrap"), choices = { "yes", "no" } } controls.processingRate = OptionControl { description = "Process Rate", option = objects.counter:getOption("Processing Rate"), choices = { "frame", "sample" } } return controls, menu end -- Describe the layout of unit expanded and collapsed views in terms of its controls. local views = { expanded = { "input", "count", "reset" }, collapsed = {} } -- Here we create each control for the unit. function Countdown:onLoadViews(objects, branches) local controls = {} -- An InputGate control wraps a comparator object (passed into the comparator argument). controls.input = InputGate { button = "input", description = "Unit Input", comparator = objects.input } -- A GainBias control wraps any object with a Bias and Gain parameter. controls.count = GainBias { button = "count", description = "Count", branch = branches.start, gainbias = objects.start, range = objects.start, biasMap = Encoder.getMap("int[1,256]"), biasPrecision = 0 } -- A Gate control wraps a comparator object (passed into the comparator parameter). controls.reset = Gate { button = "reset", description = "Reset Counter", branch = branches.reset, comparator = objects.reset, param = objects.counter:getParameter("Value"), readoutPrecision = 0 } return controls, views end -- Don't forget to return the unit class definition return Countdown
object_mobile_outbreak_undead_civilian_46 = object_mobile_shared_outbreak_undead_civilian_46:new { } ObjectTemplates:addTemplate(object_mobile_outbreak_undead_civilian_46, "object/mobile/outbreak_undead_civilian_46.iff")
------------------------------------------------------------------------------ -- Gauge class ------------------------------------------------------------------------------ local ctrl = { nick = "gauge", parent = iup.WIDGET, creation = "", callback = {}, subdir = "ctrl", include = "iupcontrols.h", } function ctrl.createElement(class, param) return iup.Gauge(param.action) end iup.RegisterWidget(ctrl) iup.SetClass(ctrl, "iupWidget")
require('nvim-lightbulb').update_lightbulb { sign = { enabled = true, priority = 10, }, float = { enabled = true, text = "💡", }, } vim.cmd [[autocmd CursorHold,CursorHoldI * lua require'nvim-lightbulb'.update_lightbulb()]]
return { ["in-ipv6-frag-reassembly-unneeded"] = 1, ["memuse-ipv4-frag-reassembly-buffer"] = 728203264, ["memuse-ipv6-frag-reassembly-buffer"] = 11378176, ["in-ndp-ns-packets"] = 1, ["in-ndp-ns-bytes"] = 86, }
#!/usr/bin/env lua5.3 package.path = "../?.lua;" .. package.path require "luarocks.loader" --pcall(require, "luacov") --measure code coverage -- -- Need to create some assertations missing from busted that -- were present in lunatest -- luaassert = require "luassert" say = require "say" local function gte( state, arguments ) local a = arguments[1] local b = arguments[2] if a <= b then return true end return false end local function gt( state, arguments ) local a = arguments[1] local b = arguments[2] if a < b then return true end return false end say:set( "assertion.is_gte.failed", "Expected number to be equal or larger.\nPassed in: \n%s\nExpected:\n%s" ) say:set( "assertion.is_gt.failed", "Expected number to be larger.\nPassed in: \n%s\nExpected:\n%s" ) luaassert:register( "assertion", "is_gte", gte, "assertion.is_gte.failed" ) luaassert:register( "assertion", "is_gt", gt, "assertion.is_gt.failed" ) require 'busted.runner'() --pcall(require, "luacov") --measure code coverage, if luacov is present sqltable = require "sqltable" -- -- Set this to 'true' to dump SQL code while tests run. -- local tdebug = false -- -- Setup tests -- local function setup_tests() if not env then env = assert(sqltable.connect( config.connection )) if tdebug then env:debugging( function ( q, args ) print(q) for k, v in pairs(args) do print(k, '"'..tostring(v)..'"') end end ) end end return env end -- -- Teardown, to clean up for the next test -- local function teardown_tests() local outstanding = env.pool:outstanding() assert(outstanding == 0, "Leaked " .. tonumber(outstanding) .. " connections!") if env then env:close() end end -- -- Get a table. -- -- We close and reopen the table for every test to ensure sane state. -- However, we don't close and reopen the connection pool: We assume -- it can keep itself sane. We prove that in test-connection.lua -- instead. -- local function gettable( table_name, key, readonly ) assert(env, "Need environment") return assert(env:open_table{ name = table_name, key = key or 'id', readonly = readonly or false, vendor = config[table_name .. '_vendor'] or {} }) end -- -- Test that we can connect. -- function test_init() local t, err = gettable('table1') assert.is_nil(err) assert(t, err) end -- -- Test that a connect with bad user/pass fails. -- function test_failure() assert.is_error(function() local t, err = sqltable.create{ connection = { type = connect_args.type, host = connect_args.host, name = 'thisisnotpossiblyarealdatabase', user = 'thisisnotpossiblyarealuser' }, sqltable = 'sqltable', key = 'thing' } end) end -- -- Test that unsupported databases aren't tried. -- function test_no_support() assert.is_error(function() local t, err = sqltable.create{ connection = { type = 'No Database', host = 'localhost', name = 'thisisnotpossiblyarealdatabase', user = 'thisisnotpossiblyarealuser' }, sqltable = 'sqltable', key = 'thing' } end) end -- -- Test that we can iterate over all rows of a table. -- function test_iterate_all() local t = gettable('table1') local count = 0 for i, v in env.all_rows(t) do assert(i > 0) assert.is_string(v.name) count = count + 1 end assert(count == 3, "Got " .. tostring(count) .. " rows, expected 3") end -- -- Prove you can iterate multiple times. -- function test_iterate_multiall() local t = gettable('table1') for count = 1, 5 do local iter = env.all_rows(t) for i, v in iter do assert(i > 0) assert.is_string(v.name) end end end -- -- Prove you can iterate by calling pairs(). -- function test_iterate_meta_pairs() local t = gettable('table1') local count = 0 for i, v in pairs(t) do assert(i > 0) assert.is_string(v.name) count = count + 1 end assert(count == 3, "Got " .. tostring(count) .. " rows, expected 3") end -- -- Prove you can iterate by calling ipairs(). -- function test_iterate_meta_ipairs() local t = gettable('table1') local count = 0 for i, v in ipairs(t) do assert.is_string(v.name) count = count + 1 assert.is_equal(count, i) end assert(count == 3, "Got " .. tostring(count) .. " rows, expected 3") end --- -- Test the primitive (string driven) where statement. -- function test_where_normal() local t = gettable('table1') local count = 0 for k, v in env.where( t, "id >= 2") do count = count + 1 assert.is_gte(2, k) assert.is_string(v.name) end assert.is_equal(2, count) end --- -- The above, with placeholders. -- function test_where_withargs() local t = gettable('table3', 'rowname') local count = 0 for k, v in env.where( t, "rowname = " .. env:placeholder(1), 'update this' ) do count = count + 1 assert.is_equal('update this', k) assert.is_equal('update this', v.rowname) assert.is_boolean(v.flag1) assert.is_boolean(v.flag2) end -- only one row, primary key assert.is_equal(1, count) end --- -- Test that an impossible predicate gets no rows calling where. -- function test_where_norows() local t = gettable('table1') local count = 0 for k, v in env.where( t, "1 != 1") do count = count + 1 end assert.is_equal(0, count) end -- -- Test that we can grab specific rows -- function test_select() local t = gettable('table1') local x = env.select(t, 1) assert.is_table(x) assert.is_equal('Thing one', x.name) assert.is_equal(24, x.value1) assert.is_equal(266, x.value2) assert.is_false(x.flag1) assert.is_false(x.flag2) end -- -- Test that select works via metamethod. -- function test_select_meta() local t = gettable('table1') local x = t[1] assert.is_table(x) assert.is_equal('Thing one', x.name) assert.is_equal(24, x.value1) assert.is_equal(266, x.value2) assert.is_false(x.flag1) assert.is_false(x.flag2) end -- -- Test that we get nil if the row doesn't exist -- function test_select_nil() local t = gettable('table1') local x = env.select(t, 235823523) assert.is_nil(x) end -- -- Test that we can insert new rows -- function test_insert() local t = gettable('table2') local new_row = { stringy = 'weeee!', floater = (os.time() % 400) / 5, inter = os.time() % 1000 } local last_insert_id, err = env.insert(t, new_row) assert.is_nil(err) assert.is_number(last_insert_id) assert.is_table(t[ last_insert_id ]) assert.is_equal(new_row.stringy, t[ last_insert_id ].stringy) assert.is_equal(math.floor(new_row.floater), math.floor(t[ last_insert_id ].floater)) assert.is_equal(new_row.inter, t[ last_insert_id ].inter) -- Check that an insert really occured: close -- connection and redo env:reset() t = gettable('table2') assert.is_table(t[ last_insert_id ]) assert.is_equal(new_row.stringy, t[ last_insert_id ].stringy) assert.is_equal(math.floor(new_row.floater), math.floor(t[ last_insert_id ].floater)) assert.is_equal(new_row.inter, t[ last_insert_id ].inter) end -- -- Test that insert works via metamethods. -- function test_insert_meta() local t = gettable('table2') local new_row = { stringy = 'weeee!', floater = (os.time() % 200) / 5, inter = os.time() % 1000 } t[env.next] = new_row local last_insert_id = env.last_insert_id(t) assert.is_table(t[ last_insert_id ]) assert.is_equal(new_row.stringy, t[ last_insert_id ].stringy) assert.is_equal(math.floor(new_row.floater), math.floor(t[ last_insert_id ].floater)) assert.is_equal(new_row.inter, t[ last_insert_id ].inter) -- Check that an insert really occured: close -- connection and redo env:reset() t = gettable('table2') assert.is_table(t[ last_insert_id ]) assert.is_equal(new_row.stringy, t[ last_insert_id ].stringy) assert.is_equal(math.floor(new_row.floater), math.floor(t[ last_insert_id ].floater)) assert.is_equal(new_row.inter, t[ last_insert_id ].inter) end -- -- Test that we can update rows -- function test_update_varchar_key() local t = gettable('table3', 'rowname') assert(env.select(t, 'update this'), "Didn't find row to update") env.update(t, { rowname = 'update this', flag1 = true, flag2 = false }) -- Did it stick? Reset connections and find out. env:reset() assert.is_true(env.select(t, 'update this').flag1) assert.is_false(env.select(t, 'update this').flag2) -- -- repeat a few times, to be sure the database just didn't happen -- to look like that when we started. -- env.update(t, { rowname = 'update this', flag1 = true, flag2 = true }) env:reset() assert.is_true(env.select(t, 'update this').flag1) assert.is_true(env.select(t, 'update this').flag2) env.update(t, { rowname = 'update this', flag1 = false, flag2 = false }) env:reset() assert.is_false(env.select(t, 'update this').flag1) assert.is_false(env.select(t, 'update this').flag2) end -- -- Test that we can update rows with integer keys -- function test_update_integer_key() local t = gettable('table1') assert(env.select(t, 3), "Didn't find row to update") local set_to = os.time() env.update(t, { id = 3, value2 = set_to }) env:reset() assert.is_equal(set_to, (env.select(t, 3).value2)) env:reset() set_to = set_to - 200 env.update(t, { id = 3, value2 = set_to }) env:reset() assert.is_equal(set_to, (env.select(t, 3).value2)) end -- -- Test that we can update metamethod style. -- function test_update_meta() local t = gettable('table1') assert(t[3], "Didn't find row to update") local set_to = os.time() t[3] = { value2 = set_to } env:reset() assert.is_equal(set_to, t[3].value2) env:reset() set_to = set_to - 200 t[3] = { value2 = set_to } env:reset() assert.is_equal(set_to, t[3].value2) end -- -- Prove that an update without the primary key dies. -- function test_update_failure() local t = gettable('table3', 'rowname') assert.is_error(function() env.update(t, { flag1 = true, flag2 = false }) end) end -- -- Test that deletes work. -- function test_delete() -- first, we need a row to delete. Add it. local t = gettable('table3', 'rowname') local row = env.select( t, 'delete me' ) if not row then env.insert( t, { rowname = 'delete me', flag1 = true, flag2 = true }) row = env.select( t, 'delete me' ) end -- it's there, right? assert.is_table(row) assert.is_equal('delete me', row.rowname) assert.is_true(row.flag1) assert.is_true(row.flag2) -- kill it! assert.is_true(env.delete( t, { rowname = 'delete me' } )) -- prove it died env:reset() t = gettable('table3', 'rowname') assert.is_nil(env.select( t, 'delete me')) end -- -- Test we can delete via the metamethods. -- function test_delete_meta() -- first, we need a row to delete. Add it. local t = gettable('table3', 'rowname') local row = t['delete me'] if not t['delete me'] then t['delete me'] = { flag1 = true, flag2 = true } end -- is it there? assert.is_true(t['delete me'].flag1) -- kill it! t['delete me'] = nil -- prove it died env:reset() t = gettable('table3', 'rowname') assert.is_nil(t['delete me']) end -- -- Prove you can't delete without a primary key. Very big -- issues can happen if not! -- function test_delete_fails() local t = gettable('table3', 'rowname') assert.is_error(function() env.delete(t, { flag1 = true, flag2 = false }) end) end -- -- Prove we can count the number of rows in a table. -- function test_count() local t = gettable('table1') assert.is_equal(3, env.count(t)) end -- -- Prove we can count the number of rows in a table, using a where -- clause. -- function test_count_where() local t = gettable('table1') local where = "id < " .. env:placeholder( 1 ) assert.is_equal(2, env.count(t, where, 3)) end -- -- Prove we can count the number of rows using the len operator -- (#). Only works in Lua > 5.2. -- function test_count_lenop() local t = gettable('table1') assert.is_equal(3, #t) end -- -- Prove that, after an error situation, we recover gracefully. -- -- This was found in Postgres: in the event of an error, rollback() -- must be performed. And DBI propagates errors to the top, thus -- unrolling the stack, thus killing our rollback command if we -- don't pcall() it. -- -- This is likely a useless test now that connection pooling works, -- but it doesn't hurt to keep it. -- function test_error_rollback() local t = gettable('table2') -- First we need a query that reliabily trips an error. Without -- check constraints this is not as easy as it sounds, particularly -- when you want portability across databases. They don't all fail -- the same way! For example, MySQL is silent about integer -- overflows and SQLite3 doesn't worry about the exact data type. assert.is_equal(0, env.pool:outstanding()) assert.is_error(function() t[env.next] = { inter = 25000, stringy = 'weeee!', floater = os.time() / 5 } end) assert.is_equal(0, env.pool:outstanding()) -- notice we don't close the table. we're checking if it still -- works afterwards. t[env.next] = { inter = 15, stringy = 'weeee!', floater = os.time() / 5 } assert.is_equal(0, env.pool:outstanding()) local last_insert_id = env.last_insert_id( t ) -- Check that an insert really occured: close -- connection and check the last key env:reset() t = gettable('table2') assert.is_table(t[ last_insert_id ]) assert.is_equal(15, t[ last_insert_id ].inter) end -- -- Prove that accessing a bad key doesn't kill our -- connection by leaving it in a bad state. -- -- This is much like the above, but for the subtle case -- of an error occuring during a select statement. -- function test_select_rollback() -- XXX: It seems only Postgres has this condition to worry about. if config.connection.type ~= 'PostgreSQL' then return end local t = gettable('table1') assert.is_error(function() local y = t['thing'] end) assert.is_table(t[1]) assert.is_boolean(t[1].flag1) assert.is_boolean(t[1].flag2) end -- -- Test that a table set to read-only is still readable. -- function test_select_readonly() local t = gettable('table1', 'id', true) assert.is_table(t[1]) assert.is_boolean(t[1].flag1) assert.is_boolean(t[1].flag2) end -- -- Test that a table set to read-only errors during a write. -- function test_error_readonly() local t = gettable('table1', 'id', true) assert.is_error(function() t[345232] = { name = 'Should fail', value1 = 3543, value2 = 3345, flag1 = true, flag2 = false } end) assert.is_nil(t[345232]) end -- -- Test that cloning a table works. -- function test_clone() local t = gettable('table1') local cloned = env.clone(t) assert.is_table(cloned) assert.is_equal(3, #cloned) assert.is_equal('Thing one', cloned[1].name) assert.is_equal('Thing two', cloned[2].name) assert.is_equal('Thing three', cloned[3].name) for i, v in ipairs(cloned) do assert.is_number(i) assert.is_number(v.value1) assert.is_number(v.value2) assert.is_boolean(v.flag1) assert.is_boolean(v.flag2) end end -- -- Test that cloning with a where clause works. -- function test_clone_where() local t = gettable('table1') local cloned = env.clone(t, "id >= 2") local count = 0 for k, v in pairs(cloned) do count = count + 1 assert.is_gte(2, k) assert.is_string(v.name) end assert.is_equal(2, count) end -- -- Test that cloning a table works, integer keys edition. -- function test_iclone() local t = gettable('table2') local cloned = env.iclone(t) local count = 0 assert.is_table(cloned) for i, v in ipairs(cloned) do assert.is_table(v) assert.is_string(v.stringy) assert.is_number(v.inter) assert.is_number(v.floater) count = count + 1 end assert.is_gt(0, count) end -- -- Test that cloning a table works, integer keys edition. And -- with where clauses! -- function test_iclone_where() local t = gettable('table2') local cloned_nowhere = env.iclone(t) local cloned = env.iclone(t, "inter > 20") local count = 0 assert.is_table(cloned) for i, v in ipairs(cloned) do assert.is_table(v) assert.is_string(v.stringy) assert.is_number(v.inter) assert.is_number(v.floater) count = count + 1 end assert.is_gt(0, count) assert.is_gt(count, #cloned_nowhere) end -- -- Test transaction support, ending in commit -- function test_transaction_commit() local t = gettable('table2') env:begin_transaction(t) local new_row = { stringy = 'weeee!', floater = (os.time() % 400) / 5, inter = os.time() % 1000 } t[env.next] = new_row local last_insert_id = env.last_insert_id(t) assert.is_table(t[ last_insert_id ]) assert.is_equal(new_row.stringy, t[ last_insert_id ].stringy) assert.is_equal(math.floor(new_row.floater), math.floor(t[ last_insert_id ].floater)) assert.is_equal(new_row.inter, t[ last_insert_id ].inter) new_row.stringy = 'Not whee' t[ last_insert_id ] = new_row env:commit( t ) -- select back, prove it holds assert.is_table(t[ last_insert_id ]) assert.is_equal(new_row.stringy, t[ last_insert_id ].stringy) assert.is_equal(math.floor(new_row.floater), math.floor(t[ last_insert_id ].floater)) assert.is_equal(new_row.inter, t[ last_insert_id ].inter) end -- -- Test transaction support, ending in rollback -- function test_transaction_rollback() local t = gettable('table2') local new_row = { stringy = 'weeee!', floater = (os.time() % 400) / 5, inter = os.time() % 1000 } t[env.next] = new_row local last_insert_id = env.last_insert_id(t) assert.is_table(t[ last_insert_id ]) assert.is_equal(new_row.stringy, t[ last_insert_id ].stringy) assert.is_equal(math.floor(new_row.floater), math.floor(t[ last_insert_id ].floater)) assert.is_equal(new_row.inter, t[ last_insert_id ].inter) env:begin_transaction(t) new_row.stringy = 'Not whee' t[ last_insert_id ] = new_row env:rollback( t ) -- select back, prove it failed assert.is_table(t[ last_insert_id ]) assert.is_equal('weeee!', t[ last_insert_id ].stringy) assert.is_equal(math.floor(new_row.floater), math.floor(t[ last_insert_id ].floater)) assert.is_equal(new_row.inter, t[ last_insert_id ].inter) end -- -- Test that you can't open a transaction twice. -- function test_transaction_begin_fails() local t = gettable('table2') env:begin_transaction(t) assert.is_error(function() env:begin_transaction(t) end) env:commit(t) end -- -- Test that you can't commit a transaction twice. -- function test_transaction_commit_fails() local t = gettable('table2') env:begin_transaction(t) env:commit(t) assert.is_error(function() env:commit(t) end) end -- -- Test that you can't rollback a transaction twice. -- function test_transaction_rollback_fails() local t = gettable('table2') env:begin_transaction(t) env:rollback(t) assert.is_error(function() env:rollback(t) end) end -- -- Test that you can iterate a table during a transaction. -- function test_transaction_all_rows() local t = gettable('table2') env:begin_transaction(t) local count = 0 for i, row in env.all_rows(t) do count = count + 1 end assert.is_gte(0, count) local ncount = env.count( t ) assert.is_equal(count, ncount) env:commit(t) end -- -- Test the debugging hook. -- function test_debugging_hook() local t = gettable('table2') local code = "select 1 as one" local hook = nil local called = false env:debugging( function( sql, args ) hook = sql assert.is_string(sql) assert.is_table(args) assert.is_equal(0, #args) called = true end ) env:exec( code, {}, function( c, s ) end ) assert.is_equal(code, hook) assert.is_true(called) end -- -- Test disabling the debugging hook. -- function test_debugging_hook_disable() local t = gettable('table2') local code1 = "select 1 as one" local code2 = "select 2 as two" local hook = nil local called = false env:debugging( function( sql, args ) hook = sql called = true end ) env:exec( code1, {}, function( c, s ) end ) assert.is_equal(code1, hook) assert.is_true(called) called = false hook = nil env:debugging() env:exec( code2, nil, function( c, s ) end ) assert.is_nil(hook) assert.is_false(called) end -- -- Test the execute function. -- -- This test might not pass in all databases... -- function test_execute() env:exec( "select 1 as one", nil, function( connection, statement ) local row = statement:fetch(true) assert.is_table(row) assert.is_equal(1, row.one) end) assert.is_equal(0, env.pool:outstanding()) assert.is_gte(1, env.pool:connections()) end -- -- Test the execute function, without a callback function. -- -- The result should be the same as above. -- function test_execute_nocallback() env:exec( "select 1 as one", nil) assert.is_equal(0, env.pool:outstanding()) assert.is_gte(1, env.pool:connections()) end -- -- Test that a failure to prepare code in the execute function -- doesn't hurt the pool. -- function test_execute_prepare_fails() assert.is_error(function() env:exec( "s43fuin23m4ruin34e", nil, function( connection, statement ) end) end) assert.is_equal(0, env.pool:outstanding()) assert.is_gte(1, env.pool:connections()) end -- -- Test that a callback failure doesn't hurt the pool. -- function test_execute_callback_fails() assert.is_error(function() env:exec( "select 1 as one", nil, function( connection, statement ) error("break me") end) end) assert.is_equal(0, env.pool:outstanding()) assert.is_gte(1, env.pool:connections()) end -- -- Test we can extract a version number. -- function test_get_database_version() assert.is_string( env:version() ) end describe("PostgreSQL #psql", function() db_type = "postgres" config = dofile("test-configs/" .. db_type .. ".lua") local env setup(setup_tests) it( "Sets up correctly", test_init ) it( "Fails sanely", test_failure ) it( "Fails on unsupported drivers", test_no_support ) it( "Can iterate over tables", test_iterate_all ) it( "Can iterate the same table multiple times", test_iterate_multiall ) it( "Supports where clauses", test_where_normal ) it( "Supports where with placeholders", test_where_withargs ) it( "Doesn't break if where returns no rows", test_where_norows ) it( "Can select a row", test_select ) it( "Can select via metamethod", test_select_meta ) it( "Returns nil if selected row doesn't exist", test_select_nil ) it( "Can select if a table is read-only", test_select_readonly ) it( "Can rollback on a bad select", test_select_rollback ) it( "Can insert rows", test_insert ) it( "Can insert via metamethods", test_insert_meta ) it( "Can update with string keys", test_update_varchar_key ) it( "Can update with integer keys", test_update_integer_key ) it( "Can update via metamethods", test_update_meta ) it( "Fails when a key isn't provided to update", test_update_failure ) it( "Can delete rows", test_delete ) it( "Can delete via metamethods", test_delete_meta ) it( "Fails when deleting without a key", test_delete_fails ) it( "Can clone a table into a temporary one", test_clone ) it( "Can clone part of a table into a temporary one", test_clone_where ) it( "Can clone into a temporary table, with integer keys", test_iclone ) it( "Can clone into an integer keys temp table, with a where clause ", test_iclone_where ) it( "Can count rows of a table", test_count ) it( "Can count a subset of a table", test_count_where ) it( "Can commit a transaction", test_transaction_commit ) it( "Can rollback a transaction", test_transaction_rollback ) it( "Won't double-commit a transaction", test_transaction_commit_fails ) it( "Won't open two transactions", test_transaction_begin_fails ) it( "Won't rollback a transaction twice", test_transaction_rollback_fails ) it( "Can iterate all rows during a transaction", test_transaction_all_rows ) it( "Fails when updating a read-only table", test_error_readonly ) it( "Rolls back a transaction on failures", test_error_rollback ) it( "Has a debugging hook", test_debugging_hook ) it( "Can disable a debugging hook", test_debugging_hook_disable ) it( "Has an execute function", test_execute ) it( "Can recover from a failed execute callback", test_execute_callback_fails ) it( "Can execute without a callback", test_execute_nocallback ) it( "Can recover if SQL code isn't valid", test_execute_prepare_fails ) it( "Can get a version number", test_get_database_version ) if _VERSION ~= 'Lua 5.1' then it( "Can count rows with the length operator", test_count_lenop ) it( "Can iterate a table using pairs", test_iterate_meta_pairs ) it( "Can iterate a table using ipairs", test_iterate_meta_ipairs ) end teardown(teardown_tests) end) describe("MySQL #mysql", function() db_type = "mysql" config = dofile("test-configs/" .. db_type .. ".lua") local env setup(setup_tests) it( "Sets up correctly", test_init ) it( "Fails sanely", test_failure ) it( "Fails on unsupported drivers", test_no_support ) it( "Can iterate over tables", test_iterate_all ) it( "Can iterate the same table multiple times", test_iterate_multiall ) it( "Supports where clauses", test_where_normal ) it( "Supports where with placeholders", test_where_withargs ) it( "Doesn't break if where returns no rows", test_where_norows ) it( "Can select a row", test_select ) it( "Can select via metamethod", test_select_meta ) it( "Returns nil if selected row doesn't exist", test_select_nil ) it( "Can select if a table is read-only", test_select_readonly ) it( "Can rollback on a bad select", test_select_rollback ) it( "Can insert rows", test_insert ) it( "Can insert via metamethods", test_insert_meta ) it( "Can update with string keys", test_update_varchar_key ) it( "Can update with integer keys", test_update_integer_key ) it( "Can update via metamethods", test_update_meta ) it( "Fails when a key isn't provided to update", test_update_failure ) it( "Can delete rows", test_delete ) it( "Can delete via metamethods", test_delete_meta ) it( "Fails when deleting without a key", test_delete_fails ) it( "Can clone a table into a temporary one", test_clone ) it( "Can clone part of a table into a temporary one", test_clone_where ) it( "Can commit a transaction", test_transaction_commit ) it( "Can rollback a transaction", test_transaction_rollback ) it( "Won't double-commit a transaction", test_transaction_commit_fails ) it( "Won't open two transactions", test_transaction_begin_fails ) it( "Won't rollback a transaction twice", test_transaction_rollback_fails ) it( "Can iterate all rows during a transaction", test_transaction_all_rows ) it( "Can clone into a temporary table, with integer keys", test_iclone ) it( "Can clone into an integer keys temp table, with a where clause ", test_iclone_where ) it( "Can count rows of a table", test_count ) it( "Can count a subset of a table", test_count_where ) it( "Fails when updating a read-only table", test_error_readonly ) it( "Rolls back a transaction on failures", test_error_rollback ) it( "Has a debugging hook", test_debugging_hook ) it( "Can disable a debugging hook", test_debugging_hook_disable ) it( "Has an execute function", test_execute ) it( "Can recover from a failed execute callback", test_execute_callback_fails ) it( "Can execute without a callback", test_execute_nocallback ) it( "Can recover if SQL code isn't valid", test_execute_prepare_fails ) it( "Can get a version number", test_get_database_version ) if _VERSION ~= 'Lua 5.1' then it( "Can count rows with the length operator", test_count_lenop ) it( "Can iterate a table using pairs", test_iterate_meta_pairs ) it( "Can iterate a table using ipairs", test_iterate_meta_ipairs ) end teardown(teardown_tests) end) describe("SQLite3 #sqlite", function() db_type = "sqlite3" config = dofile("test-configs/" .. db_type .. ".lua") local env setup(setup_tests) it( "Sets up correctly", test_init ) it( "Fails sanely", test_failure ) it( "Fails on unsupported drivers", test_no_support ) it( "Can iterate over tables", test_iterate_all ) it( "Can iterate the same table multiple times", test_iterate_multiall ) it( "Supports where clauses", test_where_normal ) it( "Supports where with placeholders", test_where_withargs ) it( "Doesn't break if where returns no rows", test_where_norows ) it( "Can select a row", test_select ) it( "Can select via metamethod", test_select_meta ) it( "Returns nil if selected row doesn't exist", test_select_nil ) it( "Can select if a table is read-only", test_select_readonly ) it( "Can rollback on a bad select", test_select_rollback ) it( "Can insert rows", test_insert ) it( "Can insert via metamethods", test_insert_meta ) it( "Can update with string keys", test_update_varchar_key ) it( "Can update with integer keys", test_update_integer_key ) it( "Can update via metamethods", test_update_meta ) it( "Fails when a key isn't provided to update", test_update_failure ) it( "Can delete rows", test_delete ) it( "Can delete via metamethods", test_delete_meta ) it( "Fails when deleting without a key", test_delete_fails ) it( "Can clone a table into a temporary one", test_clone ) it( "Can clone part of a table into a temporary one", test_clone_where ) it( "Can commit a transaction", test_transaction_commit ) it( "Can rollback a transaction", test_transaction_rollback ) it( "Won't double-commit a transaction", test_transaction_commit_fails ) it( "Won't open two transactions", test_transaction_begin_fails ) it( "Won't rollback a transaction twice", test_transaction_rollback_fails ) it( "Can iterate all rows during a transaction", test_transaction_all_rows ) it( "Can clone into a temporary table, with integer keys", test_iclone ) it( "Can clone into an integer keys temp table, with a where clause ", test_iclone_where ) it( "Can count rows of a table", test_count ) it( "Can count a subset of a table", test_count_where ) it( "Fails when updating a read-only table", test_error_readonly ) it( "Rolls back a transaction on failures", test_error_rollback ) it( "Has a debugging hook", test_debugging_hook ) it( "Can disable a debugging hook", test_debugging_hook_disable ) it( "Has an execute function", test_execute ) it( "Can recover from a failed execute callback", test_execute_callback_fails ) it( "Can execute without a callback", test_execute_nocallback ) it( "Can recover if SQL code isn't valid", test_execute_prepare_fails ) it( "Can get a version number", test_get_database_version ) if _VERSION ~= 'Lua 5.1' then it( "Can count rows with the length operator", test_count_lenop ) it( "Can iterate a table using pairs", test_iterate_meta_pairs ) it( "Can iterate a table using ipairs", test_iterate_meta_ipairs ) end teardown(teardown_tests) end)
function onUse(cid, item, fromPosition, itemEx, toPosition) local function back(item, pos) doCreateItem(item.itemid, 1, pos) end if itemEx.itemid == 13913 then --id do item arvore do sudowoodo local item = getTileItemById(toPosition, 13913) --id do item arvore do sudowoodo addEvent(back, choose(10) * 60, itemEx, toPosition) --tempo de resp varia de 5~15min doRemoveItem(item.uid, 1) doSendMagicEffect(toPosition, 1) local poke = doCreateMonster("Shiny Electabuzz", toPosition) doSendMagicEffect(getThingPos(poke), 168) doSetMonsterPassive(poke) doWildAttackPlayer(poke, cid) end return true end
AddCSLuaFile() SWEP.PrintName = "Сайга" SWEP.Category = "Call of Pripyat" SWEP.Base = "weapon_cop_base" SWEP.Slot = 2 SWEP.SlotPos = 2 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.ViewModel = "models/weapons/wick/stcopwep/saiga_model.mdl" SWEP.WorldModel = "models/weapons/wick/stcopwep/w_saiga_model.mdl" SWEP.ViewModelFOV = 42 SWEP.ViewModelFlip = false SWEP.HoldType = "ar2" SWEP.Damage = 34 SWEP.RPM = 400 SWEP.Accuracy = 80 SWEP.Handling = 65 SWEP.Primary.BulletNum = 8 SWEP.Primary.Spread = 0.033 SWEP.Primary.ClipSize = 8 SWEP.Primary.DefaultClip = 8 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "12x70" SWEP.OriginPos = Vector(-4, 4, -6.5) SWEP.OriginAng = Vector(2, 0, 0) SWEP.AimPos = Vector(-7.6, 0, -4.35) SWEP.AimAng = Vector(0.1, 0.1, 0) SWEP.ScopeAimPos = Vector(-7.6, 0, -5) SWEP.ScopeAimAng = Vector(0.5, 0, 0) SWEP.ScopeBone = "wpn_scope" SWEP.SilencerBone = "wpn_silencer" SWEP.SilencerMode = 2 SWEP.ScopeMode = 2 SWEP.AimTime = 0.2 SWEP.DeployTime = 0.8 SWEP.ReloadTime = 2.81 SWEP.ReloadFillTime = 1.4 --SWEP.ReloadEndTime = 0 --SWEP.ReloadStartTime = 0 SWEP.ScopeTexture = "wpn_crosshair_red" SWEP.CanZoom = true SWEP.ZoomCrosshair = false SWEP.ReloadType = 0 SWEP.ZoomFOV = 75 SWEP.ScopeFOV = 50 SWEP.HiddenBones = { "wpn_launcher" } SWEP.FireSound = "COPSAIGA.saiga_shoot" SWEP.SilencedSound = "COPSAIGA.saiga_shot_sil" SWEP.EmptySound = "COP_Generic.Empty" SWEP.DeploySound = "COP_Generic.Draw" SWEP.HolsterSound = "COP_Generic.Holster" SWEP.ReloadSound = "COPSAIGA.saiga_reload"
local BenchmarkScene = class("BenchmarkScene", function() return display.newScene("BenchmarkScene") end) local random = math.random function BenchmarkScene:ctor() self.layer = display.newNode() self.layer:setContentSize(cc.size(display.width, display.height)) self:addChild(self.layer) local button = display.newSprite("#AddCoinButton.png", display.right - 100, display.bottom + 270) self:addChild(button) self.addCoinButtonBoundingBox = button:getBoundingBox() local button = display.newSprite("#RemoveCoinButton.png", display.right - 100, display.bottom + 100) self:addChild(button) self.removeCoinButtonBoundingBox = button:getBoundingBox() cc.ui.UIPushButton.new({normal = "#ExitButton.png"}) :onButtonClicked(function() game.exit() end) :pos(display.right - 100, display.top - 100) :addTo(self) self.label = cc.ui.UILabel.new({ UILabelType = 1, text = "00000", font = "UIFont.fnt", x = display.cx, y = display.top - 40, }) self:addChild(self.label) self.coins = {} self.state = "IDLE" local frames = display.newFrames("CoinSpin%02d.png", 1, 8) local animation = display.newAnimation(frames, 0.4 / 8) display.setAnimationCache("Coin", animation) self.left = display.left + display.width / 4 self.right = display.right - display.width / 4 self.top = display.top - display.height / 3 self.bottom = display.bottom + display.height / 3 end function BenchmarkScene:onTouch(event, x, y) if event == "began" then local p = cc.p(x, y) if cc.rectContainsPoint(self.addCoinButtonBoundingBox, p) then self.state = "ADD" elseif cc.rectContainsPoint(self.removeCoinButtonBoundingBox, p) then self.state = "REMOVE" else self.state = "IDLE" end return true elseif event ~= "moved" then self.state = "IDLE" end end function BenchmarkScene:addCoin() local coin = display.newSprite("#CoinSpin01.png") coin:playAnimationForever(display.getAnimationCache("Coin")) coin:setPosition(random(self.left, self.right), random(self.bottom, self.top)) -- self.batch:addChild(coin) self:addChild(coin) function coin:onEnterFrame(dt) local x, y = self:getPosition() x = x + random(-2, 2) y = y + random(-2, 2) self:setPosition(x, y) end self.coins[#self.coins + 1] = coin self.coinsCount = #self.coins self.label:setString(string.format("%05d", self.coinsCount)) end function BenchmarkScene:removeCoin() local coin = self.coins[self.coinsCount] coin:removeFromParent() table.remove(self.coins, self.coinsCount) self.coinsCount = self.coinsCount - 1 self.label:setString(string.format("%05d", self.coinsCount)) end function BenchmarkScene:onEnterFrame(dt) if self.state == "ADD" then self:addCoin() elseif self.state == "REMOVE" and self.coinsCount > 0 then self:removeCoin() end local coins = self.coins for i = 1, #coins do local coin = coins[i] coin:onEnterFrame(dt) end end function BenchmarkScene:onEnter() self:addNodeEventListener(cc.NODE_ENTER_FRAME_EVENT, function(dt) self:onEnterFrame(dt) end) self:scheduleUpdate() self.layer:setTouchEnabled(true) self.layer:addNodeEventListener(cc.NODE_TOUCH_EVENT, function(event) return self:onTouch(event.name, event.x, event.y) end) end function BenchmarkScene:onExit() display.removeAnimationCache("Coin") end return BenchmarkScene
require 'Atten/Model' require 'logroll' local logger = logroll.print_logger() local LenModel = torch.class('LenModel', 'AttenModel') local Dataset = require('Atten/Dataset') function LenModel:__init(params) logger.info('loading params for the pretrained attention model: %s', params.params_file) local file = torch.DiskFile(params.params_file, "r"):binary() local atten_params = file:readObject() file:close() for k, v in pairs(atten_params) do if params[k] == nil or params[k] == "" then params[k] = v end end self.params = params logger.info('creating future prediction model') self.map = nn.Sequential() self.map:add(nn.Linear(self.params.dimension, self.params.dimension)) self.map:add(nn.Tanh()) self.map:add(nn.Linear(self.params.dimension, self.params.dimension)) self.map:add(nn.Tanh()) self.map:add(nn.Linear(self.params.dimension, 1)) self.map = self.map:cuda() self.mse = nn.MSECriterion() self.mse = self.mse:cuda() if self.params.readSequenceModel then logger.info('reading sequence model') self.dataset = Dataset.new(params) self.lstm_source = self:lstm_source_() self.lstm_target = self:lstm_target_() self.softmax = self:softmax_() self.Modules = {} self.Modules[#self.Modules + 1] = self.lstm_source self.Modules[#self.Modules + 1] = self.lstm_target self.Modules[#self.Modules + 1] = self.softmax self.lstms_s = {} self.lstms_t = {} self.lstms_s[1] = self.lstm_source self.lstms_t[1] = self.lstm_target self.store_s = {} self:readModel() end if self.params.readFutureModel then logger.info('reading future model') local parameter = self.map:parameters() local file = torch.DiskFile(self.params.FuturePredictorModelFile, "r"):binary() local future_params = file:readObject() file:close() for j = 1, #parameter do parameter[j]:copy(future_params[j]) end logger.info("length predictor intialization done") end end function LenModel:model_forward() local totalError = 0 local instance = 0 self.context = torch.Tensor(self.Word_s:size(1), self.Word_s:size(2), self.params.dimension):cuda() local output -- run the encoder rnn. for t = 1, self.Word_s:size(2) do local input = {} if t == 1 then -- Initial time step, zero input. for ll = 1, self.params.layers do table.insert(input, torch.zeros(self.Word_s:size(1), self.params.dimension):cuda()) table.insert(input, torch.zeros(self.Word_s:size(1), self.params.dimension):cuda()) end else -- Feed output as input -- recurrent. input = self:clone_(output) end table.insert(input, self.Word_s:select(2, t)) self.lstms_s[1]:evaluate() output = self.lstms_s[1]:forward(input) if self.Mask_s[t]:nDimension() ~= 0 then for i = 1, #output do output[i]:indexCopy(1, self.Mask_s[t], torch.zeros(self.Mask_s[t]:size(1), self.params.dimension):cuda()) end end self.context[{ {}, t }]:copy(output[2 * self.params.layers - 1]) end -- run the decoder rnn. for t = 1, self.Word_t:size(2) - 1 do local lstm_input if t == 1 then -- initialize from encoder's last hidden state. lstm_input = output else -- recurrent lstm_input = {} for i = 1, 2 * self.params.layers do lstm_input[i] = output[i] end end table.insert(lstm_input, self.context) table.insert(lstm_input, self.Word_t:select(2, t)) table.insert(lstm_input, self.Padding_s) output = self.lstms_t[1]:forward(lstm_input) self.Length = self.Length - 1 local left_index = (torch.range(1, #self.Source)[self.Length:gt(0)]):long() local representation_left = output[2 * self.params.layers - 1]:index(1, left_index) local length_left = self.Length:index(1, left_index) length_left = torch.reshape(length_left, length_left:size(1), 1):cuda() -- update the value function self.map:zeroGradParameters() -- predict len left using lstm output ht. local pred = self.map:forward(representation_left) local Error = self.mse:forward(pred, length_left) -- Backprop. if self.mode == "train" then self.mse:backward(pred, length_left) self.map:backward(representation_left, self.mse.gradInput) self.map:updateParameters(self.params.alpha) end totalError = totalError + Error * length_left:size(1) instance = instance + length_left:size(1) if self.Mask_t[t]:nDimension() ~= 0 then for i = 1, #output do output[i]:indexCopy(1, self.Mask_t[t], torch.zeros(self.Mask_t[t]:size(1), self.params.dimension):cuda()) end end end return totalError, instance end function LenModel:test() logger.info('test with file %s', self.params.test_file) local test_file = assert(io.open(self.params.test_file, "r"), 'cannot open test_file') local End, Word_s, Word_t, Mask_s, Mask_t local End = 0 local batch_n = 1 local totalError = 0 local n_instance = 0 while End == 0 do batch_n = batch_n + 1 self:clear() End, self.Word_s, self.Word_t, self.Mask_s, self.Mask_t, self.Left_s, self.Left_t, self.Padding_s, self.Padding_t, self.Source, self.Target = self.dataset:read_train(test_file) if End == 1 then break end self.Length = torch.Tensor(#self.Target):fill(0) for i = 1, #self.Target do self.Length[i] = self.Target[i]:size(2) end self.mode = "test" self.Word_s = self.Word_s:cuda() self.Word_t = self.Word_t:cuda() self.Padding_s = self.Padding_s:cuda() local batchError, batchInstance = self:model_forward() totalError = totalError + batchError n_instance = n_instance + batchInstance end local Error = totalError / n_instance logger.info('totalError: %.4f', totalError) logger.info('n_instance: %d', n_instance) logger.info('Error: %.4f', Error) end function LenModel:save(batch_n) local params = self.map:parameters() local filename = path.join(self.params.save_model_path, 'model' .. batch_n) logger.info('saving to %s', filename) local file = torch.DiskFile(filename, "w"):binary() file:writeObject(params) file:close() end function LenModel:train() local End, Word_s, Word_t, Mask_s, Mask_t local End = 0 local batch_n = 1 self.iter = 0 while true do End = 0 logger.info('Epoch: %d', self.iter) self.iter = self.iter + 1 local train_file = assert(io.open(self.params.train_file, "r"), 'cannot open train_file') while End == 0 do batch_n = batch_n + 1 if batch_n % 10000 == 0 then print(batch_n) self:test() self:save(batch_n) end self:clear() End, self.Word_s, self.Word_t, self.Mask_s, self.Mask_t, self.Left_s, self.Left_t, self.Padding_s, self.Padding_t, self.Source, self.Target = self.dataset:read_train(train_file) if End == 1 then break end self.Length = torch.Tensor(#self.Target):fill(0) for i = 1, #self.Target do self.Length[i] = self.Target[i]:size(2) end self.mode = "train" self.Word_s = self.Word_s:cuda() self.Word_t = self.Word_t:cuda() self.Padding_s = self.Padding_s:cuda() self:model_forward() end self:test() self:save(batch_n) if self.iter == self.params.max_iter then logger.info("Done training!") break end end end return LenModel
--local distance_text = table.deepcopy(data.raw['flying-text']['flying-text']) --distance_text.name = 'RailTools_distance-text' --distance_text.speed = 0 --distance_text.text_alignment = 'center' -- data:extend { --distance_text, --{ -- type = "simple-entity", -- name = "RailTools_bad-signal-indicator", -- flags = { "not-on-map", "not-blueprintable", "not-deconstructable", "not-flammable" }, -- render_layer = "selection-box", -- picture = { -- width = 64, -- height = 64, -- scale = 0.5, -- filename = "__core__/graphics/arrows/underground-lines-remove.png", -- }, -- collision_box = nil, -- selectable_in_game = false, -- tile_width = 1, -- tile_height = 1, --}, { type = "sprite", name = "RailTools_bad-signal-sprite", priority = "extra-high", width = 64, height = 64, scale = 0.5, filename = "__core__/graphics/arrows/underground-lines-remove.png", }, { type = "container", name = "RailTools_dummy-item-storage", --icon = "__base__/graphics/icons/wooden-chest.png", --icon_size = 32, --flags = { "placeable-neutral", "player-creation" }, --minable = { mining_time = 1, result = "wooden-chest" }, --max_health = 100, --corpse = "small-remnants", collision_box = { { 0, 0 }, { 0, 0 } }, selection_box = { { 0, 0 }, { 0, 0 } }, inventory_size = 1, --open_sound = { filename = "__base__/sound/wooden-chest-open.ogg" }, --close_sound = { filename = "__base__/sound/wooden-chest-close.ogg" }, --vehicle_impact_sound = { filename = "__base__/sound/car-wood-impact.ogg", volume = 1.0 }, picture = data.raw.container["wooden-chest"].picture, --{ -- filename = "__base__/graphics/entity/wooden-chest/wooden-chest.png", -- priority = "extra-high", -- width = 1, -- height = 1, --}, --circuit_wire_connection_point = circuit_connector_definitions["chest"].points, --circuit_connector_sprites = circuit_connector_definitions["chest"].sprites, --circuit_wire_max_distance = default_circuit_wire_max_distance }, }
local computer = require("computer") local shell = require("shell") local component = require("component") local event = require("event") local fs = require("filesystem") local unicode = require("unicode") local text = require("text") local write = io.write local args, options = shell.parse(...) options.sources = {} options.targets = {} options.source_label = args[1] local root_exception if options.help then print([[Usage: install [OPTION]... --from=ADDR install filesystem at ADDR default: builds list of candidates and prompts user --to=ADDR same as --from but for target --fromDir=PATH install PATH from source --root=PATH same as --fromDir but target --toDir=PATH same as --root -u, --update update files interactively --label override label from .prop --nosetlabel do not label target --nosetboot do not use target for boot --noreboot do not reboot after install]]) return nil -- exit success end local rootfs = fs.get("/") if not rootfs then io.stderr:write("no root filesystem, aborting\n"); os.exit(1) end local function up_deprecate(old_key, new_key) if options[new_key] == nil then options[new_key] = options[old_key] end options[old_key] = nil end local function cleanPath(path) if path then local rpath = shell.resolve(path) if fs.isDirectory(rpath) then return fs.canonical(rpath) .. '/' end end end --local rootAddress = rootfs.address -- if the rootfs is read only, it is probably the loot disk! --root_exception = rootAddress --if rootfs.isReadOnly() then -- root_exception = nil --end -- this may be OpenOS specific, default to "" in case no /dev mount point local devfsAddress = (fs.get("/dev/") or {}).address or "" -- tmp is only valid if specified as an option local tmpAddress = computer.tmpAddress() ----- For now, I am allowing source==target -- cp can handle it if the user prepares conditions correctly ----- in other words, install doesn't need to filter this scenario: --if #options.targets == 1 and #options.sources == 1 and options.targets[1] == options.sources[1] then -- io.stderr:write("It is not the intent of install to use the same source and target filesystem.\n") -- return 1 --end ------ load options up_deprecate('noboot', 'nosetboot') up_deprecate('nolabelset', 'nosetlabel') up_deprecate('name', 'label') options.source_root = cleanPath(options.from) options.target_root = cleanPath(options.to) options.target_dir = fs.canonical(options.root or options.toDir or "") options.update = options.u or options.update local function path_to_dev(path) return path and fs.isDirectory(path) and not fs.isLink(path) and fs.get(path) end local source_dev = path_to_dev(options.source_root) local target_dev = path_to_dev(options.target_root) -- use a single for loop of all filesystems to build the list of candidates of sources and targets local function validDevice(candidate, exceptions, specified, existing) local address = candidate.dev.address for _,e in ipairs(existing) do if e.dev.address == address then return end end if specified then if address:find(specified, 1, true) == 1 then return true end else for _,e in ipairs(exceptions) do if e == address then return end end return true end end for dev, path in fs.mounts() do local candidate = {dev=dev, path=path:gsub("/+$","")..'/'} if validDevice(candidate, {devfsAddress, tmpAddress, root_exception}, source_dev and source_dev.address or options.from, options.sources) then -- root path is either the command line path given for this dev or its natural mount point local root_path = source_dev == dev and options.source_root or path if (options.from or fs.list(root_path)()) then -- ignore empty sources unless specified local prop = fs.open(root_path .. '/.prop') if prop then local prop_data = prop:read(math.huge) prop:close() prop = prop_data end candidate.prop = prop and load('return ' .. prop)() or {} if not options.source_label or options.source_label:lower() == (candidate.prop.label or dev.getLabel()):lower() then table.insert(options.sources, candidate) end end end -- in case candidate is valid for BOTH, we want a new table candidate = {dev=candidate.dev, path=candidate.path} -- but not the prop if validDevice(candidate, {devfsAddress, tmpAddress}, target_dev and target_dev.address or options.to, options.targets) then if not dev.isReadOnly() then table.insert(options.targets, candidate) elseif options.to then io.stderr:write("Cannot install to " .. options.to .. ", it is read only\n") os.exit(1) end end end local source = options.sources[1] local target = options.targets[1] local utils_path = package.searchpath("tools/install_utils", package.path) if #options.sources ~= 1 or #options.targets ~= 1 then source, target = loadfile(utils_path, "bt", _G)('select', options) end if not source then return end options.source_root = options.source_root or source.path if not target then return end options.target_root = options.target_root or target.path -- now that source is selected, we can update options options.label = options.label or source.prop.label options.setlabel = source.prop.setlabel and not options.nosetlabel options.setboot = source.prop.setboot and not options.nosetboot options.reboot = source.prop.reboot and not options.noreboot options.source_dir = fs.canonical(source.prop.fromDir or options.fromDir or "") .. '/.' local cp_args = { "-vrx" .. (options.update and "ui" or ""), options.source_root .. options.source_dir, options.target_root:gsub("//","/") .. options.target_dir } local source_display = (source.prop or {}).label or source.dev.getLabel() or source.path local special_target = "" if #options.targets > 1 or options.to then special_target = " to " .. cp_args[3] end io.write("Install " .. source_display .. special_target .. "? [Y/n] ") if not ((io.read() or "n").."y"):match("^%s*[Yy]") then write("Installation cancelled\n") os.exit() end local installer_path = options.source_root .. "/.install" if fs.exists(installer_path) then os.exit(loadfile(utils_path, "bt", _G)('install', options)) end return { setlabel = options.setlabel, label = options.label, setboot = options.setboot, reboot = options.reboot, target = target, cp_args = cp_args, }
--[[ A top-down action game made with Bitty Engine Copyright (C) 2021 Tony Wang, all rights reserved Engine page: https://paladin-t.github.io/bitty/ Game page: https://paladin-t.github.io/games/hb/ ]] Blood = class({ --[[ Variables. ]] _game = nil, _r = 0, _lifetime = 20, _ticks = 0, --[[ Constructor. ]] ctor = function (self, options) Object.ctor(self, nil, nil, nil) self._game = options.game self._color = Color.new(200, 30, 30) end, --[[ Meta methods. ]] __tostring = function (self) return 'Blood' end, --[[ Methods. ]] resize = function (self, r) self._r = r return self end, behave = function (self, delta, _1) return self end, update = function (self, delta) local fadeTime = self._lifetime * 0.7 if self._ticks < fadeTime then circ(self.x, self.y, self._r, true, self._color) else local a = clamp((1 - (self._ticks - fadeTime) / (self._lifetime - fadeTime)) * 255, 0, 255) circ(self.x, self.y, self._r, true, Color.new(self._color.r, self._color.g, self._color.b, a)) end if self._game.state.playing then self._ticks = self._ticks + delta if self._ticks >= self._lifetime then self:kill('disappeared', nil) end end end }, Object)
local ev = require 'backend.event' local foreground local background local bright local underline local negative local function split(str) local r = {} str:gsub('[^;]+', function (w) r[#r+1] = tonumber(w) end) return r end local function vtmode(text) local vt = {} if foreground then vt[#vt+1] = foreground end if background then vt[#vt+1] = background end if bright then vt[#vt+1] = "1" end if underline then vt[#vt+1] = "4" end if negative then vt[#vt+1] = "7" end for vtstr in text:gmatch "\x1b%[([0-9;]+)m" do local codes = split(vtstr) local n = 1 while n <= #codes do local code = codes[n] if code == 0 then --reset foreground = nil background = nil bright = nil underline = nil negative = nil elseif code == 1 then -- bright bright = true elseif code == 4 then -- underline underline = true elseif code == 24 then -- no underline underline = false elseif code == 7 then -- negative negative = true elseif code == 27 then -- no negative negative = false elseif (code >= 30 and code <= 37) or (code >= 90 and code <= 97) then -- foreground foreground = tostring(code) elseif (code >= 40 and code <= 47) or (code >= 100 and code <= 107) then -- background background = tostring(code) elseif code == 39 then -- reset foreground foreground = nil elseif code == 40 then -- reset background background = nil elseif code == 38 then -- foreground if n + 2 <= #codes then foreground = codes[n] .. ";" .. codes[n + 1] .. ";" .. codes[n + 2] n = n + 2 end elseif code == 48 then -- background if n + 2 <= #codes then background = codes[n] .. ";" .. codes[n + 1] .. ";" .. codes[n + 2] n = n + 2 end end n = n + 1 end end if #vt > 0 then return "\x1b[" .. table.concat(vt, ";") .."m" .. text end return text end return function (msg, src, line) ev.emit('output', 'stdout', vtmode(msg), src, line) end
local tcp = require "internal.TCP" local lz = require"lz" local gzuncompress = lz.gzuncompress local new_tab = require "sys".new_tab local json = require "json" local json_encode = json.encode local xml2lua = require "xml2lua" local toxml = xml2lua.toxml local crypt = require "crypt" local url_encode = crypt.urlencode local base64encode = crypt.base64encode local HTTP_PARSER = require "protocol.http.parser" local FILEMIME = require "protocol.http.mime" local PARSER_HTTP_RESPONSE = HTTP_PARSER.PARSER_HTTP_RESPONSE local type = type local assert = assert local ipairs = ipairs local tonumber = tonumber local random = math.random local find = string.find local match = string.match local lower = string.lower local insert = table.insert local concat = table.concat local toint = math.tointeger local fmt = string.format local CRLF = '\x0d\x0a' local CRLF2 = '\x0d\x0a\x0d\x0a' local function sock_new () return tcp:new() end local function sock_recv (sock, _, bytes) return sock:recv(bytes) end local function sock_send(sock, _, data) return sock:send(data) end local function sock_connect(sock, PROTOCOL, DOAMIN, PORT) local ok = sock:connect(DOAMIN, PORT) if not ok then return nil, 'httpc连接失败.' end if PROTOCOL == 'https' and not sock:ssl_handshake(DOAMIN) then return nil, 'httpc连接失败.' end return true end local function splite_protocol(domain) if type(domain) ~= 'string' then return nil, '1. invalide domain' end local protocol, domain_port, path = match(domain, '^(http[s]?)://([^/]+)(.*)') if not protocol or not domain_port or not path then return nil, '2. invalide url' end if not path or path == '' then return nil, "3. http path need '/' in end." end local domain, port if find(domain_port, ':') then local _, Bracket_Pos = find(domain_port, '[%[%]]') if Bracket_Pos then domain, port = match(domain_port, '%[(.+)%][:]?(%d*)') else domain, port = match(domain_port, '([^:]+):(%d*)') end if not domain then return nil, "4. invalide host or port: "..domain_port end port = toint(port) if not port then port = 80 if protocol == 'https' then port = 443 end end else domain, port = domain_port, protocol == 'https' and 443 or 80 end return { protocol = protocol, domain = domain, port = port, path = path, } end local function read_data(sock, bytes) local buffers = new_tab(128, 0) while 1 do local buf = sock:recv(bytes) if not buf then return end buffers[#buffers+1] = buf bytes = bytes - #buf if bytes == 0 then break end end return concat(buffers) end local function httpc_response(sock, SSL) if not sock then return nil, "Can't used this method before other httpc method.." end local body local buf = sock:readline(CRLF2) if not buf then return nil, SSL .. " A peer of remote server close this connection." end local VERSION, CODE, STATUS, HEADER = PARSER_HTTP_RESPONSE(buf) if not CODE or not HEADER or (VERSION ~= 1.0 and VERSION ~= 1.1) then return nil, SSL .. " can't resolvable protocol." end local Content_Encoding = HEADER['Content-Encoding'] or HEADER['content-encoding'] local Content_Length = toint(HEADER['Content-Length'] or HEADER['content-length']) local Chunked = HEADER['Transfer-Encoding'] or HEADER['transfer-encoding'] if Chunked and find(Chunked, "chunked") then local resp = new_tab(128, 0) while 1 do local chunked_size = sock:readline(CRLF, true) local csize = toint(tonumber(chunked_size, 16)) if not csize or csize == 0 then if csize then -- 这行代码是用来去除`\r\n`的. read_data(sock, 2) break end return nil, "Invalid http trunked body." end local buffer = read_data(sock, csize) if not buffer then return nil, SSL .. " [Content_Length] A peer of remote server close this connection." end resp[#resp+1] = buffer -- 这行代码是用来去除`\r\n`的. read_data(sock, 2) end body = concat(resp) elseif Content_Length then body = "" if Content_Length > 0 then local buffer = read_data(sock, Content_Length) if not buffer then return nil, SSL .. " [Content_Length] A peer of remote server close this connection." end body = buffer end else return CODE, STATUS, HEADER end local RESP = body if Content_Encoding == "gzip" then RESP = gzuncompress(body) end -- 如果有重定向, 则优先返回重定向的地址; 否则返回接收到的body内容 if CODE == 301 or CODE == 302 or CODE == 303 or CODE == 307 or CODE == 308 then return CODE, HEADER['Location'] or HEADER['location'] or RESP, HEADER end return CODE, RESP, HEADER end -- 对一些特殊请求的支持 local function build_raw_req( opt ) local request = new_tab(16, 0) insert(request, fmt("%s %s HTTP/1.1", opt.method, opt.path)) insert(request, fmt("Host: %s", (opt.port == 80 or opt.port == 443) and opt.domain or opt.domain..':'..opt.port)) insert(request, fmt("User-Agent: %s", opt.server)) insert(request, 'Accept: */*') insert(request, 'Accept-Encoding: gzip, identity') insert(request, 'Connection: keep-alive') if opt.method == 'GET' and type(opt.args) == "table" then local args = new_tab(8, 0) for _, arg in ipairs(opt.args) do assert(#arg == 2, "args need key[1]->value[2] (2 values and must be string)") insert(args, url_encode(arg[1])..'='..url_encode(arg[2])) end request[1] = fmt("GET %s HTTP/1.1", opt.path .. '?' .. concat(args, "&")) end if type(opt.headers) == "table" then for _, header in ipairs(opt.headers) do assert(#header == 2, "HEADER need key[1]->value[2] (2 values)") insert(request, header[1]..': '..header[2]) end end if opt.method == 'POST' or opt.method == 'PUT' or opt.method == 'DELETE' then if type(opt.body) == "table" then local body = new_tab(8, 0) for _, item in ipairs(opt.body) do assert(#item == 2, "if BODY is TABLE, BODY need key[1]->value[2] (2 values)") insert(body, url_encode(item[1])..'='..url_encode(item[2])) end local Body = concat(body, "&") insert(request, #request, fmt('Content-Length: %s', #Body)) insert(request, #request, 'Content-Type: application/x-www-form-urlencoded\r\n') insert(request, Body) end if type(opt.body) == "string" then insert(request, fmt('Content-Length: %s\r\n', #opt.body)) insert(request, opt.body) end end return concat(request, CRLF) end local function build_get_req (opt) local request = new_tab(16, 0) insert(request, fmt("GET %s HTTP/1.1", opt.path)) insert(request, fmt("Host: %s", (opt.port == 80 or opt.port == 443) and opt.domain or opt.domain..':'..opt.port)) insert(request, fmt("User-Agent: %s", opt.server)) insert(request, 'Accept: */*') insert(request, 'Accept-Encoding: gzip, identity') insert(request, 'Connection: keep-alive') if type(opt.args) == "table" then local args = new_tab(8, 0) for _, arg in ipairs(opt.args) do assert(#arg == 2, "args need key[1]->value[2] (2 values and must be string)") insert(args, url_encode(arg[1])..'='..url_encode(arg[2])) end request[1] = fmt("GET %s HTTP/1.1", opt.path..'?'..concat(args, "&")) end if type(opt.headers) == "table" then for _, header in ipairs(opt.headers) do assert(#header == 2, "HEADER need key[1]->value[2] (2 values)") insert(request, header[1]..': '..header[2]) end end insert(request, CRLF) return concat(request, CRLF) end local function build_post_req (opt) local request = new_tab(16, 0) insert(request, fmt("POST %s HTTP/1.1\r\n", opt.path)) insert(request, fmt("Host: %s\r\n", (opt.port == 80 or opt.port == 443) and opt.domain or opt.domain..':'..opt.port)) insert(request, fmt("User-Agent: %s\r\n", opt.server)) insert(request, 'Accept: */*\r\n') insert(request, 'Accept-Encoding: gzip, identity\r\n') insert(request, 'Connection: keep-alive\r\n') if type(opt.headers) == "table" then for _, header in ipairs(opt.headers) do assert(lower(header[1]) ~= 'content-length', "please don't give Content-Length") assert(#header == 2, "HEADER need key[1]->value[2] (2 values)") insert(request, header[1] .. ': ' .. header[2] .. CRLF) end end if type(opt.body) == "table" then local body = new_tab(8, 0) for _, item in ipairs(opt.body) do assert(#item == 2, "if BODY is TABLE, BODY need key[1]->value[2] (2 values)") insert(body, url_encode(item[1])..'='..url_encode(item[2])) end local Body = concat(body, "&") insert(request, fmt('Content-Length: %s\r\n', #Body)) insert(request, 'Content-Type: application/x-www-form-urlencoded\r\n\r\n') insert(request, Body) elseif type(opt.body) == 'string' and opt.body ~= '' then insert(request, fmt('Content-Length: %s\r\n', #opt.body)) insert(request, 'Content-Type: application/x-www-form-urlencoded\r\n\r\n') insert(request, opt.body) else insert(request, "Content-Length: 0\r\n\r\n") end return concat(request) end local function build_delete_req (opt) local request = new_tab(16, 0) insert(request, fmt("DELETE %s HTTP/1.1", opt.path)) insert(request, fmt("Host: %s", (opt.port == 80 or opt.port == 443) and opt.domain or opt.domain..':'..opt.port)) insert(request, fmt("User-Agent: %s", opt.server)) insert(request, 'Accept: */*') insert(request, 'Accept-Encoding: gzip, identity') insert(request, 'Connection: keep-alive') if type(opt.headers) == "table" then for _, header in ipairs(opt.headers) do assert(#header == 2, "HEADER need key[1]->value[2] (2 values)") insert(request, header[1]..': '..header[2]) end end if type(opt.body) == "string" and opt.body ~= '' then insert(request, fmt("Content-Length: %s", #opt.body)) end return concat(request, CRLF) .. CRLF2 .. ( type(opt.body) == "string" and opt.body or '' ) end local function build_json_req (opt) local request = new_tab(16, 0) insert(request, fmt("POST %s HTTP/1.1", opt.path)) insert(request, fmt("Host: %s", (opt.port == 80 or opt.port == 443) and opt.domain or opt.domain..':'..opt.port)) insert(request, fmt("User-Agent: %s", opt.server)) insert(request, 'Accept: */*') insert(request, 'Accept-Encoding: gzip, identity') insert(request, 'Connection: keep-alive') if type(opt.headers) == "table" then for _, header in ipairs(opt.headers) do assert(lower(header[1]) ~= 'content-length', "please don't give Content-Length") assert(#header == 2, "HEADER need key[1]->value[2] (2 values)") insert(request, header[1]..': '..header[2]) end end if type(opt.json) == 'string' and opt.json ~= '' then insert(request, 'Content-Type: application/json') insert(request, fmt("Content-Length: %s", #opt.json)) elseif type(opt.json) == 'table' then opt.json = json_encode(opt.json) insert(request, 'Content-Type: application/json') insert(request, "Content-Length: " .. #opt.json) else opt.json = "" insert(request, 'Content-Type: application/json') insert(request, "Content-Length: 0") end return concat(request, CRLF) .. CRLF2 .. opt.json end local function build_xml_req(opt) local request = new_tab(16, 0) insert(request, fmt("POST %s HTTP/1.1", opt.path)) insert(request, fmt("Host: %s", (opt.port == 80 or opt.port == 443) and opt.domain or opt.domain..':'..opt.port)) insert(request, fmt("User-Agent: %s", opt.server)) insert(request, 'Accept: */*') insert(request, 'Accept-Encoding: gzip, identity') insert(request, 'Connection: keep-alive') if type(opt.headers) == "table" then for _, header in ipairs(opt.headers) do assert(lower(header[1]) ~= 'content-length', "please don't give Content-Length") assert(#header == 2, "HEADER need key[1]->value[2] (2 values)") insert(request, header[1]..': '..header[2]) end end if type(opt.xml) == 'string' and opt.xml ~= '' then insert(request, 'Content-Type: application/xml') insert(request, fmt("Content-Length: %s", #opt.xml)) elseif type(opt.xml) == 'table' then opt.xml = toxml(opt.xml, "xml") insert(request, 'Content-Type: application/xml') insert(request, "Content-Length: " .. #opt.xml) else opt.xml = "" insert(request, 'Content-Type: application/xml') insert(request, "Content-Length: 0") end return concat(request, CRLF) .. CRLF2 .. opt.xml end local function build_file_req (opt) local request = new_tab(16, 0) insert(request, fmt("POST %s HTTP/1.1\r\n", opt.path)) insert(request, fmt("Host: %s\r\n", (opt.port == 80 or opt.port == 443) and opt.domain or opt.domain..':'..opt.port)) insert(request, fmt("User-Agent: %s\r\n", opt.server)) insert(request, 'Accept: */*\r\n') insert(request, 'Accept-Encoding: gzip, identity\r\n') insert(request, 'Connection: keep-alive\r\n') if type(opt.headers) == "table" then for _, header in ipairs(opt.headers) do assert(lower(header[1]) ~= 'content-length', "please don't give Content-Length") assert(#header == 2, "HEADER need key[1]->value[2] (2 values)") insert(request, header[1]..': '..header[2]..'\r\n') end end if type(opt.files) == 'table' then local bd = random(1000000000, 9999999999) local boundary_start = fmt("------CFWebService%d", bd) local boundary_end = fmt("------CFWebService%d--", bd) insert(request, fmt('Content-Type: multipart/form-data; boundary=----CFWebService%s\r\n', bd)) local body = new_tab(16, 0) local cd = 'Content-Disposition: form-data; %s' local ct = 'Content-Type: %s' for index, file in ipairs(opt.files) do assert(file.file, "files index : [" .. index .. "] unknown multipart/form-data content.") insert(body, boundary_start) local name = file.name local filename = file.filename if not file.type then if type(name) ~= 'string' or name == '' then name = '' end insert(body, fmt(cd, fmt('name="%s"', name)) .. CRLF) else if type(name) ~= 'string' or name == '' then name = '' end if type(filename) ~= 'string' or filename == '' then filename = '' end insert(body, fmt(cd, fmt('name="%s"', name) .. '; ' .. fmt('filename="%s"', filename))) insert(body, fmt(ct, FILEMIME[file.type or ''] or 'application/octet-stream') .. CRLF) end insert(body, file.file) end insert(body, boundary_end) body = concat(body, CRLF) insert(request, fmt("Content-Length: %s\r\n\r\n", #body)) insert(request, body) end return concat(request) end local function build_put_req (opt) local request = new_tab(16, 0) insert(request, fmt("PUT %s HTTP/1.1", opt.path)) insert(request, fmt("Host: %s", (opt.port == 80 or opt.port == 443) and opt.domain or opt.domain..':'..opt.port)) insert(request, fmt("User-Agent: %s", opt.server)) insert(request, 'Accept: */*') insert(request, 'Accept-Encoding: gzip, identity') insert(request, 'Connection: keep-alive') if type(opt.headers) == "table" then for _, header in ipairs(opt.headers) do assert(lower(header[1]) ~= 'content-length', "please don't give Content-Length") assert(#header == 2, "HEADER need key[1]->value[2] (2 values)") insert(request, header[1]..': '..header[2]) end end if type(opt.body) == "string" and opt.body ~= '' then insert(request, fmt("Content-Length: %s", #opt.body)) end return concat(request, CRLF) .. CRLF2 .. ( type(opt.body) == "string" and opt.body or '' ) end -- http base authorization local function build_basic_authorization(username, password) return "Authorization", "Basic " .. base64encode(username .. ":" .. password) end return { sock_new = sock_new, sock_recv = sock_recv, sock_send = sock_send, sock_connect = sock_connect, httpc_response = httpc_response, splite_protocol = splite_protocol, build_raw_req = build_raw_req, build_get_req = build_get_req, build_post_req = build_post_req, build_json_req = build_json_req, build_file_req = build_file_req, build_xml_req = build_xml_req, build_put_req = build_put_req, build_delete_req = build_delete_req, build_basic_authorization = build_basic_authorization, }
local helpers = require('test.functional.helpers')(after_each) local screen = require('test.functional.ui.screen') local curbufmeths = helpers.curbufmeths local curwinmeths = helpers.curwinmeths local nvim_dir = helpers.nvim_dir local command = helpers.command local meths = helpers.meths local clear = helpers.clear local eq = helpers.eq describe(':edit term://*', function() local get_screen = function(columns, lines) local scr = screen.new(columns, lines) scr:attach({rgb=false}) return scr end before_each(function() clear() meths.set_option('shell', nvim_dir .. '/shell-test') meths.set_option('shellcmdflag', 'EXE') end) it('runs TermOpen event', function() meths.set_var('termopen_runs', {}) command('autocmd TermOpen * :call add(g:termopen_runs, expand("<amatch>"))') command('edit term://') local termopen_runs = meths.get_var('termopen_runs') eq(1, #termopen_runs) eq(termopen_runs[1], termopen_runs[1]:match('^term://.//%d+:$')) end) it("runs TermOpen early enough to set buffer-local 'scrollback'", function() local columns, lines = 20, 4 local scr = get_screen(columns, lines) local rep = 'a' meths.set_option('shellcmdflag', 'REP ' .. rep) local rep_size = rep:byte() -- 'a' => 97 local sb = 10 command('autocmd TermOpen * :setlocal scrollback='..tostring(sb) ..'|call feedkeys("G", "n")') command('edit term://foobar') local bufcontents = {} local winheight = curwinmeths.get_height() local buf_cont_start = rep_size - sb - winheight + 2 for i = buf_cont_start,(rep_size - 1) do bufcontents[#bufcontents + 1] = ('%d: foobar'):format(i) end bufcontents[#bufcontents + 1] = '' bufcontents[#bufcontents + 1] = '[Process exited 0]' local exp_screen = '\n' for i = 1,(winheight - 1) do local line = bufcontents[#bufcontents - winheight + i] exp_screen = (exp_screen .. line .. (' '):rep(columns - #line) .. '|\n') end exp_screen = exp_screen..'^[Process exited 0] |\n' exp_screen = exp_screen..(' '):rep(columns)..'|\n' scr:expect(exp_screen) eq(bufcontents, curbufmeths.get_lines(0, -1, true)) end) end)
local class = require 'ext.class' local Set = require 'symmath.set.Set' local Null = class(Set) Null.name = 'Null' -- is the null set a subset of itself? -- can a variable be defined to exist in the null set? function Null:variable(...) error"you cannot create a variable from the null set" end function Null:containsVariable(s) return false end function Null:containsElement(s) return false end return Null
local is_array = require "api-umbrella.utils.is_array" -- Like deep_merge_overwrite_arrays, but only assigns values from the source to -- the destination if the destination is nil. So any existing values on the -- destination object will be retained. local function deep_defaults(dest, src) if not src then return dest end for key, value in pairs(src) do if type(value) == "table" and type(dest[key]) == "table" then if is_array(value) or is_array(dest[key]) then if dest[key] == nil then dest[key] = value end else deep_defaults(dest[key], src[key]) end else if dest[key] == nil then dest[key] = value end end end return dest end return deep_defaults
function HarpiePriority() AddPriority({ -- Harpie [75064463] = {7,1,6,1,3,2,2,2,1,1,QueenCond}, -- Harpie Queen [80316585] = {4,1,4,1,5,2,4,2,1,1,CyberCond}, -- Cyber Harpie Lady [56585883] = {8,1,8,1,8,0,5,2,1,1,HarpistCond}, -- Harpie Harpist [90238142] = {9,4,9,1,1,1,6,3,1,1,ChannelerCond},-- Harpie Channeler [91932350] = {3,1,5,1,4,2,3,2,1,1,Lady1Cond}, -- Harpie Lady #1 [68815132] = {6,1,7,1,2,2,2,2,1,1,DancerCond}, -- Harpie Dancer [90219263] = {1,1,1,1,1,1,1,1,1,1,nil}, -- Elegant Egotist [19337371] = {12,6,1,1,9,1,1,1,1,1,SignCond}, -- Hysteric Sign [15854426] = {1,1,1,1,1,1,1,1,1,1,nil}, -- Divine Wind of Mist Valley [75782277] = {5,1,1,1,3,1,1,1,1,1,nil}, -- Harpie's Hunting Ground [77778835] = {13,1,1,1,1,1,1,1,1,1,nil}, -- Hysteric Party [22653490] = {1,1,1,1,1,1,3,1,1,1,nil}, -- Chidori [85909450] = {1,1,1,1,1,1,3,1,1,1,nil}, -- HPPD [86848580] = {1,1,1,1,1,1,3,1,1,1,nil}, -- Zerofyne [89399912] = {1,1,1,1,7,1,1,1,1,1,nil}, -- Tempest [52040216] = {1,1,1,1,6,1,1,1,1,1,nil}, -- Pet Dragon [94145683] = {1,1,1,1,1,1,1,1,1,1,nil}, -- Swallow's }) end HarpieLady={ 56585883, -- Harpie Harpist 75064463, -- Harpie Queen 80316585, -- Cyber Harpie Lady 91932350, -- Harpie Lady #1 76812113, -- Harpie Lady 68815132, -- Harpie Dancer 90238142, -- Harpie Channeler } function LadyFilter(c,negated) if negated then return c.id == 76812113 end for i=1,#HarpieLady do if c.original_id == HarpieLady[i] then return true end end return false end function LadyCount(cards,negated,filter,opt) return CardsMatchingFilter(SubGroup(cards,filter,opt),LadyFilter,negated) end function HarpieFilter(c,exclude) return IsSetCode(c.setcode,0x64) and (exclude == nil or c.id~=exclude) end function HarpieCount(cards,filter,opt) return CardsMatchingFilter(SubGroup(cards,filter,opt),FilterID,76812113) end function PartyCheck(c,count) return c.id==77778835 and FilterPosition(c,POS_FACEUP) and CardTargetCheck(c)==0 end function QueenCond(loc,c) if loc == PRIO_TOHAND then return not HasID(AIHand(),c.original_id,true) end if loc == PRIO_EXTRA then if FilterLocation(c,LOCATION_HAND) then return false end if FilterLocation(c,LOCATION_GRAVE) then return GetMultiple(c.original_id)==0 end end return true end function Lady1Cond(loc,c) if loc == PRIO_TOHAND then return not HasID(AIHand(),c.original_id,true) end if loc == PRIO_EXTRA then if FilterLocation(c,LOCATION_HAND) then return false end if FilterLocation(c,LOCATION_GRAVE) then return GetMultiple(c.original_id)==0 end end return true end function CyberCond(loc,c) if loc == PRIO_TOHAND then return not HasID(AIHand(),c.original_id,true) end if loc == PRIO_EXTRA then if FilterLocation(c,LOCATION_HAND) then return false end if FilterLocation(c,LOCATION_GRAVE) then return GetMultiple(c.original_id)==0 end end return true end function DancerCond(loc,c) if loc == PRIO_TOHAND then if HasIDNotNegated(AICards(),15854426,true,FilterOPT) and not HasID(AIHand(),c.original_id,true) then return 10 end return not HasID(AIHand(),c.original_id,true) end if loc == PRIO_TOFIELD then if HasIDNotNegated(AICards(),15854426,true,FilterOPT) and not HasID(AIMon(),c.original_id,true) and OPTCheck(68815132) and GetMultiple(c.original_id)==0 then return 10 end return not HasID(AIMon(),c.original_id,true) and OPTCheck(c.original_id) and GetMultiple(c.original_id)==0 end return true end function HarpistGraveFilter(c) return c.original_id == 56585883 and c.turnid == Duel.GetTurnCount() end function HarpistSearchFilter(c) return FilterRace(c,RACE_WINDBEAST) and c.level==4 and c.attack<=1500 end function HarpistCond(loc,c) if loc==PRIO_TOGRAVE then return OPTCheck(56585883) and CardsMatchingFilter(AIGrave(),HarpistGraveFilter)==0 and CardsMatchingFilter(AIDeck(),HarpistSearchFilter)>0 end if loc == PRIO_EXTRA then if FilterLocation(c,LOCATION_HAND) then return false end if FilterLocation(c,LOCATION_GRAVE) then return GetMultiple(c.original_id)==0 and not HarpistGraveFilter(c) end end if loc == PRIO_TOFIELD then return GetMultiple(c.original_id)==0 end if loc == PRIO_TOHAND then if FilterLocation(c,LOCATION_ONFIELD) and UseHarpist(c) and not HasID(AIHand(),56585883,true) then return 11 end end return true end function ChannelerCond(loc,c) if loc == PRIO_TOHAND then return not HasID(AIHand(),c.original_id,true) or FilterLocation(c,LOCATION_ONFIELD) end if loc == PRIO_TOFIELD then return not HasID(AIMon(),c.original_id,true) and OPTCheck(c.original_id) and GetMultiple(c.original_id)==0 and UseChanneler(c) and FieldCheck(4)==0 end if loc == PRIO_EXTRA then if FilterLocation(c,LOCATION_HAND) then return false end if FilterLocation(c,LOCATION_GRAVE) then return GetMultiple(c.original_id)==0 end end return true end function SignGraveFilter(c) return c.id == 19337371 and c.turnid == Duel.GetTurnCount() end function SignCheck(cards) return (cards == nil or HasID(cards,19337371,true)) and OPTCheck(19337371) and CardsMatchingFilter(AIGrave(),SignGraveFilter)==0 end function SignCond(loc,c) if loc==PRIO_TOHAND then return FilterLocation(c,LOCATION_ONFIELD) or DiscardOutlets()>0 end if loc==PRIO_TOGRAVE then return FilterLocation(c,LOCATION_ONFIELD+LOCATION_HAND) and SignCheck() end return true end function UseDivineWind(c,cards) return DualityCheck() and OPTCheck(68815132) and HasIDNotNegated(UseLists(cards,AIMon()),68815132,true) and (not HasID(AIST(),75782277,true) or DestroyCheck(OppST(),false,true)==0) end function UseHHG(c,cards) return (DestroyCheck(OppST(),false,true)>0 or SignCheck(AIST())) and (CardsMatchingFilter(cards,LadyFilter,SkillDrainCheck())>0 or HasIDNotNegated(AIMon(),90238142,true,UseChanneler)) and not (HasID(AIST(),75782277,true) or HasID(AIST(),15854426,true)) end function DancerYesNo() if FieldCheck(4)==1 and not (HasIDNotNegated(AIST(),15854426,true,FilterOPT) and DualityCheck()) or FieldCheck(4)==0 and (HasIDNotNegated(AIST(),15854426,true,FilterOPT) or HasIDNotNegated(AICards(),90219263,true) or HasIDNotNegated(AIHand(),90238142,true,UseChanneler)) and DualityCheck() or HasIDNotNegated(AIST(),75782277,true) and DestroyCheck(OppST())>0 or HasIDNotNegated(AIHand(),56585883,true,UseHarpist) then return 1 end return 0 end function UseDancer(c,mode) if mode == 1 and (HasIDNotNegated(AIST(),75782277,true) and DestroyCheck(OppST(),false,true)>0 or HasIDNotNegated(AIST(),15854426,true,FilterOPT) and DualityCheck() or HasID(AIMon(),90238142,true) and LadyCount(AIHand())>0 or HasID(AIHand(),90238142,true) and FieldCheck(4)==1) or HasID(AICards(),56585883,true,UseHarpist) then return true end if mode == 3 and HasID(AIMon(),00581014,true) and SummonEmeralHarpie() and (LadyCount(AIHand())>0 or FieldCheck(4)>1) then GlobalCardMode=1 GlobalTargetSet(FindID(00581014,AIMon())) return true end if mode == 2 and #AIMon()>3 and TurnEndCheck() then return true end return false end function SummonDancer(c,mode) if mode == 1 and (HasIDNotNegated(AIST(),75782277,true) and DestroyCheck(OppST(),false,true)>0 or HasIDNotNegated(AIST(),15854426,true,FilterOPT) and DualityCheck()) and OPTCheck(68815132) then return true end if mode == 2 and HasID(AIMon(),00581014,true,SummonEmeralHarpie) and (LadyCount(AIHand())>1 or FieldCheck(4)>0) and OPTCheck(68815132) then return true end return false end function UseQueen(c,cards) return not HasID(AICards(),75782277,true) and UseHHG(FindID(75782277,AIDeck()),cards) end function UseChanneler(c) return OPTCheck(90238142) and DualityCheck() and (FieldCheck(4)==2 and SummonHPPD() or FilterLocation(c,LOCATION_MZONE) and FieldCheck(4)==1 or FieldCheck(4)==0 and OverExtendCheck(2,5)) end function SummonChanneler(c) if UseChanneler(c) and CardsMatchingFilter(AIHand(),HarpieFilter)>1 then return true end return false end function HarpistFilter(c) return (PriorityTarget(c) or c.attack>AIGetStrongestAttack()) and Affected(c,TYPE_MONSTER,4) and Targetable(c,TYPE_MONSTER) and FilterPosition(c,POS_FACEUP) end function SummonHarpist(c) if UseHarpist(c) then return true end return false end function SummonHarpie(c,mode) if mode == 1 and (FieldCheck(4)==1 or HasID(AICards(),90219263,true) and LadyCount(AIDeck(),true)>0) and OverExtendCheck() and DualityCheck() then return true end if mode == 2 and (DestroyCheck(OppST())>0 or SignCheck(AIST())) and HasIDNotNegated(AIST(),75782277,true) and LadyFilter(c) then return true end if mode == 3 and OppHasStrongestMonster() and c.attack>OppGetStrongestAttDef() then return true end if mode == 4 and (#AIHand()>5 or c.attack>1600) then return true end end function UseParty(c,mode) if mode == 1 and Duel.GetLocationCount(player_ai,LOCATION_MZONE)>3 and LadyCount(AIGrave())>3 then return true end if mode == 2 and OppHasStrongestMonster() and (LadyCount(AIGrave())>1 and SignCheck(AIHand()) or LadyCount(AIHand())>0) then return true end if mode == 3 and OppHasStrongestMonster() and (LadyCount(AIGrave())>1 or LadyCount(AIHand())>0) then return true end return false end function UseSign(c,cards) return LadyCount(AIDeck(),true)>0 and SignCheck() and ((FieldCheck(4,LadyFilter)==1 or LadyCount(cards)>0) and OppHasStrongestMonster() or CardsMatchingFilter(AIHand(),FilterID,19337371)>1 or HasID(AICards(),05318639,true)) --or TurnEndCheck() and DiscardOutlets()==0 end function UseEgotist(c) return OverExtendCheck() end function SetSign(c,cards) return (HasID(AIHand(),75782277,true) and (LadyCount(cards)>0 or HasID(AIMon(),90238142,true,UseChanneler)) or HasID(AIHand(),75064463,true) and (LadyCount(cards)>1 or HasID(AIMon(),90238142,true,UseChanneler))) and not (DestroyCheck(OppST())==0 and not HasPriorityTarget(OppST(),DestroyFilter) and HasID(cards,90238142,true,SummonChanneler) and CardsMatchingFilter(AIHand(),HarpieFilter)>2) and SignCheck() and not HasID(AIST(),19337371,true) end function SummonHPPD(c) return AI.GetPlayerLP(2)<=4000 and MP2Check(2000) end function RepoHPPD(c) return FilterPosition(c,POS_DEFENSE) and c.xyz_material_count>0 and not FilterAffected(c,EFFECT_DISABLE) end function SummonZerofyne(c) return CardsMatchingFilter(Field(),FilterPosition,POS_FACEUP)>5 and #OppMon()>0 and BattlePhaseCheck() and OppHasStrongestMonster() end function SummonZephyrosHarpie(source,mode) if not DeckCheck(DECK_HARPIE) then return false end if mode == 1 and AI.GetPlayerLP(1)>400 then for i=1,#AIST() do local c=AIST()[i] if PartyCheck(c,0) then GlobalCardMode = 1 GlobalTargetSet(c) return true end end if HasID(AIST(),19337371,true,nil,nil,POS_FACEUP) and DiscardOutlets()>0 then return true end end if mode == 2 and FieldCheck(4) == 1 and CardsMatchingFilter(AIST(),FilterPosition,POS_FACEUP)>0 and OverExtendCheck() and AI.GetPlayerLP(1)>400 then return true end if mode == 3 and FieldCheck(4) == 1 and OverExtendCheck() then return true end return false end function SummonEmeralHarpie(c) if not DeckCheck(DECK_HARPIE) then return false end if LadyCount(UseLists(AIMon(),AIGrave(),AIMaterials()))>5 and LadyCount(AIGrave())>2 and MP2Check(1800) and not OppHasStrongestMonster() then return true end return false end function SummonChainHarpie(c) return (HasID(AIDeck(),14785765,true) or HasID(AIDeck(),56585883,true) and not HasID(AIMon(),56585883,true) and LadyCount(AIHand())<2 and CardsMatchingFilter(AIGrave(),HarpistGraveFilter)==0 and OPTCheck(56585883)) and (not OppHasStrongestMonster() or OppGetStrongestAttDef()<1800) and MP2Check(c) end function UseChainHarpie(c,mode) if not DeckCheck(DECK_HARPIE) then return false end if mode ==1 then if HasID(AIDeck(),14785765,true) then return true end if HasID(AIDeck(),56585883,true) and not HasID(c.xyz_materials,56585883,true) and LadyCount(AIHand())<2 and CardsMatchingFilter(AIGrave(),HarpistGraveFilter)==0 and OPTCheck(56585883) then return true end end if mode == 2 and EPAddedCards()==0 and not HasID(c.xyz_materials,56585883,true) and TurnEndCheck() then GlobalCardMode=2 return true end if mode == 3 and TurnEndCheck() then return true end return false end function HarpieInit(cards) local Act = cards.activatable_cards local Sum = cards.summonable_cards local SpSum = cards.spsummonable_cards local Rep = cards.repositionable_cards local SetMon = cards.monster_setable_cards local SetST = cards.st_setable_cards if HasID(SetST,19337371,SetSign,Sum) then return {COMMAND_SET_ST,CurrentIndex} end if HasIDNotNegated(Act,75782277,UseHHG,Sum) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,15854426,UseDivineWind,Sum) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,75064463,UseQueen,Sum) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,77778835,UseParty,1) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,00581014) and DeckCheck(DECK_HARPIE) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,68815132,UseDancer,3) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,68815132,UseDancer,1) then OPTSet(68815132) return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,90238142,UseChanneler) then OPTSet(90238142) return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,34086406,false,545382497,UseChainHarpie,1) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Sum,68815132,SummonDancer,1) then return {COMMAND_SUMMON,CurrentIndex} end if HasIDNotNegated(Sum,68815132,SummonDancer,2) then return {COMMAND_SUMMON,CurrentIndex} end if HasIDNotNegated(Sum,90238142,SummonChanneler) then return {COMMAND_SUMMON,CurrentIndex} end if HasIDNotNegated(Sum,56585883,SummonHarpist) then return {COMMAND_SUMMON,CurrentIndex} end if HasID(Act,14785765,SummonZephyrosHarpie,1) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(SpSum,85909450,SummonHPPD) then return XYZSummon() end if HasIDNotNegated(SpSum,34086406,SummonChainHarpie) then return XYZSummon() end if HasIDNotNegated(Act,86848580) then -- Zerofyne return {COMMAND_ACTIVATE,CurrentIndex} end for j=1,4 do for i=1,#HarpieLady do if HasID(Sum,HarpieLady[i],SummonHarpie,j) then return {COMMAND_SUMMON,CurrentIndex} end end end if HasID(Sum,14785765,SummonZephyrosHarpie,2) then return {COMMAND_SUMMON,CurrentIndex} end if HasIDNotNegated(Act,90219263,UseEgotist) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,77778835,UseParty,2) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(SpSum,00581014,SummonEmeralHarpie) then return XYZSummon() end if HasIDNotNegated(SpSum,85909450,SummonHPPD) then return XYZSummon() end if HasIDNotNegated(SpSum,86848580,SummonZerofyne) then return XYZSummon() end if HasIDNotNegated(Act,19337371,UseSign,Sum) then OPTSet(19337371) return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,14785765,SummonZephyrosHarpie,2) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,77778835,UseParty,3) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Rep,85909450,RepoHPPD) then return {COMMAND_CHANGE_POS,CurrentIndex} end if HasIDNotNegated(Act,68815132,UseDancer,2) then OPTSet(68815132) return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,34086406,false,545382498,UseChainHarpie,2) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,34086406,false,545382497,UseChainHarpie,3) then return {COMMAND_ACTIVATE,CurrentIndex} end return nil end function ChannelerTarget(cards) if LocCheck(cards,LOCATION_HAND) then return Add(cards,PRIO_TOGRAVE) end return Add(cards,PRIO_TOFIELD) end function HarpistTarget(cards) if LocCheck(cards,LOCATION_DECK) then return Add(cards) end if CurrentOwner(cards[1])==1 then return Add(cards,PRIO_TOHAND) end return BestTargets(cards,1,TARGET_TOHAND) end function DancerTarget(cards) if GlobalCardMode==1 then GlobalCardMode=nil return GlobalTargetGet(cards,true) end if LocCheck(cards,LOCATION_HAND) then return Add(cards,PRIO_TOFIELD) end return Add(cards) end function PartyTarget(cards,min) if LocCheck(cards,LOCATION_HAND) then return Add(cards,PRIO_TOGRAVE) end return Add(cards,PRIO_TOFIELD,min) end function HHGTarget(cards) if HasID(cards,19337371) and SignCheck() and not HasPriorityTarget(cards,DestroyFilter) then return {CurrentIndex} end if HasID(cards,75782277) and DestroyCheck(OppST(),false,true)==0 then return {CurrentIndex} end return BestTargets(cards,1,TARGET_DESTROY) end function ZephyrosTarget(cards) if GlobalCardMode == 1 then GlobalCardMode = nil return GlobalTargetGet(cards,true) end if HasID(cards,19337371) then return {CurrentIndex} end return BestTargets(cards,1,TARGET_TOHAND) end function HarpieCard(cards,min,max,id,c) if id == 76812113 then id = c.original_id end if id == 14785765 then return ZephyrosTarget(cards) end if id == 90238142 then return ChannelerTarget(cards) end if id == 56585883 then return HarpistTarget(cards) end if id == 68815132 then return DancerTarget(cards) end if id == 90219263 then -- Egotist return Add(cards,PRIO_TOFIELD) end if id == 19337371 then -- Sign return Add(cards) end if id == 15854426 then -- Divine Wind return Add(cards,PRIO_TOFIELD) end if id == 77778835 then return PartyTarget(cards,min) end if id == 85909450 then -- HPPD return Add(cards,PRIO_TOGRAVE) end if id == 86848580 then -- Zerofyne return Add(cards,PRIO_TOGRAVE) end if id == 75782277 then return HHGTarget(cards) end return nil end -- function HarpistBounceFilter(c,source) return FilterRace(c,RACE_WINDBEAST) and (not FilterType(c,TYPE_XYZ) or c.xyz_material_count==0) and not CardsEqual(c,source) end function UseHarpist(c) return CardsMatchingFilter(AIMon(),HarpistBounceFilter,c)>0 and CardsMatchingFilter(OppMon(),HarpistFilter)>0 and NotNegated(c) and OPTCheck(56585884) end function ChainHarpist(c) if FilterLocation(c,LOCATION_MZONE) and UseHarpist(c) then OPTSet(56585884) return true end if FilterLocation(c,LOCATION_GRAVE) then OPTSet(56585883) return true end return false end function ChainParty(c) if Duel.GetCurrentPhase()==PHASE_END and Duel.GetTurnPlayer()~=player_ai and SignCheck(AIHand()) and UnchainableCheck(77778835) then return true end if IsBattlePhase() and Duel.GetTurnPlayer()~=player_ai and UnchainableCheck(77778835) then local aimon,oppmon=GetBattlingMons() if CanFinishGame(oppmon) and #AIMon()==0 then return true end end if IsBattlePhase() and Duel.GetTurnPlayer()==player_ai and UnchainableCheck(77778835) then local loccount=Duel.GetLocationCount(player_ai,LOCATION_MZONE) local atk = TotalATK(AIGrave(),loccount,LadyFilter) if #OppMon()==0 and atk>=AI.GetPlayerLP(2) and ExpectedDamage(2)==0 then return true end end return false end function HarpieChain(cards) if HasID(cards,19337371) then -- Sign OPTSet(19337371) return {1,CurrentIndex} end if HasID(cards,15854426) then -- Divine Wind OPTSet(cards[CurrentIndex].cardid) return {1,CurrentIndex} end if HasID(cards,56585883,ChainHarpist) then return {1,CurrentIndex} end if HasIDNotNegated(cards,77778835,ChainParty) then return {1,CurrentIndex} end return nil end function HarpieEffectYesNo(id,card) local result = nil if id == 19337371 -- Sign then OPTSet(19337371) result = 1 end if id == 15854426 -- Divine Wind then OPTSet(card.cardid) result = 1 end if id == 56585883 and ChainHarpist(card) then result = 1 end return result end function HarpieOption(options) return nil end HarpieAtt={ 76812113, -- Harpie Lady 75064463, -- Harpie Queen 80316585, -- Cyber Harpie Lady 56585883, -- Harpie Harpist 90238142, -- Harpie Channeler 91932350, -- Harpie Lady #1 68815132, -- Harpie Dancer 86848580, -- Zerofyne 85909450, -- HPPD } HarpieDef={ } function HarpiePosition(id,available) result = nil for i=1,#HarpieAtt do if HarpieAtt[i]==id then if IsBattlePhase() and Duel.GetTurnPlayer()~=player_ai then result=POS_FACEUP_DEFENSE else result=POS_FACEUP_ATTACK end end end for i=1,#HarpieDef do if HarpieDef[i]==id then result=POS_FACEUP_DEFENSE end end return result end
AddCSLuaFile() AddCSLuaFile("sh_sounds.lua") AddCSLuaFile("sh_soundscript.lua") include("sh_sounds.lua") include("sh_soundscript.lua") CustomizableWeaponry.shells:addNew("khr12gbuck", "models/khrcw2/doipack/shells/12g_slug.mdl", "CW_SHELL_SHOT") if CLIENT then SWEP.DrawCrosshair = false SWEP.PrintName = "Ithaca 37" SWEP.CSMuzzleFlashes = true SWEP.UseHands = false SWEP.MuzzleEffect = "muzzleflash_m3" SWEP.PosBasedMuz = false SWEP.SightWithRail = true SWEP.EffectiveRange_Orig = 70 * 39.37 SWEP.DamageFallOff_Orig = .7 SWEP.Shell = "khr12gbuck" SWEP.ShellScale = .55 SWEP.ShellDelay = .55 SWEP.ShellOffsetMul = 1 SWEP.ShellPosOffset = {x = 0, y = 0, z = -7} SWEP.ForeGripOffsetCycle_Draw = 0 SWEP.ForeGripOffsetCycle_Reload = 0 SWEP.ForeGripOffsetCycle_Reload_Empty = 0 SWEP.IronsightPos = Vector(-2.0885, -2.25, 1.2) SWEP.IronsightAng = Vector(0.555, 0, 0) SWEP.AltIronPos = Vector(-2.0885, -2.25, 1.2) SWEP.AltIronAng = Vector(0.778550, 0, 0) SWEP.SprintPos = Vector(2, 0, 0) SWEP.SprintAng = Vector(-15.478, 20.96, 0) SWEP.CustomizePos = Vector(8, -2, .5) SWEP.CustomizeAng = Vector(10, 45, 16) SWEP.SwimPos = Vector(0.5682, -1.7045, 1.0526) SWEP.SwimAng = Vector(-40.8947, 40.0455, -12.2273) SWEP.PronePos = Vector(0, 0, -3.1579) SWEP.ProneAng = Vector(-2, 22.7368, -28.9474) SWEP.AlternativePos = Vector(-0.5, -.5, -.3) SWEP.AlternativeAng = Vector(0, 0, 0) SWEP.MoveType = 1 SWEP.ViewModelMovementScale = .9 SWEP.DisableSprintViewSimulation = false SWEP.LuaVMRecoilAxisMod = {vert = .5, hor = .5, roll = 3, forward = 1, pitch = .65} SWEP.OverallMouseSens = 1 -- 1 -- 1 -- .75 SWEP.CustomizationMenuScale = 0.022 -- 0.025 SWEP.ForegripOverridePos = { ["nah"] = { ["L Finger0"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 4, 0) }, ["L Finger01"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-1, -8, 2) }, ["L Finger02"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, -4, 0) }}, } end SWEP.MuzzleVelocity = 360 SWEP.BarrelBGs = {main = 2, nohs = 0, hs = 1} SWEP.SlingBGs = {main = 3, off = 0, on = 1} SWEP.LuaViewmodelRecoil = true SWEP.LuaViewmodelRecoilOverride = true SWEP.FullAimViewmodelRecoil = false SWEP.CanRestOnObjects = true SWEP.Attachments = { ["+reload"] = {header = "Ammo", offset = {700, 325}, atts = {"am_slugrounds", "am_trishot", "am_dartrounds"}} } SWEP.Animations = {fire = {"base_fire_1","base_fire_2"}, fire_aim = {"iron_fire_1","iron_fire_2"}, reload_start = "base_reload_start", insert = "base_reload_insert", reload_end = "base_reload_end", idle = "base_idle", draw = "base_draw"} SWEP.SpeedDec = 10 SWEP.Slot = 3 SWEP.SlotPos = 0 SWEP.HoldType = "ar2" SWEP.NormalHoldType = "ar2" SWEP.RunHoldType = "crossbow" SWEP.FireModes = {"pump"} SWEP.Base = "cw_base" SWEP.Category = "STALKER Weapons" SWEP.Author = "" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.NearWallEnabled = false SWEP.ViewModelFOV = 65 SWEP.AimViewModelFOV = 60 SWEP.ZoomAmount = 10 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/khrcw2/doipack/ithaca37.mdl" SWEP.WorldModel = "models/khrcw2/doipack/w_ithaca37.mdl" SWEP.DrawTraditionalWorldModel = false SWEP.WM = "models/khrcw2/doipack/w_ithaca37.mdl" SWEP.WMPos = Vector(-1.5, 11, -1) SWEP.WMAng = Vector(-16, 2, 180) SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.ReloadViewBobEnabled = true SWEP.RVBPitchMod = 1 SWEP.RVBYawMod = 1 SWEP.RVBRollMod = 1 SWEP.Primary.ClipSize = 7 SWEP.Primary.DefaultClip = 0 SWEP.Primary.Automatic = true SWEP.Primary.Ammo = "12 Gauge" SWEP.FireDelay = 0.9 SWEP.FireSound = "DOIM37_FIRE" SWEP.FireSoundSuppressed = "DOIM37_FIRE" SWEP.Recoil = 4.2 SWEP.FOVPerShot = 0 -- = 1 SWEP.WearDamage = 0.20 SWEP.WearEffect = 0.1 SWEP.HipSpread = 0.06 SWEP.AimSpread = 0.005 SWEP.VelocitySensitivity = 4 SWEP.MaxSpreadInc = 0.35 SWEP.ClumpSpread = 0.02 SWEP.SpreadPerShot = 0.2 SWEP.SpreadCooldown = 1.2 SWEP.Shots = 9 SWEP.Damage = 21 SWEP.DeployTime = .475 SWEP.HolsterTime = .6 SWEP.SnapToIdle = true SWEP.ADSFireAnim = true SWEP.Chamberable = true SWEP.ShotgunReload = true SWEP.PreventQuickScoping = false SWEP.ReloadSpeed = 1.3 SWEP.ReloadStartTime = 0.5 SWEP.InsertShellTime = .85 SWEP.ReloadFinishWait = 1 function SWEP:IndividualInitialize() self:setBodygroup(self.BarrelBGs.main, self.BarrelBGs.hs) end function SWEP:IndividualThink() self.Owner.ViewAff = 0 self.EffectiveRange = 70 * 39.37 self.DamageFallOff = .7 end function SWEP:fireAnimFunc() clip = self:Clip1() cycle = 0 rate = 1.1 anim = "safe" prefix = "" suffix = "" if self:isAiming() then suffix = suffix .. "_aim" cycle = self.ironFireAnimStartCycle end self:sendWeaponAnim(prefix .. "fire" .. suffix, rate, cycle) end //*/ function SWEP:Holster(wep) -- can't switch if neither the weapon we want to switch to or the wep we're trying to switch to are not valid if not IsValid(wep) and not IsValid(self.SwitchWep) then self.SwitchWep = nil return false end local CT = CurTime() -- can't holster if we have a global delay on the weapon if CT < self.GlobalDelay or CT < self.HolsterWait then self.dt.HolsterDelay = CurTime() + self.HolsterTime self.dt.State = CW_HOLSTER_START self.dt.HolsterDelay = 0 end if self.dt.HolsterDelay ~= 0 and CT < self.dt.HolsterDelay then return false end -- can't holster if there are sequenced actions if #self._activeSequences > 0 then return false end if self.ReloadDelay then self.dt.HolsterDelay = CurTime() + self.HolsterTime self.dt.State = CW_HOLSTER_START self.dt.HolsterDelay = 0 end if self.dt.State ~= CW_HOLSTER_START then self.dt.HolsterDelay = CurTime() + self.HolsterTime end self.dt.State = CW_HOLSTER_START -- if holster sequence is over, let us select the desired weapon if self.SwitchWep and self.dt.State == CW_HOLSTER_START and CurTime() > self.dt.HolsterDelay then self.dt.State = CW_IDLE self.dt.HolsterDelay = 0 return true end -- if it isn't, make preparations for it self.ShotgunReloadState = 0 self.ReloadDelay = nil if self:filterPrediction() then if self.holsterSound then -- quick'n'dirty prediction fix self:EmitSound("CW_HOLSTER", 70, 100) self.holsterSound = false if IsFirstTimePredicted() then if self.holsterAnimFunc then self:holsterAnimFunc() else if self.Animations.holster then self:sendWeaponAnim("holster") end end end end end self.SwitchWep = wep self.SuppressTime = nil if self.dt.M203Active then if SERVER and SP then SendUserMessage("CW20_M203OFF", self.Owner) end if CLIENT then self:resetM203Anim() end end self.dt.M203Active = false end
-- Copyright (c) 2020-2021 shadmansaleh -- MIT license, see LICENSE for more details. local M = {} -- Works as a decorator to expand set_lualine_theme functions -- functionality at runtime . function M.expand_set_theme(func) -- execute a local version of global function to not get in a inf recurtion local set_theme = _G.set_lualine_theme _G.set_lualine_theme = function() set_theme() func() end end return M
padawan_the_ring_02_convo_template = ConvoTemplate:new { initialScreen = "", templateType = "Lua", luaClassHandler = "padawan_the_ring_02_conv_handler", screens = {} } intro = ConvoScreen:new { id = "intro", leftDialog = "@conversation/padawan_the_ring_02:s_6a1562ad", -- What do you want? stopConversation = "false", options = { {"@conversation/padawan_the_ring_02:s_711691ff", "in_it_for_me"}, -- I'm looking for a wedding ring, have you seen one? {"@conversation/padawan_the_ring_02:s_443c85ef", "races_to_win"} -- Forty million credits and a penthouse apartment in Coruscant. } } padawan_the_ring_02_convo_template:addScreen(intro); races_to_win = ConvoScreen:new { id = "races_to_win", leftDialog = "@conversation/padawan_the_ring_02:s_f42e101f", -- I've got races to win and chumps to scam. Answer the question or get out of my face. stopConversation = "false", options = { {"@conversation/padawan_the_ring_02:s_711691ff", "in_it_for_me"}, -- I'm looking for a wedding ring, have you seen one? } } padawan_the_ring_02_convo_template:addScreen(races_to_win); in_it_for_me = ConvoScreen:new { id = "in_it_for_me", leftDialog = "@conversation/padawan_the_ring_02:s_83f28a20", -- Maybe, what is in it for me? stopConversation = "false", options = { {"@conversation/padawan_the_ring_02:s_443c85ef", "thats_funny"}, -- Forty million credits and a penthouse apartment in Coruscant. } } padawan_the_ring_02_convo_template:addScreen(in_it_for_me); thats_funny = ConvoScreen:new { id = "thats_funny", leftDialog = "@conversation/padawan_the_ring_02:s_4f77458a", -- Ha... right. That's funny. You mean this ring? The one I took from Keicho? The one he balked on when it came time to place a bet. I won his landspeeder last week, and his wifes wedding gown the week before that. I love that gown. But he wouldn't bet the ring. Couldn't understand why, so I just took it. stopConversation = "false", options = { {"@conversation/padawan_the_ring_02:s_e4815789", "test_your_luck"}, -- You took it? } } padawan_the_ring_02_convo_template:addScreen(thats_funny); test_your_luck = ConvoScreen:new { id = "test_your_luck", leftDialog = "@conversation/padawan_the_ring_02:s_80764fc6", -- Yeah, and I don't plan on giving it up. So unless you are willing test your luck and pry it off my cold dead hands I recommend you go back to Keicho and tell him to find some other chump to do his dirty work. stopConversation = "false", options = { {"@conversation/padawan_the_ring_02:s_d38d76e0", "not_getting_ring"}, -- This does not have to get violent. {"@conversation/padawan_the_ring_02:s_157b6369", "we_will_see"}, -- Believe me friend, I have far more than luck on my side. } } padawan_the_ring_02_convo_template:addScreen(test_your_luck); not_getting_ring = ConvoScreen:new { id = "not_getting_ring", leftDialog = "@conversation/padawan_the_ring_02:s_cdc241bf", -- Well then it doesn't look like you are going to be returning to your good friend with this here ring. Unless... stopConversation = "false", options = { {"@conversation/padawan_the_ring_02:s_759ab6bb", "enough_options"}, -- Unless what? } } padawan_the_ring_02_convo_template:addScreen(not_getting_ring); enough_options = ConvoScreen:new { id = "enough_options", leftDialog = "@conversation/padawan_the_ring_02:s_860ae378", -- Actually, I've given Keicho enough options. Either you fight me for this here ring, or you go back to him empty handed. stopConversation = "false", options = { {"@conversation/padawan_the_ring_02:s_8514b7c5", "good_choice"}, -- I am not willing to solve this with blood shed. Good bye. {"@conversation/padawan_the_ring_02:s_36ab201c", "we_will_see"}, -- If you insist on a fight, I won't back down. } } padawan_the_ring_02_convo_template:addScreen(enough_options); we_will_see = ConvoScreen:new { id = "we_will_see", leftDialog = "@conversation/padawan_the_ring_02:s_77a2c8a3", -- We will see about that. stopConversation = "true", options = {} } padawan_the_ring_02_convo_template:addScreen(we_will_see); good_choice = ConvoScreen:new { id = "good_choice", leftDialog = "@conversation/padawan_the_ring_02:s_cd72f93", -- Good choice. stopConversation = "true", options = {} } padawan_the_ring_02_convo_template:addScreen(good_choice); not_quest_owner = ConvoScreen:new { id = "not_quest_owner", leftDialog = "@conversation/padawan_the_ring_02:s_ce804243", -- What? Looking for a fight? Not today, chump, but definitely some other time. stopConversation = "true", options = {} } padawan_the_ring_02_convo_template:addScreen(not_quest_owner); addConversationTemplate("padawan_the_ring_02_convo_template", padawan_the_ring_02_convo_template);
--*********************************************************** --** ROBERT JOHNSON ** --*********************************************************** require "ISUI/ISPanelJoypad" ---@class ISCharacterProtection : ISPanelJoypad ISCharacterProtection = ISPanelJoypad:derive("ISCharacterProtection"); local FONT_HGT_SMALL = getTextManager():getFontHeight(UIFont.Small) local FONT_HGT_MEDIUM = getTextManager():getFontHeight(UIFont.Medium) function ISCharacterProtection:initialise() ISPanelJoypad.initialise(self); self:create(); end function ISCharacterProtection:createChildren() ISPanelJoypad.createChildren(self); self.cacheColor = Color.new( 1.0, 1.0, 1.0, 1.0 ); self.colorScheme = { { val = 0, color = Color.new( 255/255, 0/255, 0/255, 1 ) }, { val = 50, color = Color.new( 255/255, 255/255, 0/255, 1 ) }, { val = 100, color = Color.new( 0/255, 255/255, 0/255, 1 ) }, } local y = 8; self.bpPanelX = 0; self.bpPanelY = y; self.bpAnchorX = 123; self.bpAnchorY = 50; self.bodyPartPanel = ISBodyPartPanel:new(self.char, self.bpPanelX, self.bpPanelY, self, nil); self.bodyPartPanel.maxValue = 100; self.bodyPartPanel.canSelect = false; self.bodyPartPanel:initialise(); --self.bodyPartPanel:setEnableSelectLines( true, self.bpAnchorX, self.bpAnchorY ); --self.bodyPartPanel:enableNodes( "media/ui/BodyParts/bps_node_diamond", "media/ui/BodyParts/bps_node_diamond_outline" ); --self.bodyPartPanel:overrideNodeTexture( BodyPartType.Torso_Upper, "media/ui/BodyParts/bps_node_big", "media/ui/BodyParts/bps_node_big_outline" ); self.bodyPartPanel:setColorScheme(self.colorScheme); self:addChild(self.bodyPartPanel); end function ISCharacterProtection:setVisible(visible) if visible then -- init? end self.javaObject:setVisible(visible); end function ISCharacterProtection:prerender() ISPanelJoypad.prerender(self) end function ISCharacterProtection:render() local labelPart = getText("IGUI_health_Part"); local labelBite = getText("IGUI_health_Bite"); local labelScratch = getText("IGUI_health_Scratch"); local biteWidth = getTextManager():MeasureStringX(UIFont.Small, labelBite); local scratchWidth = getTextManager():MeasureStringX(UIFont.Small, labelScratch); local xOffset = 0; local yOffset = 8; local yText = yOffset; local partX = 150; local biteX = partX + self.maxLabelWidth + 20; local scratchX = biteX + biteWidth + 20; --self:drawTexture(self.bodyOutline, xOffset, yOffset, 1, 1, 1, 1); self:drawText(labelPart, partX, yText, 1, 1, 1, 1, UIFont.Small); self:drawText(labelBite, biteX, yText, 1, 1, 1, 1, UIFont.Small); self:drawText(labelScratch, scratchX, yText, 1, 1, 1, 1, UIFont.Small); yText = yText + FONT_HGT_SMALL + 5; -- draw each part as overlay for i=0, BodyPartType.ToIndex(BodyPartType.MAX) do local string = BodyPartType.ToString(BodyPartType.FromIndex(i)); if self.bparts[string] then local biteDefense = luautils.round(self.char:getBodyPartClothingDefense(i, true, false)); local scratchDefense = luautils.round(self.char:getBodyPartClothingDefense(i, false, false)); biteDefense = math.floor(biteDefense); scratchDefense = math.floor(scratchDefense); -- COMMENT MERGE: --local totalDef = biteDefense + scratchDefense; ---if totalDef > 100 then totalDef = 100; end --local rgb = luautils.getConditionRGB(totalDef); --self:drawTexture(self.textures[BodyPartType.ToString(BodyPartType.FromIndex(i))], xOffset, yOffset, 1, rgb.r, rgb.g, rgb.b); --local color = self.bodyPartPanel:setColorForValue( (biteDefense + scratchDefense), self.cacheColor ); self.bodyPartPanel:setValue( BodyPartType.FromIndex(i), (biteDefense + scratchDefense)); self:drawText(BodyPartType.getDisplayName(BodyPartType.FromIndex(i)), partX, yText, 1, 1, 1, 1, UIFont.Small); --local c = self.bodyPartPanel:setColorForValue( biteDefense , self.cacheColor ); --local r, g, b = c:getRedFloat(), c:getGreenFloat(), c:getBlueFloat(); local r, g, b = self.bodyPartPanel:getRgbForValue( biteDefense ); self:drawText(biteDefense .. "%", biteX, yText, r, g, b, 1, UIFont.Small); --c = self.bodyPartPanel:setColorForValue( scratchDefense , self.cacheColor ); --r, g, b = c:getRedFloat(), c:getGreenFloat(), c:getBlueFloat(); r, g, b = self.bodyPartPanel:getRgbForValue( scratchDefense ); self:drawText(scratchDefense .. "%", scratchX, yText, r, g, b, 1, UIFont.Small); yText = yText + FONT_HGT_SMALL; --[[ local r,g,b = self:getProtectionRGB(biteDefense + (scratchDefense)); self:drawTexture(self.textures[BodyPartType.ToString(BodyPartType.FromIndex(i))], xOffset, yOffset, 1, r, g, b); self:drawText(BodyPartType.getDisplayName(BodyPartType.FromIndex(i)), partX, yText, 1, 1, 1, 1, UIFont.Small); rgb = luautils.getConditionRGB(biteDefense); self:drawText(biteDefense .. "%", biteX, yText, rgb.r, rgb.g, rgb.b, 1, UIFont.Small); rgb = luautils.getConditionRGB(scratchDefense); self:drawText(scratchDefense .. "%", scratchX, yText, rgb.r, rgb.g, rgb.b, 1, UIFont.Small); yText = yText + FONT_HGT_SMALL; --]] end end local width = math.max(self.width, scratchX + scratchWidth + 20); self:setWidthAndParentWidth(width); local height = math.max(self.height, yText + 20); self:setHeightAndParentHeight(height); end --[[ function ISCharacterProtection:getProtectionRGB(totalProtection) if totalProtection == 0 then return 1, 0, 0; end -- print("total protection = ", totalProtection) local r,g,b = 0, 0, 0; if totalProtection > 100 then totalProtection = 100; end if totalProtection < 50 then r = 255; g = 255 * (totalProtection / 100); b = 0; else totalProtection = totalProtection - 50; r = 160 * (1 - (totalProtection / 100)); g = 255; b = 0; end return r / 255, g / 255, b / 255; end --]] function ISCharacterProtection:create() self:initTextures(); self.maxLabelWidth = 0 for i=1,BodyPartType.ToIndex(BodyPartType.MAX) do local string = BodyPartType.ToString(BodyPartType.FromIndex(i - 1)) if self.bparts[string] then local label = BodyPartType.getDisplayName(BodyPartType.FromIndex(i - 1)) local labelWidth = getTextManager():MeasureStringX(UIFont.Small, label) self.maxLabelWidth = math.max(self.maxLabelWidth, labelWidth) end end end function ISCharacterProtection:initTextures() self.bparts = {}; self.bparts["Hand_L"] = true self.bparts["Hand_R"] = true self.bparts["ForeArm_L"] = true self.bparts["ForeArm_R"] = true self.bparts["UpperArm_L"] = true self.bparts["UpperArm_R"] = true self.bparts["Torso_Upper"] = true self.bparts["Torso_Lower"] = true self.bparts["Head"] = true self.bparts["Neck"] = true self.bparts["Groin"] = true self.bparts["UpperLeg_L"] = true self.bparts["UpperLeg_R"] = true self.bparts["LowerLeg_L"] = true self.bparts["LowerLeg_R"] = true self.bparts["Foot_L"] = true self.bparts["Foot_R"] = true --[[ self.textures = {}; self.textures["Hand_L"] = getTexture("media/ui/defense/" .. self.sex .. "_hand_left.png") self.textures["Hand_R"] = getTexture("media/ui/defense/" .. self.sex .. "_hand_right.png") self.textures["ForeArm_L"] = getTexture("media/ui/defense/" .. self.sex .. "_lower_arms_left.png") self.textures["ForeArm_R"] = getTexture("media/ui/defense/" .. self.sex .. "_lower_arms_right.png") self.textures["UpperArm_L"] = getTexture("media/ui/defense/" .. self.sex .. "_upper_arms_left.png") self.textures["UpperArm_R"] = getTexture("media/ui/defense/" .. self.sex .. "_upper_arms_right.png") self.textures["Torso_Upper"] = getTexture("media/ui/defense/" .. self.sex .. "_upper_body.png") self.textures["Torso_Lower"] = getTexture("media/ui/defense/" .. self.sex .. "_lower_body.png") self.textures["Head"] = getTexture("media/ui/defense/" .. self.sex .. "_head.png") self.textures["Neck"] = getTexture("media/ui/defense/" .. self.sex .. "_neck.png") self.textures["Groin"] = getTexture("media/ui/defense/" .. self.sex .. "_groin.png") self.textures["UpperLeg_L"] = getTexture("media/ui/defense/" .. self.sex .. "_upper_legs_left.png") self.textures["UpperLeg_R"] = getTexture("media/ui/defense/" .. self.sex .. "_upper_legs_right.png") self.textures["LowerLeg_L"] = getTexture("media/ui/defense/" .. self.sex .. "_lower_legs_left.png") self.textures["LowerLeg_R"] = getTexture("media/ui/defense/" .. self.sex .. "_lower_legs_right.png") self.textures["Foot_L"] = getTexture("media/ui/defense/" .. self.sex .. "_feet_left.png") self.textures["Foot_R"] = getTexture("media/ui/defense/" .. self.sex .. "_feet_right.png") --]] end function ISCharacterProtection:onJoypadDown(button) if button == Joypad.BButton then getPlayerInfoPanel(self.playerNum):toggleView(xpSystemText.protection) setJoypadFocus(self.playerNum, nil) end if button == Joypad.LBumper then getPlayerInfoPanel(self.playerNum):onJoypadDown(button) end if button == Joypad.RBumper then getPlayerInfoPanel(self.playerNum):onJoypadDown(button) end end function ISCharacterProtection:new(x, y, width, height, playerNum) local o = {}; o = ISPanelJoypad:new(x, y, width, height); o:noBackground(); setmetatable(o, self); self.__index = self; o.playerNum = playerNum o.char = getSpecificPlayer(playerNum); o.bFemale = o.char:isFemale() o.borderColor = {r=0.4, g=0.4, b=0.4, a=1}; o.backgroundColor = {r=0, g=0, b=0, a=0.8}; o.sex = "female"; if not o.char:isFemale() then o.sex = "male"; end o.bodyOutline = getTexture("media/ui/defense/" .. o.sex .. "_base.png") return o; end
local ReplicatedStorage = game:GetService("ReplicatedStorage") local Players = game:GetService("Players") local Modules = ReplicatedStorage.Modules local Rodux = require(Modules.Rodux) -- The Rodux DevTools aren't available yet! Check the README for more details. -- local RoduxVisualizer = require(Modules.RoduxVisualizer) local commonReducers = require(Modules.RDC.commonReducers) local Dictionary = require(Modules.RDC.Dictionary) local Item = require(Modules.RDC.objects.Item) -- These imports are pretty darn verbose. local addPlayer = require(Modules.RDC.actions.addPlayer) local addItemsToPlayerInventory = require(Modules.RDC.actions.addItemsToPlayerInventory) local removeItemFromPlayerInventory = require(Modules.RDC.actions.removeItemFromPlayerInventory) local addItemsToWorld = require(Modules.RDC.actions.addItemsToWorld) local removeItemFromWorld = require(Modules.RDC.actions.removeItemFromWorld) local serverReducers = require(script.Parent.serverReducers) local ServerApi = require(script.Parent.ServerApi) local networkMiddleware = require(script.Parent.networkMiddleware) local getRandomItemName = require(script.Parent.getRandomItemName) return function(context) local reducer = Rodux.combineReducers(Dictionary.join(commonReducers, serverReducers)) local api --[[ This function contains our custom replication logic for Rodux actions. Using the Redux pattern as a way to sychronize replicated data is a new idea. Vocksel introduced the idea to me, and I used this project partly as a test bed to try it out. ]] local function replicate(action, beforeState, afterState) -- Create a version of each action that's explicitly flagged as -- replicated so that clients can handle them explicitly. local replicatedAction = Dictionary.join(action, { replicated = true, }) -- This is an action that everyone should see! if action.replicateBroadcast then return api:storeAction(ServerApi.AllPlayers, replicatedAction) end -- This is an action that we want a specific player to see. if action.replicateTo ~= nil then local player = Players:GetPlayerByUserId(action.replicateTo) if player == nil then return end return api:storeAction(player, replicatedAction) end -- We should probably replicate any actions that modify data shared -- between the client and server. for key in pairs(commonReducers) do if beforeState[key] ~= afterState[key] then return api:storeAction(ServerApi.AllPlayers, replicatedAction) end end return end --[[ For hot-reloading, we want to save a list of every action that gets run through the store. This lets us iterate on our reducers, but otherwise keep any state we want across reloads. ]] local function saveActionsMiddleware(nextDispatch) return function(action) table.insert(context.savedActions, action) return nextDispatch(action) end end -- This is a case where the simplicify of reducers shines! -- We produce the state that this store should start at based on the actions -- that the previous store had executed. local initialState = nil for _, action in ipairs(context.savedActions) do initialState = reducer(initialState, action) end -- local devTools = RoduxVisualizer.createDevTools({ -- mode = RoduxVisualizer.Mode.Plugin, -- }) local middleware = { -- Our minimal middleware to save actions to our context. saveActionsMiddleware, -- Middleware to replicate actions to the client, using the replicate -- callback defined above. networkMiddleware(replicate), -- Rodux has a built-in logger middleware to print to the console -- whenever actions are dispatched to show the store. -- Rodux.loggerMiddleware, -- Once the Rodux DevTools are available, this will be revisited! -- devTools.middleware, } local store = Rodux.Store.new(reducer, initialState, middleware) -- Construct our ServerApi, which creates RemoteEvent objects for our -- clients to listen to. api = ServerApi.create({ clientStart = function(player) store:dispatch(addPlayer(tostring(player.UserId))) -- We need to make sure not to replicate anything secret! local state = store:getState() local commonState = {} for key, value in pairs(state) do if commonReducers[key] ~= nil then commonState[key] = value end end api:initialStoreState(player, commonState) end, pickUpItem = function(player, itemId) local state = store:getState() local item = state.world[itemId] if item == nil then warn("Player can't pick up item " .. itemId) return end store:dispatch(removeItemFromWorld(itemId)) store:dispatch(addItemsToPlayerInventory(tostring(player.UserId), { [itemId] = item, })) end, dropItem = function(player, itemId) local playerId = tostring(player.UserId) local state = store:getState() local inventory = state.playerInventories[playerId] if inventory == nil then warn("Couldn't find player inventory " .. playerId) return end local item = inventory[itemId] if item == nil then warn("Player can't drop item " .. itemId) return end local character = player.Character if character == nil then warn("Can't drop item for player, no character: " .. playerId) return end local root = character:FindFirstChild("HumanoidRootPart") if root == nil then warn("No HumanoidRootPart in character from " .. playerId) return end -- That was an exhausting set of checks, oof. local newPosition = root.Position + root.CFrame.lookVector * 4 local newItem = Dictionary.join(item, { position = newPosition, }) store:dispatch(removeItemFromPlayerInventory(playerId, itemId)) store:dispatch(addItemsToWorld({ [itemId] = newItem, })) end, }) -- The hot-reloading shim has a place for us to stick destructors, since we -- need to clean up everything on the server before unloading. table.insert(context.destructors, function() store:destruct() end) table.insert(context.destructors, function() api:destroy() end) -- If we've hot-reloaded, we don't want to spawn new objects into the world -- since the reloaded state should already have them. if not context.wasReloaded then local worldItems = {} for _ = 1, 15 do local item = Item.new() local x = math.random(-20, 20) local z = math.random(-20, 20) item.position = Vector3.new(x, 1.5, z) item.name = getRandomItemName() worldItems[item.id] = item end store:dispatch(addItemsToWorld(worldItems)) end print("Server started!") end
#!/usr/bin/env tarantool -- Start the console first to allow test-run to attach even before -- box.cfg is finished. require('console').listen(os.getenv('ADMIN')) box.cfg({ listen = os.getenv("LISTEN"), replication = {os.getenv("MASTER"), os.getenv("LISTEN")}, wal_cleanup_delay = 0, })
--[[-------------------------------------------------------------------------- -- -- File: UTActivity.Ui.RevisionCheck.lua -- Copyright (c) Ubisoft Entertainment. All rights reserved. -- -- Project: Ubitoys.Tag -- Date: October 13, 2010 -- ------------------------------------------------------------------------------ -- -- Description: ... -- ----------------------------------------------------------------------------]] --[[ Dependencies ----------------------------------------------------------]] require "UI/UIPage" require "UI/UIMenuPage" require "UI/UIMenuWindow" require "UI/UITitledPanel" require "UI/UIProgress" --[[ Class -----------------------------------------------------------------]] assert(rawget(UTActivity, "Ui")) UTActivity.Ui.RevisionCheck = UTClass(UIMenuPage) -- defaults, -- this is just a fake window displayed on to of the true revision ui UTActivity.Ui.RevisionCheck.transparent = true -- banks UTActivity.Ui.RevisionCheck.banks = { ["DSN1"] = 0x05000, ["DSN2"] = 0x15000, ["DSN3"] = 0x25000, ["DSN4"] = 0x35000, ["DSN5"] = 0x45000, ["DANI"] = 0x02000, } -- __ctor -------------------------------------------------------------------- function UTActivity.Ui.RevisionCheck:__ctor(state) -- animate self.slideBegin = true self.slideEnd = false self.text = "" self.clientRectangle = { 13 + UIMenuWindow.margin.left, 87 + UIMenuWindow.margin.top, 768 - UIMenuWindow.margin.right, 608 - 12 - UIMenuWindow.margin.bottom - 34 } self.clientRectangle[1] = self.clientRectangle[1] + UIWindow.rectangle[1] self.clientRectangle[2] = self.clientRectangle[2] + UIWindow.rectangle[2] self.clientRectangle[3] = self.clientRectangle[3] + UIWindow.rectangle[1] self.clientRectangle[4] = self.clientRectangle[4] + UIWindow.rectangle[2] -- contents, self.uiPanel = self:AddComponent(UIPanel:New(), "uiPanel") self.uiPanel.rectangle = self.clientRectangle self.uiContents = self.uiPanel:AddComponent(UITitledPanel:New(), "uiContents") self.uiContents.rectangle = { 20, 20, 695, 435 } self.uiContents.title = l"oth044" .. " ..." self.uiContents.clientRectangle = {} for i = 1, 4 do self.uiContents.clientRectangle[i] = self.rectangle[i] + self.clientRectangle[i] + self.uiContents.rectangle[i] end --[[ -- progress self.uiProgress = self.uiContents:AddComponent(UIProgress:New(), "uiProgress") self.uiProgress.rectangle = { 20, 20 + 25, 655, 48 + 25 } self.uiGlobalProgress = self.uiContents:AddComponent(UIProgress:New(), "uiProgress") self.uiGlobalProgress.rectangle = { 20, 20 + 25 + 60, 655, 48 + 25 + 60 } self.uiGlobalProgress.color = UIComponent.colors.red --]] -- state assert(state) assert(state.majorRevisionDevices) self.state = state end -- LookupForRevision --------------------------------------------------------- function UTActivity.Ui.RevisionCheck:LookupForRevision(revision) -- lookup most recent revision for the given bank assert(self.target) assert(self.targetBank) local class = quartz.system.bitwise.bitwiseand(self.target.reference[1], 0x0f00fff0) local directory = string.format("game:../system/revision/0x%08x/banks/%s", class, string.lower(self.targetBank)) local wildcard = self.targetBank .. "-" .. (game.locale.locale or "en") .. "??.bin" -- print("LookupForRevision", directory, wildcard) local revisions = quartz.system.filesystem.directory(directory , wildcard) if (revisions) then -- one or many bank files have been found, -- compare current revision with the most recent file table.sort(revisions) local lastRevision = string.lower(string.format("game:../system/revision/0x%08x/banks/%s/%s-%s", class, self.targetBank, self.targetBank, revision)) local bestRevision = string.lower(revisions[#revisions]) -- shorten paths because aliases may have been discarded along the way local f, l = string.find(bestRevision, "banks") local shortBestRevision = string.sub(bestRevision, l + 2) local shortLastRevision = string.lower(string.format("%s/%s-%s.bin", self.targetBank, self.targetBank, revision)) print("^^" .. shortLastRevision .. " # ^^" .. shortBestRevision) if not (shortBestRevision == shortLastRevision) or (REG_FORCEREVISION) then -- push the upload request, -- the flash memory manager shall handle all binary uploads local address = UTActivity.Ui.RevisionCheck.banks[self.targetBank] if (address) then assert(self.flashMemoryManager) self.flashMemoryManager:Upload(self.target, bestRevision, address) print("pushing new request", bestRevision, address) end end end end -- Draw ---------------------------------------------------------------------- function UTActivity.Ui.RevisionCheck:Draw() -- base UIMenuPage.Draw(self) -- contents, quartz.system.drawing.pushcontext() quartz.system.drawing.loadtranslation(unpack(self.uiContents.clientRectangle)) quartz.system.drawing.loadtranslation(0, UITitledPanel.headerSize) -- text local fontJustification = quartz.system.drawing.justification.bottomleft + quartz.system.drawing.justification.wordbreak local rectangle = { 40, 320, 675 - 40, 390 - 20 } quartz.system.drawing.loadcolor3f(unpack(self.fontColor)) quartz.system.drawing.loadcolor3f(unpack(UIComponent.colors.red)) quartz.system.drawing.loadfont(UIComponent.fonts.default) quartz.system.drawing.drawtextjustified(self.text, fontJustification, unpack(rectangle) ) quartz.system.drawing.pop() end -- OnClose ------------------------------------------------------------------- function UTActivity.Ui.RevisionCheck:OnClose() if (engine.libraries.usb.proxy) then engine.libraries.usb.proxy._DispatchMessage:Remove(self, UTActivity.Ui.RevisionCheck.OnDispatchMessage) end end -- OnDispatchMessage --------------------------------------------------------- function UTActivity.Ui.RevisionCheck:OnDispatchMessage(device, addressee, command, arg) if (device == self.target and command == 0x85) then print("data bank revision received:", self.targetBank, unpack(arg)) local revision = string.format("%c%c%c%c", arg[1], arg[2], arg[3], arg[4]) if (self.targetBank) then self:LookupForRevision(revision) end self.targetBank = nil self.message = nil end end -- OnOpen -------------------------------------------------------------------- function UTActivity.Ui.RevisionCheck:OnOpen() assert(engine.libraries.usb) assert(engine.libraries.usb.proxy) assert(engine.libraries.usb.proxy.handle) engine.libraries.usb.proxy._DispatchMessage:Add(self, UTActivity.Ui.RevisionCheck.OnDispatchMessage) self.flashMemoryManager = engine.libraries.usb.proxy.processes.deviceFlashMemoryManager assert(self.flashMemoryManager) -- assert(self.state) assert(self.state.majorRevisionDevices) self.targets = {} for _, device in pairs(self.state.majorRevisionDevices) do table.insert(self.targets, device) end end -- Update -------------------------------------------------------------------- function UTActivity.Ui.RevisionCheck:Update() if (not self.target) then -- pickup the next device, -- for which we shall check all data revisions self.target = table.remove(self.targets) if (not self.target) then -- if all the devices have been checked, -- then pop the current ui and garbage collect the table ... UIMenuManager.stack:Pop() self.state.majorRevisionDevices = nil -- ... and launch the flash updates at last self.flashMemoryManager:Restart() return end print("2222222222") -- configure the new target, -- save all the data banks that must be checked self.targetBanks, self.targetBank = {}, nil for bankName, bankAddress in pairs(UTActivity.Ui.RevisionCheck.banks) do table.insert(self.targetBanks, bankName) end else -- pickup some bank identification from the list of all the data banks to be checked if (not self.targetBank) then self.targetBank = table.remove(self.targetBanks) if (not self.targetBank) then -- when all banks have been checked, -- then we garbage collect the target to move on to the next one self.target = nil -- send a ping message just for the sake of it ? ... quartz.system.usb.sendmessage(engine.libraries.usb.proxy.handle, { 0x00, 0xff, 0x05 }) print("ping **") return end if (self.target.revision and self.target.revisionNumber) then local majorRevision = quartz.system.bitwise.rshift(self.target.revisionNumber, 16) if (0 == majorRevision) then print("data bank revision was force-checked for device " .. tostring(self.target.reference)) self:LookupForRevision(0) self.targetBank = nil return end end -- format the message that is to be sent, -- and reset the timer self.message = { 0x04, self.target.radioProtocolId, 0x85 } for byte = 1, 4 do table.insert(self.message, string.byte(self.targetBank, byte)) end self.timeInterval = 250000 self.time = quartz.system.time.gettimemicroseconds() - self.timeInterval end if (self.message) then -- send the request message, -- every while ... local time = quartz.system.time.gettimemicroseconds() if (self.timeInterval <= time - self.time) then self.time = time quartz.system.usb.sendmessage(engine.libraries.usb.proxy.handle, self.message) end end end end
local ContentProvider = game:GetService("ContentProvider") local CoreGui = game:GetService("CoreGui") local CorePackages = game:GetService("CorePackages") local HttpService = game:GetService("HttpService") local Players = game:GetService("Players") local RobloxReplicatedStorage = game:GetService("RobloxReplicatedStorage") local RunService = game:GetService("RunService") local ScriptContext = game:GetService("ScriptContext") local UserInputService = game:GetService("UserInputService") local RobloxGui = CoreGui:WaitForChild("RobloxGui") local RateLimiter = require(RobloxGui.Modules.ErrorReporting.RateLimiter) local PiiFilter = require(RobloxGui.Modules.ErrorReporting.PiiFilter) local BacktraceReporter = require(CorePackages.ErrorReporters.Backtrace.BacktraceReporter) game:DefineFastFlag("EnableCoreScriptBacktraceReporting", false) game:DefineFastString("CoreScriptBacktraceErrorUploadToken", "") game:DefineFastInt("CoreScriptBacktracePIIFilterEraseTimeoutSeconds", 5 * 60) -- These values control how many times we report the same error in a given period. -- For these defaults, we will report the same message + stack combination 5 times per -- minute, and ignore subsequent occurrences. game:DefineFastFlag("CoreScriptBacktraceRepeatedErrorRateLimiting", true) game:DefineFastInt("CoreScriptBacktraceRepeatedErrorRateLimitCount", 5) game:DefineFastInt("CoreScriptBacktraceRepeatedErrorRateLimitPeriod", 60) -- How long to wait, in tenths of a second, between ticks of the rate limit clock. -- Higher values will improve performance but may cause repeated errors to be ignored -- beyond the settings above. game:DefineFastInt("CoreScriptBacktraceRepeatedErrorRateLimitProcessIntervalTenths", 10) -- We don't have a default for this fast string, so if it's the empty string we -- know we're at the default and we can't do error reports. if game:GetFastFlag("EnableCoreScriptBacktraceReporting") and game:GetFastString("CoreScriptBacktraceErrorUploadToken") ~= "" then local staticAttributes = { LocalVersion = RunService:GetRobloxVersion(), BaseUrl = ContentProvider.BaseUrl, PlaceId = game.PlaceId, Platform = UserInputService:GetPlatform().Name, } local piiFilter = PiiFilter.new({ eraseTimeout = game:GetFastInt("CoreScriptBacktracePIIFilterEraseTimeoutSeconds"), }) local useRateLimiting = game:GetFastFlag("CoreScriptBacktraceRepeatedErrorRateLimiting") local rateLimiter if useRateLimiting then rateLimiter = RateLimiter.new({ period = game:GetFastInt("CoreScriptBacktraceRepeatedErrorRateLimitPeriod"), threshold = game:GetFastInt("CoreScriptBacktraceRepeatedErrorRateLimitCount"), processInterval = game:GetFastInt("CoreScriptBacktraceRepeatedErrorRateLimitProcessIntervalTenths") / 10, }) end local reporter = BacktraceReporter.new({ httpService = HttpService, token = game:GetFastString("CoreScriptBacktraceErrorUploadToken"), processErrorReportMethod = function(report) report:addAttributes(staticAttributes) local playerCount = #Players:GetPlayers() report:addAttributes({ PlayerCount = playerCount, }) return report end, }) local function handleErrorDetailed(message, stack, offendingScript, details) if offendingScript ~= nil and (offendingScript:IsDescendantOf(CoreGui) or offendingScript:IsDescendantOf(CorePackages)) then local cleanedMessage = piiFilter:cleanPii(message) local cleanedStack = piiFilter:cleanPii(stack) if details ~= nil then details = piiFilter:cleanPii(details) end if useRateLimiting then -- Details includes function args, so we don't include them in the error -- signature. They'll still be included in the upload to Backtrace. local signature = cleanedMessage .. cleanedStack if rateLimiter:isRateLimited(signature) then return else rateLimiter:increment(signature) end end reporter:reportErrorDeferred(cleanedMessage, cleanedStack, details) end end ScriptContext.ErrorDetailed:Connect(function(...) local success, message = pcall(handleErrorDetailed, ...) if not success then warn(("CoreScript error reporter failed to handle an error:\n%s"):format(message)) end end) local serverVersionRemote = RobloxReplicatedStorage:WaitForChild("GetServerVersion", math.huge) local serverVersion = serverVersionRemote:InvokeServer() staticAttributes.ServerVersion = serverVersion end
-- Copyright (C) 2014 Chris Emerson <[email protected]> -- See LICENSE for details (MIT license). -- Support for regular expressions (parsed and implemented with LPeg). local M = {} local lpeg = require('lpeg') local P = lpeg.P local R = lpeg.R local S = lpeg.S local C = lpeg.C local V = lpeg.V local B = lpeg.B local Carg = lpeg.Carg local Cb = lpeg.Cb local Cc = lpeg.Cc local Cf = lpeg.Cf local Cp = lpeg.Cp local Cg = lpeg.Cg local Ct = lpeg.Ct local Cmt = lpeg.Cmt -- We use the algorithm to convert from a regular expression to a Peg -- expression from: -- http://www.inf.puc-rio.br/~roberto/docs/ry10-01.pdf local function sub1(x) return x - 1 end -- Parts of a regular expression, returning an LPEG pattern which matches it. local _start = Cg(Cp(), "_start") local _end = Cg(Cp()/sub1, "_end") local mt = { __index = { match = function(t, s, index) local result = t._pat:match(s, index) if result == nil then return result end -- Post-process to put the matches into a nicer form local groups = nil for k,v in pairs(result) do if k:sub(1,1) == "s" then local grpname= k:sub(2) local endpos = result["e"..grpname] if v and endpos then if grpname:match("(%d+)") then grpname = tonumber(grpname) end groups = groups or {} groups[grpname] = {v,endpos} result[k] = nil result["e"..grpname] = nil end end end result.groups = groups return result end, }, } -- Make special character sets local function make_b_s() return { { " \t\v\n\r", [0]="set" }, [0]="charset" } end local function make_b_S() return { { " \t\v\n\r", [0]="set" }, [0]="charset", negate=true} end local function make_b_w() return { [0]="charset", { [0]="range", "a", "z" }, { [0]="range", "A", "Z" }, { [0]="range", "0", "9" }, { [0]="char", "_" }, } end local function make_b_W() return { [0]="charset", { [0]="range", "a", "z" }, { [0]="range", "A", "Z" }, { [0]="range", "0", "9" }, { [0]="char", "_" }, negate=true } end local function make_b_d() return { [0]="charset", { [0]="range", "0", "9" }, } end local function make_b_D() return { [0]="charset", { [0]="range", "0", "9" }, negate=true, } end local function make_charset(c) return function() return { [0]="charset", { [0]="char", c } } end end local function make_char(c) return function() return { [0]="char", c } end end local special = S"()\\?*+|.^$" local any = P"." * Cc({[0] = "."}) -- Perl-style character classes local b_s = P"\\s" / make_b_s local b_S = P"\\S" / make_b_S local b_w = P"\\w" / make_b_w local b_W = P"\\W" / make_b_W local b_d = P"\\d" / make_b_d local b_D = P"\\D" / make_b_D local b_t = P"\\t" / make_charset('\t') local b_n = P"\\n" / make_charset('\n') local b_r = P"\\r" / make_charset('\r') local b_f = P"\\f" / make_charset('\f') local b_e = P"\\e" / make_charset('\x1b') local b_a = P"\\a" / make_charset('\x07') local backcharset = b_s + b_S + b_w + b_W + b_d + b_D + b_t + b_n + b_r + b_f + b_e + b_a local charset_special = S"]-" local charset_escapes = (b_t + b_n + b_r + b_f + b_e + b_a) / function(c) return c[1] end local charset_char = C(P(1) - charset_special) / function(c) return { [0] = "char", c } end local range = (C(P(1) - charset_special) * P"-" * C(P(1) - charset_special)) / function(a,b) return { [0]="range", a, b } end local charset = (P"[" * Ct((Cg(P"^"*Cc(true), "negate") + P(0)) * (range + charset_escapes + charset_char)^0) * P"]") / function(x) x[0] = "charset" return x end local char = C(P(1) - special) / function(c) return { [0] = "char", c } end local escapechar = (P"\\" * C(special)) / function(c) return { [0] = "char", c } end local backref = (P"\\" * C(R"19")) / function(c) return { tonumber(c), [0] = "backref" } end local wordchar = R("AZ", "az", "09") + S("_") local nonwordchar = 1 - wordchar -- word boundaries local word_start = P"\\<" * Cc({[0] = "\\<"}) local word_end = P"\\>" * Cc({[0] = "\\>"}) -- {n} etc. Returns two captures - (min, max); max can be nil (no max) local count_exact = (P"{" * C(R"09" ^ 1) * P"}") / function(c) return tonumber(c), tonumber(c) end local count_minmax = (P"{" * C(R"09" ^ 1) * P"," * C(R"09" ^ 1) * P"}") / function(min,max) return tonumber(min), tonumber(max) end local count_min = (P"{" * C(R"09" ^ 1) * P",}") / function(c) return tonumber(c), nil end local brace_count = count_exact + count_minmax + count_min -- Grouping local newgrp = (Cb("groups") * Cp()) / function(groups, pos) local grp = #groups+1 groups[grp] = {pos} groups.open[#groups.open+1] = grp end -- endgrp leaves the group number or name as a capture local endgrp = (Cb("groups") * Cp()) / function(groups, pos) local grp = groups.open[#groups.open] groups.open[#groups.open] = nil groups[grp][2] = pos return grp end local bra = P"(" * newgrp local ket = P")" * endgrp local anonbra = P"(?:" local anonket = P")" local pattern = P{ "pattern", -- A complete pattern, starting from an empty pattern. pattern = Cg(Carg(1),"groups") * Ct((P"^"*Cg(Cc(1),"anchorstart") + P(0)) * V"subpat" * (P"$"*(-P(1))*Cg(Cc(1),"anchorend") + (-P(1)))) / function(t) t[0] = "pattern" ; return t end, -- A set of alternate branches subpat = (V"branch" * (P"|" * V"branch") ^ 0) / function(...) return { [0] = "alt", ... } end, branch = V"concat", -- A set of concatenated pieces -- Pass a dummy capture to avoid the special case of no captures confusing -- the function. concat = Cc(nil) * (V"piece" ^ 0) / function(_, ...) return { [0] = "concat", ... } end, piece = V"atom_multi", atom_multi = V"atom_plus" + V"atom_star" + V"atom_query" + V"atom_count" + V"atom", atom_plus = (V"atom" * P"+") / function(atom) return { [0] = "+", atom } end, atom_star = (V"atom" * P"*") / function(atom) return { [0] = "*", atom } end, atom_query = (V"atom" * P"?") / function(atom) return { [0] = "?", atom } end, atom_count = (V"atom" * brace_count) / function(atom, min, max) return { [0] = "{}", min=min, max=max, atom } end, anongroup = (anonbra * V"subpat" * anonket), group = (bra * V"subpat" * ket) / function(subpat, grpname) return { [0] = "group", subpat, grpname } end, atom = any + word_start + word_end + escapechar + charset + V"anongroup" + V"group" + char + backref + backcharset, } local function foldr(f, t, init) local res = init local start = #t if res == nil then res = t[start] start = start - 1 end for i=start,1,-1 do res = f(t[i], res) end return res end local function map(f, t) local result = {} for i=1,#t do result[i] = f(t[i]) end return result end local function add(a,b) return a+b end -- Convert a charset fragment to a PEG local function charset_to_peg(charfrag) local t = charfrag[0] if t == "char" then assert(#charfrag == 1) return P(charfrag[1]) elseif t == "range" then assert(#charfrag == 2) return R(charfrag[1] .. charfrag[2]) elseif t == "set" then return S(charfrag[1]) else error("Got charset bit: "..tostring(t).."/"..tostring(t and t[0])) end end local function re_to_peg(retab, k, patternProps) local t = retab[0] if t == "pattern" then assert(#retab == 1) local pat = re_to_peg(retab[1], k, patternProps) -- If the pattern is anchored at the end, make it fail to match -- if there's another byte. This must be done *before* wrapping -- with the start/end markers, as once they've matched it's too late -- to match the next item. if retab.anchorend then -- Disallow matching anything afterwards. pat = pat * (-P(1)) end -- Add match start/end markers pat = _start * pat * _end if not retab.anchorstart then -- Match the pattern, or a character and try again. pat = P{pat + 1*V(1)} end return pat elseif t == "group" then assert(#retab == 2) -- print(debug.traceback()) patternProps.numGroups = patternProps.numGroups + 1 local grpname = tostring(retab[2]) local newk = Cg(Cp()/sub1, "e"..grpname) * k local pat = re_to_peg(retab[1], newk, patternProps) pat = Cg(Cp(), "s"..grpname) * pat return pat elseif t == "alt" then if #retab == 1 then return re_to_peg(retab[1], k, patternProps) else local parts = map(function(x) return re_to_peg(x, k, patternProps) end, retab) return foldr(add, parts) end elseif t == "concat" then return foldr(function(retab_f, k_f) return re_to_peg(retab_f, k_f, patternProps) end, retab, k) elseif t == "char" then assert(#retab == 1) return P(retab[1]) * k elseif t == "charset" then local charset_pat = foldr(add, map(charset_to_peg, retab)) if retab.negate then charset_pat = 1 - charset_pat end return charset_pat * k elseif t == "*" then return P{"A", A=re_to_peg(retab[1], V"A", patternProps) + k} elseif t == "+" then return re_to_peg(retab[1], P{"A", A=re_to_peg(retab[1], V"A", patternProps) + k}, patternProps) elseif t == "." then assert(#retab == 0) return (P(1) - P"\n") * k elseif t == "?" then assert(#retab == 1) return re_to_peg(retab[1], k, patternProps) + k elseif t == "{}" then assert(#retab == 1) -- Rewrite this in terms of ? and *. -- X{3,} => XXXX* -- X{3,5} => XXXX?X? local subpat = retab[1] local min = retab.min local max = retab.max local rewritten = { [0] = "concat" } for i=1,min do rewritten[#rewritten+1] = subpat end if max == nil then rewritten[#rewritten+1] = { [0] = "*", subpat } else local optional = { [0] = "?", subpat } for i=min+1,max do rewritten[#rewritten+1] = optional end end return re_to_peg(rewritten, k, patternProps) elseif t == "\\<" then assert(#retab == 0) return -B(wordchar) * #wordchar * k elseif t == "\\>" then assert(#retab == 0) return B(wordchar) * (-#wordchar) * k elseif t == "backref" then local grpname = retab[1] return Cmt(P(0) * Cb("s"..grpname) * Cb("e"..grpname), function(subject, pos, s, e) local backval = subject:sub(s, e) local here = subject:sub(pos, pos+e-s) if backval == here then return pos+e-s+1 else return false end end) else error("Not implemented op: " ..tostring(t) .. "/" .. tostring(retab)) end end function M.parse(re) return pattern:match(re, 1, {open={}}) end function M.compile(re) -- Since the RE->Peg construction starts backwards (using the -- continuation), it's more convenient to parse the regular expression -- backwards. local retab = M.parse(re) if retab == nil then error("Failed to parse regular expression: {"..re.."}", 2) end local patternProps = { numGroups = 0 } local _pat = re_to_peg(retab, P(0), patternProps) return setmetatable({ _pat = Ct(_pat), numgroups = patternProps.numGroups }, mt) end -- Increase match complexity lpeg.setmaxstack(1000) return M
function love.conf(t) t.author = "Maurice" t.identity = "mari0" t.console = true t.window = nil t.modules.physics = true t.version = "11.1" t.screen = false end