repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
Samanstar/Learn
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
rigeirani/tele
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
kuoruan/lede-luci
protocols/luci-proto-ipv6/luasrc/model/cbi/admin_network/proto_map.lua
32
2615
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Copyright 2013 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local peeraddr, ip6addr local tunlink, defaultroute, metric, ttl, mtu maptype = section:taboption("general", ListValue, "type", translate("Type")) maptype:value("map-e", "MAP-E") maptype:value("map-t", "MAP-T") maptype:value("lw4o6", "LW4over6") peeraddr = section:taboption("general", Value, "peeraddr", translate("BR / DMR / AFTR")) peeraddr.rmempty = false peeraddr.datatype = "ip6addr" ipaddr = section:taboption("general", Value, "ipaddr", translate("IPv4 prefix")) ipaddr.datatype = "ip4addr" ip4prefixlen = s:taboption("general", Value, "ip4prefixlen", translate("IPv4 prefix length"), translate("The length of the IPv4 prefix in bits, the remainder is used in the IPv6 addresses.")) ip4prefixlen.placeholder = "32" ip4prefixlen.datatype = "range(0,32)" ip6addr = s:taboption("general", Value, "ip6prefix", translate("IPv6 prefix"), translate("The IPv6 prefix assigned to the provider, usually ends with <code>::</code>")) ip6addr.rmempty = false ip6addr.datatype = "ip6addr" ip6prefixlen = s:taboption("general", Value, "ip6prefixlen", translate("IPv6 prefix length"), translate("The length of the IPv6 prefix in bits")) ip6prefixlen.placeholder = "16" ip6prefixlen.datatype = "range(0,64)" s:taboption("general", Value, "ealen", translate("EA-bits length")).datatype = "range(0,48)" s:taboption("general", Value, "psidlen", translate("PSID-bits length")).datatype = "range(0,16)" s:taboption("general", Value, "offset", translate("PSID offset")).datatype = "range(0,16)" tunlink = section:taboption("advanced", DynamicList, "tunlink", translate("Tunnel Link")) tunlink.template = "cbi/network_netlist" tunlink.nocreate = true defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(9200)"
apache-2.0
RicherMans/audiodataload
tests/testhtkdataloader.lua
1
6126
require 'torch' require 'nn' require 'xlua' -- Add to cpath local info = debug.getinfo(1,'S') local script_path=info.source:sub(2):gsub("testhtkdataloader",'?') package.path = package.path .. ";".. script_path .. ";../".. script_path.. ";../../" ..script_path local modeltester = torch.TestSuite() -- Inits the dataloaders local audioload = paths.dofile('../init.lua') local profi = require 'ProFi' local tester = torch.Tester() local filelist = arg[1] function modeltester:init() local filepath = filelist local dataloader = audioload.HtkDataloader(filepath) end function modeltester:testnonrandomizedsamples() local filepath = filelist local dataloader = audioload.HtkDataloader(filepath) local classsizes= torch.Tensor(dataloader:nClasses()):zero() local batchsize = 128 for s,e,k,v in dataloader:sampleiterator(batchsize) do local addone = torch.Tensor(v:size(1)):fill(1) classsizes:indexAdd(1,v:long(),addone) end tester:assert(classsizes:sum()==dataloader:size()) for i=1,3 do local tmpclasssizes = torch.Tensor(dataloader:nClasses()):zero() for s,e,k,v in dataloader:sampleiterator(batchsize) do local addone = torch.Tensor(v:size(1)):fill(1) tmpclasssizes:indexAdd(1,v:long(),addone) end tester:eq(tmpclasssizes,classsizes) end end -- function modeltester:testrandomize() local filepath = filelist local dataloader = audioload.HtkDataloader{path=filepath} -- run the size estimation local _ = dataloader:sampleiterator() local tic = torch.tic() local labcount = torch.zeros(dataloader:nClasses()):zero() local dataset = torch.Tensor(dataloader:size(),dataloader:dim()) local targets = torch.LongTensor(dataloader:size(),1) local bs = 128 for s,e,inp,lab in dataloader:sampleiterator(bs,nil) do local addone = torch.Tensor(lab:size(1)):fill(1) labcount:indexAdd(1,lab:long(),addone) local bsize = inp:size(1) dataset[{{s-bsize+1,s}}]:copy(inp) targets[{{s-bsize+1,s}}]:copy(lab) tester:assert(inp:size(1) == lab:size(1)) end tester:assert(labcount:sum() == dataloader:size()) -- Emulate some 3 iterations over the data for i=1,3 do local tmplabcount = torch.zeros(dataloader:nClasses()) local notrandomized = 0 local tmptargets = torch.Tensor(dataloader:size()):zero() local testunique = torch.Tensor(dataloader:size()):zero() dataloader:shuffle() for s,e,inp,lab in dataloader:sampleiterator(bs,nil) do local bsize = inp:size(1) for j=1,dataset:size(1) do local origtarget = targets[j][1] for k=1,inp:size(1) do if dataset[j]:equal(inp[k]) then local targetid = s-bsize + k testunique[targetid] = testunique[targetid]+ 1 tmptargets[j] = targetid tester:assert(lab[k] ==origtarget) break end end end local addone = torch.Tensor(lab:size(1)):fill(1) tmplabcount:indexAdd(1,lab:long(),addone) if dataset[{{s-bsize+1,s}}]:equal(inp) then notrandomized = notrandomized + 1 end tester:assert(inp:size(1) == lab:size(1)) end local sorted,_ = tmptargets:sort() tester:assert(notrandomized == 0,"Randomization factor is a bit small ("..notrandomized..")") tester:eq(testunique,torch.ones(dataloader:size())) tester:eq(tmplabcount,labcount,"Labels are not the same in iteration "..i) end end function modeltester:testsize() local dataloader = audioload.HtkDataloader{path=filelist} -- Simulate 3 iterations over the dataset for i=1,3 do local numsamples = 0 dataloader:shuffle() for s,e,i in dataloader:sampleiterator(2048,nil) do numsamples = numsamples + i:size(1) collectgarbage() end local size = dataloader:size() tester:assert(size == numsamples) end end function modeltester:benchmark() local timer = torch.Timer() local dataloader = audioload.HtkDataloader{path=filelist} local bsizes = {64,128,256} local time = 0 profi:start() for s,e,inp,lab in dataloader:uttiterator() do end profi:stop() profi:writeReport("Report_htkuttiter.txt") print(" ") for k,bs in pairs(bsizes) do for i=1,3 do dataloader:shuffle() collectgarbage() tic = torch.tic() for s,e,inp,lab in dataloader:sampleiterator(bs) do print(string.format("Sample [%i/%i]: Time for dataloading %.4f",s,e,timer:time().real)) timer:reset() end time = time + torch.toc(tic) end print("HTKdata: Bsize",bs,"time:",time) end end function modeltester:testloadAudioSample() local dataloader = audioload.HtkDataloader(filelist) local f=assert(io.open(filelist)) local firstline = f:read() local feat = firstline:split(" ")[1] -- print(dataloader:loadAudioSample(feat,39,40)) -- dataloader:loadAudioSample end function modeltester:testusize() local dataloader = audioload.HtkDataloader{path=filelist} local size = dataloader:usize() -- Simulate 3 iterations over the dataset for i=1,3 do local numutts = 0 for _ in dataloader:uttiterator() do numutts = numutts + 1 end tester:assert(size == numutts) end end function modeltester:testdifferentbatchsize() local batches = {1,32,64,128,256,512,1024} local dataloader = audioload.HtkDataloader{path=filelist} -- Just test if any error happen for i=1,#batches do for s,e,k,v in dataloader:sampleiterator(batches[i],nil)do end end end if not filelist or filelist == "" then print("Please pass a filelist as first argument") return end tester:add(modeltester) tester:run()
mit
LinuxTeam98/Linux_TG
plugins/rae.lua
616
1312
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/class/generator/actor/ValleyMoon.lua
1
3021
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" local Map = require "engine.Map" local DamageType = require "engine.DamageType" require "engine.Generator" module(..., package.seeall, class.inherit(engine.Generator)) function _M:init(zone, map, level, spots) engine.Generator.init(self, zone, map, level, spots) self.data = level.data.generator.actor self.level = level self.rate = self.data.rate self.max_rate = 5 self.turn_scale = game.energy_per_tick / game.energy_to_act if not _M.limmir then for i, e in pairs(level.entities) do if e.define_as and e.define_as == "LIMMIR" then _M.limmir = e break end end end end function _M:tick() local val = rng.float(0,1) for i = 1,self.max_rate - 1 do if val < rng.poissonProcess(i, self.turn_scale, self.rate) then self:generateOne() else break end end -- Fire a light AOE, healing allies damaging demons if _M.limmir and not _M.limmir.dead and game.turn % 100 == 0 then game.logSeen(_M.limmir, "Limmir summons a blast of holy light!") local rad = 2 local dam = 50 + (800 - self.level.turn_counter / 10) / 7 local grids = _M.limmir:project({type="ball", radius=rad, selffire=false}, _M.limmir.x, _M.limmir.y, DamageType.HOLY_LIGHT, dam) game.level.map:particleEmitter(_M.limmir.x, _M.limmir.y, rad, "sunburst", {radius=rad, grids=grids, tx=_M.limmir.x, ty=_M.limmir.y}) end end function _M:generateOne() local m if not self.level.balroged and self.level.turn_counter < 100 * 10 then m = self.zone:makeEntityByName(self.level, "actor", "CORRUPTED_DAELACH") self.level.balroged = true else m = self.zone:makeEntity(self.level, "actor", {type="demon"}, nil, true) end if m then local spot = self.level:pickSpot{type="portal", subtype="demon"} local x = spot.x local y = spot.y local tries = 0 while (not m:canMove(x, y)) and tries < 10 do spot = self.level:pickSpot{type="portal", subtype="demon"} x = spot.x y = spot.y tries = tries + 1 end if tries < 10 then if _M.limmir and not _M.limmir.dead then m:setTarget(_M.limmir) else m:setTarget(game.player) end if not m.unique then m.ai_state = m.ai_state or {} m.ai_state.ai_move = "move_dmap" end self.zone:addEntity(self.level, m, "actor", x, y) end end end
gpl-3.0
tdelc/EmptyEpsilon
scripts/tutorial_04_engineering.lua
2
10398
-- Name: Engineering -- Description: [Station Tutorial] --- ------------------- --- -Goes over controlling the power of each station and repairs. --- --- [Station Info] --- ------------------- ---Power Management: --- -The Engineering officer can route power to systems by selecting a system and moving its power slider. Giving a system more power increases its output. For instance, an overpowered reactor produces more energy, overpowered shields reduce more damage and regenerate faster, and overpowered impulse engines increase its maximum speed. Overpowering a system (above 100%) also increases its heat generation and, except for the reactor, its energy draw. Underpowering a system (below 100%) likewise reduces heat output and energy draw. --- ---Coolant Management: --- -By adding coolant to a system, the Engineering officer can reduce its temperature and prevent the system from damaging the ship. The ship has an unlimited reseve of coolant, but a finite amount of coolant can be applied at any given time, so the Engineering officer must budget how much coolant each system can receive. A system's change in temperature is indicated by white arrows in the temperature column. The brighter an arrow is, the larger the trend. --- ---Repairs: --- -When systems are damaged by being shot, colliding with space hazards, or overheating, the Engineering officer can dispatch repair crews to the system for repairs. Each systems has a damage state between -100% to 100%. Systems below 100% function suboptimally, in much the same way as if they are underpowered. Once a system is at or below 0%, it completely stops functioning until it is repaired. Systems can be repaired by sending a repair crew to the room containing the system. Hull damage affects the entire ship, and docking at a station can repair it, but hull repairs progress very slowly. -- Type: Basic require("utils.lua") function init() --Create the player ship player = PlayerSpaceship():setFaction("Human Navy"):setTemplate("Phobos M3P") tutorial:setPlayerShip(player) tutorial:showMessage([[Welcome to the EmptyEpsilon tutorial. Note that this tutorial is designed to give you a quick overview of the basic options for the game, but does not cover every single aspect. Press next to continue...]], true) tutorial_list = { engineeringTutorial } tutorial:onNext(function() tutorial_list_index = 1 startSequence(tutorial_list[tutorial_list_index]) end) end -- TODO: Need to refactor this region into a utility (*Need help LUA hates me) --[[ Assist function in creating tutorial sequences --]] function startSequence(sequence) current_sequence = sequence current_index = 1 runNextSequenceStep() end function runNextSequenceStep() local data = current_sequence[current_index] current_index = current_index + 1 if data == nil then tutorial_list_index = tutorial_list_index + 1 if tutorial_list[tutorial_list_index] ~= nil then startSequence(tutorial_list[tutorial_list_index]) else tutorial:finish() end elseif data["message"] ~= nil then tutorial:showMessage(data["message"], data["finish_check_function"] == nil) if data["finish_check_function"] == nil then update = nil tutorial:onNext(runNextSequenceStep) else update = function(delta) if data["finish_check_function"]() then runNextSequenceStep() end end tutorial:onNext(nil) end elseif data["run_function"] ~= nil then local has_next_step = current_index <= #current_sequence data["run_function"]() if has_next_step then runNextSequenceStep() end end end function createSequence() return {} end function addToSequence(sequence, data, data2) if type(data) == "string" then if data2 == nil then table.insert(sequence, {message = data}) else table.insert(sequence, {message = data, finish_check_function = data2}) end elseif type(data) == "function" then table.insert(sequence, {run_function = data}) end end function resetPlayerShip() player:setJumpDrive(false) player:setWarpDrive(false) player:setImpulseMaxSpeed(1) player:setRotationMaxSpeed(1) for _, system in ipairs({"reactor", "beamweapons", "missilesystem", "maneuver", "impulse", "warp", "jumpdrive", "frontshield", "rearshield"}) do player:setSystemHealth(system, 1.0) player:setSystemHeat(system, 0.0) player:setSystemPower(system, 1.0) player:commandSetSystemPowerRequest(system, 1.0) player:setSystemCoolant(system, 0.0) player:commandSetSystemCoolantRequest(system, 0.0) end player:setPosition(0, 0) player:setRotation(0) player:commandImpulse(0) player:commandWarp(0) player:commandTargetRotation(0) player:commandSetShields(false) player:setWeaponStorageMax("homing", 0) player:setWeaponStorageMax("nuke", 0) player:setWeaponStorageMax("mine", 0) player:setWeaponStorageMax("emp", 0) player:setWeaponStorageMax("hvli", 0) end --End Region Tut Utils engineeringTutorial = createSequence() addToSequence(engineeringTutorial, function() tutorial:switchViewToScreen(2) tutorial:setMessageToTopPosition() resetPlayerShip() end) addToSequence(engineeringTutorial, [[Welcome to engineering. Engineering is split into two parts. The top part shows your ship's interior, including damage control teams stationed throughout. The bottom part controls power and coolant levels of your ship's systems.]]) addToSequence(engineeringTutorial, function() player:setWarpDrive(true) end) addToSequence(engineeringTutorial, function() player:setSystemHeat("warp", 0.8) end) addToSequence(engineeringTutorial, [[First, we will explain your control over your ship's systems. Each row on the bottom area of the screen represents one of your ship's system, and each system has a damage level, heat level, power level, and coolant level. I've overheated your warp system. An overheating system can damage your ship. You can prevent this by putting coolant in your warp system. Select the warp system and increase the coolant slider.]], function() return player:getSystemHeat("warp") < 0.05 end) addToSequence(engineeringTutorial, function() player:setSystemHeat("impulse", 0.8) end) addToSequence(engineeringTutorial, [[I've also overheated the impulse system. As before, increase the system's coolant level to mitigate the effect. Note that the warp system's coolant level is automatically reduced to allow for coolant in the impulse system. This is because you have a limited amount of coolant available to distribute this across your ship's systems.]], function() return player:getSystemHeat("impulse") < 0.05 end) addToSequence(engineeringTutorial, [[Good! Next up: power levels. You can manage each system's power level independently. Adding power to a system makes it perform more effectively, but also generates more heat, and thus requires coolant to prevent it from overheating and damaging the system. Maximize the power to the front shield system.]], function() return player:getSystemPower("frontshield") > 2.5 end) addToSequence(engineeringTutorial, [[The added power increases the amount of heat in the system. Overpower the system until it overheats.]], function() return player:getSystemHealth("frontshield") < 0.5 end) addToSequence(engineeringTutorial, function() player:setSystemPower("frontshield", 0.0) end) addToSequence(engineeringTutorial, function() player:commandSetSystemPowerRequest("frontshield", 0.0) end) addToSequence(engineeringTutorial, [[Note that as the system overheats, it takes damage. Because the system is damaged, it functions less effectively. Systems can also take damage when your ship is hit while the shields are down.]]) addToSequence(engineeringTutorial, function() tutorial:setMessageToBottomPosition() end) addToSequence(engineeringTutorial, [[In this top area, you see your damage control teams in your ship.]]) addToSequence(engineeringTutorial, [[The front shield system is damaged, as indicated by the color of this room's outline. Select a damage control team from elsewhere on the ship by pressing it, then press on that room to initiate repairs. (Repairs will take a while.)]], function() player:commandSetSystemPowerRequest("frontshield", 0.0) return player:getSystemHealth("frontshield") > 0.9 end) addToSequence(engineeringTutorial, function() tutorial:setMessageToTopPosition() end) addToSequence(engineeringTutorial, [[Good. Now you know your most important tasks. Next, we'll go over each system's function in detail. Remember, each system performs better with more power, but performs less well when damaged. Your job is to keep vital systems running as well as you can.]]) addToSequence(engineeringTutorial, [[Reactor: The reactor generates energy. Adding power to the reactor increases your energy generation rate.]]) addToSequence(engineeringTutorial, [[Beam Weapons: Adding power to the beam weapons system increases their rate of fire, which causes them to do more damage. Note that every beam you fire adds additional heat to the system.]]) addToSequence(engineeringTutorial, [[Missile System: Increased missile system power lowers the reload time of weapon tubes.]]) addToSequence(engineeringTutorial, [[Maneuvering: Increasing power to the maneuvering system allows the ship to turn faster. It also increases the recharge rate for the combat maneuvering system.]]) addToSequence(engineeringTutorial, [[Impulse Engines: Adding power to the impulse engines increases your impulse flight speed.]]) addToSequence(engineeringTutorial, [[Warp Drive: Adding power to the warp drive increases your warp drive flight speed.]]) addToSequence(engineeringTutorial, [[Jump Drive: A higher-powered jump drive recharges faster and has a shorter delay before jumping.]]) addToSequence(engineeringTutorial, [[Shields: Additional power in the shield system increases their rate of recharge, and decreases the amount of degradation your shields sustain when damaged.]]) addToSequence(engineeringTutorial, [[This concludes the overview of the engineering station. Be sure to keep your ship running in top condition!]])
gpl-2.0
rdmenezes/oolua
helper4.lua
8
3165
--sets options for the different os's function configure_for_os() configuration { "windows" } defines{ "PLATFORM_CHECKED", "WINDOWS_BUILD" } configuration { "vs*" } defines{ "WIN32" } flags { "No64BitChecks"} configuration{"vs*","Debug"} buildoptions {"/Gm","/Zi"} --[[ configuration { "vs2008" } buildoptions {"/analyze"} configuration { "vs2010" } buildoptions {"/analyze"} --]] configuration { "windows","codeblocks" } buildoptions{ "-W -Wall -pedantic"} configuration { "macosx" } defines{ "PLATFORM_CHECKED" , "MAC_BUILD" } configuration { "linux" } defines{ "PLATFORM_CHECKED" , "UNIX_BUILD" } configuration { "codeblocks", "linux or macosx" } buildoptions { "-W -Wall -ansi -pedantic -std=c++98" } configuration("xcode3 or xcode4 or gmake") buildoptions { "-W -Wall -ansi -pedantic -std=c++98" } --[[ if os.getenv('LUAJIT_32BIT') then configuration('*') platforms{"x32"} end --]] end function create_package(name,path_to_root,prj_kind) local root = path_to_root or "./" local proj = project(name) project (name) language 'C++' kind( prj_kind or 'SharedLib') includepaths = { root.."include" } objdir(root.. "obj/") configuration("Debug") defines { "DEBUG", "_DEBUG" } flags {"Symbols", "ExtraWarnings"} targetdir(root.. "bin/Debug") configuration("Release") defines{ "NDEBUG", "RELEASE"} flags {"Optimize", "ExtraWarnings"} targetdir(root.. "bin/Release") configuration { 'Debug','StaticLib or SharedLib' } targetsuffix '_d' configure_for_os() end unit_test_config = function() configuration { "vs*"} postbuildcommands { "\"$(TargetPath)\"" } links{"lua51"} configuration { "vs*","Debug"} links{ "cppunitd" , "gmockd" } configuration { "vs*","Release"} links{ "cppunit" , "gmock" } buildoptions {"/MP"} configuration {"codeblocks" } postbuildcommands { "$(TARGET_OUTPUT_FILE)"} configuration {"gmake or codeblocks","linux or macosx" } libdirs {"usr/local/lib","usr/lib"} links{ "cppunit", "lua" } linkoptions{"`gmock-config --cxxflags --ldflags --libs`"} configuration {"xcode3 or xcode4" } libdirs {"usr/local/lib","usr/lib"} links{ "gmock","gtest","cppunit", "lua" } postbuildcommands {"$TARGET_BUILD_DIR/$TARGET_NAME"} --64bit LuaJIT rebasing if os.getenv('LUAJIT_REBASE') then configuration{'xcode*'} linkoptions{'-pagezero_size 10000 -image_base 100000000'} --this is required to stop a test which should call lua_atpanic and instead --makes it a nop, as LuaJIT will throw an exception on OSX x86_64 defines{"LUAJIT_VERSION_NUM=20000"} end --[[ if os.getenv('LUAJIT_32BIT') then configuration{'xcode*'} platforms{"x32"} end --]] configuration {"windows","codeblocks","Debug" } links{ "lua", "cppunitd" , "gmockd" } configuration {"windows","codeblocks","Release" } links{ "lua", "cppunit" , "gmock" } configuration {"gmake"} postbuildcommands { "$(TARGET)" } configuration {"linux" } links{ "dl" } end coverage = function() configuration{"xcode3 or xcode4 or gmake"} links{ "gcov" } buildoptions {"-fprofile-arcs -ftest-coverage"} end
mit
Blackdutchie/Zero-K
LuaUI/Widgets/unit_gadget_icons.lua
6
4380
------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Gadget Icons", desc = "Shows icons from gadgets that cannot access the widget stuff by themselves.", author = "CarRepairer and GoogleFrog", date = "2012-01-28", license = "GNU GPL, v2 or later", layer = 5, enabled = true, } end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local echo = Spring.Echo local min = math.min local floor = math.floor ---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- local myAllyTeamID = 666 local powerTexture = 'Luaui/Images/visible_energy.png' local facplopTexture = 'Luaui/Images/factory.png' local rearmTexture = 'LuaUI/Images/noammo.png' local retreatTexture = 'LuaUI/Images/unit_retreat.png' local lastLowPower = {} local lastFacPlop = {} local lastRearm = {} local lastRetreat = {} ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function SetIcons(unitID) for _,unitID in ipairs(Spring.GetAllUnits()) do local lowpower = Spring.GetUnitRulesParam(unitID, "lowpower") if lowpower then local _,_,inbuild = Spring.GetUnitIsStunned(unitID) if inbuild then lowpower = 0 -- Draw as if not on low power end if (not lastLowPower[unitID]) or lastLowPower[unitID] ~= lowpower then lastLowPower[unitID] = lowpower if lowpower ~= 0 then WG.icons.SetUnitIcon( unitID, {name='lowpower', texture=powerTexture} ) else WG.icons.SetUnitIcon( unitID, {name='lowpower', texture=nil} ) end end end local facplop = Spring.GetUnitRulesParam(unitID, "facplop") if facplop or lastFacPlop[unitID] == 1 then if not facplop then facplop = 0 end if (not lastFacPlop[unitID]) or lastFacPlop[unitID] ~= facplop then lastFacPlop[unitID] = facplop if facplop ~= 0 then WG.icons.SetUnitIcon( unitID, {name='facplop', texture=facplopTexture} ) WG.icons.SetPulse( 'facplop', true ) else WG.icons.SetUnitIcon( unitID, {name='facplop', texture=nil} ) end end end local rearm = Spring.GetUnitRulesParam(unitID, "noammo") if rearm then if (not lastRearm[unitID]) or lastRearm[unitID] ~= rearm then lastRearm[unitID] = rearm if rearm == 1 or rearm == 2 then WG.icons.SetUnitIcon( unitID, {name='rearm', texture=rearmTexture} ) elseif rearm == 3 then WG.icons.SetUnitIcon( unitID, {name='rearm', texture=repairTexture} ) else WG.icons.SetUnitIcon( unitID, {name='rearm', texture=nil} ) end end end local retreat = Spring.GetUnitRulesParam(unitID, "retreat") if retreat then if (not lastRetreat[unitID]) or lastRetreat[unitID] ~= retreat then lastRetreat[unitID] = retreat if retreat ~= 0 then WG.icons.SetUnitIcon( unitID, {name='retreat', texture=retreatTexture} ) else WG.icons.SetUnitIcon( unitID, {name='retreat', texture=nil} ) end end end end end function widget:UnitDestroyed(unitID, unitDefID, unitTeam) -- There should be a better way to do this, lazy fix. WG.icons.SetUnitIcon( unitID, {name='lowpower', texture=nil} ) WG.icons.SetUnitIcon( unitID, {name='facplop', texture=nil} ) WG.icons.SetUnitIcon( unitID, {name='rearm', texture=nil} ) WG.icons.SetUnitIcon( unitID, {name='retreat', texture=nil} ) end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function widget:GameFrame(f) if f%8 == 0 then SetIcons() end end function widget:Initialize() WG.icons.SetOrder( 'lowpower', 2 ) WG.icons.SetOrder( 'retreat', 5 ) WG.icons.SetDisplay( 'retreat', true ) WG.icons.SetPulse( 'retreat', true ) end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
froggatt/openwrt-luci
contrib/luadoc/lua/luadoc/taglet/standard/tags.lua
93
5221
------------------------------------------------------------------------------- -- Handlers for several tags -- @release $Id: tags.lua,v 1.8 2007/09/05 12:39:09 tomas Exp $ ------------------------------------------------------------------------------- local luadoc = require "luadoc" local util = require "luadoc.util" local string = require "string" local table = require "table" local assert, type, tostring = assert, type, tostring module "luadoc.taglet.standard.tags" ------------------------------------------------------------------------------- local function author (tag, block, text) block[tag] = block[tag] or {} if not text then luadoc.logger:warn("author `name' not defined [["..text.."]]: skipping") return end table.insert (block[tag], text) end ------------------------------------------------------------------------------- -- Set the class of a comment block. Classes can be "module", "function", -- "table". The first two classes are automatic, extracted from the source code local function class (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function cstyle (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function copyright (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function description (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function field (tag, block, text) if block["class"] ~= "table" then luadoc.logger:warn("documenting `field' for block that is not a `table'") end block[tag] = block[tag] or {} local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)") assert(name, "field name not defined") table.insert(block[tag], name) block[tag][name] = desc end ------------------------------------------------------------------------------- -- Set the name of the comment block. If the block already has a name, issue -- an error and do not change the previous value local function name (tag, block, text) if block[tag] and block[tag] ~= text then luadoc.logger:error(string.format("block name conflict: `%s' -> `%s'", block[tag], text)) end block[tag] = text end ------------------------------------------------------------------------------- -- Processes a parameter documentation. -- @param tag String with the name of the tag (it must be "param" always). -- @param block Table with previous information about the block. -- @param text String with the current line beeing processed. local function param (tag, block, text) block[tag] = block[tag] or {} -- TODO: make this pattern more flexible, accepting empty descriptions local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)") if not name then luadoc.logger:warn("parameter `name' not defined [["..text.."]]: skipping") return end local i = table.foreachi(block[tag], function (i, v) if v == name then return i end end) if i == nil then luadoc.logger:warn(string.format("documenting undefined parameter `%s'", name)) table.insert(block[tag], name) end block[tag][name] = desc end ------------------------------------------------------------------------------- local function release (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function ret (tag, block, text) tag = "ret" if type(block[tag]) == "string" then block[tag] = { block[tag], text } elseif type(block[tag]) == "table" then table.insert(block[tag], text) else block[tag] = text end end ------------------------------------------------------------------------------- -- @see ret local function see (tag, block, text) -- see is always an array block[tag] = block[tag] or {} -- remove trailing "." text = string.gsub(text, "(.*)%.$", "%1") local s = util.split("%s*,%s*", text) table.foreachi(s, function (_, v) table.insert(block[tag], v) end) end ------------------------------------------------------------------------------- -- @see ret local function usage (tag, block, text) if type(block[tag]) == "string" then block[tag] = { block[tag], text } elseif type(block[tag]) == "table" then table.insert(block[tag], text) else block[tag] = text end end ------------------------------------------------------------------------------- local handlers = {} handlers["author"] = author handlers["class"] = class handlers["cstyle"] = cstyle handlers["copyright"] = copyright handlers["description"] = description handlers["field"] = field handlers["name"] = name handlers["param"] = param handlers["release"] = release handlers["return"] = ret handlers["see"] = see handlers["usage"] = usage ------------------------------------------------------------------------------- function handle (tag, block, text) if not handlers[tag] then luadoc.logger:error(string.format("undefined handler for tag `%s'", tag)) return end -- assert(handlers[tag], string.format("undefined handler for tag `%s'", tag)) return handlers[tag](tag, block, text) end
apache-2.0
Knight-Team/KnightGuard-OLD-TG
plugins/stats.lua
866
4001
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
agpl-3.0
peachoftree/reverseGaliga
reverseGaliga/globals.lua
1
1781
local globals = {} globals.bullets = {} globals.level = 1 globals.firePoints = {} globals.paths = {} globals.paths.allPoints = {} globals.mode = "path" function globals.fire(position, kind) if kind == "ship" then position[2] = position[2] - 10 else position[2] = position[2] + 30 end table.insert(globals.bullets, 1, {position[1], position[2], kind}) globals.bullets[i].box = {position[1], position[2], 5, 10} end function globals.reset() require("bugs").reset() require("ship").lives = 3 globals.bullets = {} globals.level = 1 globals.firePoints = {} globals.paths = {} globals.paths.allPoints = {} for i = 1, 10 do globals.levels[i] = i * 10 end globals.level = globals.level + 1 end function globals.checkCollision(rect1, rect2) local x1 = rect1[1] local y1 = rect1[2] local w1 = rect1[3] local h1 = rect1[4] local x2 = rect1[1] local y2 = rect1[2] local w2 = rect1[3] local h2 = rect1[4] return x1 < x2+w2 and x2 < x1+w1 and y1 < y2+h2 and y2 < y1+h1 end function globals.update() for i = 1, #globals.bullets do local bullet = globals.bullets[i] if bullet[3] == "ship" then bullet[2] = bullet[2] - 20 else bullet[2] = bullet[2] + 20 end if globals.checkCollision(ship.box, bullet.box) then ship.lives = ship.lies - 1 end for i = 1, #bugs do local bug = bugs[i] if globals.checkCollision(bullet.box, bug.box) then table.remove(bugs, i) bugs.dead = bugs.dead + 1 bugs.deployed = bugs.deployed - 1 end end end return globals
mit
Blackdutchie/Zero-K
scripts/corvalk.lua
4
7162
local base = piece 'base' --New bits local lUpperCl1 = piece 'lUpperCl1' local rUpperCl1 = piece 'rUpperCl1' local lLowerCl1 = piece 'lLowerCl1' local rLowerCl1 = piece 'rLowerCl1' local lUpperCl2 = piece 'lUpperCl2' local rUpperCl2 = piece 'rUpperCl2' local lLowerCl2 = piece 'lLowerCl2' local rLowerCl2 = piece 'rLowerCl2' local engineEmit = piece 'engineEmit' local link = piece 'link' local AttachUnit = Spring.UnitScript.AttachUnit local DropUnit = Spring.UnitScript.DropUnit local loaded = false local unitLoaded = nil local doorOpen = false local SIG_OPENDOORS = 1 local SIG_CLOSEDOORS = 2 local smokePiece = {base, engineEmit} include "constants.lua" local function openDoors() Signal(SIG_OPENDOORS) SetSignalMask(SIG_OPENDOORS) Turn(lUpperCl1,z_axis, rad(-140),6) Turn(rUpperCl1,z_axis, rad(140), 6) Sleep(100) Turn(lUpperCl2,z_axis, rad(-140),6) Turn(rUpperCl2,z_axis, rad(140), 6) WaitForTurn(lUpperCl1, z_axis) WaitForTurn(rUpperCl1, z_axis) WaitForTurn(lUpperCl2, z_axis) WaitForTurn(rUpperCl2, z_axis) doorOpen = true end function closeDoors() Signal(SIG_CLOSEDOORS) SetSignalMask(SIG_CLOSEDOORS) Turn(lUpperCl1,z_axis, rad(0),4) Turn(rUpperCl1,z_axis, rad(0),4) Sleep(100) Turn(lUpperCl2,z_axis, rad(0),4) Turn(rUpperCl2,z_axis, rad(0),4) WaitForTurn(lUpperCl1, z_axis) WaitForTurn(rUpperCl1, z_axis) WaitForTurn(lUpperCl2, z_axis) WaitForTurn(rUpperCl2, z_axis) doorOpen = false end --Special ability: drop unit midair function ForceDropUnit() if (unitLoaded ~= nil) and Spring.ValidUnitID(unitLoaded) then local x,y,z = Spring.GetUnitPosition(unitLoaded) --cargo position local _,ty = Spring.GetUnitPosition(unitID) --transport position local vx,vy,vz = Spring.GetUnitVelocity(unitID) --transport speed DropUnit(unitLoaded) --detach cargo local transRadius = Spring.GetUnitRadius(unitID) Spring.SetUnitPosition(unitLoaded, x,math.min(y, ty-transRadius),z) --set cargo position below transport Spring.AddUnitImpulse(unitLoaded,0,4,0) --hax to prevent teleport to ground Spring.AddUnitImpulse(unitLoaded,0,-4,0) --hax to prevent teleport to ground Spring.SetUnitVelocity(unitLoaded,0,0,0) --remove any random velocity caused by collision with transport (especially Spring 91) Spring.AddUnitImpulse(unitLoaded,vx,vy,vz) --readd transport momentum end unitLoaded = nil StartThread(script.EndTransport) --formalize unit drop (finish animation, clear tag, ect) end --fetch unit id of passenger (from the load command) function getPassengerId() local cmd = Spring.GetUnitCommands(unitID, 1) local unitId = nil if cmd and cmd[1] then if cmd[1]['id'] == 75 then -- CMDTYPE.LOAD_UNITS = 75 unitId = cmd[1]['params'][1] end end return unitId end --fetch id of command function getCommandId() local cmd=Spring.GetUnitCommands(unitID, 1) if cmd and cmd[1] then return cmd[1]['id'] end return nil end --fetch unit id of passenger (from the load command) function getDropPoint() local cmd=Spring.GetUnitCommands(unitID, 1) local dropx, dropy,dropz = nil if cmd and cmd[1] then if cmd[1]['id'] == 81 then -- CMDTYPE.LOAD_UNITS = 75 dropx, dropy,dropz = cmd[1]['params'][1], cmd[1]['params'][2], cmd[1]['params'][3] end end return {dropx, dropy,dropz} end function isNearPickupPoint(passengerId, requiredDist) if passengerId == nil then return false end local px, py, pz = Spring.GetUnitBasePosition(passengerId) if not px then return end local px2, py2, pz2 = Spring.GetUnitBasePosition(unitID) if not px2 then return end local dx = px2 - px local dz = pz2 - pz local dist = (dx^2 + dz^2) if dist < requiredDist^2 then return true else return false end end function isNearDropPoint(transportUnitId, requiredDist) if transportUnitId == nil then return false end local px, py, pz = Spring.GetUnitBasePosition(transportUnitId) local dropPoint = getDropPoint() local px2, py2, pz2 = dropPoint[1], dropPoint[2], dropPoint[3] local dx = px - px2 local dz = pz - pz2 local dist = (dx^2 + dz^2) if dist < requiredDist^2 then return true else return false end end function isValidCargo(soonPassenger, passenger) return ((soonPassenger and Spring.ValidUnitID(soonPassenger)) or (passenger and Spring.ValidUnitID(passenger))) end local function PickupAndDropFixer() while true do local passengerId = getPassengerId() if passengerId and (getCommandId() == 75) and isValidCargo(passengerId) and isNearPickupPoint(passengerId, 120) then Sleep(1500) local passengerId = getPassengerId() if passengerId and (getCommandId() == 75) and isValidCargo(passengerId) and isNearPickupPoint(passengerId, 120) then Spring.GiveOrderToUnit(unitID, CMD.WAIT, {}, {}) Spring.GiveOrderToUnit(unitID, CMD.WAIT, {}, {}) end end if unitLoaded and (getCommandId() == 81) and isNearDropPoint(unitLoaded, 80) then Sleep(1500) if unitLoaded and (getCommandId() == 81) and isNearDropPoint(unitLoaded, 80) then Spring.GiveOrderToUnit(unitID, CMD.WAIT, {}, {}) Spring.GiveOrderToUnit(unitID, CMD.WAIT, {}, {}) end end Sleep(500) end end function script.MoveRate(curRate) local passengerId = getPassengerId() if doorOpen and not isValidCargo(passengerId,unitLoaded) then unitLoaded = nil StartThread(script.EndTransport) --formalize unit drop (finish animation, clear tag, ect) elseif getCommandId() == 75 and isNearPickupPoint(passengerId, 1000) then StartThread(openDoors) elseif getCommandId() == 81 and isNearDropPoint(unitLoaded, 1000) then StartThread(openDoors) end end function script.BeginTransport(passengerID) if loaded then return end Move(link, y_axis, -Spring.GetUnitHeight(passengerID), nil, true) --local px, py, pz = Spring.GetUnitBasePosition(passengerID) SetUnitValue(COB.BUSY, 1) AttachUnit(link, passengerID) unitLoaded = passengerID loaded = true Sleep(500) --StartThread(closeDoors) end function script.Create() StartThread(SmokeUnit, smokePiece) StartThread(PickupAndDropFixer) end function script.Activate() end function script.Deactivate() StartThread(closeDoors) end function script.QueryTransport(passengerID) return link end -- note x, y z is in worldspace --function script.TransportDrop(passengerID, x, y, z) function script.EndTransport() --StartThread(openDoors) if (unitLoaded ~= nil) then DropUnit(unitLoaded) unitLoaded = nil end loaded = false SetUnitValue(COB.BUSY, 0) Sleep(500) StartThread(closeDoors) end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if severity <= 0.25 then Explode(base, sfxNone) return 1 elseif severity <= 0.50 or ((Spring.GetUnitMoveTypeData(unitID).aircraftState or "") == "crashing") then Explode(base, sfxShatter) return 1 elseif severity <= 0.75 then Explode(base, sfxShatter) return 2 else Explode(base, sfxShatter) Explode(lLowerCl1, sfxFall + sfxSmoke + sfxFire) Explode(rLowerCl1, sfxFall + sfxSmoke + sfxFire) Explode(lUpperCl2, sfxFall + sfxSmoke + sfxFire) Explode(rUpperCl2, sfxFall + sfxSmoke + sfxFire) end end
gpl-2.0
LuaDist2/lua-nucleo
lua-nucleo/ensure.lua
2
11414
-------------------------------------------------------------------------------- --- Tools to ensure correct code behaviour -- @module lua-nucleo.ensure -- This file is a part of lua-nucleo library -- @copyright lua-nucleo authors (see file `COPYRIGHT` for the license) -------------------------------------------------------------------------------- local error, tostring, pcall, type, pairs, select, next = error, tostring, pcall, type, pairs, select, next local math_min, math_max, math_abs = math.min, math.max, math.abs local string_char = string.char local tdeepequals, tstr, taccumulate, tnormalize = import 'lua-nucleo/table.lua' { 'tdeepequals', 'tstr', 'taccumulate', 'tnormalize' } local assert_is_number = import 'lua-nucleo/typeassert.lua' { 'assert_is_number' } local make_checker = import 'lua-nucleo/checker.lua' { 'make_checker' } -- TODO: Write tests for this one -- https://github.com/lua-nucleo/lua-nucleo/issues/13 local ensure = function(msg, value, ...) if not value then error( "ensure failed: " .. msg .. ((...) and (": " .. (tostring(...) or "?")) or ""), 2 ) end return value, ... end -- TODO: Write tests for this one -- https://github.com/lua-nucleo/lua-nucleo/issues/13 local ensure_equals = function(msg, actual, expected) return (actual ~= expected) and error( "ensure_equals failed: " .. msg .. ": actual `" .. tostring(actual) .. "', expected `" .. tostring(expected) .. "'", 2 ) or actual -- NOTE: Should be last to allow false and nil values. end local ensure_is = function(msg, value, expected_type) local actual = type(value) return (actual ~= expected_type) and error( "ensure_is failed: " .. msg .. ": actual type `" .. tostring(actual) .. "', expected type `" .. tostring(expected_type) .. "'", 2 ) or value -- NOTE: Should be last to allow false and nil values. end -- TODO: Write tests for this one -- https://github.com/lua-nucleo/lua-nucleo/issues/13 local ensure_tequals = function(msg, actual, expected) if type(expected) ~= "table" then error( "ensure_tequals failed: " .. msg .. ": bad expected type, must be `table', got `" .. type(expected) .. "'", 2 ) end if type(actual) ~= "table" then error( "ensure_tequals failed: " .. msg .. ": bad actual type, expected `table', got `" .. type(actual) .. "'", 2 ) end -- TODO: Employ tdiff() (when it would be written) -- TODO: Use checker to get info on all bad keys! for k, expected_v in pairs(expected) do local actual_v = actual[k] if actual_v ~= expected_v then error( "ensure_tequals failed: " .. msg .. ": bad actual value at key `" .. tostring(k) .. "': got `" .. tostring(actual_v) .. "', expected `" .. tostring(expected_v) .. "'", 2 ) end end for k, actual_v in pairs(actual) do if expected[k] == nil then error( "ensure_tequals failed: " .. msg .. ": unexpected actual value at key `" .. tostring(k) .. "': got `" .. tostring(actual_v) .. "', should be nil", 2 ) end end return actual end local ensure_tdeepequals = function(msg, actual, expected) -- Heavy! Use ensure_tequals if possible if not tdeepequals(actual, expected) then -- TODO: Bad! Improve error reporting (use tdiff) error( "ensure_tdeepequals failed: " .. msg .. ":" .. "\n actual: " .. tstr(actual) .. "\nexpected: " .. tstr(expected), 2 ) end end -- TODO: ?! Improve and generalize! local strdiff_msg do -- TODO: Generalize? local string_window = function(str, pos, window_radius) return str:sub( math_max(1, pos - window_radius), math_min(pos + window_radius, #str) ) end -- TODO: Uncomment and move to proper tests --[=[ assert(string_window("abCde", 3, 0) == [[C]]) assert(string_window("abCde", 3, 1) == [[bCd]]) assert(string_window("abCde", 3, 2) == [[abCde]]) assert(string_window("abCde", 3, 3) == [[abCde]]) --]=] local nl_byte = ("\n"):byte() strdiff_msg = function(actual, expected, window_radius) window_radius = window_radius or 10 local result = false --print(("%q"):format(expected)) --print(("%q"):format(actual)) if type(actual) ~= "string" or type(expected) ~= "string" then result = "(bad input)" else local nactual, nexpected = #actual, #expected local len = math_min(nactual, nexpected) local lineno, lineb = 1, 1 for i = 1, len do local ab, eb = expected:byte(i), actual:byte(i) --print(string_char(eb), string_char(ab)) if ab ~= eb then -- TODO: Do not want to have \n-s here. Too low level?! result = "different at byte " .. i .. " (line " .. lineno .. ", offset " .. lineb .. "):\n\n expected |" .. string_window(expected, i, window_radius) .. "|\nvs. actual |" .. string_window(actual, i, window_radius) .. "|\n\n" break end if eb == nl_byte then lineno, lineb = lineno + 1, 1 end end if nactual > nexpected then result = (result or "different: ") .. "actual has " .. (nactual - nexpected) .. " extra characters" elseif nactual < nexpected then result = (result or "different:" ) .. "expected has " .. (nexpected - nactual) .. " extra characters" end end return result or "(identical)" end end -------------------------------------------------------------------------------- local ensure_strequals = function(msg, actual, expected, ...) if actual == expected then return actual, expected, ... end error( "ensure_strequals: " .. msg .. ":\n" .. strdiff_msg(actual, expected) .. "\nactual:\n" .. tostring(actual) .. "\nexpected:\n" .. tostring(expected) ) end -------------------------------------------------------------------------------- local ensure_error = function(msg, expected_message, res, actual_message, ...) if res ~= nil then error( "ensure_error failed: " .. msg .. ": failure expected, got non-nil result: `" .. tostring(res) .. "'", 2 ) end -- TODO: Improve error reporting ensure_strequals(msg, actual_message, expected_message) end -------------------------------------------------------------------------------- local ensure_error_with_substring = function(msg, substring, res, err) if res ~= nil then error( "ensure_error_with_substring failed: " .. msg .. ": failure expected, got non-nil result: `" .. tostring(res) .. "'", 2 ) end if substring ~= err and not err:find(substring, nil, true) and not err:find(substring) then error( "ensure_error_with_substring failed: " .. msg .. ": can't find expected substring `" .. tostring(substring) .. "' in error message:\n" .. err ) end end -------------------------------------------------------------------------------- local ensure_fails_with_substring = function(msg, fn, substring) local res, err = pcall(fn) if res ~= false then error("ensure_fails_with_substring failed: " .. msg .. ": call was expected to fail, but did not") end if type(err) ~= "string" then error("ensure_fails_with_substring failed: " .. msg .. ": call failed with non-string error") end if substring ~= err and not err:find(substring, nil, true) and not err:find(substring) then error( "ensure_fails_with_substring failed: " .. msg .. ": can't find expected substring `" .. tostring(substring) .. "' in error message:\n" .. err ) end end -------------------------------------------------------------------------------- local ensure_has_substring = function(msg, str, substring) if type(str) ~= "string" then error( "ensure_has_substring failed: " .. msg .. ": value is not a string", 2 ) end ensure( 'ensure_has_substring failed: ' .. msg .. ": can't find expected substring `" .. tostring(substring) .. "' in string: `" .. str .. "'", (str == substring) or str:find(substring, nil, true) or str:find(substring) ) return str end -------------------------------------------------------------------------------- -- We want 99.9% probability of success -- Would not work for high-contrast weights. Use for tests only. local ensure_aposteriori_probability = function(num_runs, weights, stats, max_acceptable_diff) ensure_equals("total sum check", taccumulate(stats), num_runs) local apriori_probs = tnormalize(weights) local aposteriori_probs = tnormalize(stats) for k, apriori in pairs(apriori_probs) do local aposteriori = assert_is_number(aposteriori_probs[k]) ensure("apriori must be positive", apriori > 0) ensure("aposteriori must be non-negative", aposteriori >= 0) -- TODO: Lame check. Improve it. local diff = math_abs(apriori - aposteriori) / apriori if diff > max_acceptable_diff then error( "inacceptable apriori-aposteriori difference key: `" .. tostring(k) .. "'" .. " num_runs: " .. num_runs .. " apriori: " .. apriori .. " aposteriori: " .. aposteriori .. " actual_diff: " .. diff .. " max_diff: " .. max_acceptable_diff ) end aposteriori_probs[k] = nil -- To check there is no extra data below. end ensure_equals("no extra data", next(aposteriori_probs), nil) end local ensure_returns = function(msg, num, expected, ...) local checker = make_checker() -- Explicit check to separate no-return-values from all-nils local actual_num = select("#", ...) if num ~= actual_num then checker:fail( "return value count mismatch: expected " .. num .. " actual " .. actual_num ) end for i = 1, math_max(num, actual_num) do if not tdeepequals(expected[i], (select(i, ...))) then -- TODO: Enhance error reporting (especially for tables and long strings) checker:fail( "return value #" .. i .. " mismatch: " .. "actual `" .. tstr((select(i, ...))) .. "', expected `" .. tstr(expected[i]) .. "'" ) end end if not checker:good() then error( checker:msg( "return values check failed: " .. msg .. "\n -- ", "\n -- " ), 2 ) end return ... end return { ensure = ensure; ensure_equals = ensure_equals; ensure_is = ensure_is; ensure_tequals = ensure_tequals; ensure_tdeepequals = ensure_tdeepequals; ensure_strequals = ensure_strequals; ensure_error = ensure_error; ensure_error_with_substring = ensure_error_with_substring; ensure_fails_with_substring = ensure_fails_with_substring; ensure_has_substring = ensure_has_substring; ensure_aposteriori_probability = ensure_aposteriori_probability; ensure_returns = ensure_returns; }
mit
electricpandafishstudios/Spoon
game/engines/te4-1.4.1/engine/ui/Dropdown.lua
1
3516
-- TE4 - T-Engine 4 -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" local Base = require "engine.ui.Base" local Focusable = require "engine.ui.Focusable" local List = require "engine.ui.List" local Dialog = require "engine.ui.Dialog" --- A generic UI list dropdown box -- @classmod engine.ui.Dropdown module(..., package.seeall, class.inherit(Base, Focusable)) function _M:init(t) self.text = t.text or "" self.w = assert(t.width, "no dropdown width") self.fct = assert(t.fct, "no dropdown fct") self.list = assert(t.list, "no dropdown list") self.nb_items = assert(t.nb_items, "no dropdown nb_items") self.on_select = t.on_select self.display_prop = t.display_prop or "name" self.scrollbar = t.scrollbar Base.init(self, t) end function _M:generate() self.mouse:reset() self.key:reset() -- Draw UI self.h = self.font_h + 6 self.height = self.h self.frame = self:makeFrame("ui/textbox", self.w, self.h) self.frame_sel = self:makeFrame("ui/textbox-sel", self.w, self.h) -- Add UI controls self.mouse:registerZone(0, 0, self.w, self.h, function(button, x, y, xrel, yrel, bx, by, event) if event == "button" and button == "left" then self:showSelect() end end) self.key:addBind("ACCEPT", function() self:showSelect() end) end function _M:positioned(x, y, sx, sy) self.c_list = List.new{width=self.w, list=self.list, select=self.on_select, display_prop=self.display_prop, scrollbar=self.scrollbar, nb_items=self.nb_items, fct=function() game:unregisterDialog(self.popup) self:sound("button") self.fct(self.c_list.list[self.c_list.sel]) end} self.popup = Dialog.new(nil, self.w, self.c_list.h, sx, sy + self.h, nil, nil, false, "simple") self.popup.frame.a = 0.7 self.popup:loadUI{{left=0, top=0, ui=self.c_list}} self.popup:setupUI(true, true) self.popup.key:addBind("EXIT", function() game:unregisterDialog(self.popup) self.c_list.sel = self.previous self:sound("button") self.fct(self.c_list.list[self.c_list.sel]) end) end function _M:showSelect() self.previous = self.c_list.sel game:registerDialog(self.popup) end function _M:display(x, y, nb_keyframes) if self.focused then self:drawFrame(self.frame_sel, x, y) else self:drawFrame(self.frame, x, y) if self.focus_decay then self:drawFrame(self.frame_sel, x, y, 1, 1, 1, self.focus_decay / self.focus_decay_max_d) self.focus_decay = self.focus_decay - nb_keyframes if self.focus_decay <= 0 then self.focus_decay = nil end end end local item = self.c_list.list[self.c_list.sel] if item then local cy = (self.c_list.fh - self.c_list.font_h) / 2 if self.text_shadow then self:textureToScreen(item._tex, x + 1 + self.frame_sel.b4.w, y + 1 + cy, 0, 0, 0, self.text_shadow) end self:textureToScreen(item._tex, x + self.frame_sel.b4.w, y + cy, 1, 1, 1, 1) end end
gpl-3.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/class/uiset/Minimalist.lua
1
101854
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" local UI = require "engine.ui.Base" local UISet = require "mod.class.uiset.UISet" local DebugConsole = require "engine.DebugConsole" local HotkeysDisplay = require "engine.HotkeysDisplay" local HotkeysIconsDisplay = require "engine.HotkeysIconsDisplay" local ActorsSeenDisplay = require "engine.ActorsSeenDisplay" local LogDisplay = require "engine.LogDisplay" local LogFlasher = require "engine.LogFlasher" local FlyingText = require "engine.FlyingText" local Shader = require "engine.Shader" local ActorResource = require "engine.interface.ActorResource" local Tooltip = require "mod.class.Tooltip" local TooltipsData = require "mod.class.interface.TooltipsData" local Dialog = require "engine.ui.Dialog" local Map = require "engine.Map" local FontPackage = require "engine.FontPackage" module(..., package.seeall, class.inherit(UISet, TooltipsData)) local function imageLoader(file) local sfile = "/data/gfx/"..UI.ui.."-ui/minimalist/"..file if fs.exists(sfile) then return core.display.loadImage(sfile) else return core.display.loadImage( "/data/gfx/ui/"..file) end end local move_handle = {imageLoader("move_handle.png"):glTexture()} local frames_colors = { ok = {0.3, 0.6, 0.3}, sustain = {0.6, 0.6, 0}, cooldown = {0.6, 0, 0}, disabled = {0.65, 0.65, 0.65}, } -- Load the various shaders used to display resources air_c = {0x92/255, 0xe5, 0xe8} air_sha = Shader.new("resources", {require_shader=4, delay_load=true, color=air_c, speed=100, amp=0.8, distort={2,2.5}}) life_c = {0xc0/255, 0, 0} life_sha = Shader.new("resources", {require_shader=4, delay_load=true, color=life_c, speed=1000, distort={1.5,1.5}}) shield_c = {0.5, 0.5, 0.5} shield_sha = Shader.new("resources", {require_shader=4, delay_load=true, color=shield_c, speed=5000, a=0.5, distort={0.5,0.5}}) psi_sha = Shader.new("resources", {require_shader=4, delay_load=true, color={colors.BLUE.r/255, colors.BLUE.g/255, colors.BLUE.b/255}, speed=2000, distort={0.4,0.4}}) feedback_c = {colors.YELLOW.r/255, colors.YELLOW.g/255, colors.YELLOW.b/255} feedback_sha = Shader.new("resources", {require_shader=4, delay_load=true, color=feedback_c, speed=2000, distort={0.4,0.4}}) fortress_c = {0x39/255, 0xd5/255, 0x35/255} fortress_sha = Shader.new("resources", {require_shader=4, delay_load=true, color=fortress_c, speed=2000, distort={0.4,0.4}}) save_c = {colors.GOLD.r/255, colors.GOLD.g/255, colors.GOLD.b/255} save_sha = Shader.new("resources", {require_shader=4, delay_load=true, color=save_c, speed=1000, distort={1.6,0.2}}) sshat = {imageLoader("resources/shadow.png"):glTexture()} bshat = {imageLoader("resources/back.png"):glTexture()} shat = {imageLoader("resources/fill.png"):glTexture()} fshat = {imageLoader("resources/front.png"):glTexture()} fshat_life = {imageLoader("resources/front_life.png"):glTexture()} fshat_life_dark = {imageLoader("resources/front_life_dark.png"):glTexture()} fshat_shield = {imageLoader("resources/front_life_armored.png"):glTexture()} fshat_shield_dark = {imageLoader("resources/front_life_armored_dark.png"):glTexture()} fshat_feedback = {imageLoader("resources/front_psi.png"):glTexture()} fshat_feedback_dark = {imageLoader("resources/front_psi_dark.png"):glTexture()} fshat_air = {imageLoader("resources/front_air.png"):glTexture()} fshat_air_dark = {imageLoader("resources/front_air_dark.png"):glTexture()} fshat_fortress = {imageLoader("resources/front_fortress.png"):glTexture()} fshat_fortress_dark = {imageLoader("resources/front_fortress_dark.png"):glTexture()} fshat_hourglass = {imageLoader("resources/hourglass_front.png"):glTexture()} sshat_hourglass = {imageLoader("resources/hourglass_shadow.png"):glTexture()} shat_hourglass_top = {imageLoader("resources/hourglass_top.png"):glTexture()} shat_hourglass_bottom = {imageLoader("resources/hourglass_bottom.png"):glTexture()} ammo_shadow_default = {imageLoader("resources/ammo_shadow_default.png"):glTexture()} ammo_default = {imageLoader("resources/ammo_default.png"):glTexture()} ammo_shadow_arrow = {imageLoader("resources/ammo_shadow_arrow.png"):glTexture()} ammo_arrow = {imageLoader("resources/ammo_arrow.png"):glTexture()} ammo_shadow_shot = {imageLoader("resources/ammo_shadow_shot.png"):glTexture()} ammo_shot = {imageLoader("resources/ammo_shot.png"):glTexture()} _M['ammo_shadow_alchemist-gem'] = {imageLoader("resources/ammo_shadow_alchemist-gem.png"):glTexture()} _M['ammo_alchemist-gem'] = {imageLoader("resources/ammo_alchemist-gem.png"):glTexture()} font_sha = FontPackage:get("resources_normal", true) sfont_sha = FontPackage:get("resources_small", true) icon_green = { imageLoader("talent_frame_ok.png"):glTexture() } icon_yellow = { imageLoader("talent_frame_sustain.png"):glTexture() } icon_red = { imageLoader("talent_frame_cooldown.png"):glTexture() } local portrait = {imageLoader("party-portrait.png"):glTexture()} local portrait_unsel = {imageLoader("party-portrait-unselect.png"):glTexture()} local portrait_lev = {imageLoader("party-portrait-lev.png"):glTexture()} local portrait_unsel_lev = {imageLoader("party-portrait-unselect-lev.png"):glTexture()} local pf_bg_x, pf_bg_y = 0, 0 local pf_player_x, pf_player_y = 0, 0 local pf_bg = {imageLoader("playerframe/back.png"):glTexture()} local pf_shadow = {imageLoader("playerframe/shadow.png"):glTexture()} local pf_defend = {imageLoader("playerframe/defend.png"):glTexture()} local pf_attackdefend_x, pf_attackdefend_y = 0, 0 local pf_attack = {imageLoader("playerframe/attack.png"):glTexture()} local pf_levelup_x, pf_levelup_y = 0, 0 local pf_levelup = {imageLoader("playerframe/levelup.png"):glTexture()} local pf_encumber_x, pf_encumber_y = 0, 0 local pf_encumber = {imageLoader("playerframe/encumber.png"):glTexture()} local pf_exp_x, pf_exp_y = 0, 0 local pf_exp = {imageLoader("playerframe/exp.png"):glTexture()} local pf_exp_levelup = {imageLoader("playerframe/exp_levelup.png"):glTexture()} local pf_money_x, pf_money_y = 0, 0 local pf_exp_cur_x, pf_exp_cur_y = 0, 0 local pf_name_x, pf_name_y = 0, 0 local pf_level_x, pf_level_y = 0, 0 local mm_bg_x, mm_bg_y = 0, 0 local mm_bg = {imageLoader("minimap/back.png"):glTexture()} local mm_comp = {imageLoader("minimap/compass.png"):glTexture()} local mm_shadow = {imageLoader("minimap/shadow.png"):glTexture()} local mm_transp = {imageLoader("minimap/transp.png"):glTexture()} local tb_bg = {imageLoader("hotkeys/icons_bg.png"):glTexture()} local tb_talents = {imageLoader("hotkeys/talents.png"):glTexture()} local tb_inven = {imageLoader("hotkeys/inventory.png"):glTexture()} local tb_lore = {imageLoader("hotkeys/lore.png"):glTexture()} local tb_quest = {imageLoader("hotkeys/quest.png"):glTexture()} local tb_mainmenu = {imageLoader("hotkeys/mainmenu.png"):glTexture()} local tb_padlock_open = {imageLoader("padlock_open.png"):glTexture()} local tb_padlock_closed = {imageLoader("padlock_closed.png"):glTexture()} local hk1 = {imageLoader("hotkeys/hotkey_1.png"):glTexture()} local hk2 = {imageLoader("hotkeys/hotkey_2.png"):glTexture()} local hk3 = {imageLoader("hotkeys/hotkey_3.png"):glTexture()} local hk4 = {imageLoader("hotkeys/hotkey_4.png"):glTexture()} local hk5 = {imageLoader("hotkeys/hotkey_5.png"):glTexture()} local hk6 = {imageLoader("hotkeys/hotkey_6.png"):glTexture()} local hk7 = {imageLoader("hotkeys/hotkey_7.png"):glTexture()} local hk8 = {imageLoader("hotkeys/hotkey_8.png"):glTexture()} local hk9 = {imageLoader("hotkeys/hotkey_9.png"):glTexture()} _M:bindHook("UISet:Minimalist:Load", function(self, data) if UI.ui ~= "dark" then return end data.alterlocal("pf_bg_y", -5) data.alterlocal("pf_attackdefend_x", 8) data.alterlocal("pf_attackdefend_y", -8) data.alterlocal("pf_player_x", 5) data.alterlocal("pf_player_y", -4) data.alterlocal("pf_levelup_x", -5) data.alterlocal("pf_levelup_y", -9) data.alterlocal("pf_exp_x", 10) data.alterlocal("pf_exp_y", -1) data.alterlocal("pf_level_x", 9) data.alterlocal("pf_level_y", -2) data.alterlocal("pf_name_x", 10) data.alterlocal("pf_name_y", -2) data.alterlocal("pf_money_x", 7) data.alterlocal("pf_money_y", -2) data.alterlocal("pf_exp_cur_x", 7) data.alterlocal("pf_exp_cur_y", -1) data.alterlocal("mm_bg_x", -5) data.alterlocal("mm_bg_y", -3) end) -- Note: could use a bit more room for some of the resource texts -- Additional (optional) resource parameters for the Minimalist UI (defined in ActorResource:resources_def[resource_name].Minimalist): -- images = {front = <highlighted graphic file path> , front_dark = <unhighlighted graphic file path>} -- (base directories: "/data/gfx/"..UI.ui.."-ui/minimalist/" or "/data/gfx/ui/") -- highlight = function(player, vc, vn, vm, vr) return true to display the highlighted resource graphic -- vc, vn, vm, vr = resource current, min, max, regen values -- shader_params = { shader parameters used to define the shader for the resource bar (merged into default parameters below) -- display_resource_bar = function(player, shader, x, y, color, a) --function to draw the resource bar within the resource graphic -- shader = a Shader object to be drawn at x, y with color = vector {r, g, b}/255 and alpha a (0-1) -- called with the uiset fenv -- Note: will be called with player = false before the ui is initialized -- } -- see Minimalist:initialize_resources, Minimalist:displayResources -- Default shader parameters used to draw the resource bars -- Overridden by resource_def.Minimalist.shader_params _M.shader_params = {default = {name = "resources", require_shader=4, delay_load=true, speed=1000, distort={1.5,1.5}}, air={name = "resources", require_shader=4, delay_load=true, color=air_c, speed=100, amp=0.8, distort={2,2.5}}, life={name = "resources", require_shader=4, delay_load=true, color=life_c, speed=1000, distort={1.5,1.5}}, stamina={name = "resources", require_shader=4, delay_load=true, color={0xff/255, 0xcc/255, 0x80/255}, speed=700, distort={1,1.4}}, mana={name = "resources", require_shader=4, delay_load=true, color={106/255, 146/255, 222/255}, speed=1000, distort={0.4,0.4}}, soul={name = "resources", require_shader=4, delay_load=true, color={128/255, 128/255, 128/255}, speed=1200, distort={0.4,-0.4}}, equilibrium={name = "resources2", require_shader=4, delay_load=true, color1={0x00/255, 0xff/255, 0x74/255}, color2={0x80/255, 0x9f/255, 0x44/255}, amp=0.8, speed=20000, distort={0.3,0.25}}, paradox={name = "resources2", require_shader=4, delay_load=true, color1={0x2f/255, 0xa0/255, 0xb4/255}, color2={0x8f/255, 0x80/255, 0x44/255}, amp=0.8, speed=20000, distort={0.1,0.25}}, positive={name = "resources", require_shader=4, delay_load=true, color={colors.GOLD.r/255, colors.GOLD.g/255, colors.GOLD.b/255}, speed=1000, distort={1.6,0.2}}, negative={name = "resources", require_shader=4, delay_load=true, color={colors.DARK_GREY.r/255, colors.DARK_GREY.g/255, colors.DARK_GREY.b/255}, speed=1000, distort={1.6,-0.2}}, vim={name = "resources", require_shader=4, delay_load=true, color={210/255, 180/255, 140/255}, speed=1000, distort={0.4,0.4}}, hate={name = "resources", require_shader=4, delay_load=true, color={0xF5/255, 0x3C/255, 0xBE/255}, speed=1000, distort={0.4,0.4}}, psi={name = "resources", require_shader=4, delay_load=true, color={colors.BLUE.r/255, colors.BLUE.g/255, colors.BLUE.b/255}, speed=2000, distort={0.4,0.4}}, feedback={require_shader=4, delay_load=true, speed=2000, distort={0.4,0.4}}, } _M:triggerHook{"UISet:Minimalist:Load", alterlocal=function(k, v) local i = 1 while true do local kk, _ = debug.getlocal(4, i) if not kk then break end if kk == k then debug.setlocal(4, i, v) break end i = i + 1 end end } -- load and set up resource graphics function _M:initialize_resources() local res_gfx = {} for res, res_def in ipairs(ActorResource.resources_def) do local rname = res_def.short_name res_gfx[rname] = table.clone(res_def.minimalist_gfx) or {color = {}, shader = {}} -- use the graphics defined with the resource, if possible local res_color = res_def.color or "#WHITE#" -- set up color if type(res_color) == "string" then local r, g, b res_color = res_color:gsub("#", ""):upper() if colors[res_color] then -- lookup r, g, b = colors.unpack(colors[res_color]) r, g, b = r/255, g/255, b/255 else -- parse r, g, b = colors.hex1unpack(res_color) end res_gfx[rname].color = {r, g, b} else res_gfx[rname].color = res_color end local shad_params = table.clone(_M.shader_params[rname] or _M.shader_params.default) local extra_shader_params = table.get(res_def, "Minimalist", "shader_params") -- note: Shader init calls all arg functions if extra_shader_params then -- update fenv for custom functions for p, val in pairs(extra_shader_params) do if type(val) == "function" then setfenv(val, getfenv(_M.init)) end end table.merge(shad_params, extra_shader_params) end -- get color from resource_definition.Minimalist.shader_params, then _M.shader_params (defined here), then resource_definition.color shad_params.color = table.get(res_def, "Minimalist", "shader_color") or shad_params.color or res_gfx[rname].color res_gfx[rname].shader = Shader.new(shad_params.name, shad_params) -- optional custom highlight select function res_gfx[rname].highlight = table.get(res_def, "Minimalist", "highlight") -- load graphic images local res_imgs = table.merge({front = "resources/front_"..rname..".png", front_dark = "resources/front_"..rname.."_dark.png"}, table.get(res_def, "Minimalist", "images") or {}) local sbase, bbase = "/data/gfx/"..UI.ui.."-ui/minimalist/", "/data/gfx/ui/" for typ, file in pairs(res_imgs) do local sfile = sbase..file local bfile = bbase..file if fs.exists(sfile) then -- load the specific image print("[Minimalist] resource ui:", rname, "gfx file", sfile, "found") res_gfx[rname][typ] = {core.display.loadImage(sfile):glTexture()} elseif fs.exists(bfile) then -- load the specific image print("[Minimalist] resource base:", rname, "gfx file", bfile, "found") res_gfx[rname][typ] = {core.display.loadImage(bfile):glTexture()} else -- load a default image (Psi graphics) print("[Minimalist] Warning: resource", rname, "gfx file", file, "**NOT FOUND** in directories", sbase, "or", bbase, "(using default image)") if typ == "front" then res_gfx[rname][typ] = {imageLoader("resources/front_psi.png"):glTexture()} else res_gfx[rname][typ] = {imageLoader("resources/front_psi_dark.png"):glTexture()} end end end -- generate default tooltip if needed res_gfx[rname].tooltip = _M["TOOLTIP_"..rname:upper()] or ([[#GOLD#%s#LAST# %s]]):format(res_def.name, res_def.description or "no description") end self.res_gfx = res_gfx end function _M:init() UISet.init(self) self.mhandle = {} self.res = {} self.party = {} self.tbuff = {} self.pbuff = {} self.locked = true self.mhandle_pos = { player = {x=296, y=73, name="Player Infos"}, resources = {x=fshat[6] / 2 - move_handle[6], y=0, name="Resources"}, minimap = {x=208, y=176, name="Minimap"}, buffs = {x=40 - move_handle[6], y=0, name="Current Effects"}, party = {x=portrait[6] - move_handle[6], y=0, name="Party Members"}, gamelog = {x=function(self) return self.logdisplay.w - move_handle[6] end, y=function(self) return self.logdisplay.h - move_handle[6] end, name="Game Log"}, chatlog = {x=function(self) return profile.chat.w - move_handle[6] end, y=function(self) return profile.chat.h - move_handle[6] end, name="Online Chat Log"}, hotkeys = {x=function(self) return self.places.hotkeys.w - move_handle[6] end, y=function(self) return self.places.hotkeys.h - move_handle[6] end, name="Hotkeys"}, mainicons = {x=0, y=0, name="Game Actions"}, } self:resetPlaces() table.merge(self.places, config.settings.tome.uiset_minimalist and config.settings.tome.uiset_minimalist.places or {}, true) local w, h = core.display.size() -- Adjust to account for resolution change if config.settings.tome.uiset_minimalist and config.settings.tome.uiset_minimalist.save_size then local ow, oh = config.settings.tome.uiset_minimalist.save_size.w, config.settings.tome.uiset_minimalist.save_size.h -- Adjust UI local w2, h2 = math.floor(ow / 2), math.floor(oh / 2) for what, d in pairs(self.places) do if d.x > w2 then d.x = d.x + w - ow end if d.y > h2 then d.y = d.y + h - oh end end end self.sizes = {} self.tbbuttons = {inven=0.6, talents=0.6, mainmenu=0.6, lore=0.6, quest=0.6} self.buffs_base = UI:makeFrame("ui/icon-frame/frame", 40, 40) self:initialize_resources() end function _M:isLocked() return self.locked end function _M:switchLocked() self.locked = not self.locked if self.locked then game.bignews:say(60, "#CRIMSON#Interface locked, mouse enabled on the map") else game.bignews:say(60, "#CRIMSON#Interface unlocked, mouse disabled on the map") end end function _M:getMainMenuItems() return { {"Reset interface positions", function() Dialog:yesnoPopup("Reset UI", "Reset all the interface?", function(ret) if ret then self:resetPlaces() self:saveSettings() end end) end}, } end --- Forbid some options from showing up, they are useless for this ui function _M:checkGameOption(name) local list = table.reverse{"icons_temp_effects", "icons_hotkeys", "hotkeys_rows", "log_lines"} return not list[name] end function _M:resetPlaces() local w, h = core.display.size() local th = 52 if config.settings.tome.hotkey_icons then th = (8 + config.settings.tome.hotkey_icons_size) * config.settings.tome.hotkey_icons_rows end local hup = h - th self.places = { player = {x=0, y=0, scale=1, a=1}, resources = {x=0, y=111, scale=1, a=1}, minimap = {x=w - 239, y=0, scale=1, a=1}, buffs = {x=w - 40, y=200, scale=1, a=1}, party = {x=pf_bg[6], y=0, scale=1, a=1}, gamelog = {x=0, y=hup - 210, w=math.floor(w/2), h=200, scale=1, a=1}, chatlog = {x=math.floor(w/2), y=hup - 210, w=math.floor(w/2), h=200, scale=1, a=1}, mainicons = {x=w - tb_bg[6] * 0.5, y=h - tb_bg[7] * 6 * 0.5 - 5, scale=1, a=1}, hotkeys = {x=10, y=h - th, w=w-60, h=th, scale=1, a=1}, } end function _M:boundPlaces(w, h) w = w or game.w h = h or game.h for what, d in pairs(self.places) do if d.x then d.x = math.floor(d.x) d.y = math.floor(d.y) if d.w and d.h then d.scale = 1 d.x = util.bound(d.x, 0, w - d.w) d.y = util.bound(d.y, 0, h - d.h) elseif d.scale then d.scale = util.bound(d.scale, 0.5, 2) local mx, my = util.getval(self.mhandle_pos[what].x, self), util.getval(self.mhandle_pos[what].y, self) d.x = util.bound(d.x, -mx * d.scale, w - mx * d.scale - move_handle[6] * d.scale) d.y = util.bound(d.y, -my * d.scale, self.map_h_stop - my * d.scale - move_handle[7] * d.scale) end end end end function _M:saveSettings() self:boundPlaces() local lines = {} lines[#lines+1] = ("tome.uiset_minimalist = {}"):format() lines[#lines+1] = ("tome.uiset_minimalist.save_size = {w=%d, h=%d}"):format(game.w, game.h) lines[#lines+1] = ("tome.uiset_minimalist.places = {}"):format(w) for _, w in ipairs{"player", "resources", "party", "buffs", "minimap", "gamelog", "chatlog", "hotkeys", "mainicons"} do lines[#lines+1] = ("tome.uiset_minimalist.places.%s = {}"):format(w) if self.places[w] then for k, v in pairs(self.places[w]) do lines[#lines+1] = ("tome.uiset_minimalist.places.%s.%s = %f"):format(w, k, v) end end end self:triggerHook{"UISet:Minimalist:saveSettings", lines=lines} game:saveSettings("tome.uiset_minimalist", table.concat(lines, "\n")) end function _M:toggleUI() UISet.toggleUI(self) print("Toggling UI", self.no_ui) self:resizeIconsHotkeysToolbar() self.res = {} self.party = {} self.tbuff = {} self.pbuff = {} if game.level then self:setupMinimap(game.level) end game.player.changed = true end function _M:activate() Shader:setDefault("textoutline", "textoutline") local font, size = FontPackage:getFont("default") local font_mono, size_mono = FontPackage:getFont("mono_small", "mono") local font_mono_h, font_h local f = core.display.newFont(font, size) font_h = f:lineSkip() f = core.display.newFont(font_mono, size_mono) font_mono_h = f:lineSkip() self.init_font = font self.init_size_font = size self.init_font_h = font_h self.init_font_mono = font_mono self.init_size_mono = size_mono self.init_font_mono_h = font_mono_h self.buff_font = core.display.newFont(font_mono, size_mono * 2, true) self.buff_font_small = core.display.newFont(font_mono, size_mono * 1.4, true) self.buff_font_smaller = core.display.newFont(font_mono, size_mono * 1, true) self.hotkeys_display_text = HotkeysDisplay.new(nil, self.places.hotkeys.x, self.places.hotkeys.y, self.places.hotkeys.w, self.places.hotkeys.h, nil, font_mono, size_mono) self.hotkeys_display_text:enableShadow(0.6) self.hotkeys_display_text:setColumns(3) self:resizeIconsHotkeysToolbar() self.logdisplay = LogDisplay.new(0, 0, self.places.gamelog.w, self.places.gamelog.h, nil, font, size, nil, nil) self.logdisplay.resizeToLines = function() end self.logdisplay:enableShadow(1) self.logdisplay:enableFading(config.settings.tome.log_fade or 3) profile.chat:resize(0, 0, self.places.chatlog.w, self.places.chatlog.h, font, size, nil, nil) profile.chat.resizeToLines = function() profile.chat:resize(0 + (game.w) / 2, self.map_h_stop - font_h * config.settings.tome.log_lines -16, (game.w) / 2, font_h * config.settings.tome.log_lines) end profile.chat:enableShadow(1) profile.chat:enableFading(config.settings.tome.log_fade or 3) profile.chat:enableDisplayChans(false) self.npcs_display = ActorsSeenDisplay.new(nil, 0, game.h - font_mono_h * 4.2, game.w, font_mono_h * 4.2, "/data/gfx/ui/talents-list.png", font_mono, size_mono) self.npcs_display:setColumns(3) game.log = function(style, ...) if type(style) == "number" then game.uiset.logdisplay(...) else game.uiset.logdisplay(style, ...) end end game.logChat = function(style, ...) if true or not config.settings.tome.chat_log then return end if type(style) == "number" then local old = game.uiset.logdisplay.changed game.uiset.logdisplay(...) else game.uiset.logdisplay(style, ...) end if game.uiset.show_userchat then game.uiset.logdisplay.changed = old end end -- game.logSeen = function(e, style, ...) if e and e.player or (not e.dead and e.x and e.y and game.level and game.level.map.seens(e.x, e.y) and game.player:canSee(e)) then game.log(style, ...) end end game.logPlayer = function(e, style, ...) if e == game.player or e == game.party then game.log(style, ...) end end self:boundPlaces() end function _M:setupMinimap(level) level.map._map:setupMiniMapGridSize(3) end function _M:resizeIconsHotkeysToolbar() local h = 52 if config.settings.tome.hotkey_icons then h = (8 + config.settings.tome.hotkey_icons_size) * config.settings.tome.hotkey_icons_rows end local oldstop = self.map_h_stop_up or (game.h - h) self.map_h_stop = game.h self.map_h_stop_up = game.h - h self.map_h_stop_tooltip = self.map_h_stop_up if not self.hotkeys_display_icons then self.hotkeys_display_icons = HotkeysIconsDisplay.new(nil, self.places.hotkeys.x, self.places.hotkeys.y, self.places.hotkeys.w, self.places.hotkeys.h, nil, self.init_font_mono, self.init_size_mono, config.settings.tome.hotkey_icons_size, config.settings.tome.hotkey_icons_size) self.hotkeys_display_icons:enableShadow(0.6) else self.hotkeys_display_icons:resize(self.places.hotkeys.x, self.places.hotkeys.y, self.places.hotkeys.w, self.places.hotkeys.h, config.settings.tome.hotkey_icons_size, config.settings.tome.hotkey_icons_size) end if self.no_ui then self.map_h_stop = game.h game:resizeMapViewport(game.w, self.map_h_stop, 0, 0) self.logdisplay.display_y = self.logdisplay.display_y + self.map_h_stop_up - oldstop profile.chat.display_y = profile.chat.display_y + self.map_h_stop_up - oldstop game:setupMouse(true) return end if game.inited then game:resizeMapViewport(game.w, self.map_h_stop, 0, 0) self.logdisplay.display_y = self.logdisplay.display_y + self.map_h_stop_up - oldstop profile.chat.display_y = profile.chat.display_y + self.map_h_stop_up - oldstop game:setupMouse(true) end self.hotkeys_display = config.settings.tome.hotkey_icons and self.hotkeys_display_icons or self.hotkeys_display_text self.hotkeys_display.actor = game.player end function _M:handleResolutionChange(w, h, ow, oh) print("minimalist:handleResolutionChange: adjusting UI") -- what was the point of this recursive call? -- local w, h = core.display.size() -- game:setResolution(w.."x"..h, true) -- Adjust UI local w2, h2 = math.floor(ow / 2), math.floor(oh / 2) for what, d in pairs(self.places) do if d.x > w2 then d.x = d.x + w - ow end if d.y > h2 then d.y = d.y + h - oh end end print("minimalist:handleResolutionChange: toggling UI to refresh") -- Toggle the UI to refresh the changes self:toggleUI() self:toggleUI() self:boundPlaces() self:saveSettings() print("minimalist:handleResolutionChange: saved settings") return true end function _M:getMapSize() local w, h = core.display.size() return 0, 0, w, (self.map_h_stop or 80) - 16 end function _M:uiMoveResize(what, button, mx, my, xrel, yrel, bx, by, event, mode, on_change, add_text) if self.locked then return end mode = mode or "rescale" game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, self.mhandle_pos[what].name.."\n---\nLeft mouse drag&drop to move the frame\nRight mouse drag&drop to scale up/down\nMiddle click to reset to default scale"..(add_text or "")) if event == "button" and button == "middle" then self.places[what].scale = 1 self:saveSettings() elseif event == "motion" and button == "left" then self.ui_moving = what game.mouse:startDrag(mx, my, s, {kind="ui:move", id=what, dx=bx*self.places[what].scale, dy=by*self.places[what].scale}, function(drag, used) self:saveSettings() self.ui_moving = nil if on_change then on_change("move") end end, function(drag, _, x, y) if self.places[drag.payload.id] then self.places[drag.payload.id].x = x-drag.payload.dx self.places[drag.payload.id].y = y-drag.payload.dy self:boundPlaces() if on_change then on_change("move") end end end, true ) elseif event == "motion" and button == "right" then if mode == "rescale" then game.mouse:startDrag(mx, my, s, {kind="ui:rescale", id=what, bx=bx, by=by}, function(drag, used) self:saveSettings() if on_change then on_change(mode) end end, function(drag, _, x, y) if self.places[drag.payload.id] then self.places[drag.payload.id].scale = util.bound(math.max((x-self.places[drag.payload.id].x)/drag.payload.bx), 0.5, 2) self:boundPlaces() if on_change then on_change(mode) end end end, true ) elseif mode == "resize" and self.places[what] then game.mouse:startDrag(mx, my, s, {kind="ui:resize", id=what, ox=mx - (self.places[what].x + util.getval(self.mhandle_pos[what].x, self)), oy=my - (self.places[what].y + util.getval(self.mhandle_pos[what].y, self))}, function(drag, used) self:saveSettings() if on_change then on_change(mode) end end, function(drag, _, x, y) if self.places[drag.payload.id] then self.places[drag.payload.id].w = math.max(20, x - self.places[drag.payload.id].x + drag.payload.ox) self.places[drag.payload.id].h = math.max(20, y - self.places[drag.payload.id].y + drag.payload.oy) if on_change then on_change(mode) end end end, true ) end end end function _M:computePadding(what, x1, y1, x2, y2) self.sizes[what] = {} local size = self.sizes[what] if x2 < x1 then x1, x2 = x2, x1 end if y2 < y1 then y1, y2 = y2, y1 end size.x1 = x1 size.x2 = x2 size.y1 = y1 size.y2 = y2 -- This is Marson's code to make you not get stuck under UI elements -- I have tested and love it but I don't understand it very well, may be oversights --if config.settings.marson.view_scrolling == "No Hiding" then if x2 <= Map.viewport.width / 4 then Map.viewport_padding_4 = math.max(Map.viewport_padding_4, math.ceil(x2 / Map.tile_w)) end if x1 >= (Map.viewport.width / 4) * 3 then Map.viewport_padding_6 = math.max(Map.viewport_padding_6, math.ceil((Map.viewport.width - x1) / Map.tile_w)) end if y2 <= Map.viewport.height / 4 then Map.viewport_padding_8 = math.max(Map.viewport_padding_8, math.ceil(y2 / Map.tile_h)) end if y1 >= (Map.viewport.height / 4) * 3 then Map.viewport_padding_2 = math.max(Map.viewport_padding_2, math.ceil((Map.viewport.height - y1) / Map.tile_h)) end if x1 <= 0 then size.orient = "right" end if x2 >= Map.viewport.width then size.orient = "left" end if y1 <= 0 then size.orient = "down" end if y2 >= Map.viewport.height then size.orient = "up" end --[[ else if x1 <= 0 then Map.viewport_padding_4 = math.max(Map.viewport_padding_4, math.floor((x2 - x1) / Map.tile_w)) size.left = true end if x2 >= Map.viewport.width then Map.viewport_padding_6 = math.max(Map.viewport_padding_6, math.floor((x2 - x1) / Map.tile_w)) size.right = true end if y1 <= 0 then Map.viewport_padding_8 = math.max(Map.viewport_padding_8, math.floor((y2 - y1) / Map.tile_h)) size.top = true end if y2 >= Map.viewport.height then Map.viewport_padding_2 = math.max(Map.viewport_padding_2, math.floor((y2 - y1) / Map.tile_h)) size.bottom = true end if size.top then size.orient = "down" elseif size.bottom then size.orient = "up" elseif size.left then size.orient = "right" elseif size.right then size.orient = "left" end end --]] end function _M:showResourceTooltip(x, y, w, h, id, desc, is_first) if not game.mouse:updateZone(id, x, y, w, h, nil, self.places.resources.scale) then game.mouse:registerZone(x, y, w, h, function(button, mx, my, xrel, yrel, bx, by, event) if is_first then if event == "out" then self.mhandle.resources = nil return else self.mhandle.resources = true end -- Move handle if not self.locked and bx >= self.mhandle_pos.resources.x and bx <= self.mhandle_pos.resources.x + move_handle[6] and by >= self.mhandle_pos.resources.y and by <= self.mhandle_pos.resources.y + move_handle[7] then if event == "button" and button == "right" then local player = game.player local list = {} local rname for res, res_def in ipairs(ActorResource.resources_def) do rname = res_def.short_name if not res_def.hidden_resource and player:knowTalent(res_def.talent) then list[#list+1] = {name=res_def.name, id=rname} end end if player:knowTalent(player.T_FEEDBACK_POOL) then list[#list+1] = {name="Feedback", id="feedback"} end if player.is_fortress and player:hasQuest("shertul-fortress") then list[#list+1] = {name="Fortress Energy", id="fortress"} end Dialog:listPopup("Display/Hide resources", "Toggle:", list, 300, util.bound((8+#list)*(self.init_font_h+1), 14*(self.init_font_h+1), game.h*.75), function(sel) if not sel or not sel.id then return end game.player["_hide_resource_"..sel.id] = not game.player["_hide_resource_"..sel.id] end) return end self:uiMoveResize("resources", button, mx, my, xrel, yrel, bx, by, event, nil, nil, "\nRight click to toggle resources bars visibility") return end end local extra = {log_str=desc} game.mouse:delegate(button, mx, my, xrel, yrel, nil, nil, event, "playmap", extra) end, nil, id, true, self.places.resources.scale) end end function _M:resourceOrientStep(orient, bx, by, scale, x, y, w, h) if orient == "down" or orient == "up" then x = x + w if (x + w) * scale >= game.w - bx then x = 0 y = y + h end elseif orient == "right" or orient == "left" then y = y + h if (y + h) * scale >= self.map_h_stop - by then y = 0 x = x + w end end return x, y end function _M:displayResources(scale, bx, by, a) local player = game.player if player then local orient = self.sizes.resources and self.sizes.resources.orient or "right" local x, y = 0, 0 ----------------------------------------------------------------------------------- -- Air if player.air < player.max_air then sshat[1]:toScreenFull(x-6, y+8, sshat[6], sshat[7], sshat[2], sshat[3], 1, 1, 1, a) bshat[1]:toScreenFull(x, y, bshat[6], bshat[7], bshat[2], bshat[3], 1, 1, 1, a) if air_sha.shad then air_sha:setUniform("a", a) air_sha.shad:use(true) end local p = math.min(1, math.max(0, player:getAir() / player.max_air)) shat[1]:toScreenPrecise(x+49, y+10, shat[6] * p, shat[7], 0, p * 1/shat[4], 0, 1/shat[5], air_c[1], air_c[2], air_c[3], a) if air_sha.shad then air_sha.shad:use(false) end if not self.res.air or self.res.air.vc ~= player.air or self.res.air.vm ~= player.max_air or self.res.air.vr ~= player.air_regen then self.res.air = { vc = player.air, vm = player.max_air, vr = player.air_regen, cur = {core.display.drawStringBlendedNewSurface(font_sha, ("%d/%d"):format(player.air, player.max_air), 255, 255, 255):glTexture()}, regen={core.display.drawStringBlendedNewSurface(sfont_sha, ("%+0.2f"):format(player.air_regen), 255, 255, 255):glTexture()}, } end local dt = self.res.air.cur dt[1]:toScreenFull(2+x+64, 2+y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+64, y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) dt = self.res.air.regen dt[1]:toScreenFull(2+x+144, 2+y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+144, y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) local front = fshat_air_dark if player.air >= player.max_air * 0.5 then front = fshat_air end front[1]:toScreenFull(x, y, front[6], front[7], front[2], front[3], 1, 1, 1, a) self:showResourceTooltip(bx+x*scale, by+y*scale, fshat[6], fshat[7], "res:air", self.TOOLTIP_AIR) x, y = self:resourceOrientStep(orient, bx, by, scale, x, y, fshat[6], fshat[7]) elseif game.mouse:getZone("res:air") then game.mouse:unregisterZone("res:air") end ----------------------------------------------------------------------------------- -- Life & shield sshat[1]:toScreenFull(x-6, y+8, sshat[6], sshat[7], sshat[2], sshat[3], 1, 1, 1, a) bshat[1]:toScreenFull(x, y, bshat[6], bshat[7], bshat[2], bshat[3], 1, 1, 1, a) if life_sha.shad then life_sha:setUniform("a", a) life_sha.shad:use(true) end local p = math.min(1, math.max(0, player.life / player.max_life)) shat[1]:toScreenPrecise(x+49, y+10, shat[6] * p, shat[7], 0, p * 1/shat[4], 0, 1/shat[5], life_c[1], life_c[2], life_c[3], a) if life_sha.shad then life_sha.shad:use(false) end local life_regen = player.life_regen * util.bound((player.healing_factor or 1), 0, 2.5) if not self.res.life or self.res.life.vc ~= player.life or self.res.life.vm ~= player.max_life or self.res.life.vr ~= life_regen then local status_text = ("%s/%d"):format(player.life > 0 and math.round(player.life) or "???", math.round(player.max_life)) local reg_text = string.limit_decimals(life_regen,3, "+") self.res.life = { vc = player.life, vm = player.max_life, vr = life_regen, cur = {core.display.drawStringBlendedNewSurface(#status_text*1.1 + #reg_text <=14 and font_sha or sfont_sha, status_text, 255, 255, 255):glTexture()}, -- adjust font for space regen={core.display.drawStringBlendedNewSurface(sfont_sha, reg_text, 255, 255, 255):glTexture()}, } end local shield, max_shield = 0, 0 if player:attr("time_shield") then shield = shield + player.time_shield_absorb max_shield = max_shield + player.time_shield_absorb_max end if player:attr("damage_shield") then shield = shield + player.damage_shield_absorb max_shield = max_shield + player.damage_shield_absorb_max end if player:attr("displacement_shield") then shield = shield + player.displacement_shield max_shield = max_shield + player.displacement_shield_max end local front = fshat_life_dark if max_shield > 0 then front = fshat_shield_dark if shield >= max_shield * 0.8 then front = fshat_shield end elseif player.life >= player.max_life then front = fshat_life end front[1]:toScreenFull(x, y, front[6], front[7], front[2], front[3], 1, 1, 1, a) -- draw text on top of graphic for legibility local dt = self.res.life.cur dt[1]:toScreenFull(2+x+64, 2+y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+64, y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) dt = self.res.life.regen dt[1]:toScreenFull(2+x+144, 2+y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+144, y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) if max_shield > 0 then if shield_sha.shad then shield_sha:setUniform("a", a * 0.5) shield_sha.shad:use(true) end local p = math.min(1, math.max(0, shield / max_shield)) shat[1]:toScreenPrecise(x+49, y+10, shat[6] * p, shat[7], 0, p * 1/shat[4], 0, 1/shat[5], shield_c[1], shield_c[2], shield_c[3], 0.5 * a) if shield_sha.shad then shield_sha.shad:use(false) end if not self.res.shield or self.res.shield.vc ~= shield or self.res.shield.vm ~= max_shield then self.res.shield = { vc = shield, vm = max_shield, cur = {core.display.drawStringBlendedNewSurface(font_sha, ("%d/%d"):format(shield, max_shield), 255, 215, 0):glTexture()}, } end local dt = self.res.shield.cur dt[1]:toScreenFull(2+x+45+(shat[6]-dt[6])/2, 2+y+front[7]-dt[7], dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) -- shadow dt[1]:toScreenFull(x+45+(shat[6]-dt[6])/2, y+front[7]-dt[7], dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) self:showResourceTooltip(bx+x*scale, by+y*scale, fshat[6], fshat[7], "res:shield", self.TOOLTIP_DAMAGE_SHIELD.."\n---\n"..self.TOOLTIP_LIFE, true) if game.mouse:getZone("res:life") then game.mouse:unregisterZone("res:life") end else self:showResourceTooltip(bx+x*scale, by+y*scale, fshat[6], fshat[7], "res:life", self.TOOLTIP_LIFE, true) if game.mouse:getZone("res:shield") then game.mouse:unregisterZone("res:shield") end end x, y = self:resourceOrientStep(orient, bx, by, scale, x, y, fshat[6], fshat[7]) if not self.locked then move_handle[1]:toScreenFull(fshat[6] / 2 - move_handle[6], 0, move_handle[6], move_handle[7], move_handle[2], move_handle[3]) end -- Note: unnatural_body_heal not shown (difference from classic ui) -- display standard resources local vc, vn, vm, vr for res, res_def in ipairs(ActorResource.resources_def) do local rname = res_def.short_name local rgfx = self.res_gfx[rname] local rshad_args = rgfx.shader and rgfx.shader.args if not res_def.hidden_resource then if player:knowTalent(res_def.talent) and not player["_hide_resource_"..res_def.short_name] then sshat[1]:toScreenFull(x-6, y+8, sshat[6], sshat[7], sshat[2], sshat[3], 1, 1, 1, a) --shadow bshat[1]:toScreenFull(x, y, bshat[6], bshat[7], bshat[2], bshat[3], 1, 1, 1, a) --background vc, vn, vm, vr = player[res_def.getFunction](player), player[res_def.getMinFunction](player), player[res_def.getMaxFunction](player), player[res_def.regen_prop] -- draw the resource bar if rshad_args.display_resource_bar then -- use a resource-specific method rshad_args.display_resource_bar(player, rgfx.shader, x, y, rgfx.color, a) else -- use the default method, as fraction of maximum if rgfx.shader and rgfx.shader.shad then rgfx.shader:setUniform("a", a) rgfx.shader.shad:use(true) end local p -- proportion of resource bar to display if vn and vm then p = math.min(1, math.max(0, vc/vm)) else p = 1 end shat[1]:toScreenPrecise(x+49, y+10, shat[6] * p, shat[7], 0, p * 1/shat[4], 0, 1/shat[5], rgfx.color[1], rgfx.color[2], rgfx.color[3], a) if rgfx.shader and rgfx.shader.shad then rgfx.shader.shad:use(false) end end -- draw the resource graphic using the highlighted/dim resource display based on values local front = self.res_gfx[rname].front_dark if self.res_gfx[rname].highlight then if util.getval(self.res_gfx[rname].highlight, player, vc, vn, vm, vr) then front = self.res_gfx[rname].front end elseif vm and vc >= vm then front = self.res_gfx[rname].front end front[1]:toScreenFull(x, y, front[6], front[7], front[2], front[3], 1, 1, 1, a) -- update display values (draw text on top of graphics for legibility) if not self.res[rname] or self.res[rname].vc ~= vc or self.res[rname].vn ~= vn or self.res[rname].vm ~= vm or self.res[rname].vr ~= vr then local status_text = util.getval(res_def.status_text, player) or ("%d/%d"):format(vc, vm) status_text = (status_text):format() -- fully resolve format codes (%%) self.res[rname] = { hidable = rname:capitalize(), vc = vc, vn = vn, vm = vm, vr = vr, -- use smaller font if needed for room cur = {core.display.drawStringBlendedNewSurface(#status_text <=15 and font_sha or sfont_sha, status_text, 255, 255, 255):glTexture()}, -- only draw regen if it's non-zero and there is room regen = vr and vr ~= 0 and #status_text < 10 and {core.display.drawStringBlendedNewSurface(sfont_sha, string.limit_decimals(vr, 3, "+"), 255, 255, 255):glTexture()}, } end local dt = self.res[rname].cur dt[1]:toScreenFull(2+x+64, 2+y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+64, y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) dt = self.res[rname].regen if dt then dt[1]:toScreenFull(2+x+144, 2+y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+144, y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) end self:showResourceTooltip(bx+x*scale, by+y*scale, fshat[6], fshat[7], "res:"..rname, self.res_gfx[rname].tooltip) x, y = self:resourceOrientStep(orient, bx, by, scale, x, y, fshat[6], fshat[7]) elseif game.mouse:getZone("res:"..rname) then game.mouse:unregisterZone("res:"..rname) end end end ----------------------------------------------------------------------------------- -- Feedback -- pseudo resource if player.psionic_feedback_max and player:knowTalent(player.T_FEEDBACK_POOL) and not player._hide_resource_feedback then sshat[1]:toScreenFull(x-6, y+8, sshat[6], sshat[7], sshat[2], sshat[3], 1, 1, 1, a) bshat[1]:toScreenFull(x, y, bshat[6], bshat[7], bshat[2], bshat[3], 1, 1, 1, a) if feedback_sha.shad then feedback_sha:setUniform("a", a) feedback_sha.shad:use(true) end local p = player:getFeedback() / player:getMaxFeedback() shat[1]:toScreenPrecise(x+49, y+10, shat[6] * p, shat[7], 0, p * 1/shat[4], 0, 1/shat[5], feedback_c[1], feedback_c[2], feedback_c[3], a) if feedback_sha.shad then feedback_sha.shad:use(false) end local front = fshat_feedback_dark if player.psionic_feedback >= player.psionic_feedback_max then front = fshat_feedback end front[1]:toScreenFull(x, y, front[6], front[7], front[2], front[3], 1, 1, 1, a) if not self.res.feedback or self.res.feedback.vc ~= player:getFeedback() or self.res.feedback.vm ~= player:getMaxFeedback() or self.res.feedback.vr ~= player:getFeedbackDecay() then self.res.feedback = { hidable = "Feedback", vc = player:getFeedback(), vm = player:getMaxFeedback(), vr = player:getFeedbackDecay(), cur = {core.display.drawStringBlendedNewSurface(font_sha, ("%d/%d"):format(player:getFeedback(), player:getMaxFeedback()), 255, 255, 255):glTexture()}, regen={core.display.drawStringBlendedNewSurface(sfont_sha, ("%+0.2f"):format(-player:getFeedbackDecay()), 255, 255, 255):glTexture()}, } end local dt = self.res.feedback.cur dt[1]:toScreenFull(2+x+64, 2+y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+64, y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) dt = self.res.feedback.regen dt[1]:toScreenFull(2+x+144, 2+y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+144, y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) self:showResourceTooltip(bx+x*scale, by+y*scale, fshat[6], fshat[7], "res:feedback", self.TOOLTIP_FEEDBACK) x, y = self:resourceOrientStep(orient, bx, by, scale, x, y, fshat[6], fshat[7]) elseif game.mouse:getZone("res:feedback") then game.mouse:unregisterZone("res:feedback") end ----------------------------------------------------------------------------------- -- Fortress Energy -- special if player.is_fortress and not player._hide_resource_fortress then local q = game:getPlayer(true):hasQuest("shertul-fortress") sshat[1]:toScreenFull(x-6, y+8, sshat[6], sshat[7], sshat[2], sshat[3], 1, 1, 1, a) bshat[1]:toScreenFull(x, y, bshat[6], bshat[7], bshat[2], bshat[3], 1, 1, 1, a) local p = 100 / 100 if fortress_sha.shad then fortress_sha:setUniform("a", a) fortress_sha.shad:use(true) end shat[1]:toScreenPrecise(x+49, y+10, shat[6] * p, shat[7], 0, p * 1/shat[4], 0, 1/shat[5], fortress_c[1], fortress_c[2], fortress_c[3], a) if fortress_sha.shad then fortress_sha.shad:use(false) end local front = fshat_fortress front[1]:toScreenFull(x, y, front[6], front[7], front[2], front[3], 1, 1, 1, a) if not self.res.fortress or self.res.fortress.vc ~= q.shertul_energy then self.res.fortress = { hidable = "Fortress", vc = q.shertul_energy, cur = {core.display.drawStringBlendedNewSurface(font_sha, ("%d"):format(q.shertul_energy), 255, 255, 255):glTexture()}, } end local dt = self.res.fortress.cur dt[1]:toScreenFull(2+x+64, 2+y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+64, y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) self:showResourceTooltip(bx+x*scale, by+y*scale, fshat[6], fshat[7], "res:fortress", self.TOOLTIP_FORTRESS_ENERGY) x, y = self:resourceOrientStep(orient, bx, by, scale, x, y, fshat[6], fshat[7]) elseif game.mouse:getZone("res:fortress") then game.mouse:unregisterZone("res:fortress") end -- Any hooks? -- Use to display other pseudo resources or those with .hidden_resource set under special circumstances local hd = {"UISet:Minimalist:Resources", a=a, player=player, x=x, y=y, bx=bx, by=by, orient=orient, scale=scale} if self:triggerHook(hd) then x, y = hd.x, hd.y end ----------------------------------------------------------------------------------- -- Ammo local quiver = player:getInven("QUIVER") local ammo = quiver and quiver[1] if ammo then local amt, max = 0, 0 local shad, bg if ammo.type == "alchemist-gem" then shad, bg = _M["ammo_shadow_alchemist-gem"], _M["ammo_alchemist-gem"] amt = ammo:getNumber() else shad, bg = _M["ammo_shadow_"..ammo.subtype] or ammo_shadow_default, _M["ammo_"..ammo.subtype] or ammo_default amt, max = ammo.combat.shots_left, ammo.combat.capacity end shad[1]:toScreenFull(x, y, shad[6], shad[7], shad[2], shad[3], 1, 1, 1, a) bg[1]:toScreenFull(x, y, bg[6], bg[7], bg[2], bg[3], 1, 1, 1, a) if not self.res.ammo or self.res.ammo.vc ~= amt or self.res.ammo.vm ~= max then self.res.ammo = { vc = amt, vm = max, cur = {core.display.drawStringBlendedNewSurface(font_sha, max > 0 and ("%d/%d"):format(amt, max) or ("%d"):format(amt), 255, 255, 255):glTexture()}, } end local dt = self.res.ammo.cur dt[1]:toScreenFull(2+x+44, 2+y+3 + (bg[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+44, y+3 + (bg[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) self:showResourceTooltip(bx+x*scale, by+y*scale, shad[6], shad[7], "res:ammo", self.TOOLTIP_COMBAT_AMMO) x, y = self:resourceOrientStep(orient, bx, by, scale, x, y, fshat[6], fshat[7]) elseif game.mouse:getZone("res:ammo") then game.mouse:unregisterZone("res:ammo") end -- consider separating these from resources into their own frame ----------------------------------------------------------------------------------- -- Hourglass if game.level and game.level.turn_counter then sshat_hourglass[1]:toScreenFull(x-6, y+8, sshat_hourglass[6], sshat_hourglass[7], sshat_hourglass[2], sshat_hourglass[3], 1, 1, 1, a) local c = game.level.turn_counter local m = math.max(game.level.max_turn_counter, c) local p = 1 - c / m shat_hourglass_top[1]:toScreenPrecise(x+11, y+32 + shat_hourglass_top[7] * p, shat_hourglass_top[6], shat_hourglass_top[7] * (1-p), 0, 1/shat_hourglass_top[4], p/shat_hourglass_top[5], 1/shat_hourglass_top[5], save_c[1], save_c[2], save_c[3], a) shat_hourglass_bottom[1]:toScreenPrecise(x+12, y+72 + shat_hourglass_bottom[7] * (1-p), shat_hourglass_bottom[6], shat_hourglass_bottom[7] * p, 0, 1/shat_hourglass_bottom[4], (1-p)/shat_hourglass_bottom[5], 1/shat_hourglass_bottom[5], save_c[1], save_c[2], save_c[3], a) if not self.res.hourglass or self.res.hourglass.vc ~= c or self.res.hourglass.vm ~= m then self.res.hourglass = { vc = c, vm = m, cur = {core.display.drawStringBlendedNewSurface(font_sha, ("%d"):format(c/10), 255, 255, 255):glTexture()}, } end local front = fshat_hourglass local dt = self.res.hourglass.cur dt[1]:toScreenFull(2+x+(front[6]-dt[6])/2, 2+y+90, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+(front[6]-dt[6])/2, y+90, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) front[1]:toScreenFull(x, y, front[6], front[7], front[2], front[3], 1, 1, 1, a) self:showResourceTooltip(bx+x*scale, by+y*scale, front[6], front[7], "res:hourglass", game.level.turn_counter_desc or "") x, y = self:resourceOrientStep(orient, bx, by, scale, x, y, fshat[6], front[7]) elseif game.mouse:getZone("res:hourglass") then game.mouse:unregisterZone("res:hourglass") end ----------------------------------------------------------------------------------- -- Arena display if game.level and game.level.arena then local h = self.init_font_h + 2 if not self.arenaframe then self.arenaframe = UI:makeFrame("ui/textbox", 250, 7 + h * 6) UI:drawFrame(self.arenaframe, x, y, 1, 1, 1, 0.65) else UI:drawFrame(self.arenaframe, x, y, 1, 1, 1, 0.65) end local py = y + 2 local px = x + 5 local arena = game.level.arena local aprint = function (_x, _y, _text, r, g, b) local surf = { core.display.drawStringBlendedNewSurface(font_sha, _text, r, g, b):glTexture() } surf[1]:toScreenFull(_x, _y, surf[6], surf[7], surf[2], surf[3], 0, 0, 0, 0.7 * a) surf[1]:toScreenFull(_x, _y, surf[6], surf[7], surf[2], surf[3], 1, 1, 1, a) end if arena.score > world.arena.scores[1].score then aprint(px, py, ("Score[1st]: %d"):format(arena.score), 255, 255, 100) else aprint(px, py, ("Score: %d"):format(arena.score), 255, 255, 255) end local _event = "" if arena.event > 0 then if arena.event == 1 then _event = "[MiniBoss]" elseif arena.event == 2 then _event = "[Boss]" elseif arena.event == 3 then _event = "[Final]" end end py = py + h if arena.currentWave > world.arena.bestWave then aprint(px, py, ("Wave(TOP) %d %s"):format(arena.currentWave, _event), 255, 255, 100) elseif arena.currentWave > world.arena.lastScore.wave then aprint(px, py, ("Wave %d %s"):format(arena.currentWave, _event), 100, 100, 255) else aprint(px, py, ("Wave %d %s"):format(arena.currentWave, _event), 255, 255, 255) end py = py + h if arena.pinch == true then aprint(px, py, ("Bonus: %d (x%.1f)"):format(arena.bonus, arena.bonusMultiplier), 255, 50, 50) else aprint(px, py, ("Bonus: %d (x%.1f)"):format(arena.bonus, arena.bonusMultiplier), 255, 255, 255) end py = py + h if arena.display then aprint(px, py, arena.display[1], 255, 0, 255) aprint(px, py + h, " VS", 255, 0, 255) aprint(px, py + h + h, arena.display[2], 255, 0, 255) else aprint(px, py, "Rank: "..arena.printRank(arena.rank, arena.ranks), 255, 255, 255) end end ----------------------------------------------------------------------------------- -- Specific display for zone if game.zone and game.zone.specific_ui then local w, h = game.zone.specific_ui(self, game.zone, x, y) if w and h then self:showResourceTooltip(bx+x*scale, by+y*scale, w, h, "res:levelspec", "") x, y = self:resourceOrientStep(orient, bx, by, scale, x, y, w, h) end elseif game.mouse:getZone("res:levelspec") then game.mouse:unregisterZone("res:levelspec") end ----------------------------------------------------------------------------------- -- Saving if savefile_pipe.saving then sshat[1]:toScreenFull(x-6, y+8, sshat[6], sshat[7], sshat[2], sshat[3], 1, 1, 1, a) bshat[1]:toScreenFull(x, y, bshat[6], bshat[7], bshat[2], bshat[3], 1, 1, 1, a) if save_sha.shad then save_sha:setUniform("a", a) save_sha.shad:use(true) end local p = savefile_pipe.current_nb / savefile_pipe.total_nb shat[1]:toScreenPrecise(x+49, y+10, shat[6] * p, shat[7], 0, p * 1/shat[4], 0, 1/shat[5], save_c[1], save_c[2], save_c[3], a) if save_sha.shad then save_sha.shad:use(false) end if not self.res.save or self.res.save.vc ~= p then self.res.save = { vc = p, cur = {core.display.drawStringBlendedNewSurface(font_sha, ("Saving... %d%%"):format(p * 100), 255, 255, 255):glTexture()}, } end local dt = self.res.save.cur dt[1]:toScreenFull(2+x+64, 2+y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7 * a) dt[1]:toScreenFull(x+64, y+10 + (shat[7]-dt[7])/2, dt[6], dt[7], dt[2], dt[3], 1, 1, 1, a) local front = fshat front[1]:toScreenFull(x, y, front[6], front[7], front[2], front[3], 1, 1, 1, a) x, y = self:resourceOrientStep(orient, bx, by, scale, x, y, fshat[6], fshat[7]) end -- Compute how much space to reserve on the side self:computePadding("resources", bx, by, bx + (x + fshat[6]) * scale, by + y * scale) end end function _M:buffOrientStep(orient, bx, by, scale, x, y, w, h, next) if orient == "down" or orient == "up" then x = x + w if (x + w) * scale >= game.w - bx or next then x = 0 y = y + h * (orient == "down" and 1 or -1) end elseif orient == "right" or orient == "left" then y = y + h if (y + h) * scale >= self.map_h_stop - by or next then y = 0 x = x + w * (orient == "right" and 1 or -1) end end return x, y end function _M:handleEffect(player, eff_id, e, p, x, y, hs, bx, by, is_first, scale, allow_remove) local shader = Shader.default.textoutline and Shader.default.textoutline.shad local dur = p.dur + 1 local charges = e.charges and tostring(e.charges(player, p)) or "0" if not self.tbuff[eff_id..":"..dur..":"..charges] then local name = e.desc local desc = nil local eff_subtype = table.concat(table.keys(e.subtype), "/") if e.display_desc then name = e.display_desc(self, p) end if p.save_string and p.amount_decreased and p.maximum and p.total_dur then desc = ("#{bold}##GOLD#%s\n(%s: %s)#WHITE##{normal}#\n"):format(name, e.type, eff_subtype)..e.long_desc(player, p).." "..("%s reduced the duration of this effect by %d turns, from %d to %d."):format(p.save_string, p.amount_decreased, p.maximum, p.total_dur) else desc = ("#{bold}##GOLD#%s\n(%s: %s)#WHITE##{normal}#\n"):format(name, e.type, eff_subtype)..e.long_desc(player, p) end if allow_remove then desc = desc.."\n---\nRight click to cancel early." end local txt = nil local txt2 = nil if e.decrease > 0 then local font = e.charges and self.buff_font_small or self.buff_font dur = tostring(dur) txt = font:draw(dur, 40, colors.WHITE.r, colors.WHITE.g, colors.WHITE.b, true)[1] txt.fw, txt.fh = font:size(dur) end if e.charges then local font = e.decrease > 0 and self.buff_font_small or self.buff_font txt2 = font:draw(charges, 40, colors.WHITE.r, colors.WHITE.g, colors.WHITE.b, true)[1] txt2.fw, txt2.fh = font:size(charges) dur = dur..":"..charges end local icon = e.status ~= "detrimental" and frames_colors.ok or frames_colors.cooldown local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if is_first then if event == "out" then self.mhandle.buffs = nil return else self.mhandle.buffs = true end -- Move handle if not self.locked and bx >= self.mhandle_pos.buffs.x and bx <= self.mhandle_pos.buffs.x + move_handle[6] and by >= self.mhandle_pos.buffs.y and by <= self.mhandle_pos.buffs.y + move_handle[7] then self:uiMoveResize("buffs", button, mx, my, xrel, yrel, bx, by, event) end end if config.settings.cheat and event == "button" and core.key.modState("shift") then if button == "left" then p.dur = p.dur + 1 elseif button == "right" then p.dur = p.dur - 1 end elseif allow_remove and event == "button" and button == "right" then Dialog:yesnoPopup(name, "Really cancel "..name.."?", function(ret) if ret then player:removeEffect(eff_id) end end) end game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, desc) end local flash = 0 if p.__set_time and p.__set_time >= self.now - 500 then flash = 5 end self.tbuff[eff_id..":"..dur..":"..charges] = {eff_id, "tbuff"..eff_id, function(x, y) core.display.drawQuad(x+4, y+4, 32, 32, 0, 0, 0, 255) e.display_entity:toScreen(self.hotkeys_display_icons.tiles, x+4, y+4, 32, 32) if e.get_fractional_percent then core.display.drawQuadPart(x +4 , y + 4, 32, 32, e.get_fractional_percent(self, p), 128, 128, 128, 200) end UI:drawFrame(self.buffs_base, x, y, icon[1], icon[2], icon[3], 1) if txt and not txt2 then if shader then shader:use(true) shader:uniOutlineSize(1, 1) shader:uniTextSize(txt._tex_w, txt._tex_h) else txt._tex:toScreenFull(x+4+2 + (32 - txt.fw)/2, y+4+2 + (32 - txt.fh)/2, txt.w, txt.h, txt._tex_w, txt._tex_h, 0, 0, 0, 0.7) end txt._tex:toScreenFull(x+4 + (32 - txt.fw)/2, y+4 + (32 - txt.fh)/2, txt.w, txt.h, txt._tex_w, txt._tex_h) elseif not txt and txt2 then if shader then shader:use(true) shader:uniOutlineSize(1, 1) shader:uniTextSize(txt2._tex_w, txt2._tex_h) else txt2._tex:toScreenFull(x+4+2, y+4+2 + (32 - txt2.fh)/2+5, txt2.w, txt2.h, txt2._tex_w, txt2._tex_h, 0, 0, 0, 0.7) end txt2._tex:toScreenFull(x+4, y+4 + (32 - txt2.fh)/2+5, txt2.w, txt2.h, txt2._tex_w, txt2._tex_h, 0, 1, 0, 1) elseif txt and txt2 then if shader then shader:use(true) shader:uniOutlineSize(1, 1) shader:uniTextSize(txt._tex_w, txt._tex_h) else txt._tex:toScreenFull(x+4+2 + (32 - txt.fw), y+4+2 + (32 - txt.fh)/2-5, txt.w, txt.h, txt._tex_w, txt._tex_h, 0, 0, 0, 0.7) end txt._tex:toScreenFull(x+4 + (32 - txt.fw), y+4 + (32 - txt.fh)/2-5, txt.w, txt.h, txt._tex_w, txt._tex_h) if shader then shader:uniOutlineSize(1, 1) shader:uniTextSize(txt2._tex_w, txt2._tex_h) else txt2._tex:toScreenFull(x+4+2, y+4+2 + (32 - txt2.fh)/2+5, txt2.w, txt2.h, txt2._tex_w, txt2._tex_h, 0, 0, 0, 0.7) end txt2._tex:toScreenFull(x+4, y+4 + (32 - txt2.fh)/2+5, txt2.w, txt2.h, txt2._tex_w, txt2._tex_h, 0, 1, 0, 1) end if shader and (txt or txt2) then shader:use(false) end if flash > 0 then if e.status ~= "detrimental" then core.display.drawQuad(x+4, y+4, 32, 32, 0, 255, 0, 170 - flash * 30) else core.display.drawQuad(x+4, y+4, 32, 32, 255, 0, 0, 170 - flash * 30) end flash = flash - 1 end end, desc_fct} end if not game.mouse:updateZone("tbuff"..eff_id, bx+x*scale, by+y*scale, hs, hs, self.tbuff[eff_id..":"..dur..":"..charges][4], scale) then game.mouse:unregisterZone("tbuff"..eff_id) game.mouse:registerZone(bx+x*scale, by+y*scale, hs, hs, self.tbuff[eff_id..":"..dur..":"..charges][4], nil, "tbuff"..eff_id, true, scale) end self.tbuff[eff_id..":"..dur..":"..charges][3](x, y) end function _M:displayBuffs(scale, bx, by) local player = game.player local shader = Shader.default.textoutline and Shader.default.textoutline.shad if player then if player.changed then for _, d in pairs(self.pbuff) do if not player.sustain_talents[d[1]] then game.mouse:unregisterZone(d[2]) end end for _, d in pairs(self.tbuff) do if not player.tmp[d[1]] then game.mouse:unregisterZone(d[2]) end end self.tbuff = {} self.pbuff = {} end local orient = self.sizes.buffs and self.sizes.buffs.orient or "right" local hs = 40 local x, y = 0, 0 local is_first = true for tid, act in pairs(player.sustain_talents) do if act then if not self.pbuff[tid] or act.__update_display then local t = player:getTalentFromId(tid) if act.__update_display then game.mouse:unregisterZone("pbuff"..tid) end act.__update_display = false local displayName = t.name if t.getDisplayName then displayName = t.getDisplayName(player, t, player:isTalentActive(tid)) end local overlay = nil if t.iconOverlay then overlay = {} overlay.fct = function(x, y, overlay) local o, fnt = t.iconOverlay(player, t, act) if not overlay.txt or overlay.str ~= o then overlay.str = o local font = self[fnt or "buff_font_small"] txt = font:draw(o, 40, colors.WHITE.r, colors.WHITE.g, colors.WHITE.b, true)[1] txt.fw, txt.fh = font:size(o) overlay.txt = txt end local txt = overlay.txt if shader then shader:use(true) shader:uniOutlineSize(1, 1) shader:uniTextSize(txt._tex_w, txt._tex_h) else txt._tex:toScreenFull(x+4+2 + (32 - txt.fw)/2, y+4+2 + (32 - txt.fh)/2, txt.w, txt.h, txt._tex_w, txt._tex_h, 0, 0, 0, 0.7) end txt._tex:toScreenFull(x+4 + (32 - txt.fw)/2, y+4 + (32 - txt.fh)/2, txt.w, txt.h, txt._tex_w, txt._tex_h) if shader then shader:use(false) end end end local is_first = is_first local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if is_first then if event == "out" then self.mhandle.buffs = nil return else self.mhandle.buffs = true end -- Move handle if not self.locked and bx >= self.mhandle_pos.buffs.x and bx <= self.mhandle_pos.buffs.x + move_handle[6] and by >= self.mhandle_pos.buffs.y and by <= self.mhandle_pos.buffs.y + move_handle[7] then self:uiMoveResize("buffs", button, mx, my, xrel, yrel, bx, by, event) end end local desc = "#GOLD##{bold}#"..displayName.."#{normal}##WHITE#\n"..tostring(player:getTalentFullDescription(t)) game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, desc) end self.pbuff[tid] = {tid, "pbuff"..tid, function(x, y) core.display.drawQuad(x+4, y+4, 32, 32, 0, 0, 0, 255) t.display_entity:toScreen(self.hotkeys_display_icons.tiles, x+4, y+4, 32, 32) if overlay then overlay.fct(x, y, overlay) end UI:drawFrame(self.buffs_base, x, y, frames_colors.sustain[1], frames_colors.sustain[2], frames_colors.sustain[3], 1) end, desc_fct} end if not game.mouse:updateZone("pbuff"..tid, bx+x*scale, by+y*scale, hs, hs, nil, scale) then game.mouse:unregisterZone("pbuff"..tid) game.mouse:registerZone(bx+x*scale, by+y*scale, hs, hs, self.pbuff[tid][4], nil, "pbuff"..tid, true, scale) end self.pbuff[tid][3](x, y) is_first = false x, y = self:buffOrientStep(orient, bx, by, scale, x, y, hs, hs) end end local good_e, bad_e = {}, {} for eff_id, p in pairs(player.tmp) do local e = player.tempeffect_def[eff_id] if e.status == "detrimental" then bad_e[eff_id] = p else good_e[eff_id] = p end end for eff_id, p in pairs(good_e) do local e = player.tempeffect_def[eff_id] self:handleEffect(player, eff_id, e, p, x, y, hs, bx, by, is_first, scale, (e.status == "beneficial") or config.settings.cheat) is_first = false x, y = self:buffOrientStep(orient, bx, by, scale, x, y, hs, hs) end x, y = self:buffOrientStep(orient, bx, by, scale, x, y, hs, hs, true) for eff_id, p in pairs(bad_e) do local e = player.tempeffect_def[eff_id] self:handleEffect(player, eff_id, e, p, x, y, hs, bx, by, is_first, scale, config.settings.cheat) is_first = false x, y = self:buffOrientStep(orient, bx, by, scale, x, y, hs, hs) end if not self.locked then move_handle[1]:toScreenFull(40 - move_handle[6], 0, move_handle[6], move_handle[7], move_handle[2], move_handle[3]) end if orient == "down" or orient == "up" then self:computePadding("buffs", bx, by, bx + x * scale + hs, by + hs) else self:computePadding("buffs", bx, by, bx + hs, by + y * scale + hs) end end end function _M:partyOrientStep(orient, bx, by, scale, x, y, w, h) if orient == "down" or orient == "up" then x = x + w if (x + w) * scale >= game.w - bx then x = 0 y = y + h end elseif orient == "right" or orient == "left" then y = y + h if (y + h) * scale >= self.map_h_stop - by then y = 0 x = x + w end end return x, y end function _M:displayParty(scale, bx, by) if game.player.changed and next(self.party) then for a, d in pairs(self.party) do if not game.party:hasMember(a) then game.mouse:unregisterZone(d[2]) end end self.party = {} end -- Party members if #game.party.m_list >= 2 and game.level then local orient = self.sizes.party and self.sizes.party.orient or "down" local hs = portrait[7] + 3 local x, y = 0, 0 local is_first = true for i = 1, #game.party.m_list do local a = game.party.m_list[i] if not self.party[a] then local def = game.party.members[a] local text = "#GOLD##{bold}#"..a.name.."\n#WHITE##{normal}#Life: "..math.floor(100 * a.life / a.max_life).."%\nLevel: "..a.level.."\n"..def.title if a.summon_time then text = text.."\nTurns remaining: "..a.summon_time end local is_first = is_first local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if is_first then if event == "out" then self.mhandle.party = nil return else self.mhandle.party = true end -- Move handle if not self.locked and bx >= self.mhandle_pos.party.x and bx <= self.mhandle_pos.party.x + move_handle[6] and by >= self.mhandle_pos.party.y and by <= self.mhandle_pos.party.y + move_handle[7] then self:uiMoveResize("party", button, mx, my, xrel, yrel, bx, by, event) return end end game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, text) if event == "button" and button == "left" then if def.control == "full" then game.party:select(a) elseif def.orders then game.party:giveOrders(a) end elseif event == "button" and button == "right" then if def.orders then game.party:giveOrders(a) end end end self.party[a] = {a, "party"..a.uid, function(x, y) core.display.drawQuad(x, y, 40, 40, 0, 0, 0, 255) if life_sha.shad then life_sha.shad:use(true) end local p = math.min(1, math.max(0, a.life / a.max_life)) core.display.drawQuad(x+1, y+1 + (1-p)*hs, 38, p*38, life_c[1]*255, life_c[2]*255, life_c[3]*255, 178) if life_sha.shad then life_sha.shad:use(false) end local scale, bx, by = self.places.party.scale, self.places.party.x, self.places.party.y core.display.glScissor(true, bx+x*scale, by+y*scale, 40*scale, 40*scale) a:toScreen(nil, x+4, y+4, 32, 32) core.display.glScissor(false) local p = (game.player == a) and portrait or portrait_unsel if a.unused_stats > 0 or a.unused_talents > 0 or a.unused_generics > 0 or a.unused_talents_types > 0 and def.control == "full" then p = (game.player == a) and portrait_lev or portrait_unsel_lev end p[1]:toScreenFull(x, y, p[6], p[7], p[2], p[3]) -- Display turns remaining on summon's portrait — Marson if a.summon_time and a.name ~= "shadow" then local gtxt = self.party[a].txt_summon_time if not gtxt or self.party[a].cur_summon_time ~= a.summon_time then local txt = tostring(a.summon_time) local fw, fh = self.buff_font_small:size(txt) self.party[a].txt_summon_time = self.buff_font_small:draw(txt, fw, colors.WHITE.r, colors.WHITE.g, colors.WHITE.b, true)[1] gtxt = self.party[a].txt_summon_time gtxt.fw, gtxt.fh = fw, fh self.party[a].cur_summon_time = a.summon_time end if shader then shader:use(true) shader:uniOutlineSize(0.7, 0.7) shader:uniTextSize(gtxt._tex_w, gtxt._tex_h) else gtxt._tex:toScreenFull(x-gtxt.fw+36+1, y-2+1, gtxt.w, gtxt.h, gtxt._tex_w, gtxt._tex_h, 0, 0, 0, self.shadow or 0.6) end gtxt._tex:toScreenFull(x-gtxt.fw+36, y-2, gtxt.w, gtxt.h, gtxt._tex_w, gtxt._tex_h) if shader then shader:use(false) end end end, desc_fct} end if not game.mouse:updateZone("party"..a.uid, bx+x*scale, by+y*scale, hs, hs, self.party[a][4], scale) then game.mouse:unregisterZone("party"..a.uid) game.mouse:registerZone(bx+x*scale, by+y*scale, hs, hs, self.party[a][4], nil, "party"..a.uid, true, scale) end self.party[a][3](x, y) is_first = false x, y = self:partyOrientStep(orient, bx, by, scale, x, y, hs, hs) end if not self.locked then move_handle[1]:toScreenFull(portrait[6] - move_handle[6], 0, move_handle[6], move_handle[7], move_handle[2], move_handle[3]) end self:computePadding("party", bx, by, bx + x * scale, by + y * scale) end end function _M:displayPlayer(scale, bx, by) local player = game.player if not game.player then return end pf_shadow[1]:toScreenFull(0, 0, pf_shadow[6], pf_shadow[7], pf_shadow[2], pf_shadow[3]) pf_bg[1]:toScreenFull(pf_bg_x, pf_bg_y, pf_bg[6], pf_bg[7], pf_bg[2], pf_bg[3]) core.display.glScissor(true, bx+15*scale, by+15*scale, 54*scale, 54*scale) player:toScreen(nil, 22 + pf_player_x, 22 + pf_player_y, 40, 40) core.display.glScissor(false) if (not config.settings.tome.actor_based_movement_mode and self or player).bump_attack_disabled then pf_defend[1]:toScreenFull(22 + pf_attackdefend_x, 67 + pf_attackdefend_y, pf_defend[6], pf_defend[7], pf_defend[2], pf_defend[3]) else pf_attack[1]:toScreenFull(22 + pf_attackdefend_x, 67 + pf_attackdefend_y, pf_attack[6], pf_attack[7], pf_attack[2], pf_attack[3]) end if player.unused_stats > 0 or player.unused_talents > 0 or player.unused_generics > 0 or player.unused_talents_types > 0 then local glow = (1+math.sin(core.game.getTime() / 500)) / 2 * 100 + 120 pf_levelup[1]:toScreenFull(269 + pf_levelup_x, 78 + pf_levelup_y, pf_levelup[6], pf_levelup[7], pf_levelup[2], pf_levelup[3], 1, 1, 1, glow / 255) pf_exp_levelup[1]:toScreenFull(108 + pf_exp_x, 74 + pf_exp_y, pf_exp_levelup[6], pf_exp_levelup[7], pf_exp_levelup[2], pf_exp_levelup[3], 1, 1, 1, glow / 255) end local cur_exp, max_exp = player.exp, player:getExpChart(player.level+1) local p = math.min(1, math.max(0, cur_exp / max_exp)) pf_exp[1]:toScreenPrecise(117 + pf_exp_x, 85 + pf_exp_y, pf_exp[6] * p, pf_exp[7], 0, p * 1/pf_exp[4], 0, 1/pf_exp[5]) if not self.res.exp or self.res.exp.vc ~= p then self.res.exp = { vc = p, cur = {core.display.drawStringBlendedNewSurface(sfont_sha, ("%d%%"):format(p * 100), 255, 255, 255):glTexture()}, } end local dt = self.res.exp.cur dt[1]:toScreenFull(pf_exp_cur_x + 2+87 - dt[6] / 2, pf_exp_cur_y + 2+89 - dt[7] / 2, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7) dt[1]:toScreenFull(pf_exp_cur_x + 87 - dt[6] / 2, pf_exp_cur_y + 89 - dt[7] / 2, dt[6], dt[7], dt[2], dt[3]) if not self.res.money or self.res.money.vc ~= player.money then self.res.money = { vc = player.money, cur = {core.display.drawStringBlendedNewSurface(font_sha, ("%d"):format(player.money), 255, 215, 0):glTexture()}, } end local dt = self.res.money.cur dt[1]:toScreenFull(pf_money_x + 2+112 - dt[6] / 2, pf_money_y + 2+43, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7) dt[1]:toScreenFull(pf_money_x + 112 - dt[6] / 2, pf_money_y + 43, dt[6], dt[7], dt[2], dt[3]) if not self.res.pname or self.res.pname.vc ~= player.name then self.res.pname = { vc = player.name, cur = {core.display.drawStringBlendedNewSurface(font_sha, player.name, 255, 255, 255):glTexture()}, } end local dt = self.res.pname.cur dt[1]:toScreenFull(pf_name_x + 2+166, pf_name_y + 2+13, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7) dt[1]:toScreenFull(pf_name_x + 166, pf_name_y + 13, dt[6], dt[7], dt[2], dt[3]) if not self.res.plevel or self.res.plevel.vc ~= player.level then self.res.plevel = { vc = player.level, cur = {core.display.drawStringBlendedNewSurface(font_sha, "Lvl "..player.level, 255, 255, 255):glTexture()}, } end local dt = self.res.plevel.cur dt[1]:toScreenFull(pf_level_x + 2+253, pf_level_y + 2+46, dt[6], dt[7], dt[2], dt[3], 0, 0, 0, 0.7) dt[1]:toScreenFull(pf_level_x + 253, pf_level_y + 46, dt[6], dt[7], dt[2], dt[3]) if player:attr("encumbered") then local glow = (1+math.sin(core.game.getTime() / 500)) / 2 * 100 + 120 pf_encumber[1]:toScreenFull(162, 38, pf_encumber[6], pf_encumber[7], pf_encumber[2], pf_encumber[3], 1, 1, 1, glow / 255) end if not self.locked then move_handle[1]:toScreenFull(self.mhandle_pos.player.x, self.mhandle_pos.player.y, move_handle[6], move_handle[7], move_handle[2], move_handle[3]) end if not game.mouse:updateZone("pframe", bx, by, pf_bg[6], pf_bg[7], nil, scale) then game.mouse:unregisterZone("pframe") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.mhandle.player = nil return else self.mhandle.player = true end -- Attack/defend if bx >= 22 and bx <= 22 + pf_defend[6] and by >= 67 and by <= 67 + pf_defend[7] then game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, "Toggle for movement mode.\nDefault: when trying to move onto a creature it will attack if hostile.\nPassive: when trying to move onto a creature it will not attack (use ctrl+direction, or right click to attack manually)") if event == "button" and button == "left" then game.key:triggerVirtual("TOGGLE_BUMP_ATTACK") end -- Character sheet elseif bx >= 22 and bx <= 22 + 40 and by >= 22 and by <= 22 + 40 then game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, "Show character infos") if event == "button" and button == "left" then game.key:triggerVirtual("SHOW_CHARACTER_SHEET") end -- Levelup elseif bx >= 269 and bx <= 269 + pf_levelup[6] and by >= 78 and by <= 78 + pf_levelup[7] and (player.unused_stats > 0 or player.unused_talents > 0 or player.unused_generics > 0 or player.unused_talents_types > 0) then game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, "Click to assign stats and talents!") if event == "button" and button == "left" then game.key:triggerVirtual("LEVELUP") end -- Move handle elseif not self.locked and bx >= self.mhandle_pos.player.x and bx <= self.mhandle_pos.player.x + move_handle[6] and by >= self.mhandle_pos.player.y and by <= self.mhandle_pos.player.y + move_handle[7] then self:uiMoveResize("player", button, mx, my, xrel, yrel, bx, by, event) else game.mouse:delegate(button, mx, my, xrel, yrel, nil, nil, event, "playmap", nil) end end game.mouse:registerZone(bx, by, pf_bg[6], pf_bg[7], desc_fct, nil, "pframe", true, scale) end -- Compute how much space to reserve on the side self:computePadding("player", bx, by, bx + pf_bg[6] * scale, by + pf_bg[7] * scale) end function _M:displayMinimap(scale, bx, by) if self.no_minimap then game.mouse:unregisterZone("minimap") return end local map = game.level.map mm_shadow[1]:toScreenFull(0, 2, mm_shadow[6], mm_shadow[7], mm_shadow[2], mm_shadow[3]) mm_bg[1]:toScreenFull(mm_bg_x, mm_bg_y, mm_bg[6], mm_bg[7], mm_bg[2], mm_bg[3]) if game.player.x then game.minimap_scroll_x, game.minimap_scroll_y = util.bound(game.player.x - 25, 0, map.w - 50), util.bound(game.player.y - 25, 0, map.h - 50) else game.minimap_scroll_x, game.minimap_scroll_y = 0, 0 end map:minimapDisplay(50 - mm_bg_x, 30 - mm_bg_y, game.minimap_scroll_x, game.minimap_scroll_y, 50, 50, 0.85) mm_transp[1]:toScreenFull(50 - mm_bg_x, 30 - mm_bg_y, mm_transp[6], mm_transp[7], mm_transp[2], mm_transp[3]) mm_comp[1]:toScreenFull(169, 178, mm_comp[6], mm_comp[7], mm_comp[2], mm_comp[3]) if not self.locked then move_handle[1]:toScreenFull(self.mhandle_pos.minimap.x, self.mhandle_pos.minimap.y, move_handle[6], move_handle[7], move_handle[2], move_handle[3]) end if not game.mouse:updateZone("minimap", bx, by, mm_bg[6], mm_bg[7], nil, scale) then game.mouse:unregisterZone("minimap") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.mhandle.minimap = nil return else self.mhandle.minimap = true end if self.no_minimap then return end game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, "Left mouse to move\nRight mouse to scroll\nMiddle mouse to show full map") -- Move handle if not self.locked and bx >= self.mhandle_pos.minimap.x and bx <= self.mhandle_pos.minimap.x + move_handle[6] and by >= self.mhandle_pos.minimap.y and by <= self.mhandle_pos.minimap.y + move_handle[7] then self:uiMoveResize("minimap", button, mx, my, xrel, yrel, bx, by, event) return end if bx >= 50 and bx <= 50 + 150 and by >= 30 and by <= 30 + 150 then if button == "left" and not xrel and not yrel and event == "button" then local tmx, tmy = math.floor((bx-50) / 3), math.floor((by-30) / 3) game.player:mouseMove(tmx + game.minimap_scroll_x, tmy + game.minimap_scroll_y) elseif button == "right" then local tmx, tmy = math.floor((bx-50) / 3), math.floor((by-30) / 3) game.level.map:moveViewSurround(tmx + game.minimap_scroll_x, tmy + game.minimap_scroll_y, 1000, 1000) elseif event == "button" and button == "middle" then game.key:triggerVirtual("SHOW_MAP") end end end game.mouse:registerZone(bx, by, mm_bg[6], mm_bg[7], desc_fct, nil, "minimap", true, scale) end game.zone_name_s:toScreenFull( (mm_bg[6] - game.zone_name_w) / 2, 0, game.zone_name_w, game.zone_name_h, game.zone_name_tw, game.zone_name_th ) -- Compute how much space to reserve on the side self:computePadding("minimap", bx, by, bx + mm_bg[6] * scale, by + (mm_bg[7] + game.zone_name_h) * scale) end function _M:displayGameLog(scale, bx, by) local log = self.logdisplay if not self.locked then core.display.drawQuad(0, 0, log.w, log.h, 0, 0, 0, 60) end local ox, oy = log.display_x, log.display_y log.display_x, log.display_y = 0, 0 log:toScreen() log.display_x, log.display_y = ox, oy if not self.locked then move_handle[1]:toScreenFull(util.getval(self.mhandle_pos.gamelog.x, self), util.getval(self.mhandle_pos.gamelog.y, self), move_handle[6], move_handle[7], move_handle[2], move_handle[3]) end if not game.mouse:updateZone("gamelog", bx, by, log.w, log.h, nil, scale) then game.mouse:unregisterZone("gamelog") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.mhandle.gamelog = nil return else self.mhandle.gamelog = true end -- Move handle local mhx, mhy = util.getval(self.mhandle_pos.gamelog.x, self), util.getval(self.mhandle_pos.gamelog.y, self) if not self.locked and bx >= mhx and bx <= mhx + move_handle[6] and by >= mhy and by <= mhy + move_handle[7] then self:uiMoveResize("gamelog", button, mx, my, xrel, yrel, bx, by, event, "resize", function(mode) log:resize(self.places.gamelog.x, self.places.gamelog.x, self.places.gamelog.w, self.places.gamelog.h) log:display() log:resetFade() end) return end log:mouseEvent(button, mx, my, xrel, yrel, bx, by, event) end game.mouse:registerZone(bx, by, log.w, log.h, desc_fct, nil, "gamelog", true, scale) end end function _M:displayChatLog(scale, bx, by) local log = profile.chat if not self.locked then core.display.drawQuad(0, 0, log.w, log.h, 0, 0, 0, 60) end local ox, oy = log.display_x, log.display_y log.display_x, log.display_y = 0, 0 log:toScreen() log.display_x, log.display_y = ox, oy if not self.locked then move_handle[1]:toScreenFull(util.getval(self.mhandle_pos.chatlog.x, self), util.getval(self.mhandle_pos.chatlog.y, self), move_handle[6], move_handle[7], move_handle[2], move_handle[3]) end if not game.mouse:updateZone("chatlog", bx, by, log.w, log.h, nil, scale) then game.mouse:unregisterZone("chatlog") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.mhandle.chatlog = nil return else self.mhandle.chatlog = true end -- Move handle local mhx, mhy = util.getval(self.mhandle_pos.chatlog.x, self), util.getval(self.mhandle_pos.chatlog.y, self) if not self.locked and bx >= mhx and bx <= mhx + move_handle[6] and by >= mhy and by <= mhy + move_handle[7] then self:uiMoveResize("chatlog", button, mx, my, xrel, yrel, bx, by, event, "resize", function(mode) log:resize(self.places.chatlog.x, self.places.chatlog.y, self.places.chatlog.w, self.places.chatlog.h) log:resetFade() end) return end profile.chat:mouseEvent(button, mx, my, xrel, yrel, bx, by, event) end game.mouse:registerZone(bx, by, log.w, log.h, desc_fct, nil, "chatlog", true, scale) end end function _M:displayHotkeys(scale, bx, by) local hkeys = self.hotkeys_display local ox, oy = hkeys.display_x, hkeys.display_y hk5[1]:toScreenFull(0, 0, self.places.hotkeys.w, self.places.hotkeys.h, hk5[2], hk5[3]) hk8[1]:toScreenFull(0, -hk8[7], self.places.hotkeys.w, hk8[7], hk8[2], hk8[3]) hk2[1]:toScreenFull(0, self.places.hotkeys.h, self.places.hotkeys.w, hk2[7], hk2[2], hk2[3]) hk4[1]:toScreenFull(-hk4[6], 0, hk4[6], self.places.hotkeys.h, hk4[2], hk4[3]) hk6[1]:toScreenFull(self.places.hotkeys.w, 0, hk6[6], self.places.hotkeys.h, hk6[2], hk6[3]) hk7[1]:toScreenFull(-hk7[6], -hk7[6], hk7[6], hk7[7], hk7[2], hk7[3]) hk9[1]:toScreenFull(self.places.hotkeys.w, -hk9[6], hk9[6], hk9[7], hk9[2], hk9[3]) hk1[1]:toScreenFull(-hk7[6], self.places.hotkeys.h, hk1[6], hk1[7], hk1[2], hk1[3]) hk3[1]:toScreenFull(self.places.hotkeys.w, self.places.hotkeys.h, hk3[6], hk3[7], hk3[2], hk3[3]) hkeys.orient = self.sizes.hotkeys and self.sizes.hotkeys.orient or "down" hkeys.display_x, hkeys.display_y = 0, 0 hkeys:toScreen() hkeys.display_x, hkeys.display_y = ox, oy if not self.locked then move_handle[1]:toScreenFull(util.getval(self.mhandle_pos.hotkeys.x, self), util.getval(self.mhandle_pos.hotkeys.y, self), move_handle[6], move_handle[7], move_handle[2], move_handle[3]) end if not game.mouse:updateZone("hotkeys", bx, by, self.places.hotkeys.w, self.places.hotkeys.h, nil, scale) then game.mouse:unregisterZone("hotkeys") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.mhandle.hotkeys = nil self.hotkeys_display.cur_sel = nil return else self.mhandle.hotkeys = true end -- Move handle local mhx, mhy = util.getval(self.mhandle_pos.hotkeys.x, self), util.getval(self.mhandle_pos.hotkeys.y, self) if not self.locked and bx >= mhx and bx <= mhx + move_handle[6] and by >= mhy and by <= mhy + move_handle[7] then self:uiMoveResize("hotkeys", button, mx, my, xrel, yrel, bx, by, event, "resize", function(mode) hkeys:resize(self.places.hotkeys.x, self.places.hotkeys.y, self.places.hotkeys.w, self.places.hotkeys.h) end) return end if event == "button" and button == "left" and ((game.zone and game.zone.wilderness and not game.player.allow_talents_worldmap) or (game.key ~= game.normal_key)) then return end self.hotkeys_display:onMouse(button, mx, my, event == "button", function(text) text = text:toTString() text:add(true, "---", true, {"font","italic"}, {"color","GOLD"}, "Left click to use", true, "Right click to configure", true, "Press 'm' to setup", {"color","LAST"}, {"font","normal"}) game:tooltipDisplayAtMap(game.w, game.h, text) end, function(i, hk) if button == "right" and hk and hk[1] == "talent" then local d = require("mod.dialogs.UseTalents").new(game.player) d:use({talent=hk[2], name=game.player:getTalentFromId(hk[2]).name}, "right") return true elseif button == "right" and hk and hk[1] == "inventory" then Dialog:yesnoPopup("Unbind "..hk[2], "Remove this object from your hotkeys?", function(ret) if ret then for i = 1, 12 * game.player.nb_hotkey_pages do if game.player.hotkey[i] and game.player.hotkey[i][1] == "inventory" and game.player.hotkey[i][2] == hk[2] then game.player.hotkey[i] = nil end end end end) return true end end ) end game.mouse:registerZone(bx, by, self.places.hotkeys.w, self.places.hotkeys.h, desc_fct, nil, "hotkeys", true, scale) end -- Compute how much space to reserve on the side self:computePadding("hotkeys", bx, by, bx + hkeys.w * scale, by + hkeys.h * scale) end function _M:toolbarOrientStep(orient, bx, by, scale, x, y, w, h) if orient == "down" or orient == "up" then x = x + w if (x + w) * scale >= game.w - bx then x = 0 y = y + h end elseif orient == "right" or orient == "left" then y = y + h if (y + h) * scale >= self.map_h_stop - by then y = 0 x = x + w end end return x, y end function _M:displayToolbar(scale, bx, by) -- Toolbar icons local x, y = 0, 0 local orient = self.sizes.mainicons and self.sizes.mainicons.orient or "down" tb_bg[1]:toScreenFull (x, y, tb_bg[6], tb_bg[7], tb_bg[2], tb_bg[3], 1, 1, 1, 1) tb_inven[1]:toScreenFull (x, y, tb_inven[6], tb_inven[7], tb_inven[2], tb_inven[3], self.tbbuttons.inven, self.tbbuttons.inven, self.tbbuttons.inven, 1) if not game.mouse:updateZone("tb_inven", bx + x * scale, by +y*scale, tb_inven[6], tb_inven[7], nil, scale) then game.mouse:unregisterZone("tb_inven") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.tbbuttons.inven = 0.6 return else self.tbbuttons.inven = 1 end game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, "Left mouse to show inventory") if button == "left" and not xrel and not yrel and event == "button" then game.key:triggerVirtual("SHOW_INVENTORY") end end game.mouse:registerZone(bx + x * scale, by +y*scale, tb_inven[6], tb_inven[7], desc_fct, nil, "tb_inven", true, scale) end x, y = self:toolbarOrientStep(orient, bx, by, scale, x, y, tb_bg[6], tb_bg[7]) tb_bg[1]:toScreenFull (x, y, tb_bg[6], tb_bg[7], tb_bg[2], tb_bg[3], 1, 1, 1, 1) tb_talents[1]:toScreenFull (x, y, tb_talents[6], tb_talents[7], tb_talents[2], tb_talents[3], self.tbbuttons.talents, self.tbbuttons.talents, self.tbbuttons.talents, 1) if not game.mouse:updateZone("tb_talents", bx + x * scale, by +y*scale, tb_talents[6], tb_talents[7], nil, scale) then game.mouse:unregisterZone("tb_talents") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.tbbuttons.talents = 0.6 return else self.tbbuttons.talents = 1 end game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, "Left mouse to show known talents") if button == "left" and not xrel and not yrel and event == "button" then game.key:triggerVirtual("USE_TALENTS") end end game.mouse:registerZone(bx + x * scale, by +y*scale, tb_talents[6], tb_talents[7], desc_fct, nil, "tb_talents", true, scale) end x, y = self:toolbarOrientStep(orient, bx, by, scale, x, y, tb_bg[6], tb_bg[7]) tb_bg[1]:toScreenFull (x, y, tb_bg[6], tb_bg[7], tb_bg[2], tb_bg[3], 1, 1, 1, 1) tb_quest[1]:toScreenFull (x, y, tb_quest[6], tb_quest[7], tb_quest[2], tb_quest[3], self.tbbuttons.quest, self.tbbuttons.quest, self.tbbuttons.quest, 1) if not game.mouse:updateZone("tb_quest", bx + x * scale, by +y*scale, tb_quest[6], tb_quest[7], nil, scale) then game.mouse:unregisterZone("tb_quest") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.tbbuttons.quest = 0.6 return else self.tbbuttons.quest = 1 end game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, "Left mouse to show message/chat log.") if button == "left" and not xrel and not yrel and event == "button" then game.key:triggerVirtual("SHOW_MESSAGE_LOG") end end game.mouse:registerZone(bx + x * scale, by +y*scale, tb_quest[6], tb_quest[7], desc_fct, nil, "tb_quest", true, scale) end x, y = self:toolbarOrientStep(orient, bx, by, scale, x, y, tb_bg[6], tb_bg[7]) tb_bg[1]:toScreenFull (x, y, tb_bg[6], tb_bg[7], tb_bg[2], tb_bg[3], 1, 1, 1, 1) tb_lore[1]:toScreenFull (x, y, tb_lore[6], tb_lore[7], tb_lore[2], tb_lore[3], self.tbbuttons.lore, self.tbbuttons.lore, self.tbbuttons.lore, 1) if not game.mouse:updateZone("tb_lore", bx + x * scale, by +y*scale, tb_lore[6], tb_lore[7], nil, scale) then game.mouse:unregisterZone("tb_lore") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.tbbuttons.lore = 0.6 return else self.tbbuttons.lore = 1 end game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, "Left mouse to show quest log.\nRight mouse to show all known lore.") if button == "left" and not xrel and not yrel and event == "button" then game.key:triggerVirtual("SHOW_QUESTS") elseif button == "right" and not xrel and not yrel and event == "button" then game:registerDialog(require("mod.dialogs.ShowLore").new("Tales of Maj'Eyal Lore", game.party)) end end game.mouse:registerZone(bx + x * scale, by +y*scale, tb_lore[6], tb_lore[7], desc_fct, nil, "tb_lore", true, scale) end x, y = self:toolbarOrientStep(orient, bx, by, scale, x, y, tb_bg[6], tb_bg[7]) tb_bg[1]:toScreenFull (x, y, tb_bg[6], tb_bg[7], tb_bg[2], tb_bg[3], 1, 1, 1, 1) tb_mainmenu[1]:toScreenFull (x, y, tb_mainmenu[6], tb_mainmenu[7], tb_mainmenu[2], tb_mainmenu[3], self.tbbuttons.mainmenu, self.tbbuttons.mainmenu, self.tbbuttons.mainmenu, 1) if not game.mouse:updateZone("tb_mainmenu", bx + x * scale, by + y*scale, tb_mainmenu[6], tb_mainmenu[7], nil, scale) then game.mouse:unregisterZone("tb_mainmenu") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.tbbuttons.mainmenu = 0.6 return else self.tbbuttons.mainmenu = 1 end game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, "Left mouse to show main menu") if button == "left" and not xrel and not yrel and event == "button" then game.key:triggerVirtual("EXIT") end end game.mouse:registerZone(bx + x * scale, by +y*scale, tb_mainmenu[6], tb_mainmenu[7], desc_fct, nil, "tb_mainmenu", true, scale) end x, y = self:toolbarOrientStep(orient, bx, by, scale, x, y, tb_bg[6], tb_bg[7]) local padlock = self.locked and tb_padlock_closed or tb_padlock_open tb_bg[1]:toScreenFull (x, y, tb_bg[6], tb_bg[7], tb_bg[2], tb_bg[3], 1, 1, 1, 1) padlock[1]:toScreenFull (x, y, padlock[6], padlock[7], padlock[2], padlock[3], self.tbbuttons.padlock, self.tbbuttons.padlock, self.tbbuttons.padlock, 1) if not game.mouse:updateZone("padlock", bx + x * scale, by +y*scale, padlock[6], padlock[7], nil, scale) then game.mouse:unregisterZone("padlock") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) if event == "out" then self.tbbuttons.padlock = 0.6 return else self.tbbuttons.padlock = 1 end game.tooltip_x, game.tooltip_y = 1, 1; game:tooltipDisplayAtMap(game.w, game.h, self.locked and "Unlock all interface elements so they can be moved and resized." or "Lock all interface elements so they can not be moved nor resized.") if button == "left" and not xrel and not yrel and event == "button" then self:switchLocked() end end game.mouse:registerZone(bx + x * scale, by +y*scale, padlock[6], padlock[7], desc_fct, nil, "padlock", true, scale) end x, y = self:toolbarOrientStep(orient, bx, by, scale, x, y, tb_bg[6], tb_bg[7]) -- Any hooks local hd = {"UISet:Minimalist:Toolbar", x=x, y=y, bx=bx, by=by, orient=orient, scale=scale, tb_bg=tb_bg} if self:triggerHook(hd) then x, y = hd.x, hd.y end local mhx, mhy = util.getval(self.mhandle_pos.mainicons.x, self), util.getval(self.mhandle_pos.mainicons.y, self) if not self.locked then move_handle[1]:toScreenFull(mhx, mhy, move_handle[6], move_handle[7], move_handle[2], move_handle[3]) end if not game.mouse:updateZone("tb_handle", bx + mhx * scale, by + mhy * scale, move_handle[6], move_handle[7], nil, scale) then game.mouse:unregisterZone("tb_handle") local desc_fct = function(button, mx, my, xrel, yrel, bx, by, event) -- Move handle if not self.locked then self:uiMoveResize("mainicons", button, mx, my, xrel, yrel, bx+mhx*scale, by+mhy*scale, event) return end end game.mouse:registerZone(bx + mhx * scale, by + mhy * scale, move_handle[6], move_handle[7], desc_fct, nil, "tb_handle", true, scale) end -- Compute how much space to reserve on the side self:computePadding("mainicons", bx, by, bx + x * scale, by + y * scale) end function _M:display(nb_keyframes) local d = core.display self.now = core.game.getTime() -- Now the map, if any game:displayMap(nb_keyframes) if game.creating_player then return end if self.no_ui then return end Map.viewport_padding_4 = 0 Map.viewport_padding_6 = 0 Map.viewport_padding_8 = 0 Map.viewport_padding_2 = 0 -- Game log d.glTranslate(self.places.gamelog.x, self.places.gamelog.y, 0) self:displayGameLog(1, self.places.gamelog.x, self.places.gamelog.y) d.glTranslate(-self.places.gamelog.x, -self.places.gamelog.y, -0) -- Chat log d.glTranslate(self.places.chatlog.x, self.places.chatlog.y, 0) self:displayChatLog(1, self.places.chatlog.x, self.places.chatlog.y) d.glTranslate(-self.places.chatlog.x, -self.places.chatlog.y, -0) -- Minimap display if game.level and game.level.map then d.glTranslate(self.places.minimap.x, self.places.minimap.y, 0) d.glScale(self.places.minimap.scale, self.places.minimap.scale, self.places.minimap.scale) self:displayMinimap(self.places.minimap.scale, self.places.minimap.x, self.places.minimap.y) d.glScale() d.glTranslate(-self.places.minimap.x, -self.places.minimap.y, -0) end -- Player d.glTranslate(self.places.player.x, self.places.player.y, 0) d.glScale(self.places.player.scale, self.places.player.scale, self.places.player.scale) self:displayPlayer(self.places.player.scale, self.places.player.x, self.places.player.y) d.glScale() d.glTranslate(-self.places.player.x, -self.places.player.y, -0) -- Resources d.glTranslate(self.places.resources.x, self.places.resources.y, 0) d.glScale(self.places.resources.scale, self.places.resources.scale, self.places.resources.scale) self:displayResources(self.places.resources.scale, self.places.resources.x, self.places.resources.y, 1) d.glScale() d.glTranslate(-self.places.resources.x, -self.places.resources.y, -0) -- Buffs d.glTranslate(self.places.buffs.x, self.places.buffs.y, 0) d.glScale(self.places.buffs.scale, self.places.buffs.scale, self.places.buffs.scale) self:displayBuffs(self.places.buffs.scale, self.places.buffs.x, self.places.buffs.y) d.glScale() d.glTranslate(-self.places.buffs.x, -self.places.buffs.y, -0) -- Party d.glTranslate(self.places.party.x, self.places.party.y, 0) d.glScale(self.places.party.scale, self.places.party.scale, self.places.party.scale) self:displayParty(self.places.party.scale, self.places.party.x, self.places.party.y) d.glScale() d.glTranslate(-self.places.party.x, -self.places.party.y, -0) -- Hotkeys d.glTranslate(self.places.hotkeys.x, self.places.hotkeys.y, 0) self:displayHotkeys(1, self.places.hotkeys.x, self.places.hotkeys.y) d.glTranslate(-self.places.hotkeys.x, -self.places.hotkeys.y, -0) -- Main icons d.glTranslate(self.places.mainicons.x, self.places.mainicons.y, 0) d.glScale(self.places.mainicons.scale * 0.5, self.places.mainicons.scale * 0.5, self.places.mainicons.scale * 0.5) self:displayToolbar(self.places.mainicons.scale * 0.5, self.places.mainicons.x, self.places.mainicons.y) d.glScale() d.glTranslate(-self.places.mainicons.x, -self.places.mainicons.y, -0) -- Display border indicators when possible if self.ui_moving and self.sizes[self.ui_moving] then local size = self.sizes[self.ui_moving] d.glTranslate(Map.display_x, Map.display_y, 0) if size.left then d.drawQuad(0, 0, 10, Map.viewport.height, 0, 200, 0, 50) end if size.right then d.drawQuad(Map.viewport.width - 10, 0, 10, Map.viewport.height, 0, 200, 0, 50) end if size.top then d.drawQuad(0, 0, Map.viewport.width, 10, 0, 200, 0, 50) end if size.bottom then d.drawQuad(0, Map.viewport.height - 10, Map.viewport.width, 10, 0, 200, 0, 50) end d.glTranslate(-Map.display_x, -Map.display_y, -0) end UISet.display(self, nb_keyframes) end function _M:setupMouse(mouse) -- Log tooltips self.logdisplay:onMouse(function(item, sub_es, button, event, x, y, xrel, yrel, bx, by) local mx, my = core.mouse.get() if ((not item or not sub_es or #sub_es == 0) and (not item or not item.url)) or (item and item.faded == 0) then game.mouse:delegate(button, mx, my, xrel, yrel, nil, nil, event, "playmap") return end local tooltips = {} if sub_es then for i, e in ipairs(sub_es) do if e.tooltip then local t = e:tooltip() if t then table.append(tooltips, t) end if i < #sub_es then table.append(tooltips, { tstring{ true, "---" } } ) else table.append(tooltips, { tstring{ true } } ) end end end end if item.url then table.append(tooltips, tstring{"Clicking will open ", {"color", "LIGHT_BLUE"}, {"font", "italic"}, item.url, {"color", "WHITE"}, {"font", "normal"}, " in your browser"}) end local extra = {} extra.log_str = tooltips game.tooltip.old_ttmx = -100 game.mouse:delegate(button, mx, my, xrel, yrel, nil, nil, event, "playmap", extra) end) -- Chat tooltips profile.chat:onMouse(function(user, item, button, event, x, y, xrel, yrel, bx, by) local mx, my = core.mouse.get() if not item or not user or item.faded == 0 then game.mouse:delegate(button, mx, my, xrel, yrel, nil, nil, event, "playmap") return end local str = tstring{{"color","GOLD"}, {"font","bold"}, user.name, {"color","LAST"}, {"font","normal"}, true} if (user.donator and user.donator ~= "none") or (user.status and user.status == 'dev') then local text, color = "Donator", colors.WHITE if user.status and user.status == 'dev' then text, color = "Developer", colors.CRIMSON elseif user.status and user.status == 'mod' then text, color = "Moderator / Helper", colors.GOLD elseif user.donator == "oneshot" then text, color = "Donator", colors.LIGHT_GREEN elseif user.donator == "recurring" then text, color = "Recurring Donator", colors.LIGHT_BLUE end str:add({"color",unpack(colors.simple(color))}, text, {"color", "LAST"}, true) end str:add({"color","ANTIQUE_WHITE"}, "Playing: ", {"color", "LAST"}, user.current_char, true) str:add({"color","ANTIQUE_WHITE"}, "Game: ", {"color", "LAST"}, user.module, "(", user.valid, ")",true) if item.url then str:add(true, "---", true, "Clicking will open ", {"color", "LIGHT_BLUE"}, {"font", "italic"}, item.url, {"color", "WHITE"}, {"font", "normal"}, " in your browser") end local extra = {} if item.extra_data and item.extra_data.mode == "tooltip" then local rstr = tstring{item.extra_data.tooltip, true, "---", true, "Linked by: "} rstr:merge(str) extra.log_str = rstr else extra.log_str = str if button == "right" and event == "button" then extra.add_map_action = { { name="Show chat user", fct=function() profile.chat:showUserInfo(user.login) end }, { name="Whisper", fct=function() profile.chat:setCurrentTarget(false, user.login) profile.chat:talkBox() end }, { name="Ignore", fct=function() Dialog:yesnoPopup("Ignore user", "Really ignore all messages from: "..user.login, function(ret) if ret then profile.chat:ignoreUser(user.login) end end) end }, { name="Report user for bad behavior", fct=function() game:registerDialog(require('engine.dialogs.GetText').new("Reason to report: "..user.login, "Reason", 4, 500, function(text) profile.chat:reportUser(user.login, text) game.log("#VIOLET#", "Report sent.") end)) end }, } if profile.chat:isFriend(user.login) then table.insert(extra.add_map_action, 3, { name="Remove Friend", fct=function() Dialog:yesnoPopup("Remove Friend", "Really remove "..user.login.." from your friends?", function(ret) if ret then profile.chat:removeFriend(user.login, user.id) end end) end }) else table.insert(extra.add_map_action, 3, { name="Add Friend", fct=function() Dialog:yesnoPopup("Add Friend", "Really add "..user.login.." to your friends?", function(ret) if ret then profile.chat:addFriend(user.login, user.id) end end) end }) end end end game.tooltip.old_tmx = -100 game.mouse:delegate(button, mx, my, xrel, yrel, nil, nil, event, "playmap", extra) end) end
gpl-3.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/general/objects/egos/charms.lua
1
1895
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org newEntity{ name = "quick ", prefix=true, keywords = {quick=true}, level_range = {1, 50}, rarity = 15, cost = 5, resolvers.genericlast(function(e) if not e.use_power or not e.charm_power then return end e.use_power.power = math.ceil(e.use_power.power * rng.float(0.6, 0.8)) e.charm_power = math.ceil(e.charm_power * rng.float(0.4, 0.7)) end), } newEntity{ name = "supercharged ", prefix=true, keywords = {['super.c']=true}, level_range = {1, 50}, rarity = 15, cost = 5, resolvers.genericlast(function(e) if not e.use_power or not e.charm_power then return end e.use_power.power = math.ceil(e.use_power.power * rng.float(1.2, 1.5)) e.charm_power = math.ceil(e.charm_power * rng.float(1.3, 1.5)) end), } newEntity{ name = "overpowered ", prefix=true, keywords = {['overpower']=true}, level_range = {30, 50}, greater_ego = 1, rarity = 16, cost = 5, resolvers.genericlast(function(e) if not e.use_power or not e.charm_power then return end e.use_power.power = math.ceil(e.use_power.power * rng.float(1.4, 1.7)) e.charm_power = math.ceil(e.charm_power * rng.float(1.6, 1.9)) end), }
gpl-3.0
moteus/lzmq
examples/perf/remote_lat.lua
16
2160
-- Copyright (c) 2010 Aleksey Yeschenko <aleksey@yeschenko.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. if not arg[3] then print("usage: lua remote_lat.lua <connect-to> <message-size> <roundtrip-count>") os.exit() end local connect_to = arg[1] local message_size = tonumber(arg[2]) local roundtrip_count = tonumber(arg[3]) local zmq = require"lzmq" local assert = zmq.assert local ctx = zmq.init(1) local s = ctx:socket(zmq.REQ) assert(s:set_sndhwm(roundtrip_count + 1)) assert(s:set_rcvhwm(roundtrip_count + 1)) assert(s:connect(connect_to)) local data = ("0"):rep(message_size) local msg = zmq.msg_init_size(message_size) zmq.utils.sleep(1) local timer = zmq.utils.stopwatch():start() for i = 1, roundtrip_count do assert(s:send_msg(msg)) assert(s:recv_msg(msg)) assert(msg:size() == message_size, "Invalid message size") end local elapsed = timer:stop() s:close() ctx:term() local latency = elapsed / roundtrip_count / 2 print(string.format("message size: %i [B]", message_size)) print(string.format("roundtrip count: %i", roundtrip_count)) print(string.format("mean latency: %.3f [us]", latency))
mit
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/quests/wild-wild-east.lua
1
1058
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org -- Explore the far east name = "The wild wild east" desc = function(self, who) local desc = {} desc[#desc+1] = "There must be a way to go into the far east from the lair of Golbug. Find it and explore the unknown far east, looking for clues." return table.concat(desc, "\n") end
gpl-3.0
LuaDist2/lua-nucleo
lua-nucleo/timed_queue.lua
3
2062
-------------------------------------------------------------------------------- --- Queue of objects sorted by time -- @module lua-nucleo.times_queue -- This file is a part of lua-nucleo library -- @copyright lua-nucleo authors (see file `COPYRIGHT` for the license) -------------------------------------------------------------------------------- local math_huge = math.huge -------------------------------------------------------------------------------- local arguments, method_arguments = import 'lua-nucleo/args.lua' { 'arguments', 'method_arguments' } local make_priority_queue = import 'lua-nucleo/priority_queue.lua' { 'make_priority_queue' } -------------------------------------------------------------------------------- local make_timed_queue do local insert = function(self, expiration_time, value) method_arguments( self, "number", expiration_time ) assert(expiration_time >= 0, "negative time is not supported") assert(expiration_time ~= math_huge, "infinite time is not supported") assert(value ~= nil) -- TODO: Need *arguments metatype for that self.priority_queue_:insert(expiration_time, value) end -- TODO: Batch element removal? local pop_next_expired = function(self, time_current) method_arguments( self, "number", time_current ) local time_of_first_elem = (self.priority_queue_:front()) if time_of_first_elem and time_of_first_elem <= time_current then return self.priority_queue_:pop() end return nil end local get_next_expiration_time = function(self) method_arguments( self ) return (self.priority_queue_:front()) or math_huge end make_timed_queue = function() return { insert = insert; pop_next_expired = pop_next_expired; get_next_expiration_time = get_next_expiration_time; -- priority_queue_ = make_priority_queue(); } end end return { make_timed_queue = make_timed_queue; }
mit
hexahedronic/basewars
basewars_free/gamemode/client/cl_druglab.lua
2
1826
local grayTop = Color(128, 128, 128, 250) local grayBottom = Color(96, 96, 96, 250) surface.CreateFont("DrugLab.GUI", { font = "Roboto", size = 24, weight = 800, }) local function RequestCook( ent, drug ) net.Start( "BaseWars.DrugLab.Menu" ) net.WriteEntity( ent ) net.WriteString( drug ) net.SendToServer() end local function Menu( ent ) local Frame = vgui.Create( "DFrame" ) Frame:SetSize( 900, 600 ) Frame:Center() Frame:SetTitle( "Drug Lab" ) Frame:MakePopup() function Frame:Paint(w, h) draw.RoundedBoxEx(8, 0, 0, w, 24, grayTop, true, true, false, false) draw.RoundedBox(0, 0, 24, w, h - 24, grayBottom) end local List = vgui.Create( "DPanelList", Frame ) List:EnableHorizontal(false) List:EnableVerticalScrollbar(true) List:SetPadding(5) List:SetSpacing(5) List:Dock(FILL) for k, v in pairs( BaseWars.Config.Drugs ) do if k == "CookTime" then continue end local Panel = vgui.Create( "DPanel", List ) Panel:SetSize( 100, 75 ) local Label = vgui.Create( "DLabel", Panel ) Label:SetPos( 80, 5 ) Label:SetFont( "DrugLab.GUI" ) Label:SetTextColor( Color( 130, 130, 130 ) ) Label:SetText( k ) Label:SizeToContents() local Item = vgui.Create( "SpawnIcon", Panel ) Item:SetPos( 6, 6 ) Item:SetSize( 64, 64 ) Item:SetModel( "models/props_junk/PopCan01a.mdl" ) Item:SetTooltip( "Drug: " .. k ) function Item:DoClick() RequestCook( ent, k ) Frame:Close() end List:AddItem( Panel ) end end net.Receive( "BaseWars.DrugLab.Menu", function( len ) Menu( net.ReadEntity() ) end )
mit
kuoruan/lede-luci
modules/luci-mod-admin-mini/luasrc/controller/mini/index.lua
74
1261
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.mini.index", package.seeall) function index() local root = node() if not root.lock then root.target = alias("mini") root.index = true end entry({"about"}, template("about")) local page = entry({"mini"}, alias("mini", "index"), _("Essentials"), 10) page.sysauth = "root" page.sysauth_authenticator = "htmlauth" page.index = true entry({"mini", "index"}, alias("mini", "index", "index"), _("Overview"), 10).index = true entry({"mini", "index", "index"}, form("mini/index"), _("General"), 1).ignoreindex = true entry({"mini", "index", "luci"}, cbi("mini/luci", {autoapply=true}), _("Settings"), 10) entry({"mini", "index", "logout"}, call("action_logout"), _("Logout")) end function action_logout() local dsp = require "luci.dispatcher" local utl = require "luci.util" if dsp.context.authsession then utl.ubus("session", "destroy", { ubus_rpc_session = dsp.context.authsession }) dsp.context.urltoken.stok = nil end luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url()) luci.http.redirect(luci.dispatcher.build_url()) end
apache-2.0
HandsomeCharming/RPG
Cocos2dx/frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Animate3D.lua
6
1692
-------------------------------- -- @module Animate3D -- @extend ActionInterval -- @parent_module cc -------------------------------- -- @function [parent=#Animate3D] setSpeed -- @param self -- @param #float float -------------------------------- -- @function [parent=#Animate3D] setWeight -- @param self -- @param #float float -------------------------------- -- @function [parent=#Animate3D] getSpeed -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Animate3D] getWeight -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @overload self, cc.Animation3D, float, float -- @overload self, cc.Animation3D -- @function [parent=#Animate3D] create -- @param self -- @param #cc.Animation3D animation3d -- @param #float float -- @param #float float -- @return Animate3D#Animate3D ret (retunr value: cc.Animate3D) -------------------------------- -- @function [parent=#Animate3D] startWithTarget -- @param self -- @param #cc.Node node -------------------------------- -- @function [parent=#Animate3D] step -- @param self -- @param #float float -------------------------------- -- @function [parent=#Animate3D] clone -- @param self -- @return Animate3D#Animate3D ret (return value: cc.Animate3D) -------------------------------- -- @function [parent=#Animate3D] reverse -- @param self -- @return Animate3D#Animate3D ret (return value: cc.Animate3D) -------------------------------- -- @function [parent=#Animate3D] update -- @param self -- @param #float float return nil
gpl-2.0
Tristramg/osrm-backend
profiles/testbot.lua
69
3444
-- Testbot profile -- Moves at fixed, well-known speeds, practical for testing speed and travel times: -- Primary road: 36km/h = 36000m/3600s = 100m/10s -- Secondary road: 18km/h = 18000m/3600s = 100m/20s -- Tertiary road: 12km/h = 12000m/3600s = 100m/30s -- modes: -- 1: normal -- 2: route -- 3: river downstream -- 4: river upstream -- 5: steps down -- 6: steps up speed_profile = { ["primary"] = 36, ["secondary"] = 18, ["tertiary"] = 12, ["steps"] = 6, ["default"] = 24 } -- these settings are read directly by osrm take_minimum_of_speeds = true obey_oneway = true obey_barriers = true use_turn_restrictions = true ignore_areas = true -- future feature traffic_signal_penalty = 7 -- seconds u_turn_penalty = 20 function limit_speed(speed, limits) -- don't use ipairs(), since it stops at the first nil value for i=1, #limits do limit = limits[i] if limit ~= nil and limit > 0 then if limit < speed then return limit -- stop at first speedlimit that's smaller than speed end end end return speed end function node_function (node, result) local traffic_signal = node:get_value_by_key("highway") if traffic_signal and traffic_signal == "traffic_signals" then result.traffic_lights = true; -- TODO: a way to set the penalty value end end function way_function (way, result) local highway = way:get_value_by_key("highway") local name = way:get_value_by_key("name") local oneway = way:get_value_by_key("oneway") local route = way:get_value_by_key("route") local duration = way:get_value_by_key("duration") local maxspeed = tonumber(way:get_value_by_key ( "maxspeed")) local maxspeed_forward = tonumber(way:get_value_by_key( "maxspeed:forward")) local maxspeed_backward = tonumber(way:get_value_by_key( "maxspeed:backward")) local junction = way:get_value_by_key("junction") if name then result.name = name end if duration and durationIsValid(duration) then result.duration = math.max( 1, parseDuration(duration) ) result.forward_mode = 2 result.backward_mode = 2 else local speed_forw = speed_profile[highway] or speed_profile['default'] local speed_back = speed_forw if highway == "river" then local temp_speed = speed_forw; result.forward_mode = 3 result.backward_mode = 4 speed_forw = temp_speed*1.5 speed_back = temp_speed/1.5 elseif highway == "steps" then result.forward_mode = 5 result.backward_mode = 6 end if maxspeed_forward ~= nil and maxspeed_forward > 0 then speed_forw = maxspeed_forward else if maxspeed ~= nil and maxspeed > 0 and speed_forw > maxspeed then speed_forw = maxspeed end end if maxspeed_backward ~= nil and maxspeed_backward > 0 then speed_back = maxspeed_backward else if maxspeed ~=nil and maxspeed > 0 and speed_back > maxspeed then speed_back = maxspeed end end result.forward_speed = speed_forw result.backward_speed = speed_back end if oneway == "no" or oneway == "0" or oneway == "false" then -- nothing to do elseif oneway == "-1" then result.forward_mode = 0 elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" then result.backward_mode = 0 end if junction == 'roundabout' then result.roundabout = true end end
bsd-2-clause
aphenriques/integral
samples/core/regex/regex.lua
1
2084
-- -- regex.lua -- integral -- -- MIT License -- -- Copyright (c) 2013, 2014, 2020 André Pereira Henriques (aphenriques (at) outlook (dot) com) -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. -- MacOX specific shared library extension package.cpath = package.cpath .. ";?.dylib" local Regex = require("libRegex") local pattern = Regex.new([[(.)\.(.)]]) -- literal string to avoid dealing with escape characters local matches = pattern:match("4.2") print("matches:", matches) if matches then print("matches:getSize():", matches:getSize()) for i = 0, matches:getSize() - 1 do print("matches("..i.."):", matches(i)) end end print("---") pattern = Regex.new("(.)") matches = pattern:search("42") print("matches:", matches) -- maybe matches == nil. c++ std::regex implementation may be incomplete if matches then print("matches:getSize():", matches:getSize()) for i = 0, matches:getSize() - 1 do print("matches("..i.."):", matches(i)) end end print("---") -- should be nil print("matches:", pattern:match("42"))
mit
vaughamhong/vlc
share/lua/playlist/bbc_co_uk.lua
112
1468
--[[ $Id$ Copyright © 2008 the VideoLAN team Authors: Dominique Leuenberger <dominique-vlc.suse@leuenberger.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "bbc.co.uk/iplayer/" ) end -- Parse function. function parse() p = {} while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "title: " ) then _,_,name = string.find( line, "title: \"(.*)\"" ) end if string.match( line, "metaFile: \".*%.ram\"" ) then _,_,video = string.find( line, "metaFile: \"(.-)\"" ) table.insert( p, { path = video; name = name } ) end end return p end
gpl-2.0
kuoruan/lede-luci
applications/luci-app-clamav/luasrc/model/cbi/clamav.lua
100
6776
--[[ LuCI ClamAV module Copyright (C) 2015, Itus Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Author: Marko Ratkaj <marko.ratkaj@sartura.hr> Luka Perkov <luka.perkov@sartura.hr> ]]-- local fs = require "nixio.fs" local sys = require "luci.sys" require "ubus" m = Map("clamav", translate("ClamAV")) m.on_after_commit = function() luci.sys.call("/etc/init.d/clamav restart") end s = m:section(TypedSection, "clamav") s.anonymous = true s.addremove = false s:tab("tab_advanced", translate("Settings")) s:tab("tab_logs", translate("Log")) --------------- Settings -------------- LogFileMaxSize = s:taboption("tab_advanced", Value, "LogFileMaxSize", translate("Max size of log file")) LogFileMaxSize:value("512K", translate("512K")) LogFileMaxSize:value("1M", translate("1M")) LogFileMaxSize:value("2M", translate("2M")) LogFileMaxSize.default = "1M" LogTime = s:taboption("tab_advanced", ListValue, "LogTime", translate("Log time with each message")) LogTime:value("no", translate("No")) LogTime:value("yes", translate("Yes")) LogTime.default = "no" LogVerbose = s:taboption("tab_advanced", ListValue, "LogVerbose", translate("Enable verbose logging")) LogVerbose:value("no", translate("No")) LogVerbose:value("yes", translate("Yes")) LogVerbose.default = "no" ExtendedDetectionInfo = s:taboption("tab_advanced", ListValue, "ExtendedDetectionInfo", translate("Log additional infection info")) ExtendedDetectionInfo:value("no", translate("No")) ExtendedDetectionInfo:value("yes", translate("Yes")) ExtendedDetectionInfo.default = "no" dummy3 = s:taboption("tab_advanced", DummyValue, "") dummy4 = s:taboption("tab_advanced", DummyValue, "") MaxDirectoryRecursion = s:taboption("tab_advanced", Value, "MaxDirectoryRecursion", translate("Max directory scan depth")) MaxDirectoryRecursion:value("15", translate("15")) MaxDirectoryRecursion:value("20", translate("20")) MaxDirectoryRecursion.default = "15" FollowDirectorySymlink = s:taboption("tab_advanced", ListValue, "FollowDirectorySymlink", translate("Follow directory symlinks")) FollowDirectorySymlink:value("no", translate("No")) FollowDirectorySymlink:value("yes", translate("Yes")) FollowDirectorySymlink.default = "no" FollowFileSymlinks = s:taboption("tab_advanced", ListValue, "FollowFileSymlinks", translate("Follow file symlinks")) FollowFileSymlinks:value("no", translate("No")) FollowFileSymlinks:value("yes", translate("Yes")) FollowFileSymlinks.default = "no" DetectPUA = s:taboption("tab_advanced", ListValue, "DetectPUA", translate("Detect possibly unwanted apps")) DetectPUA:value("no", translate("No")) DetectPUA:value("yes", translate("Yes")) DetectPUA.default = "no" ScanPE = s:taboption("tab_advanced", ListValue, "ScanPE", translate("Scan portable executables")) ScanPE:value("no", translate("No")) ScanPE:value("yes", translate("Yes")) ScanPE.default = "yes" ScanELF = s:taboption("tab_advanced", ListValue, "ScanELF", translate("Scan ELF files")) ScanELF:value("no", translate("No")) ScanELF:value("yes", translate("Yes")) ScanELF.default = "yes" DetectBrokenExecutables = s:taboption("tab_advanced", ListValue, "DetectBrokenExecutables", translate("Detect broken executables")) DetectBrokenExecutables:value("no", translate("No")) DetectBrokenExecutables:value("yes", translate("Yes")) DetectBrokenExecutables.default = "no" ScanOLE2 = s:taboption("tab_advanced", ListValue, "ScanOLE2", translate("Scan MS Office and .msi files")) ScanOLE2:value("no", translate("No")) ScanOLE2:value("yes", translate("Yes")) ScanOLE2.default = "yes" ScanPDF = s:taboption("tab_advanced", ListValue, "ScanPDF", translate("Scan pdf files")) ScanPDF:value("no", translate("No")) ScanPDF:value("yes", translate("Yes")) ScanPDF.default = "yes" ScanSWF = s:taboption("tab_advanced", ListValue, "ScanSWF", translate("Scan swf files")) ScanSWF:value("no", translate("No")) ScanSWF:value("yes", translate("Yes")) ScanSWF.default = "yes" ScanMail = s:taboption("tab_advanced", ListValue, "ScanMail", translate("Scan emails")) ScanMail:value("no", translate("No")) ScanMail:value("yes", translate("Yes")) ScanMail.default = "yes" ScanPartialMessages = s:taboption("tab_advanced", ListValue, "ScanPartialMessages", translate("Scan RFC1341 messages split over many emails")) ScanPartialMessages:value("no", translate("No")) ScanPartialMessages:value("yes", translate("Yes")) ScanPartialMessages.default = "no" ScanArchive = s:taboption("tab_advanced", ListValue, "ScanArchive", translate("Scan archives")) ScanArchive:value("no", translate("No")) ScanArchive:value("yes", translate("Yes")) ScanArchive.default = "yes" ArchiveBlockEncrypted = s:taboption("tab_advanced", ListValue, "ArchiveBlockEncrypted", translate("Block encrypted archives")) ArchiveBlockEncrypted:value("no", translate("No")) ArchiveBlockEncrypted:value("yes", translate("Yes")) ArchiveBlockEncrypted.default = "no" dummy5 = s:taboption("tab_advanced", DummyValue, "") dummy6 = s:taboption("tab_advanced", DummyValue, "") StreamMinPort = s:taboption("tab_advanced", Value, "StreamMinPort", translate("Port range, lowest port")) StreamMinPort.datatype = "portrange" StreamMinPort:value("1024",translate("1024")) StreamMinPort.default = "1024" StreamMaxPort = s:taboption("tab_advanced", Value, "StreamMaxPort", translate("Port range, highest port")) StreamMaxPort.datatype = "portrange" StreamMaxPort:value("2048",translate("2048")) StreamMaxPort.default = "2048" MaxThreads = s:taboption("tab_advanced", Value, "MaxThreads", translate("Max number of threads")) MaxThreads.datatype = "and(uinteger,min(1))" MaxThreads:value("10",translate("10")) MaxThreads:value("20",translate("20")) MaxThreads.default = "10" SelfCheck = s:taboption("tab_advanced", Value, "SelfCheck", translate("Database check every N sec")) SelfCheck.datatype = "and(uinteger,min(1))" SelfCheck:value("600",translate("600")) SelfCheck.default = "600" MaxFileSize = s:taboption("tab_advanced", Value, "MaxFileSize", translate("Max size of scanned file")) MaxFileSize.datatype = "string" MaxFileSize:value("150M",translate("150M")) MaxFileSize:value("50M",translate("50M")) MaxFileSize.default = "150M" ------------------ Log -------------------- clamav_logfile = s:taboption("tab_logs", TextValue, "lines", "") clamav_logfile.wrap = "off" clamav_logfile.rows = 25 clamav_logfile.rmempty = true function clamav_logfile.cfgvalue() local uci = require "luci.model.uci".cursor_state() local file = "/tmp/clamd.log" if file then return fs.readfile(file) or "" else return "" end end function clamav_logfile.write() end return m
apache-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/general/npcs/orc.lua
1
10658
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Talents = require("engine.interface.ActorTalents") newEntity{ define_as = "BASE_NPC_ORC", type = "humanoid", subtype = "orc", display = "o", color=colors.UMBER, faction = "orc-pride", combat = { dam=resolvers.rngavg(5,12), atk=2, apr=6, physspeed=2 }, body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1, QUIVER=1, TOOL=1 }, resolvers.drops{chance=20, nb=1, {} }, resolvers.drops{chance=10, nb=1, {type="money"} }, infravision = 10, lite = 2, life_rating = 11, rank = 2, size_category = 3, open_door = true, autolevel = "warrior", ai = "dumb_talented_simple", ai_state = { ai_move="move_complex", talent_in=3, }, stats = { str=20, dex=8, mag=6, con=16 }, resolvers.talents{ [Talents.T_WEAPON_COMBAT]={base=1, every=10, max=5}, }, ingredient_on_death = "ORC_HEART", } newEntity{ base = "BASE_NPC_ORC", define_as = "HILL_ORC_WARRIOR", name = "orc warrior", color=colors.LIGHT_UMBER, desc = [[He is a hardy, well-weathered survivor.]], level_range = {10, nil}, exp_worth = 1, rarity = 1, max_life = resolvers.rngavg(70,80), resolvers.equip{ {type="weapon", subtype="waraxe", autoreq=true}, {type="armor", subtype="shield", autoreq=true}, }, resolvers.inscriptions(1, "infusion"), combat_armor = 2, combat_def = 0, resolvers.talents{ [Talents.T_WEAPONS_MASTERY]={base=1, every=10, max=5}, [Talents.T_SHIELD_PUMMEL]={base=1, every=6, max=5}, }, resolvers.racial(), } newEntity{ base = "BASE_NPC_ORC", define_as = "HILL_ORC_ARCHER", name = "orc archer", color=colors.UMBER, desc = [[He is a hardy, well-weathered survivor.]], level_range = {10, nil}, exp_worth = 1, rarity = 3, max_life = resolvers.rngavg(70,80), combat_armor = 5, combat_def = 1, resolvers.talents{ [Talents.T_BOW_MASTERY]={base=1, every=10, max=5}, [Talents.T_SHOOT]=1, }, ai_state = { talent_in=1, }, autolevel = "archer", resolvers.inscriptions(1, "infusion"), resolvers.equip{ {type="weapon", subtype="longbow", autoreq=true}, {type="ammo", subtype="arrow", autoreq=true}, }, resolvers.racial(), } newEntity{ base = "BASE_NPC_ORC", define_as = "ORC", name = "orc soldier", color=colors.DARK_RED, desc = [[A fierce soldier-orc.]], level_range = {10, nil}, exp_worth = 1, rarity = 2, max_life = resolvers.rngavg(120,140), life_rating = 11, resolvers.equip{ {type="weapon", subtype="battleaxe", autoreq=true}, }, combat_armor = 2, combat_def = 0, resolvers.inscriptions(1, "infusion"), resolvers.talents{ [Talents.T_WEAPONS_MASTERY]={base=1, every=10, max=5}, [Talents.T_SUNDER_ARMOUR]={base=1, every=7, max=5}, [Talents.T_CRUSH]={base=1, every=4, max=5}, }, resolvers.racial(), } newEntity{ base = "BASE_NPC_ORC", define_as = "ORC_FIRE_WYRMIC", name = "fiery orc wyrmic", color=colors.RED, desc = [[A fierce soldier-orc trained in the discipline of dragons.]], level_range = {11, nil}, exp_worth = 1, rarity = 6, rank = 3, max_life = resolvers.rngavg(100,110), life_rating = 10, resolvers.equip{ {type="weapon", subtype="battleaxe", autoreq=true}, {type="charm", subtype="totem"} }, combat_armor = 2, combat_def = 0, ai = "tactical", ai_tactic = resolvers.tactic"melee", resolvers.inscriptions(1, "infusion"), make_escort = { {type="humanoid", subtype="orc", name="orc soldier", number=resolvers.mbonus(3, 2)}, }, resolvers.talents{ [Talents.T_WEAPONS_MASTERY]={base=2, every=10, max=5}, [Talents.T_BELLOWING_ROAR]={base=2, every=6, max=5}, [Talents.T_WING_BUFFET]={base=2, every=5, max=5}, [Talents.T_FIRE_BREATH]={base=2, every=5, max=5}, }, resolvers.racial(), } newEntity{ base = "BASE_NPC_ORC", name = "icy orc wyrmic", color=colors.BLUE, define_as = "ORC_ICE_WYRMIC", desc = [[A fierce soldier-orc trained in the discipline of dragons.]], level_range = {11, nil}, exp_worth = 1, rarity = 6, rank = 3, max_life = resolvers.rngavg(100,110), life_rating = 10, resolvers.equip{ {type="weapon", subtype="battleaxe", autoreq=true}, {type="charm", subtype="totem"} }, combat_armor = 2, combat_def = 0, ai = "tactical", ai_tactic = resolvers.tactic"melee", resolvers.inscriptions(1, "infusion"), make_escort = { {type="humanoid", subtype="orc", name="orc soldier", number=resolvers.mbonus(3, 2)}, }, resolvers.talents{ [Talents.T_WEAPONS_MASTERY]={base=2, every=10, max=5}, [Talents.T_ICE_CLAW]={base=2, every=6, max=5}, [Talents.T_ICY_SKIN]={base=2, every=5, max=5}, [Talents.T_ICE_BREATH]={base=2, every=5, max=5}, }, resolvers.racial(), } newEntity{ base = "BASE_NPC_ORC", name = "orc assassin", color_r=0, color_g=0, color_b=resolvers.rngrange(175, 195), desc = [[An orc trained in the secret ways of assassination, stealthy and deadly.]], level_range = {12, nil}, exp_worth = 1, rarity = 3, infravision = 10, combat_armor = 2, combat_def = 12, resolvers.equip{ {type="weapon", subtype="dagger", autoreq=true}, {type="weapon", subtype="dagger", autoreq=true}, {type="armor", subtype="light", autoreq=true} }, resolvers.talents{ [Talents.T_KNIFE_MASTERY]={base=2, every=10, max=5}, [Talents.T_STEALTH]=5, [Talents.T_LETHALITY]=4, [Talents.T_SHADOWSTRIKE]={base=3, every=6, max=5}, [Talents.T_VILE_POISONS]={base=2, every=8, max=5}, [Talents.T_VENOMOUS_STRIKE]={last=15, base=0, every=6, max=5}, }, max_life = resolvers.rngavg(80,100), resolvers.inscriptions(1, "infusion"), resolvers.sustains_at_birth(), autolevel = "rogue", resolvers.racial(), } newEntity{ base = "BASE_NPC_ORC", name = "orc master assassin", color_r=0, color_g=70, color_b=resolvers.rngrange(175, 195), desc = [[An orc trained in the secret ways of assassination, stealthy and deadly.]], level_range = {15, nil}, exp_worth = 1, rarity = 4, rank = 3, infravision = 10, combat_armor = 2, combat_def = 18, resolvers.equip{ {type="weapon", subtype="dagger", ego_chance=20, autoreq=true}, {type="weapon", subtype="dagger", ego_chance=20, autoreq=true}, {type="armor", subtype="light", autoreq=true}, {type="charm"} }, ai = "tactical", ai_tactic = resolvers.tactic"melee", resolvers.inscriptions(1, "infusion"), resolvers.talents{ [Talents.T_KNIFE_MASTERY]={base=2, every=10, max=5}, [Talents.T_STEALTH]=5, [Talents.T_LETHALITY]=4, [Talents.T_SHADOWSTRIKE]=5, [Talents.T_HIDE_IN_PLAIN_SIGHT]={base=2, every=6, max=5}, [Talents.T_VILE_POISONS]={base=3, every=8, max=5}, [Talents.T_VENOMOUS_STRIKE]={base=1, every=6, max=5}, }, max_life = resolvers.rngavg(80,100), resolvers.sustains_at_birth(), autolevel = "rogue", resolvers.racial(), } newEntity{ base = "BASE_NPC_ORC", name = "orc grand master assassin", color_r=0, color_g=70, color_b=resolvers.rngrange(175, 195), desc = [[An orc trained in the secret ways of assassination, stealthy and deadly.]], level_range = {15, nil}, exp_worth = 1, rarity = 5, rank = 3, infravision = 10, combat_armor = 2, combat_def = 18, resolvers.equip{ {type="weapon", subtype="dagger", ego_chance=20, autoreq=true}, {type="weapon", subtype="dagger", ego_chance=20, autoreq=true}, {type="armor", subtype="light", autoreq=true}, {type="charm"} }, ai = "tactical", ai_tactic = resolvers.tactic"melee", resolvers.inscriptions(3, "infusion"), resolvers.talents{ [Talents.T_KNIFE_MASTERY]={base=2, every=10, max=5}, [Talents.T_STEALTH]=5, [Talents.T_LETHALITY]={base=4, every=5, max=6}, [Talents.T_DEADLY_STRIKES]={base=3, every=5, max=6}, [Talents.T_SHADOWSTRIKE]=5, [Talents.T_HIDE_IN_PLAIN_SIGHT]={base=3, every=5, max=5}, [Talents.T_UNSEEN_ACTIONS]={base=3, every=5, max=5}, [Talents.T_VILE_POISONS]={base=3, every=8, max=5}, [Talents.T_VENOMOUS_STRIKE]={base=2, every=6, max=5}, [Talents.T_EMPOWER_POISONS]={base=3, every=7, max=5}, }, max_life = resolvers.rngavg(80,100), resolvers.sustains_at_birth(), autolevel = "rogue", resolvers.racial(), } -- Unique orcs newEntity{ base = "BASE_NPC_ORC", name = "Kra'Tor the Gluttonous", unique = true, color=colors.DARK_KHAKI, resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/humanoid_orc_kra_tor_the_gluttonous.png", display_h=2, display_y=-1}}}, desc = [[A morbidly obese orc with greasy pockmarked skin and oily long black hair. He's clad in plate mail and carries a huge granite battleaxe that's nearly as large as he is.]], level_range = {38, nil}, exp_worth = 2, rarity = 50, rank = 3.5, max_life = resolvers.rngavg(600, 800), life_rating = 22, move_others=true, resolvers.equip{ {type="weapon", subtype="battleaxe", defined="GAPING_MAW", random_art_replace={chance=75}, autoreq=true}, {type="armor", subtype="massive", tome_drops="boss", autoreq=true}, {type="charm", forbid_power_source={arcane=true}, autoreq=true} }, resolvers.drops{chance=100, nb=2, {tome_drops="boss"} }, combat_armor = 2, combat_def = 0, blind_immune = 0.5, confuse_immune = 0.5, stun_immune = 0.7, knockback_immune = 1, autolevel = "wyrmic", ai = "tactical", ai_state = { talent_in=1, ai_move="move_astar", }, ai_tactic = resolvers.tactic"melee", resolvers.inscriptions(4, {"movement infusion", "healing infusion", "regeneration infusion", "wild infusion"}), resists = { all=25}, resolvers.talents{ [Talents.T_ICE_CLAW]={base=4, every=4, max=8}, [Talents.T_ICY_SKIN]={base=5, every=4, max=9}, [Talents.T_SAND_BREATH]={base=5, every=4, max=9}, [Talents.T_RESOLVE]=5, [Talents.T_AURA_OF_SILENCE]=5, [Talents.T_MANA_CLASH]={base=5, every=5, max=8}, [Talents.T_WARSHOUT]={base=4, every=4, max=8}, [Talents.T_DEATH_DANCE]={base=3, every=4, max=7}, [Talents.T_BERSERKER]={base=5, every=4, max=10}, [Talents.T_BATTLE_CALL]={base=5, every=4, max=8}, [Talents.T_CRUSH]={base=3, every=4, max=8}, [Talents.T_WEAPON_COMBAT]={base=3, every=8, max=5}, [Talents.T_WEAPONS_MASTERY]={base=3, every=8, max=5}, [Talents.T_ARMOUR_TRAINING]={base=3, every=7, max=7}, [Talents.T_SPELL_FEEDBACK] = 1, }, resolvers.sustains_at_birth(), }
gpl-3.0
HandsomeCharming/RPG
Cocos2dx/frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua
6
1100
-------------------------------- -- @module ActionManagerEx -- @extend Ref -- @parent_module ccs -------------------------------- -- @overload self, char, char, cc.CallFunc -- @overload self, char, char -- @function [parent=#ActionManagerEx] playActionByName -- @param self -- @param #char char -- @param #char char -- @param #cc.CallFunc callfunc -- @return ActionObject#ActionObject ret (retunr value: ccs.ActionObject) -------------------------------- -- @function [parent=#ActionManagerEx] getActionByName -- @param self -- @param #char char -- @param #char char -- @return ActionObject#ActionObject ret (return value: ccs.ActionObject) -------------------------------- -- @function [parent=#ActionManagerEx] releaseActions -- @param self -------------------------------- -- @function [parent=#ActionManagerEx] destroyInstance -- @param self -------------------------------- -- @function [parent=#ActionManagerEx] getInstance -- @param self -- @return ActionManagerEx#ActionManagerEx ret (return value: ccs.ActionManagerEx) return nil
gpl-2.0
LinuxTeam98/Linux_TG
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/zones/arena/objects.lua
1
4713
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org load("/data/general/objects/objects.lua") local Talents = require "engine.interface.ActorTalents" newEntity{ base = "BASE_LORE", define_as = "ARENA_SCORING", name = "Arena for dummies", lore="arena-scoring", desc = [[A note explaining the arena's scoring rules. Someone must have dropped it.]], rarity = false, encumberance = 0, } newEntity{ define_as = "ARENA_BOOTS_DISE", name = "a pair of leather boots of disengagement", slot = "FEET", type = "armor", subtype="feet", power_source = {technique=true}, add_name = " (#ARMOR#)#CHARGES#", display = "]", color=colors.UMBER, image = resolvers.image_material("boots", "leather"), encumber = 2, desc = [[A pair of boots made of leather. They seem to be of exceptional quality.]], suffix=true, instant_resolve=true, egoed = true, greater_ego = 1, identified = true, rarity = false, cost = 0, material_level = 1, wielder = { combat_armor = 2, fatigue = 1, }, max_power = 12, power_regen = 1, use_talent = { id = Talents.T_DISENGAGE, level = 2, power = 12 }, } newEntity{ define_as = "ARENA_BOOTS_PHAS", name = "a pair of leather boots of phasing", slot = "FEET", type = "armor", subtype="feet", power_source = {arcane=true}, add_name = " (#ARMOR#)#CHARGES#", display = "]", color=colors.UMBER, image = resolvers.image_material("boots", "leather"), encumber = 2, desc = [[A pair of boots made of leather. They seem to be of exceptional quality.]], suffix=true, instant_resolve=true, egoed = true, greater_ego = 1, identified = true, cost = 0, rarity = false, material_level = 1, wielder = { combat_armor = 2, fatigue = 1, }, max_power = 25, power_regen = 1, use_power = { name = function(self, who) return ("blink to a nearby random location within range %d (based on Magic)"):format(self.use_power.range(self, who)) end, power = 15, range = function(self, who) return 10 + who:getMag(5) end, use = function(self, who) game.level.map:particleEmitter(who.x, who.y, 1, "teleport") who:teleportRandom(who.x, who.y, self.use_power.range(self, who)) game.level.map:particleEmitter(who.x, who.y, 1, "teleport") game:playSoundNear(who, "talents/teleport") game.logSeen(who, "%s uses %s!", who.name:capitalize(), self:getName{no_count=true, no_add_name=true}) return {id=true, used=true} end} } newEntity{ define_as = "ARENA_BOOTS_RUSH", name = "a pair of leather boots of rushing", slot = "FEET", type = "armor", subtype="feet", power_source = {technique=true}, add_name = " (#ARMOR#)#CHARGES#", display = "]", color=colors.UMBER, image = resolvers.image_material("boots", "leather"), encumber = 2, desc = [[A pair of boots made of leather. They seem to be of exceptional quality.]], suffix=true, instant_resolve=true, egoed = true, rarity = false, greater_ego = 1, identified = true, cost = 0, material_level = 1, wielder = { combat_armor = 2, fatigue = 1, }, max_power = 32, power_regen = 1, use_talent = { id = Talents.T_RUSH, level = 2, power = 32 }, } newEntity{ define_as = "ARENA_BOW", name = "elm longbow of piercing arrows", base = "BASE_LONGBOW", level_range = {1, 10}, power_source = {technique=true}, require = { stat = { dex=11 }, }, rarity = 30, add_name = " #CHARGES#", egoed = true, greater_ego = 1, identified = true, cost = 0, material_level = 1, use_talent = { id = Talents.T_PIERCING_ARROW, level = 2, power = 10 }, max_power = 10, power_regen = 1, combat = { range = 8, physspeed = 0.8, }, } newEntity{ define_as = "ARENA_SLING", name = "rough leather sling of flare", base = "BASE_SLING", level_range = {1, 10}, power_source = {technique=true}, require = { stat = { dex=11 }, }, add_name = " #CHARGES#", rarity = 30, egoed = true, greater_ego = 1, identified = true, cost = 0, material_level = 1, use_talent = { id = Talents.T_FLARE, level = 3, power = 25 }, max_power = 25, power_regen = 1, combat = { range = 8, physspeed = 0.8, }, }
gpl-3.0
teslamint/luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/network.lua
14
4221
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" m = Map("network", translate("Interfaces")) m.pageaction = false m:section(SimpleSection).template = "admin_network/iface_overview" if fs.access("/etc/init.d/dsl_control") then dsl = m:section(TypedSection, "dsl", translate("DSL")) dsl.anonymous = true annex = dsl:option(ListValue, "annex", translate("Annex")) annex:value("a", translate("Annex A + L + M (all)")) annex:value("b", translate("Annex B (all)")) annex:value("j", translate("Annex J (all)")) annex:value("m", translate("Annex M (all)")) annex:value("bdmt", translate("Annex B G.992.1")) annex:value("b2", translate("Annex B G.992.3")) annex:value("b2p", translate("Annex B G.992.5")) annex:value("at1", translate("ANSI T1.413")) annex:value("admt", translate("Annex A G.992.1")) annex:value("alite", translate("Annex A G.992.2")) annex:value("a2", translate("Annex A G.992.3")) annex:value("a2p", translate("Annex A G.992.5")) annex:value("l", translate("Annex L G.992.3 POTS 1")) annex:value("m2", translate("Annex M G.992.3")) annex:value("m2p", translate("Annex M G.992.5")) tone = dsl:option(ListValue, "tone", translate("Tone")) tone:value("", translate("auto")) tone:value("a", translate("A43C + J43 + A43")) tone:value("av", translate("A43C + J43 + A43 + V43")) tone:value("b", translate("B43 + B43C")) tone:value("bv", translate("B43 + B43C + V43")) xfer_mode = dsl:option(ListValue, "xfer_mode", translate("Encapsulation mode")) xfer_mode:value("atm", translate("ATM (Asynchronous Transfer Mode)")) xfer_mode:value("ptm", translate("PTM/EFM (Packet Transfer Mode)")) line_mode = dsl:option(ListValue, "line_mode", translate("DSL line mode")) line_mode:value("", translate("auto")) line_mode:value("adsl", translate("ADSL")) line_mode:value("vdsl", translate("VDSL")) firmware = dsl:option(Value, "firmware", translate("Firmware File")) m.pageaction = true end -- Show ATM bridge section if we have the capabilities if fs.access("/usr/sbin/br2684ctl") then atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"), translate("ATM bridges expose encapsulated ethernet in AAL5 " .. "connections as virtual Linux network interfaces which can " .. "be used in conjunction with DHCP or PPP to dial into the " .. "provider network.")) atm.addremove = true atm.anonymous = true atm.create = function(self, section) local sid = TypedSection.create(self, section) local max_unit = -1 m.uci:foreach("network", "atm-bridge", function(s) local u = tonumber(s.unit) if u ~= nil and u > max_unit then max_unit = u end end) m.uci:set("network", sid, "unit", max_unit + 1) m.uci:set("network", sid, "atmdev", 0) m.uci:set("network", sid, "encaps", "llc") m.uci:set("network", sid, "payload", "bridged") m.uci:set("network", sid, "vci", 35) m.uci:set("network", sid, "vpi", 8) return sid end atm:tab("general", translate("General Setup")) atm:tab("advanced", translate("Advanced Settings")) vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)")) vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)")) encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode")) encaps:value("llc", translate("LLC")) encaps:value("vc", translate("VC-Mux")) atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number")) unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number")) payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode")) payload:value("bridged", translate("bridged")) payload:value("routed", translate("routed")) m.pageaction = true end local network = require "luci.model.network" if network:has_ipv6() then local s = m:section(NamedSection, "globals", "globals", translate("Global network options")) local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix")) o.datatype = "ip6addr" o.rmempty = true m.pageaction = true end return m
apache-2.0
Blackdutchie/Zero-K
units/attackdrone.lua
2
3863
unitDef = { unitname = [[attackdrone]], name = [[Firefly]], description = [[Attack Drone]], acceleration = 0.3, airHoverFactor = 4, amphibious = true, brakeRate = 0.3, buildCostEnergy = 50, buildCostMetal = 50, builder = false, buildPic = [[attackdrone.png]], buildTime = 50, canAttack = true, canFly = true, canGuard = true, canMove = true, canPatrol = true, canSubmerge = false, category = [[GUNSHIP]], collide = false, cruiseAlt = 100, explodeAs = [[TINY_BUILDINGEX]], floater = true, footprintX = 2, footprintZ = 2, hoverAttack = true, iconType = [[fighter]], mass = 84, maxDamage = 180, maxVelocity = 7, minCloakDistance = 75, noAutoFire = false, noChaseCategory = [[TERRAFORM SATELLITE SUB]], objectName = [[attackdrone.s3o]], reclaimable = false, refuelTime = 10, script = [[attackdrone.lua]], seismicSignature = 0, selfDestructAs = [[TINY_BUILDINGEX]], customParams = { description_de = [[Kampfdrohne]], description_fr = [[Drone d'attaque]], description_pl = [[Dron bojowy]], helptext = [[The Firefly is an attack drone with a weak high precision pulse laser. They can protect their parent unit from light enemy units. They do not share stealth with it though, so they can also betray the presence of a cloaked commander.]], helptext_de = [[Der Firefly ist eine Kampfdrohne, die seinen Besitzer schutzt.]], helptext_fr = [[La Luciole est un drone miniature d'attaque autonome équipé d'un faible laser pulsé. Un commandant en possède deux qui patrouillent autour de lui et le protêge efficacement des petites unités adverses. Néanmoins leur présence peut trahir un commandant invisible.]], helptext_pl = [[Firefly to dron bojowy, ktory chroni wlasciciela przed lekkimi jednostkami swoim laserem pulsacyjnym.]], is_drone = 1, }, sfxtypes = { explosiongenerators = { }, }, side = [[ARM]], sightDistance = 500, turnRate = 792, upright = true, weapons = { { def = [[LASER]], badTargetCategory = [[FIXEDWING]], mainDir = [[0 0 1]], maxAngleDif = 90, onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { LASER = { name = [[Light Particle Beam]], beamDecay = 0.9, beamTime = 0.01, beamttl = 60, coreThickness = 0.25, craterBoost = 0, craterMult = 0, cylinderTargeting = 1, damage = { default = 32, subs = 1.6, }, explosionGenerator = [[custom:flash_teal7]], fireStarter = 100, impactOnly = true, impulseFactor = 0, interceptedByShieldType = 1, laserFlareSize = 3.25, minIntensity = 1, range = 250, reloadtime = 0.8, rgbColor = [[0 1 0]], soundStart = [[weapon/laser/mini_laser]], soundStartVolume = 4, thickness = 2.165, tolerance = 8192, turret = true, weaponType = [[BeamLaser]], }, }, } return lowerkeys({ attackdrone = unitDef })
gpl-2.0
khavnu/VLCLIB
share/lua/playlist/metachannels.lua
92
2096
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Rémi Duraffort <ivoire at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] require "simplexml" function probe() return vlc.access == 'http' and string.match( vlc.path, 'metachannels.com' ) end function parse() local webpage = '' while true do local line = vlc.readline() if line == nil then break end webpage = webpage .. line end local feed = simplexml.parse_string( webpage ) local channel = feed.children[1] -- list all children that are items local tracks = {} for _,item in ipairs( channel.children ) do if( item.name == 'item' ) then simplexml.add_name_maps( item ) local url = vlc.strings.resolve_xml_special_chars( item.children_map['link'][1].children[1] ) local title = vlc.strings.resolve_xml_special_chars( item.children_map['title'][1].children[1] ) local arturl = nil if item.children_map['media:thumbnail'] then arturl = vlc.strings.resolve_xml_special_chars( item.children_map['media:thumbnail'][1].attributes['url'] ) end table.insert( tracks, { path = url, title = title, arturl = arturl, options = {':play-and-pause'} } ) end end return tracks end
gpl-2.0
vaughamhong/vlc
share/lua/playlist/metachannels.lua
92
2096
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Rémi Duraffort <ivoire at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] require "simplexml" function probe() return vlc.access == 'http' and string.match( vlc.path, 'metachannels.com' ) end function parse() local webpage = '' while true do local line = vlc.readline() if line == nil then break end webpage = webpage .. line end local feed = simplexml.parse_string( webpage ) local channel = feed.children[1] -- list all children that are items local tracks = {} for _,item in ipairs( channel.children ) do if( item.name == 'item' ) then simplexml.add_name_maps( item ) local url = vlc.strings.resolve_xml_special_chars( item.children_map['link'][1].children[1] ) local title = vlc.strings.resolve_xml_special_chars( item.children_map['title'][1].children[1] ) local arturl = nil if item.children_map['media:thumbnail'] then arturl = vlc.strings.resolve_xml_special_chars( item.children_map['media:thumbnail'][1].attributes['url'] ) end table.insert( tracks, { path = url, title = title, arturl = arturl, options = {':play-and-pause'} } ) end end return tracks end
gpl-2.0
Blackdutchie/Zero-K
units/corbhmth.lua
2
5796
unitDef = { unitname = [[corbhmth]], name = [[Behemoth]], description = [[Plasma Artillery Battery - Requires 50 Power]], acceleration = 0, activateWhenBuilt = true, brakeRate = 0, buildAngle = 8192, buildCostEnergy = 2500, buildCostMetal = 2500, builder = false, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 8, buildingGroundDecalSizeY = 8, buildingGroundDecalType = [[corbhmth_aoplane.dds]], buildPic = [[CORBHMTH.png]], buildTime = 2500, canAttack = true, canstop = [[1]], category = [[SINK]], corpse = [[DEAD]], customParams = { description_de = [[Plasmabatterie - Benötigt ein angeschlossenes Stromnetz von 50 Energie, um feuern zu können.]], description_pl = [[Bateria plazmowa]], helptext = [[The Behemoth offers long-range artillery/counter-artillery capability, making it excellent for area denial. It is not designed as a defense turret, and will go down if attacked directly.]], helptext_de = [[Der Behemoth besitzt eine weitreichende (Erwiderungs-)Artilleriefähigkeit, um Zugang zu größeren Arealen zu verhindern. Er wurde nicht als Verteidigungsturm entwickelt und wird bei direktem Angriff in die Knie gezwungen.]], helptext_pl = [[Behemoth to bateria (przeciw-)artyleryjska. Swietnie radzi sobie z zabezpieczaniem terytorium, jednak latwo go zniszczyc bezposrednio. Aby strzelac, musi znajdowac sie w sieci energetycznej o mocy co najmniej 50 energii.]], keeptooltip = [[any string I want]], neededlink = 50, pylonrange = 50, }, explodeAs = [[LARGE_BUILDINGEX]], footprintX = 5, footprintZ = 5, highTrajectory = 2, iconType = [[staticarty]], idleAutoHeal = 5, idleTime = 1800, mass = 605, maxDamage = 3750, maxSlope = 18, maxVelocity = 0, maxWaterDepth = 0, minCloakDistance = 150, noAutoFire = false, noChaseCategory = [[FIXEDWING LAND SHIP SATELLITE SWIM GUNSHIP SUB HOVER]], objectName = [[corbhmth.s3o]], onoffable = false, script = [[corbhmth.lua]], seismicSignature = 4, selfDestructAs = [[LARGE_BUILDINGEX]], sfxtypes = { explosiongenerators = { [[custom:LARGE_MUZZLE_FLASH_FX]], }, }, side = [[CORE]], sightDistance = 660, smoothAnim = true, turnRate = 0, useBuildingGroundDecal = true, workerTime = 0, yardMap = [[ooooo ooooo ooooo ooooo ooooo]], weapons = { { def = [[PLASMA]], badTargetCategory = [[GUNSHIP]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]], }, }, weaponDefs = { PLASMA = { name = [[Long-Range Plasma Battery]], areaOfEffect = 192, avoidFeature = false, avoidGround = false, burst = 3, burstRate = 0.16, craterBoost = 1, craterMult = 2, damage = { default = 601, planes = 601, subs = 30, }, edgeEffectiveness = 0.5, explosionGenerator = [[custom:330rlexplode]], fireStarter = 120, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, mygravity = 0.1, range = 1850, reloadtime = 10, soundHit = [[explosion/ex_large4]], soundStart = [[explosion/ex_large5]], sprayangle = 1024, turret = true, weaponType = [[Cannon]], weaponVelocity = 400, }, }, featureDefs = { DEAD = { description = [[Wreckage - Behemoth]], blocking = true, category = [[corpses]], damage = 3750, energy = 0, featureDead = [[HEAP]], featurereclamate = [[SMUDGE01]], footprintX = 5, footprintZ = 5, height = [[20]], hitdensity = [[100]], metal = 1000, object = [[corbhmth_dead.s3o]], reclaimable = true, reclaimTime = 1000, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Behemoth]], blocking = false, category = [[heaps]], damage = 3750, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 5, footprintZ = 5, height = [[4]], hitdensity = [[100]], metal = 500, object = [[debris4x4b.s3o]], reclaimable = true, reclaimTime = 500, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ corbhmth = unitDef })
gpl-2.0
Blackdutchie/Zero-K
effects/paris.lua
12
4272
-- paris_glow -- paris -- paris_gflash -- paris_sphere return { ["paris_glow"] = { glow = { air = true, class = [[CSimpleParticleSystem]], count = 2, ground = true, water = true, properties = { airdrag = 1, colormap = [[0 0 0 0.01 0.8 0.8 0.8 0.9 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[-0, 1, 0]], gravity = [[0, 0.00, 0]], numparticles = 1, particlelife = 10, particlelifespread = 0, particlesize = 60, particlesizespread = 10, particlespeed = 1, particlespeedspread = 0, pos = [[0, 2, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[circularthingy]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.5, flashsize = 100, ttl = 10, color = { [1] = 0.80000001192093, [2] = 0.80000001192093, [3] = 1, }, }, }, ["paris"] = { dustring = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:GEORGE]], pos = [[0, 0, 0]], }, }, gflash = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:PARIS_GFLASH]], pos = [[0, 0, 0]], }, }, glow = { air = true, class = [[CExpGenSpawner]], count = 0, ground = true, water = true, properties = { delay = [[0 i0.5]], explosiongenerator = [[custom:PARIS_GLOW]], pos = [[0, 0, 0]], }, }, shere = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:PARIS_SPHERE]], pos = [[0, 5, 0]], }, }, }, ["paris_gflash"] = { groundflash = { circlealpha = 0.5, circlegrowth = 60, flashalpha = 0, flashsize = 30, ttl = 20, color = { [1] = 0.80000001192093, [2] = 0.80000001192093, [3] = 1, }, }, }, ["paris_sphere"] = { groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.5, flashsize = 60, ttl = 60, color = { [1] = 0.80000001192093, [2] = 0.80000001192093, [3] = 1, }, }, pikez = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.15, color = [[1.0,1.0,0.8]], dir = [[-15 r30,-15 r30,-15 r30]], length = 40, width = 15, }, }, sphere = { air = true, class = [[CSpherePartSpawner]], count = 1, ground = true, water = true, properties = { alpha = 0.3, alwaysvisible = false, color = [[0.8,0.8,1]], expansionspeed = 60, ttl = 10, }, }, }, }
gpl-2.0
Blackdutchie/Zero-K
units/spiderassault.lua
5
5125
unitDef = { unitname = [[spiderassault]], name = [[Hermit]], description = [[All Terrain Assault Bot]], acceleration = 0.18, brakeRate = 0.22, buildCostEnergy = 160, buildCostMetal = 160, buildPic = [[spiderassault.png]], buildTime = 160, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[LAND]], collisionVolumeOffsets = [[0 -3 0]], collisionVolumeScales = [[24 30 24]], collisionVolumeType = [[cylY]], corpse = [[DEAD]], customParams = { description_de = [[Geländegängige Sturmspinne]], description_bp = [[Rob?assaltante]], description_es = [[Robot de Asalto]], description_fr = [[Robot d'assaut arachnide]], description_it = [[Robot d'assalto]], description_pl = [[Pajak szturmowy]], helptext = [[The Hermit can take an incredible beating, and is useful as a shield for the weaker, more-damaging Recluses.]], helptext_bp = [[Hermit ?um rob?assaultante. Pode resistir muito dano, e ?útil como um escudo para os mais fracos porém mais potentes Recluses.]], helptext_es = [[El Hermit es increiblemente resistente, y es útil como esudo para los Recluse que hacen más da?o]], helptext_fr = [[Le Hermit est extraordinairement résistant pour sa taille. Si son canon ?plasma n'a pas la précision requise pour abattre les cibles rapides il reste néanmoins un bouclier parfait pour des unités moins solides telles que les Recluses.]], helptext_it = [[Il Hermit ?incredibilmente resistente, ed e utile come scudo per i Recluse che fanno pi?danno]], helptext_de = [[Der Hermit kann unglaublich viel Pr?el einstecken und ist als Schutzschild f? schwächere, oder zu schonende Einheiten, hervorragend geeignet.]], helptext_pl = [[Hermit jest niesamowicie wytrzymaly, dzieki czemu jest uzyteczny do przejmowania na siebie obrazen, aby chronic lzejsze pajaki.]], modelradius = [[12]], }, explodeAs = [[BIG_UNITEX]], footprintX = 2, footprintZ = 2, iconType = [[spiderassault]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 1400, maxSlope = 36, maxVelocity = 1.7, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[TKBOT3]], noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE SUB]], objectName = [[hermit.s3o]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], script = [[spiderassault.lua]], sfxtypes = { explosiongenerators = { [[custom:RAIDMUZZLE]], [[custom:RAIDDUST]], [[custom:THUDDUST]], }, }, sightDistance = 420, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ChickenTrackPointy]], trackWidth = 30, turnRate = 1600, weapons = { { def = [[THUD_WEAPON]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { THUD_WEAPON = { name = [[Light Plasma Cannon]], areaOfEffect = 36, craterBoost = 0, craterMult = 0, damage = { default = 141, planes = 141, subs = 7, }, explosionGenerator = [[custom:MARY_SUE]], impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, noSelfDamage = true, range = 350, reloadtime = 2.6, soundHit = [[explosion/ex_med5]], soundStart = [[weapon/cannon/cannon_fire5]], turret = true, weaponType = [[Cannon]], weaponVelocity = 280, }, }, featureDefs = { DEAD = { description = [[Wreckage - Hermit]], blocking = true, damage = 1400, energy = 0, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, metal = 64, object = [[hermit_wreck.s3o]], reclaimable = true, reclaimTime = 64, }, HEAP = { description = [[Debris - Hermit]], blocking = false, damage = 1400, energy = 0, footprintX = 2, footprintZ = 2, metal = 32, object = [[debris2x2c.s3o]], reclaimable = true, reclaimTime = 32, }, }, } return lowerkeys({ spiderassault = unitDef })
gpl-2.0
bayas/AutoRunner
Bin/Data/LuaScripts/16_Chat.lua
2
6838
-- Chat example -- This sample demonstrates: -- - Starting up a network server or connecting to it -- - Implementing simple chat functionality with network messages require "LuaScripts/Utilities/Sample" -- Identifier for the chat network messages local MSG_CHAT = 32 -- UDP port we will use local CHAT_SERVER_PORT = 2345 local chatHistory = {} local chatHistoryText = nil local buttonContainer = nil local textEdit = nil local sendButton = nil local connectButton = nil local disconnectButton = nil local startServerButton = nil function Start() -- Execute the common startup for samples SampleStart() -- Enable OS cursor input.mouseVisible = true -- Create the user interface CreateUI() -- Subscribe to UI and network events SubscribeToEvents() end function CreateUI() SetLogoVisible(false) -- We need the full rendering window local uiStyle = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") -- Set style to the UI root so that elements will inherit it ui.root.defaultStyle = uiStyle local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf") chatHistoryText = ui.root:CreateChild("Text") chatHistoryText:SetFont(font, 12) buttonContainer = ui.root:CreateChild("UIElement") buttonContainer:SetFixedSize(graphics.width, 20) buttonContainer:SetPosition(0, graphics.height - 20) buttonContainer.layoutMode = LM_HORIZONTAL textEdit = buttonContainer:CreateChild("LineEdit") textEdit:SetStyleAuto() sendButton = CreateButton("Send", 70) connectButton = CreateButton("Connect", 90) disconnectButton = CreateButton("Disconnect", 100) startServerButton = CreateButton("Start Server", 110) UpdateButtons() local size = (graphics.height - 20) / chatHistoryText.rowHeight for i = 1, size do table.insert(chatHistory, "") end -- No viewports or scene is defined. However, the default zone's fog color controls the fill color renderer.defaultZone.fogColor = Color(0.0, 0.0, 0.1) end function SubscribeToEvents() -- Subscribe to UI element events SubscribeToEvent(textEdit, "TextFinished", "HandleSend") SubscribeToEvent(sendButton, "Released", "HandleSend") SubscribeToEvent(connectButton, "Released", "HandleConnect") SubscribeToEvent(disconnectButton, "Released", "HandleDisconnect") SubscribeToEvent(startServerButton, "Released", "HandleStartServer") -- Subscribe to log messages so that we can pipe them to the chat window SubscribeToEvent("LogMessage", "HandleLogMessage") -- Subscribe to network events SubscribeToEvent("NetworkMessage", "HandleNetworkMessage") SubscribeToEvent("ServerConnected", "HandleConnectionStatus") SubscribeToEvent("ServerDisconnected", "HandleConnectionStatus") SubscribeToEvent("ConnectFailed", "HandleConnectionStatus") end function CreateButton(text, width) local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf") local button = buttonContainer:CreateChild("Button") button:SetStyleAuto() button:SetFixedWidth(width) local buttonText = button:CreateChild("Text") buttonText:SetFont(font, 12) buttonText:SetAlignment(HA_CENTER, VA_CENTER) buttonText.text = text return button end function ShowChatText(row) table.remove(chatHistory, 1) table.insert(chatHistory, row) -- Concatenate all the rows in history local allRows = "" for i, r in ipairs(chatHistory) do allRows = allRows .. r .. "\n" end chatHistoryText.text = allRows end function UpdateButtons() local serverConnection = network.serverConnection local serverRunning = network.serverRunning -- Show and hide buttons so that eg. Connect and Disconnect are never shown at the same time sendButton.visible = serverConnection ~= nil connectButton.visible = (serverConnection == nil) and (not serverRunning) disconnectButton.visible = (serverConnection ~= nil) or serverRunning startServerButton.visible = (serverConnection == nil) and (not serverRunning) end function HandleLogMessage(eventType, eventData) ShowChatText(eventData:GetString("Message")) end function HandleSend(eventType, eventData) local text = textEdit.text if text == "" then return -- Do not send an empty message end local serverConnection = network.serverConnection if serverConnection ~= nil then -- A VectorBuffer object is convenient for constructing a message to send local msg = VectorBuffer() msg:WriteString(text) -- Send the chat message as in-order and reliable serverConnection:SendMessage(MSG_CHAT, true, true, msg) -- Empty the text edit after sending textEdit.text = "" end end function HandleConnect(eventType, eventData) local address = textEdit.text if address == "" then address = "localhost" -- Use localhost to connect if nothing else specified end -- Empty the text edit after reading the address to connect to textEdit.text = "" -- Connect to server, do not specify a client scene as we are not using scene replication, just messages. -- At connect time we could also send identity parameters (such as username) in a VariantMap, but in this -- case we skip it for simplicity network:Connect(address, CHAT_SERVER_PORT, nil) UpdateButtons() end function HandleDisconnect(eventType, eventData) local serverConnection = network.serverConnection -- If we were connected to server, disconnect if serverConnection ~= nil then serverConnection:Disconnect() -- Or if we were running a server, stop it else if network.serverRunning then network:StopServer() end end UpdateButtons() end function HandleStartServer(eventType, eventData) network:StartServer(CHAT_SERVER_PORT) UpdateButtons() end function HandleNetworkMessage(eventType, eventData) local msgID = eventData:GetInt("MessageID") if msgID == MSG_CHAT then local msg = eventData:GetBuffer("Data") local text = msg:ReadString() -- If we are the server, prepend the sender's IP address and port and echo to everyone -- If we are a client, just display the message if network.serverRunning then local sender = eventData:GetPtr("Connection", "Connection") text = sender:ToString() .. " " .. text local sendMsg = VectorBuffer() sendMsg:WriteString(text) -- Broadcast as in-order and reliable network:BroadcastMessage(MSG_CHAT, true, true, sendMsg) end ShowChatText(text) end end function HandleConnectionStatus(eventType, eventData) UpdateButtons() end
mit
sleepingwit/premake-core
binmodules/luasocket/test/ftptest.lua
19
3735
local socket = require("socket") local ftp = require("socket.ftp") local url = require("socket.url") local ltn12 = require("ltn12") -- use dscl to create user "luasocket" with password "password" -- with home in /Users/diego/luasocket/test/ftp -- with group com.apple.access_ftp -- with shell set to /sbin/nologin -- set /etc/ftpchroot to chroot luasocket -- must set group com.apple.access_ftp on user _ftp (for anonymous access) -- copy index.html to /var/empty/pub (home of user ftp) -- start ftp server with -- sudo -s launchctl load -w /System/Library/LaunchDaemons/ftp.plist -- copy index.html to /Users/diego/luasocket/test/ftp -- stop with -- sudo -s launchctl unload -w /System/Library/LaunchDaemons/ftp.plist -- override protection to make sure we see all errors --socket.protect = function(s) return s end dofile("testsupport.lua") local host = host or "localhost" local port, index_file, index, back, err, ret local t = socket.gettime() index_file = "index.html" -- a function that returns a directory listing local function nlst(u) local t = {} local p = url.parse(u) p.command = "nlst" p.sink = ltn12.sink.table(t) local r, e = ftp.get(p) return r and table.concat(t), e end -- function that removes a remote file local function dele(u) local p = url.parse(u) p.command = "dele" p.argument = string.gsub(p.path, "^/", "") if p.argumet == "" then p.argument = nil end p.check = 250 return ftp.command(p) end -- read index with CRLF convention index = readfile(index_file) io.write("testing wrong scheme: ") back, err = ftp.get("wrong://banana.com/lixo") assert(not back and err == "wrong scheme 'wrong'", err) print("ok") io.write("testing invalid url: ") back, err = ftp.get("localhost/dir1/index.html;type=i") assert(not back and err) print("ok") io.write("testing anonymous file download: ") back, err = socket.ftp.get("ftp://" .. host .. "/pub/index.html;type=i") assert(not err and back == index, err) print("ok") io.write("erasing before upload: ") ret, err = dele("ftp://luasocket:password@" .. host .. "/index.up.html") if not ret then print(err) else print("ok") end io.write("testing upload: ") ret, err = ftp.put("ftp://luasocket:password@" .. host .. "/index.up.html;type=i", index) assert(ret and not err, err) print("ok") io.write("downloading uploaded file: ") back, err = ftp.get("ftp://luasocket:password@" .. host .. "/index.up.html;type=i") assert(ret and not err and index == back, err) print("ok") io.write("erasing after upload/download: ") ret, err = dele("ftp://luasocket:password@" .. host .. "/index.up.html") assert(ret and not err, err) print("ok") io.write("testing weird-character translation: ") back, err = ftp.get("ftp://luasocket:password@" .. host .. "/%23%3f;type=i") assert(not err and back == index, err) print("ok") io.write("testing parameter overriding: ") local back = {} ret, err = ftp.get{ url = "//stupid:mistake@" .. host .. "/index.html", user = "luasocket", password = "password", type = "i", sink = ltn12.sink.table(back) } assert(ret and not err and table.concat(back) == index, err) print("ok") io.write("testing upload denial: ") ret, err = ftp.put("ftp://" .. host .. "/index.up.html;type=a", index) assert(not ret and err, "should have failed") print(err) io.write("testing authentication failure: ") ret, err = ftp.get("ftp://luasocket:wrong@".. host .. "/index.html;type=a") assert(not ret and err, "should have failed") print(err) io.write("testing wrong file: ") back, err = ftp.get("ftp://".. host .. "/index.wrong.html;type=a") assert(not back and err, "should have failed") print(err) print("passed all tests") print(string.format("done in %.2fs", socket.gettime() - t))
bsd-3-clause
moteus/lzmq
examples/zap.lua
15
1952
local zmq = require "lzmq" local zloop = require "lzmq.loop" local function recv_zap(sok) local msg, err = sok:recv_all() if not msg then return nil, err end local req = { version = msg[1]; -- Version number, must be "1.0" sequence = msg[2]; -- Sequence number of request domain = msg[3]; -- Server socket domain address = msg[4]; -- Client IP address identity = msg[5]; -- Server socket idenntity mechanism = msg[6]; -- Security mechansim } if req.mechanism == "PLAIN" then req.username = msg[7]; -- PLAIN user name req.password = msg[8]; -- PLAIN password, in clear text elseif req.mechanism == "CURVE" then req.client_key = msg[7]; -- CURVE client public key end return req end local function send_zap(sok, req, status, text, user, meta) return sok:sendx(req.version, req.sequence, status, text, user or "", meta or "") end local loop = zloop.new() -- Setup auth handler -- http://rfc.zeromq.org/spec:27 zmq.assert(loop:add_new_bind(zmq.REP, "inproc://zeromq.zap.01", function(sok) local req = zmq.assert(recv_zap(sok)) print("Accept :", req.address) -- accept all connections zmq.assert(send_zap(sok, req, "200", "welcome")) end)) -- This is server local server = zmq.assert(loop:create_socket(zmq.REP,{ zap_domain = "global"; bind = "tcp://*:9000"; })) loop:add_socket(server, function(sok) print("SERVER: ", (zmq.assert(sok:recv()))) sok:send(", world!") end) -- This is client `process` loop:add_once(0, function() -- try connect to server local client = zmq.assert(loop:create_socket(zmq.REQ, { connect = "tcp://127.0.0.1:9000" })) loop:add_socket(client, zmq.POLLOUT + zmq.POLLIN, function(sok, ev) if ev == zmq.POLLOUT then sok:send("Hello") else print("CLIENT: ", (zmq.assert(sok:recv()))) loop:interrupt() end end) end) loop:add_once(1000, function() loop:interrupt() end) loop:start()
mit
Cat5TV/tps_skyblock
mods/skyblock/skyblock_levels/register_command.lua
1
2384
--[[ Skyblock for Minetest Copyright (c) 2015 cornernote, Brett O'Donnell <cornernote@gmail.com> Source Code: https://github.com/cornernote/minetest-skyblock License: GPLv3 ]]-- -- register register_privilege minetest.register_privilege('level', 'Can use /level') -- level minetest.register_chatcommand('level', { description = 'Get or change a players current level.', privs = {level = true}, params = "<player_name> <level>", func = function(name, param) local found, _, player_name, level = param:find("^([^%s]+)%s+(.+)$") if not player_name then player_name = name end level = tonumber(level) if not level then minetest.chat_send_player(name, player_name..' is on level '..skyblock.feats.get_level(player_name)) return end if skyblock.feats.set_level(player_name, level) then minetest.chat_send_player(name, player_name..' has been set to level '..level) else minetest.chat_send_player(name, 'cannot change '..player_name..' to level '..level) end end, }) -- who minetest.register_chatcommand('who', { description = 'Display list of online players and their current level.', func = function(name) minetest.chat_send_player(name, 'Current Players:') for _,player in ipairs(minetest.get_connected_players()) do local player_name = player:get_player_name() minetest.chat_send_player(name, ' - '..player_name..' - level '..skyblock.feats.get_level(player_name)) end end, }) if minetest.get_modpath('sethome') then minetest.unregister_chatcommand('sethome') minetest.override_chatcommand('home', { privs = {home=true}, description = "Teleports you to your spawn position", func = function(name) local spawn = skyblock.get_spawn(name) local pos = {x = spawn.x, y = spawn.y + 1.5, z= spawn.z} local player = minetest.get_player_by_name(name) player:setpos(pos) return end, }) else minetest.register_privilege('home', { description = "Can use /home", give_to_singleplayer = true }) minetest.register_chatcommand('home', { privs = {home=true}, description = "Teleports you to your spawn position", func = function(name) local spawn = skyblock.get_spawn(name) local pos = {x = spawn.x, y = spawn.y + 1.5, z= spawn.z} local player = minetest.get_player_by_name(name) player:setpos(pos) return end, }) end
lgpl-2.1
Blackdutchie/Zero-K
units/armaak.lua
2
6778
unitDef = { unitname = [[armaak]], name = [[Archangel]], description = [[Heavy Anti-Air Jumper]], acceleration = 0.18, brakeRate = 0.2, buildCostEnergy = 550, buildCostMetal = 550, buildPic = [[ARMAAK.png]], buildTime = 550, canMove = true, category = [[LAND]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[30 48 30]], collisionVolumeTest = 1, collisionVolumeType = [[cylY]], corpse = [[DEAD]], customParams = { canjump = 1, jump_range = 400, jump_speed = 6, jump_reload = 10, jump_from_midair = 0, description_bp = [[Robô anti-ar pesado]], description_de = [[Flugabwehr Springer]], description_fi = [[Korkeatehoinen ilmatorjuntarobotti]], description_fr = [[Marcheur Anti-Air Lourd]], description_pl = [[Ciezki robot przeciwlotniczy (skacze)]], helptext = [[The Archangel packs twin anti-air lasers and an autocannon for slaying enemy aircraft rapidly. It can also jump to quickly access high ground or to escape.]], helptext_de = [[Der Archangel besitzt ein Doppel-Anti-Air-Laser und eine automatische Kanone, um gegnerische Lufteinheiten zu zerstören. Der Archangel kann auch einen Sprung machen.]], helptext_bp = [[]], helptext_fi = [[Archangel:in kaksoislaserit sek? automaattitykki tuhoavat vihollisen ilma-alukset tehokkaasti ja nopeasti.]], helptext_fr = [[L'Archangel est munis d'un laser double anti air et d'un autocannon similaire au packo pour pouvoir an?antire les avions enemis.]], helptext_pl = [[Archangel posiada silne dzialko i lasery przeciwlotnicze, ktore zadaja lotnictwu ogromne straty. Posiada takze mozliwosc skoku.]], modelradius = [[15]], }, explodeAs = [[BIG_UNITEX]], footprintX = 2, footprintZ = 2, iconType = [[jumpjetaa]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, mass = 236, maxDamage = 1500, maxSlope = 36, maxVelocity = 2.017, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[KBOT2]], moveState = 0, noChaseCategory = [[TERRAFORM LAND SINK TURRET SHIP SATELLITE SWIM FLOAT SUB HOVER]], objectName = [[hunchback.s3o]], script = [[armaak.lua]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], side = [[ARM]], sightDistance = 660, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 28, turnRate = 1400, upright = true, weapons = { { def = [[LASER]], --badTargetCategory = [[GUNSHIP]], onlyTargetCategory = [[GUNSHIP FIXEDWING]], }, { def = [[EMG]], --badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING GUNSHIP]], }, }, weaponDefs = { EMG = { name = [[Anti-Air Autocannon]], accuracy = 512, alphaDecay = 0.7, areaOfEffect = 8, canattackground = false, craterBoost = 0, craterMult = 0, cylinderTargeting = 1, customParams = { isaa = [[1]], }, damage = { default = 0.78, planes = 7.8, subs = 0.5, }, explosionGenerator = [[custom:ARCHPLOSION]], impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, intensity = 0.8, interceptedByShieldType = 1, predictBoost = 1, proximityPriority = 4, range = 1040, reloadtime = 0.1, rgbColor = [[1 0.95 0.4]], separation = 1.5, soundStart = [[weapon/cannon/brawler_emg]], stages = 10, sweepfire = false, tolerance = 8192, turret = true, weaponTimer = 1, weaponType = [[Cannon]], weaponVelocity = 1500, }, LASER = { name = [[Anti-Air Laser Battery]], areaOfEffect = 12, beamDecay = 0.736, beamTime = 0.01, beamttl = 15, canattackground = false, coreThickness = 0.5, craterBoost = 0, craterMult = 0, cylinderTargeting = 1, customParams = { isaa = [[1]], }, damage = { default = 1.636, planes = 16.36, subs = 0.94, }, explosionGenerator = [[custom:flash_teal7]], fireStarter = 100, impactOnly = true, impulseFactor = 0, interceptedByShieldType = 1, laserFlareSize = 3.25, minIntensity = 1, noSelfDamage = true, range = 820, reloadtime = 0.1, rgbColor = [[0 1 1]], soundStart = [[weapon/laser/rapid_laser]], soundStartVolume = 4, thickness = 2.165, tolerance = 8192, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 2200, }, }, featureDefs = { DEAD = { description = [[Wreckage - Archangel]], blocking = true, damage = 1500, energy = 0, featureDead = [[HEAP]], footprintX = 4, footprintZ = 4, height = [[15]], hitdensity = [[100]], metal = 220, object = [[hunchback_dead.s3o]], reclaimable = true, reclaimTime = 220, }, HEAP = { description = [[Debris - Archangel]], blocking = false, damage = 1500, energy = 0, footprintX = 4, footprintZ = 4, height = [[4]], hitdensity = [[100]], metal = 110, object = [[debris4x4c.s3o]], reclaimable = true, reclaimTime = 110, }, }, } return lowerkeys({ armaak = unitDef })
gpl-2.0
moononournation/nodemcu-webide
bin/led-text.lua
2
1201
return function (connection, req, args) dofile('httpserver-header.lc')(connection, 200, 'html') local w, h, dataWidth, offset = 10, 6, 36, 0 -- timer id(0-6), interval in ms local tmrId, tmrMs = 4, 200 if req.method == 'POST' then local rd = req.getRequestData() if (rd['data'] ~= nil) then file.open('led-text.dat', 'w+') file.write(rd['data']) file.close() end end collectgarbage() tmr.alarm(tmrId, tmrMs, tmr.ALARM_SEMI, function() if offset < dataWidth then local data = '' file.open('led-text.dat', 'r') local row = 0 while row < h do file.seek("set", (row * dataWidth + offset) * 3) local size = w if (offset + w > dataWidth) then size = dataWidth - offset end data = data .. file.read(size * 3) if size < w then data = data .. string.char(0):rep((w - size) * 3) end row = row + 1 end file.close() ws2812.write(data) offset = offset + 1 tmr.start(tmrId) else ws2812.write(string.char(0):rep(w*h*3)) tmr.unregister(tmrId) end end) end
gpl-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/talents/uber/dex.lua
1
9590
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org uberTalent{ name = "Through The Crowd", require = { special={desc="Have had at least 6 party members at the same time", fct=function(self) return self:attr("huge_party") end} }, mode = "sustained", on_learn = function(self, t) self:attr("bump_swap_speed_divide", 10) end, on_unlearn = function(self, t) self:attr("bump_swap_speed_divide", -10) end, callbackOnAct = function(self, t) local nb_friends = 0 local act for i = 1, #self.fov.actors_dist do act = self.fov.actors_dist[i] if act and self:reactionToward(act) > 0 and self:canSee(act) then nb_friends = nb_friends + 1 end end if nb_friends > 1 then nb_friends = math.min(nb_friends, 5) self:setEffect(self.EFF_THROUGH_THE_CROWD, 4, {power=nb_friends * 10}) end end, activate = function(self, t) local ret = {} self:talentTemporaryValue(ret, "nullify_all_friendlyfire", 1) return ret end, deactivate = function(self, t, p) return true end, info = function(self, t) return ([[You are used to a crowded party: - you can swap places with friendly creatures in just one tenth of a turn as a passive effect. - you can never damage your friends or neutral creatures while this talent is active. - you love being surrounded by friends; for each friendly creature in sight you gain +10 to all saves]]) :format() end, } uberTalent{ name = "Swift Hands", mode = "passive", on_learn = function(self, t) self:attr("quick_weapon_swap", 1) self:attr("quick_equip_cooldown", 1) self:attr("quick_wear_takeoff", 1) end, on_unlearn = function(self, t) self:attr("quick_weapon_swap", -1) self:attr("quick_equip_cooldown", -1) self:attr("quick_wear_takeoff", -1) end, info = function(self, t) return ([[You have very agile hands; swapping equipment sets (default q key) takes no time, nor does equipping/unequipping items. The free item switch may only happen once per turn. The cooldown for equipping activatable equipment is removed.]]) :format() end, } uberTalent{ name = "Windblade", mode = "activated", require = { special={desc="Have dealt over 50000 damage with dual wielded weapons", fct=function(self) return self.damage_log and self.damage_log.weapon.dualwield and self.damage_log.weapon.dualwield >= 50000 end} }, cooldown = 12, radius = 4, range = 0, tactical = { ATTACKAREA = { weapon = 2 }, DISABLE = { disarm = 2 } }, target = function(self, t) return {type="ball", range=self:getTalentRange(t), selffire=false, radius=self:getTalentRadius(t)} end, is_melee = true, requires_target = true, action = function(self, t) local tg = self:getTalentTarget(t) self:project(tg, self.x, self.y, function(px, py, tg, self) local target = game.level.map(px, py, Map.ACTOR) if target and target ~= self then local hit = self:attackTarget(target, nil, 3.2, true) if hit and target:canBe("disarm") then target:setEffect(target.EFF_DISARMED, 4, {}) end end end) self:addParticles(Particles.new("meleestorm", 1, {radius=4, img="spinningwinds_blue"})) return true end, info = function(self, t) return ([[You spin madly, generating a sharp gust of wind with your weapons that deals 320%% weapon damage to all targets within radius 4 and disarms them for 4 turns.]]) :format() end, } uberTalent{ name = "Windtouched Speed", mode = "passive", require = { special={desc="Know at least 20 talent levels of equilibrium-using talents", fct=function(self) return knowRessource(self, "equilibrium", 20) end} }, on_learn = function(self, t) self:attr("global_speed_add", 0.2) self:attr("avoid_pressure_traps", 1) self:recomputeGlobalSpeed() end, on_unlearn = function(self, t) self:attr("global_speed_add", -0.2) self:attr("avoid_pressure_traps", -1) self:recomputeGlobalSpeed() end, info = function(self, t) return ([[You are attuned with Nature, and she helps you in your fight against the arcane forces. You gain 20%% permanent global speed and do not trigger pressure traps.]]) :format() end, } uberTalent{ name = "Giant Leap", mode = "activated", require = { special={desc="Have dealt over 50000 damage with any weapon or unarmed", fct=function(self) return self.damage_log and ( (self.damage_log.weapon.twohanded and self.damage_log.weapon.twohanded >= 50000) or (self.damage_log.weapon.shield and self.damage_log.weapon.shield >= 50000) or (self.damage_log.weapon.dualwield and self.damage_log.weapon.dualwield >= 50000) or (self.damage_log.weapon.other and self.damage_log.weapon.other >= 50000) ) end} }, cooldown = 20, radius = 1, range = 10, is_melee = true, tactical = { CLOSEIN = 2, ATTACKAREA = { weapon = 2 }, DISABLE = { daze = 1 } }, target = function(self, t) return {type="ball", range=self:getTalentRange(t), selffire=false, radius=self:getTalentRadius(t)} end, action = function(self, t) local tg = self:getTalentTarget(t) local x, y, target = self:getTarget(tg) if not x or not y then return nil end local _ _, x, y = self:canProject(tg, x, y) if game.level.map(x, y, Map.ACTOR) then x, y = util.findFreeGrid(x, y, 1, true, {[Map.ACTOR]=true}) if not x then return end end if game.level.map:checkAllEntities(x, y, "block_move") then return end local ox, oy = self.x, self.y self:move(x, y, true) if config.settings.tome.smooth_move > 0 then self:resetMoveAnim() self:setMoveAnim(ox, oy, 8, 5) end self:project(tg, self.x, self.y, function(px, py, tg, self) local target = game.level.map(px, py, Map.ACTOR) if target and target ~= self then local hit = self:attackTarget(target, nil, 2, true) if hit and target:canBe("stun") then target:setEffect(target.EFF_DAZED, 3, {}) end end end) return true end, info = function(self, t) return ([[You accurately jump to the target and deal 200%% weapon damage to all foes within radius 1 on impact as well as dazing them for 3 turns.]]) :format() end, } uberTalent{ name = "Crafty Hands", mode = "passive", require = { special={desc="Know Imbue Item to level 5", fct=function(self) return self:getTalentLevelRaw(self.T_IMBUE_ITEM) >= 5 end} }, info = function(self, t) return ([[You are very crafty. You can now also embed gems into helms and belts.]]) :format() end, } uberTalent{ name = "Roll With It", mode = "sustained", cooldown = 10, tactical = { ESCAPE = 1 }, require = { special={desc="Have been knocked around at least 50 times", fct=function(self) return self:attr("knockback_times") and self:attr("knockback_times") >= 50 end} }, -- Called by default projector in mod.data.damage_types.lua getMult = function(self, t) return self:combatLimit(self:getDex(), 0.7, 0.9, 50, 0.85, 100) end, -- Limit > 70% damage taken activate = function(self, t) local ret = {} self:talentTemporaryValue(ret, "knockback_on_hit", 1) self:talentTemporaryValue(ret, "movespeed_on_hit", {speed=3, dur=1}) return ret end, deactivate = function(self, t, p) return true end, info = function(self, t) return ([[You have learned to take a few hits when needed and can flow with the tide of battle. So long as you can move, you find a way to dodge, evade, deflect or otherwise reduce physical damage against you by %d%%. Once per turn, when you get hit by a melee or archery attack you move back one tile for free and gain 200%% movement speed for a turn. The damage avoidance scales with your Dexterity and applies after resistances.]]) :format(100*(1-t.getMult(self, t))) end, } uberTalent{ name = "Vital Shot", no_energy = "fake", cooldown = 10, range = archery_range, require = { special={desc="Have dealt over 50000 damage with ranged weapons", fct=function(self) return self.damage_log and self.damage_log.weapon.archery and self.damage_log.weapon.archery >= 50000 end} }, tactical = { ATTACK = { weapon = 3 }, DISABLE = 3 }, requires_target = true, on_pre_use = function(self, t, silent) return Talents.archerPreUse(self, t, silent) end, archery_onhit = function(self, t, target, x, y) if target:canBe("stun") then target:setEffect(target.EFF_STUNNED, 5, {apply_power=self:combatAttack()}) end target:setEffect(target.EFF_CRIPPLE, 5, {speed=0.50, apply_power=self:combatAttack()}) end, action = function(self, t) local targets = self:archeryAcquireTargets(nil, {one_shot=true}) if not targets then return end self:archeryShoot(targets, t, nil, {mult=4.5}) return true end, info = function(self, t) return ([[You fire a shot straight at your enemy's vital areas, wounding them terribly. Enemies hit by this shot will take 450%% weapon damage and will be stunned and crippled (losing 50%% physical, magical and mental attack speeds) for five turns due to the devastating impact of the shot. The stun and cripple chances increase with your Accuracy.]]):format() end, }
gpl-3.0
sleepingwit/premake-core
modules/vstudio/tests/vc2010/test_config_props.lua
8
9262
-- -- tests/actions/vstudio/vc2010/test_config_props.lua -- Validate generation of the configuration property group. -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_vs2010_config_props") local vc2010 = p.vstudio.vc2010 local project = p.project -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2010") wks, prj = test.createWorkspace() end local function prepare() cfg = test.getconfig(prj, "Debug") vc2010.configurationProperties(cfg) end -- -- Check the structure with the default project values. -- function suite.structureIsCorrect_onDefaultValues() prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v100</PlatformToolset> </PropertyGroup> ]] end -- -- Check the configuration type for differenet project kinds. -- function suite.configurationType_onConsoleApp() kind "ConsoleApp" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> ]] end function suite.configurationType_onWindowedApp() kind "WindowedApp" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> ]] end function suite.configurationType_onSharedLib() kind "SharedLib" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> ]] end function suite.configurationType_onStaticLib() kind "StaticLib" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> ]] end -- -- Debug configurations (for some definition of "debug") should use the debug libraries. -- function suite.debugLibraries_onDebugConfig() symbols "On" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> ]] end -- -- Check the support for Managed C++. -- function suite.clrSupport_onClrOn() clr "On" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CLRSupport>true</CLRSupport> ]] end function suite.clrSupport_onClrOff() clr "Off" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> ]] end function suite.clrSupport_onClrUnsafe() clr "Unsafe" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CLRSupport>true</CLRSupport> ]] end function suite.clrSupport_onClrSafe() clr "Safe" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CLRSupport>Safe</CLRSupport> ]] end function suite.clrSupport_onClrPure() clr "Pure" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CLRSupport>Pure</CLRSupport> ]] end -- -- Check the support for building with MFC. -- function suite.useOfMfc_onDynamicRuntime() flags "MFC" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <UseOfMfc>Dynamic</UseOfMfc> ]] end function suite.useOfMfc_onStaticRuntime() flags { "MFC" } staticruntime "On" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <UseOfMfc>Static</UseOfMfc> ]] end -- -- Check the support for building with ATL. -- function suite.useOfAtl_onDynamicRuntime() atl "Dynamic" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <UseOfATL>Dynamic</UseOfATL> ]] end function suite.useOfAtl_onStaticRuntime() atl "Static" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <UseOfATL>Static</UseOfATL> ]] end -- -- Check handling of the ReleaseRuntime flag; should override the -- default behavior of linking the debug runtime when symbols are -- enabled with no optimizations. -- function suite.releaseRuntime_onFlag() runtime "Release" symbols "On" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> ]] end -- -- Check the default settings for a Makefile configuration: new -- configuration type, no character set, output and intermediate -- folders are moved up from their normal location in the output -- configuration element. -- function suite.structureIsCorrect_onMakefile() kind "Makefile" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Makefile</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <OutDir>bin\Debug\</OutDir> <IntDir>obj\Debug\</IntDir> </PropertyGroup> ]] end function suite.structureIsCorrect_onNone() kind "None" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Makefile</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <OutDir>bin\Debug\</OutDir> <IntDir>obj\Debug\</IntDir> </PropertyGroup> ]] end -- -- Same as above but for Utility -- function suite.structureIsCorrect_onUtility() kind "Utility" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Utility</ConfigurationType> <PlatformToolset>v100</PlatformToolset> </PropertyGroup> ]] end -- -- Check the LinkTimeOptimization flag -- function suite.useOfLinkTimeOptimization() flags { "LinkTimeOptimization" } prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v100</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> ]] end -- -- Check the WindowsSDKDesktopARMSupport element -- function suite.WindowsSDKDesktopARMSupport_off() system "ios" architecture "ARM" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v100</PlatformToolset> </PropertyGroup> ]] end function suite.WindowsSDKDesktopARMSupport_on() system "windows" architecture "ARM" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v100</PlatformToolset> <WindowsSDKDesktopARMSupport>true</WindowsSDKDesktopARMSupport> </PropertyGroup> ]] end function suite.WindowsSDKDesktopARM64Support() system "windows" architecture "ARM64" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v100</PlatformToolset> <WindowsSDKDesktopARM64Support>true</WindowsSDKDesktopARM64Support> </PropertyGroup> ]] end
bsd-3-clause
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/general/grids/water.lua
1
11029
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org ------------------------------------------------------------ -- For inside the sea ------------------------------------------------------------ newEntity{ define_as = "WATER_FLOOR", type = "floor", subtype = "underwater", name = "underwater", image = "terrain/underwater/subsea_floor_02.png", display = '.', color=colors.LIGHT_BLUE, back_color=colors.DARK_BLUE, air_level = -5, air_condition="water", nice_tiler = { method="replace", base={"WATER_FLOOR", 10, 1, 5}}, } for i = 1, 5 do newEntity{ base="WATER_FLOOR", define_as = "WATER_FLOOR"..i, image = "terrain/underwater/subsea_floor_02"..string.char(string.byte('a')+i-1)..".png" } end newEntity{ define_as = "WATER_WALL", type = "wall", subtype = "underwater", name = "coral wall", image = "terrain/underwater/subsea_granite_wall1.png", display = '#', color=colors.AQUAMARINE, back_color=colors.DARK_BLUE, always_remember = true, can_pass = {pass_wall=1}, does_block_move = true, block_sight = true, air_level = -5, z = 3, nice_tiler = { method="wall3d", inner={"WATER_WALL", 100, 1, 5}, north={"WATER_WALL_NORTH", 100, 1, 5}, south={"WATER_WALL_SOUTH", 10, 1, 14}, north_south="WATER_WALL_NORTH_SOUTH", small_pillar="WATER_WALL_SMALL_PILLAR", pillar_2="WATER_WALL_PILLAR_2", pillar_8={"WATER_WALL_PILLAR_8", 100, 1, 5}, pillar_4="WATER_WALL_PILLAR_4", pillar_6="WATER_WALL_PILLAR_6" }, always_remember = true, does_block_move = true, can_pass = {pass_wall=1}, block_sight = true, air_level = -20, dig = "WATER_FLOOR", } for i = 1, 5 do newEntity{ base = "WATER_WALL", define_as = "WATER_WALL"..i, image = "terrain/underwater/subsea_granite_wall1_"..i..".png", z = 3} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_NORTH"..i, image = "terrain/underwater/subsea_granite_wall1_"..i..".png", z = 3, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall3.png", z=18, display_y=-1}}} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_PILLAR_8"..i, image = "terrain/underwater/subsea_granite_wall1_"..i..".png", z = 3, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall_pillar_8.png", z=18, display_y=-1}}} end newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_NORTH_SOUTH", image = "terrain/underwater/subsea_granite_wall2.png", z = 3, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall3.png", z=18, display_y=-1}}} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_SOUTH", image = "terrain/underwater/subsea_granite_wall2.png", z = 3} for i = 1, 14 do newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_SOUTH"..i, image = "terrain/underwater/subsea_granite_wall2_"..i..".png", z = 3} end newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_SMALL_PILLAR", image = "terrain/underwater/subsea_floor_02.png", z=1, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall_pillar_small.png",z=3}, class.new{image="terrain/underwater/subsea_granite_wall_pillar_small_top.png", z=18, display_y=-1}}} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_PILLAR_6", image = "terrain/underwater/subsea_floor_02.png", z=1, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall_pillar_3.png",z=3}, class.new{image="terrain/underwater/subsea_granite_wall_pillar_9.png", z=18, display_y=-1}}} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_PILLAR_4", image = "terrain/underwater/subsea_floor_02.png", z=1, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall_pillar_1.png",z=3}, class.new{image="terrain/underwater/subsea_granite_wall_pillar_7.png", z=18, display_y=-1}}} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_PILLAR_2", image = "terrain/underwater/subsea_floor_02.png", z=1, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall_pillar_2.png",z=3}}} newEntity{ define_as = "WATER_DOOR", type = "wall", subtype = "underwater", name = "door", image = "terrain/underwater/subsea_stone_wall_door_closed.png", display = '+', color_r=238, color_g=154, color_b=77, back_color=colors.DARK_UMBER, nice_tiler = { method="door3d", north_south="WATER_DOOR_VERT", west_east="WATER_DOOR_HORIZ" }, notice = true, always_remember = true, block_sight = true, air_level = -5, air_condition="water", is_door = true, door_opened = "WATER_DOOR_OPEN", dig = "WATER_FLOOR", } newEntity{ define_as = "WATER_DOOR_OPEN", type = "wall", subtype = "underwater", name = "open door", image="terrain/underwater/subsea_granite_door1_open.png", display = "'", color_r=238, color_g=154, color_b=77, back_color=colors.DARK_GREY, always_remember = true, air_level = -5, air_condition="water", is_door = true, door_closed = "WATER_DOOR", } newEntity{ base = "WATER_DOOR", define_as = "WATER_DOOR_HORIZ", image = "terrain/underwater/subsea_stone_wall_door_closed.png", add_displays = {class.new{image="terrain/underwater/subsea_granite_wall3.png", z=18, display_y=-1}}, door_opened = "WATER_DOOR_HORIZ_OPEN"} newEntity{ base = "WATER_DOOR_OPEN", define_as = "WATER_DOOR_HORIZ_OPEN", image = "terrain/underwater/subsea_floor_02.png", add_displays = {class.new{image="terrain/underwater/subsea_stone_store_open.png", z=17}, class.new{image="terrain/underwater/subsea_granite_wall3.png", z=18, display_y=-1}}, door_closed = "WATER_DOOR_HORIZ"} newEntity{ base = "WATER_DOOR", define_as = "WATER_DOOR_VERT", image = "terrain/underwater/subsea_floor_02.png", add_displays = {class.new{image="terrain/underwater/subsea_granite_door1_vert.png", z=17}, class.new{image="terrain/underwater/subsea_granite_door1_vert_north.png", z=18, display_y=-1}}, door_opened = "WATER_DOOR_OPEN_VERT", dig = "WATER_DOOR_OPEN_VERT"} newEntity{ base = "WATER_DOOR_OPEN", define_as = "WATER_DOOR_OPEN_VERT", image = "terrain/underwater/subsea_floor_02.png", add_displays = {class.new{image="terrain/underwater/subsea_granite_door1_open_vert.png", z=17}, class.new{image="terrain/underwater/subsea_granite_door1_open_vert_north.png", z=18, display_y=-1}}, door_closed = "WATER_DOOR_VERT"} newEntity{ define_as = "WATER_FLOOR_BUBBLE", type = "floor", subtype = "water", name = "underwater air bubble", image = "terrain/underwater/subsea_floor_bubbles.png", desc = "#LIGHT_BLUE#Replenishes air level when standing inside.#LAST#", show_tooltip = true, display = ':', color=colors.LIGHT_BLUE, back_color=colors.DARK_BLUE, air_level = 15, nb_charges = resolvers.rngrange(4, 7), force_clone = true, on_stand = function(self, x, y, who) if ((who.can_breath.water and who.can_breath.water <= 0) or not who.can_breath.water) and not who:attr("no_breath") then self.nb_charges = self.nb_charges - 1 if self.nb_charges <= 0 then game.logSeen(who, "#AQUAMARINE#The air bubbles are depleted!") local g = game.zone:makeEntityByName(game.level, "terrain", "WATER_FLOOR") game.zone:addEntity(game.level, g, "terrain", x, y) end end end, } ------------------------------------------------------------ -- For outside ------------------------------------------------------------ newEntity{ define_as = "WATER_BASE", type = "floor", subtype = "water", name = "deep water", image = "terrain/water_floor.png", display = '~', color=colors.AQUAMARINE, back_color=colors.DARK_BLUE, always_remember = true, special_minimap = colors.BLUE, shader = "water", } ----------------------------------------- -- Water/grass ----------------------------------------- newEntity{ base="WATER_BASE", define_as = "DEEP_WATER", image="terrain/water_grass_5_1.png", air_level = -5, air_condition="water", } ----------------------------------------- -- Water(ocean)/grass ----------------------------------------- newEntity{ base="WATER_BASE", define_as = "DEEP_OCEAN_WATER", image = "terrain/ocean_water_grass_5_1.png", air_level = -5, air_condition="water", } ----------------------------------------- -- Poison water ----------------------------------------- newEntity{ define_as = "POISON_DEEP_WATER", type = "floor", subtype = "water", name = "poisoned deep water", image = "terrain/poisoned_water_01.png", display = '~', color=colors.YELLOW_GREEN, back_color=colors.DARK_GREEN, -- add_displays = class:makeWater(true, "poison_"), always_remember = true, air_level = -5, air_condition="water", mindam = resolvers.mbonus(10, 25), maxdam = resolvers.mbonus(20, 50), on_stand = function(self, x, y, who) if self.faction and who:reactionToward(self.faction) >= 0 then return end local DT = engine.DamageType local dam = DT:get(DT.POISON).projector(self, x, y, DT.POISON, rng.range(self.mindam, self.maxdam)) self.x, self.y = x, y if dam > 0 and who.player then self:logCombat(who, "#Source# poisons #Target#!") end end, combatAttack = function(self) return rng.range(self.mindam, self.maxdam) end, nice_tiler = { method="replace", base={"POISON_DEEP_WATER", 100, 1, 6}}, shader = "water", } for i = 1, 6 do newEntity{ base="POISON_DEEP_WATER", define_as = "POISON_DEEP_WATER"..i, image = "terrain/poisoned_water_0"..i..".png" } end ----------------------------------------- -- Dungeony exits ----------------------------------------- newEntity{ define_as = "WATER_UP_WILDERNESS", type = "floor", subtype = "water", name = "exit to the worldmap", image = "terrain/underwater/subsea_floor_02.png", add_mos = {{image="terrain/underwater/subsea_stair_up_wild.png"}}, display = '<', color_r=255, color_g=0, color_b=255, always_remember = true, notice = true, change_level = 1, change_zone = "wilderness", air_level = -5, air_condition="water", } newEntity{ define_as = "WATER_UP", type = "floor", subtype = "water", image = "terrain/underwater/subsea_floor_02.png", add_mos = {{image="terrain/underwater/subsea_stair_up.png"}}, name = "previous level", display = '<', color_r=255, color_g=255, color_b=0, notice = true, always_remember = true, change_level = -1, air_level = -5, air_condition="water", } newEntity{ define_as = "WATER_DOWN", type = "floor", subtype = "water", image = "terrain/underwater/subsea_floor_02.png", add_mos = {{image="terrain/underwater/subsea_stair_down_03_64.png"}}, name = "next level", display = '>', color_r=255, color_g=255, color_b=0, notice = true, always_remember = true, change_level = 1, air_level = -5, air_condition="water", }
gpl-3.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/general/objects/gloves.lua
1
2442
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Talents = require "engine.interface.ActorTalents" newEntity{ define_as = "BASE_GLOVES", slot = "HANDS", type = "armor", subtype="hands", add_name = " (#ARMOR#)", display = "[", color=colors.UMBER, image = resolvers.image_material("gloves", "leather"), moddable_tile = resolvers.moddable_tile("gloves"), encumber = 1, rarity = 9, wielder={combat = {accuracy_effect = "axe", physspeed = 0},}, desc = [[Light gloves which do not seriously hinder finger movements, while still protecting the hands somewhat.]], randart_able = "/data/general/objects/random-artifacts/gloves.lua", egos = "/data/general/objects/egos/gloves.lua", egos_chance = { prefix=resolvers.mbonus(40, 5), suffix=resolvers.mbonus(40, 5) }, } newEntity{ base = "BASE_GLOVES", name = "rough leather gloves", short_name = "rough", level_range = {1, 20}, cost = 5, material_level = 1, wielder = { combat_armor = 1, combat = { dam = resolvers.rngavg(5, 8), apr = 1, physcrit = 1, dammod = {dex=0.4, str=-0.6, cun=0.4 }, }, }, } newEntity{ base = "BASE_GLOVES", name = "hardened leather gloves", short_name = "hardened", level_range = {20, 40}, cost = 7, material_level = 3, wielder = { combat_armor = 2, combat = { dam = resolvers.rngavg(14, 18), apr = 3, physcrit = 3, dammod = {dex=0.4, str=-0.6, cun=0.4 }, }, }, } newEntity{ base = "BASE_GLOVES", name = "drakeskin leather gloves", short_name = "drakeskin", level_range = {40, 50}, cost = 10, material_level = 5, wielder = { combat_armor = 3, combat = { dam = resolvers.rngavg(23, 28), apr = 5, physcrit = 5, dammod = {dex=0.4, str=-0.6, cun=0.4 }, }, }, }
gpl-3.0
samuelmaddock/zombie-escape
ZombieEscape/gamemode/cl_init.lua
1
1998
include('shared.lua') --[[--------------------------------------- HUD -----------------------------------------]] CVars.ZombieFOV = CreateClientConVar( "ze_zfov", 110, true, false ) CVars.Vignette = CreateClientConVar( "ze_vignette", 1, true, false ) -- Because vignettes make everything look nicer local VignetteMat = Material("ze/vignette") function GM:HUDPaintBackground() self.BaseClass.HUDPaintBackground( self ) if CVars.Vignette:GetBool() then surface.SetDrawColor(0,0,0,200) surface.SetMaterial(VignetteMat) surface.DrawTexturedRect(0,0,ScrW(),ScrH()) end end /*--------------------------------------------------------- HUDShouldDraw Determine whether to draw parts of HUD ---------------------------------------------------------*/ GM.ZEHideHUD = {} GM.ZEHideHUD[ "CHudCrosshair" ] = true GM.ZEHideHUD[ "CHudZoom" ] = true GM.ZEShowHUD = {} GM.ZEShowHUD[ "CHudGMod" ] = true GM.ZEShowHUD[ "CHudChat" ] = true function GM:HUDShouldDraw(name) -- Hide certain HUD elements if self.ZEHideHUD[ name ] then return false end -- Don't draw too much over the win overlays if WinningTeam != nil and !self.ZEShowHUD[ name ] then return false end -- Sanity check if !LocalPlayer().IsZombie or !LocalPlayer().IsSpectator then return true end -- Hide parts of HUD for zombies and during weapon selection if ( !LocalPlayer():IsHuman() or self.bSelectingWeapons ) and name == "CHudWeaponSelection" then return false end return self.BaseClass.HUDShouldDraw( self, name ) end function GM:PlayerBindPress( ply, bind, pressed ) self.BaseClass.PlayerBindPress( self, ply, bind, pressed ) if ( bind == "+menu" && pressed ) then LocalPlayer():ConCommand( "lastinv" ) return true end return false end --[[--------------------------------------------------------- Name: gamemode:HUDPaint( ) Desc: Use this section to paint your HUD -----------------------------------------------------------]] function GM:HUDDrawTargetID() return false end
mit
mahdibagheri/aqa-mp3
plugins/twitter_send.lua
627
1555
do local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function run(msg, matches) if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter_send.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua" end if not is_sudo(msg) then return "You aren't allowed to send tweets" end local response_code, response_headers, response_status_line, response_body = client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", { status = matches[1] }) if response_code ~= 200 then return "Error: "..response_code end return "Tweet sent" end return { description = "Sends a tweet", usage = "!tw [text]: Sends the Tweet with the configured account.", patterns = {"^!tw (.+)"}, run = run } end
gpl-2.0
froggatt/openwrt-luci
libs/sys/luasrc/sys/zoneinfo/tzoffset.lua
72
3904
--[[ LuCI - Autogenerated Zoneinfo Module Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module "luci.sys.zoneinfo.tzoffset" OFFSET = { gmt = 0, -- GMT eat = 10800, -- EAT cet = 3600, -- CET wat = 3600, -- WAT cat = 7200, -- CAT wet = 0, -- WET sast = 7200, -- SAST eet = 7200, -- EET hast = -36000, -- HAST hadt = -32400, -- HADT akst = -32400, -- AKST akdt = -28800, -- AKDT ast = -14400, -- AST brt = -10800, -- BRT art = -10800, -- ART pyt = -14400, -- PYT pyst = -10800, -- PYST est = -18000, -- EST cst = -21600, -- CST cdt = -18000, -- CDT amt = -14400, -- AMT cot = -18000, -- COT mst = -25200, -- MST mdt = -21600, -- MDT vet = -16200, -- VET gft = -10800, -- GFT pst = -28800, -- PST pdt = -25200, -- PDT ect = -18000, -- ECT gyt = -14400, -- GYT bot = -14400, -- BOT pet = -18000, -- PET pmst = -10800, -- PMST pmdt = -7200, -- PMDT uyt = -10800, -- UYT uyst = -7200, -- UYST fnt = -7200, -- FNT srt = -10800, -- SRT egt = -3600, -- EGT egst = 0, -- EGST nst = -12600, -- NST ndt = -9000, -- NDT wst = 28800, -- WST davt = 25200, -- DAVT ddut = 36000, -- DDUT mist = 39600, -- MIST mawt = 18000, -- MAWT nzst = 43200, -- NZST nzdt = 46800, -- NZDT rott = -10800, -- ROTT syot = 10800, -- SYOT vost = 21600, -- VOST almt = 21600, -- ALMT anat = 43200, -- ANAT aqtt = 18000, -- AQTT tmt = 18000, -- TMT azt = 14400, -- AZT azst = 18000, -- AZST ict = 25200, -- ICT kgt = 21600, -- KGT bnt = 28800, -- BNT chot = 28800, -- CHOT ist = 19800, -- IST bdt = 21600, -- BDT tlt = 32400, -- TLT gst = 14400, -- GST tjt = 18000, -- TJT hkt = 28800, -- HKT hovt = 25200, -- HOVT irkt = 32400, -- IRKT wit = 25200, -- WIT eit = 32400, -- EIT aft = 16200, -- AFT pett = 43200, -- PETT pkt = 18000, -- PKT npt = 20700, -- NPT krat = 28800, -- KRAT myt = 28800, -- MYT magt = 43200, -- MAGT cit = 28800, -- CIT pht = 28800, -- PHT novt = 25200, -- NOVT omst = 25200, -- OMST orat = 18000, -- ORAT kst = 32400, -- KST qyzt = 21600, -- QYZT mmt = 23400, -- MMT sakt = 39600, -- SAKT uzt = 18000, -- UZT sgt = 28800, -- SGT get = 14400, -- GET btt = 21600, -- BTT jst = 32400, -- JST ulat = 28800, -- ULAT vlat = 39600, -- VLAT yakt = 36000, -- YAKT yekt = 21600, -- YEKT azot = -3600, -- AZOT azost = 0, -- AZOST cvt = -3600, -- CVT fkt = -14400, -- FKT fkst = -10800, -- FKST cwst = 31500, -- CWST lhst = 37800, -- LHST lhst = 39600, -- LHST fet = 10800, -- FET msk = 14400, -- MSK samt = 14400, -- SAMT volt = 14400, -- VOLT iot = 21600, -- IOT cxt = 25200, -- CXT cct = 23400, -- CCT tft = 18000, -- TFT sct = 14400, -- SCT mvt = 18000, -- MVT mut = 14400, -- MUT ret = 14400, -- RET chast = 45900, -- CHAST chadt = 49500, -- CHADT chut = 36000, -- CHUT vut = 39600, -- VUT phot = 46800, -- PHOT tkt = -36000, -- TKT fjt = 43200, -- FJT tvt = 43200, -- TVT galt = -21600, -- GALT gamt = -32400, -- GAMT sbt = 39600, -- SBT hst = -36000, -- HST lint = 50400, -- LINT kost = 39600, -- KOST mht = 43200, -- MHT mart = -34200, -- MART sst = -39600, -- SST nrt = 43200, -- NRT nut = -39600, -- NUT nft = 41400, -- NFT nct = 39600, -- NCT pwt = 32400, -- PWT pont = 39600, -- PONT pgt = 36000, -- PGT ckt = -36000, -- CKT taht = -36000, -- TAHT gilt = 43200, -- GILT tot = 46800, -- TOT wakt = 43200, -- WAKT wft = 43200, -- WFT }
apache-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/maps/towns/last-hope.lua
1
6492
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org quickEntity('@', {show_tooltip=true, name="Statue of King Tolak the Fair", display='@', image="terrain/grass.png", add_displays = {mod.class.Grid.new{image="terrain/statues/statue_tolak.png", z=18, display_y=-1, display_h=2}}, color=colors.LIGHT_BLUE, block_move=function(self, x, y, e, act, couldpass) if e and e.player and act then game.party:learnLore("last-hope-tolak-statue") end return true end}) quickEntity('Z', {show_tooltip=true, name="Statue of King Toknor the Brave", display='@', image="terrain/grass.png", add_displays = {mod.class.Grid.new{image="terrain/statues/statue_toknor.png", z=18, display_y=-1, display_h=2}}, color=colors.LIGHT_BLUE, block_move=function(self, x, y, e, act, couldpass) if e and e.player and act then game.party:learnLore("last-hope-toknor-statue") end return true end}) quickEntity('Y', {show_tooltip=true, name="Statue of Queen Mirvenia the Inspirer", display='@', image="terrain/grass.png", add_displays = {mod.class.Grid.new{image="terrain/statues/statue_mirvenia.png", z=18, display_y=-1, display_h=2}}, color=colors.LIGHT_BLUE, block_move=function(self, x, y, e, act, couldpass) if e and e.player and act then game.party:learnLore("last-hope-mirvenia-statue") end return true end}) quickEntity('X', {show_tooltip=true, name="Declaration of the Unification of the Allied Kingdoms", display='@', image="terrain/grass.png", add_displays = {mod.class.Grid.new{image="terrain/statues/monument_allied_kingdoms.png", z=18, display_y=-1, display_h=2}}, color=colors.LIGHT_BLUE, block_move=function(self, x, y, e, act, couldpass) if e and e.player and act then game.party:learnLore("last-hope-allied-kingdoms-foundation") end return true end}) -- defineTile section defineTile("<", "GRASS_UP_WILDERNESS") defineTile("#", "HARDWALL") defineTile("&", "HARDMOUNTAIN_WALL") defineTile("~", "DEEP_WATER") defineTile("_", "FLOOR_ROAD_STONE") defineTile("-", "GRASS_ROAD_STONE") defineTile(".", "GRASS") defineTile("t", "TREE") defineTile(" ", "FLOOR") defineTile('1', "HARDWALL", nil, nil, "SWORD_WEAPON_STORE") defineTile('2', "HARDWALL", nil, nil, "AXE_WEAPON_STORE") defineTile('3', "HARDWALL", nil, nil, "KNIFE_WEAPON_STORE") defineTile('4', "HARDWALL", nil, nil, "MAUL_WEAPON_STORE") defineTile('5', "HARDWALL", nil, nil, "HEAVY_ARMOR_STORE") defineTile('6', "HARDWALL", nil, nil, "LIGHT_ARMOR_STORE") defineTile('7', "HARDWALL", nil, nil, "CLOTH_ARMOR_STORE") defineTile('8', "HARDWALL", nil, nil, "HERBALIST") defineTile('9', "HARDWALL", nil, nil, "RUNES") defineTile('A', "HARDWALL", nil, nil, "ARCHER_WEAPON_STORE") defineTile('B', "HARDWALL", nil, nil, "LIBRARY") defineTile('E', "HARDWALL", nil, nil, "ELDER") defineTile('T', "HARDWALL", nil, nil, "TANNEN") defineTile('H', "HARDWALL", nil, nil, "ALCHEMIST") defineTile('M', "HARDWALL", nil, nil, "RARE_GOODS") defineTile('F', "HARDWALL", nil, nil, "MELINDA_FATHER") startx = 25 starty = 0 endx = 25 endy = 0 -- addSpot section addSpot({6, 20}, "pop-quest", "farportal") addSpot({7, 19}, "pop-quest", "farportal-player") addSpot({10, 19}, "pop-quest", "tannen-remove") addSpot({6, 19}, "pop-quest", "farportal-npc") -- addZone section -- ASCII map section return [[ ttttttttttttttttttttttttt<tttttttttttttttttttttttt ttttttttttttttttttttt~~~X-X~~~tttttttttttttttttttt ttttttttttttttttt~~~~~~~.-.~~~~~~~tttttttttttttttt ttttttttttttttt~~~~~~~~~.-.~~~~~~~~~tttttttttttttt ttttttttttttt~~~~~~~~####.####~~~~~~~~tttttttttttt tttttttttttt~~~~~~####_______####~~~~~~ttttttttttt tttttttttt~~~~~~### _ _ ###~~~~~~ttttttttt ttttttttt~~~~~### _ ### _ ###~~~~~tttttttt tttttttt~~~~~## _ ### _ ##~~~~~ttttttt ttttttt~~~~### ___ ### ___ ###~~~~tttttt tttttt~~~~## __ ### __ ##~~~~ttttt tttttt~~~## # __ ####### __ ##~~~ttttt ttttt~~~~# ### _ ##5# 7### _ # #~~~~tttt tttt~~~~## ##A# _ #6# ### _ ### ##~~~~ttt tttt~~~## ### _ # # _ M### ##~~~ttt ttt~~~~# 1# _ _________ _ ### #~~~~tt ttt~~~## ____~~~_~~~____ ## ##~~~tt tt~~~~# ### __~~~##.##~~~__ #~~~~t tt~~~## ### __~~###@.t###~~__ ##~~~t tt~~~# #T# __~~##ttY-Ztt##~~__ #~~~t tt~~~# ## _~~##tt-----tt##~~_ ## #~~~t t~~~## ## __~##t---&-&---t##~__ ## ##~~~ t~~~# ### _~~#tt-&&&-&&&-tt#~~_ ### #~~~ t~~~# ## _~##t--&&---&&--t##~_ ## #~~~ t~~~# ###### _~#tt-&&-###-&&-tt#~_ ###### #~~~ t~~~# ##### _~#tt-&&-#E#-&&-tt#~_ ##### #~~~ t~~~# #8#### _~#tt-&&-----&&-tt#~_ ##3#4# #~~~ t~~~# ## _~##t--&&---&&--t##~_ ## #~~~ t~~~# ### _~~#tt-&&&&&&&-tt#~~_ ### #~~~ t~~~## ## __~##t---&&&---t##~__ ## ##~~~ tt~~~# 2# _~~##tt-----tt##~~_ ## #~~~t tt~~~# __~~##ttttttt##~~__ #~~~t tt~~~## __~~###ttt###~~__ ##~~~t tt~~~~# __~~~#####~~~__ #~~~~t ttt~~~## ___~~~~~~~___ ## ##~~~tt ttt~~~~# ## _________ ### #~~~~tt tttt~~~## ### # # #### ##~~~ttt tttt~~~~## #### ### ### ##H ##~~~~ttt ttttt~~~~# ### #### #### # #~~~~tttt tttttt~~~## # 9####B# ##~~~ttttt tttttt~~~~## ### ##~~~~ttttt ttttttt~~~~### ### ###~~~~tttttt tttttttt~~~~~## ### ##~~~~~ttttttt ttttttttt~~~~~### #F# ###~~~~~tttttttt tttttttttt~~~~~~### ###~~~~~~ttttttttt tttttttttttt~~~~~~#### ####~~~~~~ttttttttttt ttttttttttttt~~~~~~~~#########~~~~~~~~tttttttttttt ttttttttttttttt~~~~~~~~~~~~~~~~~~~~~tttttttttttttt ttttttttttttttttt~~~~~~~~~~~~~~~~~tttttttttttttttt ttttttttttttttttttttt~~~~~~~~~tttttttttttttttttttt]]
gpl-3.0
musenshen/SandBoxLua
frameworks/cocos2d-x/external/lua/luajit/src/src/host/genminilua.lua
73
11943
---------------------------------------------------------------------------- -- Lua script to generate a customized, minified version of Lua. -- The resulting 'minilua' is used for the build process of LuaJIT. ---------------------------------------------------------------------------- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- local sub, match, gsub = string.sub, string.match, string.gsub local LUA_VERSION = "5.1.5" local LUA_SOURCE local function usage() io.stderr:write("Usage: ", arg and arg[0] or "genminilua", " lua-", LUA_VERSION, "-source-dir\n") os.exit(1) end local function find_sources() LUA_SOURCE = arg and arg[1] if not LUA_SOURCE then usage() end if sub(LUA_SOURCE, -1) ~= "/" then LUA_SOURCE = LUA_SOURCE.."/" end local fp = io.open(LUA_SOURCE .. "lua.h") if not fp then LUA_SOURCE = LUA_SOURCE.."src/" fp = io.open(LUA_SOURCE .. "lua.h") if not fp then usage() end end local all = fp:read("*a") fp:close() if not match(all, 'LUA_RELEASE%s*"Lua '..LUA_VERSION..'"') then io.stderr:write("Error: version mismatch\n") usage() end end local LUA_FILES = { "lmem.c", "lobject.c", "ltm.c", "lfunc.c", "ldo.c", "lstring.c", "ltable.c", "lgc.c", "lstate.c", "ldebug.c", "lzio.c", "lopcodes.c", "llex.c", "lcode.c", "lparser.c", "lvm.c", "lapi.c", "lauxlib.c", "lbaselib.c", "ltablib.c", "liolib.c", "loslib.c", "lstrlib.c", "linit.c", } local REMOVE_LIB = {} gsub([[ collectgarbage dofile gcinfo getfenv getmetatable load print rawequal rawset select tostring xpcall foreach foreachi getn maxn setn popen tmpfile seek setvbuf __tostring clock date difftime execute getenv rename setlocale time tmpname dump gfind len reverse LUA_LOADLIBNAME LUA_MATHLIBNAME LUA_DBLIBNAME ]], "%S+", function(name) REMOVE_LIB[name] = true end) local REMOVE_EXTINC = { ["<assert.h>"] = true, ["<locale.h>"] = true, } local CUSTOM_MAIN = [[ typedef unsigned int UB; static UB barg(lua_State *L,int idx){ union{lua_Number n;U64 b;}bn; bn.n=lua_tonumber(L,idx)+6755399441055744.0; if (bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number"); return(UB)bn.b; } #define BRET(b) lua_pushnumber(L,(lua_Number)(int)(b));return 1; static int tobit(lua_State *L){ BRET(barg(L,1))} static int bnot(lua_State *L){ BRET(~barg(L,1))} static int band(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)} static int bor(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)} static int bxor(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)} static int lshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)} static int rshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)} static int arshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)} static int rol(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))} static int ror(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))} static int bswap(lua_State *L){ UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)} static int tohex(lua_State *L){ UB b=barg(L,1); int n=lua_isnone(L,2)?8:(int)barg(L,2); const char *hexdigits="0123456789abcdef"; char buf[8]; int i; if(n<0){n=-n;hexdigits="0123456789ABCDEF";} if(n>8)n=8; for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;} lua_pushlstring(L,buf,(size_t)n); return 1; } static const struct luaL_Reg bitlib[] = { {"tobit",tobit}, {"bnot",bnot}, {"band",band}, {"bor",bor}, {"bxor",bxor}, {"lshift",lshift}, {"rshift",rshift}, {"arshift",arshift}, {"rol",rol}, {"ror",ror}, {"bswap",bswap}, {"tohex",tohex}, {NULL,NULL} }; int main(int argc, char **argv){ lua_State *L = luaL_newstate(); int i; luaL_openlibs(L); luaL_register(L, "bit", bitlib); if (argc < 2) return sizeof(void *); lua_createtable(L, 0, 1); lua_pushstring(L, argv[1]); lua_rawseti(L, -2, 0); lua_setglobal(L, "arg"); if (luaL_loadfile(L, argv[1])) goto err; for (i = 2; i < argc; i++) lua_pushstring(L, argv[i]); if (lua_pcall(L, argc - 2, 0, 0)) { err: fprintf(stderr, "Error: %s\n", lua_tostring(L, -1)); return 1; } lua_close(L); return 0; } ]] local function read_sources() local t = {} for i, name in ipairs(LUA_FILES) do local fp = assert(io.open(LUA_SOURCE..name, "r")) t[i] = fp:read("*a") assert(fp:close()) end t[#t+1] = CUSTOM_MAIN return table.concat(t) end local includes = {} local function merge_includes(src) return gsub(src, '#include%s*"([^"]*)"%s*\n', function(name) if includes[name] then return "" end includes[name] = true local fp = assert(io.open(LUA_SOURCE..name, "r")) local src = fp:read("*a") assert(fp:close()) src = gsub(src, "#ifndef%s+%w+_h\n#define%s+%w+_h\n", "") src = gsub(src, "#endif%s*$", "") return merge_includes(src) end) end local function get_license(src) return match(src, "/%*+\n%* Copyright %(.-%*/\n") end local function fold_lines(src) return gsub(src, "\\\n", " ") end local strings = {} local function save_str(str) local n = #strings+1 strings[n] = str return "\1"..n.."\2" end local function save_strings(src) src = gsub(src, '"[^"\n]*"', save_str) return gsub(src, "'[^'\n]*'", save_str) end local function restore_strings(src) return gsub(src, "\1(%d+)\2", function(numstr) return strings[tonumber(numstr)] end) end local function def_istrue(def) return def == "INT_MAX > 2147483640L" or def == "LUAI_BITSINT >= 32" or def == "SIZE_Bx < LUAI_BITSINT-1" or def == "cast" or def == "defined(LUA_CORE)" or def == "MINSTRTABSIZE" or def == "LUA_MINBUFFER" or def == "HARDSTACKTESTS" or def == "UNUSED" end local head, defs = {[[ #ifdef _MSC_VER typedef unsigned __int64 U64; #else typedef unsigned long long U64; #endif ]]}, {} local function preprocess(src) local t = { match(src, "^(.-)#") } local lvl, on, oldon = 0, true, {} for pp, def, txt in string.gmatch(src, "#(%w+) *([^\n]*)\n([^#]*)") do if pp == "if" or pp == "ifdef" or pp == "ifndef" then lvl = lvl + 1 oldon[lvl] = on on = def_istrue(def) elseif pp == "else" then if oldon[lvl] then if on == false then on = true else on = false end end elseif pp == "elif" then if oldon[lvl] then on = def_istrue(def) end elseif pp == "endif" then on = oldon[lvl] lvl = lvl - 1 elseif on then if pp == "include" then if not head[def] and not REMOVE_EXTINC[def] then head[def] = true head[#head+1] = "#include "..def.."\n" end elseif pp == "define" then local k, sp, v = match(def, "([%w_]+)(%s*)(.*)") if k and not (sp == "" and sub(v, 1, 1) == "(") then defs[k] = gsub(v, "%a[%w_]*", function(tok) return defs[tok] or tok end) else t[#t+1] = "#define "..def.."\n" end elseif pp ~= "undef" then error("unexpected directive: "..pp.." "..def) end end if on then t[#t+1] = txt end end return gsub(table.concat(t), "%a[%w_]*", function(tok) return defs[tok] or tok end) end local function merge_header(src, license) local hdr = string.format([[ /* This is a heavily customized and minimized copy of Lua %s. */ /* It's only used to build LuaJIT. It does NOT have all standard functions! */ ]], LUA_VERSION) return hdr..license..table.concat(head)..src end local function strip_unused1(src) return gsub(src, '( {"?([%w_]+)"?,%s+%a[%w_]*},\n)', function(line, func) return REMOVE_LIB[func] and "" or line end) end local function strip_unused2(src) return gsub(src, "Symbolic Execution.-}=", "") end local function strip_unused3(src) src = gsub(src, "extern", "static") src = gsub(src, "\nstatic([^\n]-)%(([^)]*)%)%(", "\nstatic%1 %2(") src = gsub(src, "#define lua_assert[^\n]*\n", "") src = gsub(src, "lua_assert%b();?", "") src = gsub(src, "default:\n}", "default:;\n}") src = gsub(src, "lua_lock%b();", "") src = gsub(src, "lua_unlock%b();", "") src = gsub(src, "luai_threadyield%b();", "") src = gsub(src, "luai_userstateopen%b();", "{}") src = gsub(src, "luai_userstate%w+%b();", "") src = gsub(src, "%(%(c==.*luaY_parser%)", "luaY_parser") src = gsub(src, "trydecpoint%(ls,seminfo%)", "luaX_lexerror(ls,\"malformed number\",TK_NUMBER)") src = gsub(src, "int c=luaZ_lookahead%b();", "") src = gsub(src, "luaL_register%(L,[^,]*,co_funcs%);\nreturn 2;", "return 1;") src = gsub(src, "getfuncname%b():", "NULL:") src = gsub(src, "getobjname%b():", "NULL:") src = gsub(src, "if%([^\n]*hookmask[^\n]*%)\n[^\n]*\n", "") src = gsub(src, "if%([^\n]*hookmask[^\n]*%)%b{}\n", "") src = gsub(src, "if%([^\n]*hookmask[^\n]*&&\n[^\n]*%b{}\n", "") src = gsub(src, "(twoto%b()%()", "%1(size_t)") src = gsub(src, "i<sizenode", "i<(int)sizenode") return gsub(src, "\n\n+", "\n") end local function strip_comments(src) return gsub(src, "/%*.-%*/", " ") end local function strip_whitespace(src) src = gsub(src, "^%s+", "") src = gsub(src, "%s*\n%s*", "\n") src = gsub(src, "[ \t]+", " ") src = gsub(src, "(%W) ", "%1") return gsub(src, " (%W)", "%1") end local function rename_tokens1(src) src = gsub(src, "getline", "getline_") src = gsub(src, "struct ([%w_]+)", "ZX%1") return gsub(src, "union ([%w_]+)", "ZY%1") end local function rename_tokens2(src) src = gsub(src, "ZX([%w_]+)", "struct %1") return gsub(src, "ZY([%w_]+)", "union %1") end local function func_gather(src) local nodes, list = {}, {} local pos, len = 1, #src while pos < len do local d, w = match(src, "^(#define ([%w_]+)[^\n]*\n)", pos) if d then local n = #list+1 list[n] = d nodes[w] = n else local s d, w, s = match(src, "^(([%w_]+)[^\n]*([{;])\n)", pos) if not d then d, w, s = match(src, "^(([%w_]+)[^(]*%b()([{;])\n)", pos) if not d then d = match(src, "^[^\n]*\n", pos) end end if s == "{" then d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3) if sub(d, -2) == "{\n" then d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3) end end local k, v = nil, d if w == "typedef" then if match(d, "^typedef enum") then head[#head+1] = d else k = match(d, "([%w_]+);\n$") if not k then k = match(d, "^.-%(.-([%w_]+)%)%(") end end elseif w == "enum" then head[#head+1] = v elseif w ~= nil then k = match(d, "^[^\n]-([%w_]+)[(%[=]") if k then if w ~= "static" and k ~= "main" then v = "static "..d end else k = w end end if w and k then local o = nodes[k] if o then nodes["*"..k] = o end local n = #list+1 list[n] = v nodes[k] = n end end pos = pos + #d end return nodes, list end local function func_visit(nodes, list, used, n) local i = nodes[n] for m in string.gmatch(list[i], "[%w_]+") do if nodes[m] then local j = used[m] if not j then used[m] = i func_visit(nodes, list, used, m) elseif i < j then used[m] = i end end end end local function func_collect(src) local nodes, list = func_gather(src) local used = {} func_visit(nodes, list, used, "main") for n,i in pairs(nodes) do local j = used[n] if j and j < i then used["*"..n] = j end end for n,i in pairs(nodes) do if not used[n] then list[i] = "" end end return table.concat(list) end find_sources() local src = read_sources() src = merge_includes(src) local license = get_license(src) src = fold_lines(src) src = strip_unused1(src) src = save_strings(src) src = strip_unused2(src) src = strip_comments(src) src = preprocess(src) src = strip_whitespace(src) src = strip_unused3(src) src = rename_tokens1(src) src = func_collect(src) src = rename_tokens2(src) src = restore_strings(src) src = merge_header(src, license) io.write(src)
mit
weinrank/wireshark
epan/wslua/dtd_gen.lua
38
8369
-- dtd_gen.lua -- -- a DTD generator for wireshark -- -- (c) 2006 Luis E. Garcia Ontanon <luis@ontanon.org> -- -- Wireshark - Network traffic analyzer -- By Gerald Combs <gerald@wireshark.org> -- Copyright 1998 Gerald Combs -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. if gui_enabled() then local xml_fld = Field.new("xml") local function dtd_generator() local displayed = {} -- whether or not a dtd is already displayed local dtds = {} -- the dtds local changed = {} -- whether or not a dtd has been modified local dtd -- the dtd being dealt with local dtd_name -- its name -- we'll tap onto every frame that has xml local ws = {} -- the windows for each dtd local w = TextWindow.new("DTD Generator") local function help() local wh = TextWindow.new("DTD Generator Help") -- XXX write help wh:set('DTD Generator Help\n') end local function get_dtd_from_xml(text,d,parent) -- obtains dtd information from xml -- text: xml to be parsed -- d: the current dtd (if any) -- parent: parent entity (if any) -- cleanup the text from useless chars text = string.gsub(text ,"%s*<%s*","<"); text = string.gsub(text ,"%s*>%s*",">"); text = string.gsub(text ,"<%-%-(.-)%-%->"," "); text = string.gsub(text ,"%s+"," "); while true do -- find the first tag local open_tag = string.match(text,"%b<>") if open_tag == nil then -- no more tags, we're done return true end local name = string.match(open_tag,"[%w%d_-]+") local this_ent = nil if d == nil then -- there's no current dtd, this is entity is it d = dtds[name] if d == nil then d = {ents = {}, attrs = {}} dtds[name] = d end dtd = d dtd_name = name end this_ent = d[name] if this_ent == nil then -- no entity by this name in this dtd, create it this_ent = {ents = {}, attrs = {}} d.ents[name] = this_ent changed[dtd_name] = true end if parent ~= nil then -- add this entity to its parent parent.ents[name] = 1 changed[dtd_name] = true end -- add the attrs to the entity for att in string.gmatch(open_tag, "([%w%d_-]+)%s*=") do if not this_ent.attrs[att] then changed[dtd_name] = true this_ent.attrs[att] = true end end if string.match(open_tag,"/>") then -- this tag is "self closed" just remove it and continue text = string.gsub(text,"%b<>","",1) else local close_tag_pat = "</%s*" .. name .. "%s*>" if not string.match(text,close_tag_pat) then return false end local span,left = string.match(text,"%b<>(.-)" .. close_tag_pat .. "(.*)") if span ~= nil then -- recurse to find child entities if not get_dtd_from_xml(span,d,this_ent) then return false end end -- continue with what's left text = left end end return true end local function entity_tostring(name,entity_data) -- name: the name of the entity -- entity_data: a table containg the entity data -- returns the dtd text for that entity local text = '' text = text .. '\t<!ELEMENT ' .. name .. ' (' --) for e,j in pairs(entity_data.ents) do text = text .. " " .. e .. ' |' end text = text .. " #PCDATA ) >\n" text = text .. "\t<!ATTLIST " .. name for a,j in pairs(entity_data.attrs) do text = text .. "\n\t\t" .. a .. ' CDTATA #IMPLIED' end text = text .. " >\n\n" text = string.gsub(text,"<!ATTLIST " .. name .. " >\n","") return text end local function dtd_tostring(name,doctype) local text = '<? wireshark:protocol proto_name="' .. name ..'" hierarchy="yes" ?>\n\n' local root = doctype.ents[name] doctype.ents[name] = nil text = text .. entity_tostring(name,root) for n,es in pairs(doctype.ents) do text = text .. entity_tostring(n,es) end doctype.ents[name] = root return text end local function element_body(name,text) -- get the entity's children from dtd text -- name: the name of the element -- text: the list of children text = string.gsub(text,"[%s%?%*%#%+%(%)]","") text = string.gsub(text,"$","|") text = string.gsub(text, "^(.-)|", function(s) if dtd.ents[name] == nil then dtd.ents[name] = {ents={},attrs={}} end dtd.ents[name].ents[s] = true return "" end ) return '' end local function attlist_body(name,text) -- get the entity's attributes from dtd text -- name: the name of the element -- text: the list of attributes text = string.gsub(text,"([%w%d_-]+) [A-Z]+ #[A-Z]+", function(s) dtd.atts[s] = true return "" end ) return '' end local function dtd_body(buff) -- get the dtd's entities from dtd text -- buff: the dtd text local old_buff = buff buff = string.gsub(buff,"<!ELEMENT ([%w%d_-]+) (%b())>%s*",element_body) buff = string.gsub(buff,"<!ATTLIST ([%w%d_-]+) (.-)>%s*",attlist_body) end local function load_dtd(filename) local dtd_filename = USER_DIR .. "/dtds/" .. filename local buff = '' local wireshark_info dtd_name = nil dtd = nil for line in io.lines(dtd_filename) do buff = buff .. line end buff = string.gsub(buff ,"%s*<%!%s*","<!"); buff = string.gsub(buff ,"%s*>%s*",">"); buff = string.gsub(buff ,"<!%-%-(.-)%-%->"," "); buff = string.gsub(buff ,"%s+"," "); buff = string.gsub(buff ,"^%s+",""); buff = string.gsub(buff,'(<%?%s*wireshark:protocol%s+.-%s*%?>)', function(s) wireshark_info = s end ) buff = string.gsub(buff,"^<!DOCTYPE ([%w%d_-]+) (%b[])%s*>", function(name,body) dtd = { ents = {}, attrs = {}} dtd_name = name dtds[name] = dtd dtd_body(body) return "" end ) if not dtd then dtd_body(buff) end if wireshark_info then dtd.wstag = wireshark_info end end local function load_dtds() -- loads all existing dtds in the user directory local dirname = persconffile_path("dtds") local status, dir = pcall(Dir.open,dirname,".dtd") w:set('Loading DTDs from ' .. dirname .. ' \n') if not status then w:append("Error: could not open the directory" .. dirname .. " , make sure it exists.\n") return end for dtd_filename in dir do w:append("File:" .. dtd_filename .. "\n") load_dtd(dtd_filename) end end local function dtd_window(name) return function() local wd = TextWindow.new(name .. '.dtd') wd:set(dtd_tostring(name,dtds[name])) wd:set_editable() local function save() local file = io.open(persconffile_path("dtds/") .. name .. ".dtd" ,"w") file:write(wd:get_text()) file:close() end wd:add_button("Save",save) end end local function close() if li ~= nil then li:remove() li = nil end end w:set_atclose(close) -- w:add_button("Help",help) load_dtds() local li = Listener.new("frame","xml") w:append('Running') function li.packet() w:append('.') local txt = xml_fld().range:string(); get_dtd_from_xml(txt) end function li.draw() for name,j in pairs(changed) do w:append("\n" .. name .. " has changed\n") if not displayed[name] then w:add_button(name,dtd_window(name)) displayed[name] = true end end end retap_packets() w:append(t2s(dtds)) w:append('\n') end register_menu("DTD Generator",dtd_generator,MENU_TOOLS_UNSORTED) end
gpl-2.0
yetsky/packages
net/luci-app-sqm/files/sqm-cbi.lua
4
8072
--[[ LuCI - Lua Configuration Interface Copyright 2014 Steven Barth <steven@midlink.org> Copyright 2014 Dave Taht <dave.taht@bufferbloat.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local wa = require "luci.tools.webadmin" local fs = require "nixio.fs" local net = require "luci.model.network".init() local sys = require "luci.sys" --local ifaces = net:get_interfaces() local ifaces = sys.net:devices() local path = "/usr/lib/sqm" m = Map("sqm", translate("Smart Queue Management"), translate("With <abbr title=\"Smart Queue Management\">SQM</abbr> you " .. "can enable traffic shaping, better mixing (Fair Queueing)," .. " active queue length management (AQM) " .. " and prioritisation on one " .. "network interface.")) s = m:section(TypedSection, "queue", translate("Queues")) s:tab("tab_basic", translate("Basic Settings")) s:tab("tab_qdisc", translate("Queue Discipline")) s:tab("tab_linklayer", translate("Link Layer Adaptation")) s.addremove = true -- set to true to allow adding SQM instances in the GUI s.anonymous = true -- BASIC e = s:taboption("tab_basic", Flag, "enabled", translate("Enable")) e.rmempty = false n = s:taboption("tab_basic", ListValue, "interface", translate("Interface name")) -- sm lifted from luci-app-wol, the original implementation failed to show pppoe-ge00 type interface names for _, iface in ipairs(ifaces) do -- if iface:is_up() then -- n:value(iface:name()) -- end if iface ~= "lo" then n:value(iface) end end n.rmempty = false dl = s:taboption("tab_basic", Value, "download", translate("Download speed (kbit/s) (ingress):")) dl.datatype = "and(uinteger,min(0))" dl.rmempty = false ul = s:taboption("tab_basic", Value, "upload", translate("Upload speed (kbit/s) (egress):")) ul.datatype = "and(uinteger,min(0))" ul.rmempty = false -- QDISC c = s:taboption("tab_qdisc", ListValue, "qdisc", translate("Queueing discipline")) c:value("fq_codel", "fq_codel ("..translate("default")..")") c:value("efq_codel") c:value("nfq_codel") c:value("sfq") c:value("codel") c:value("ns2_codel") c:value("pie") c:value("sfq") c.default = "fq_codel" c.rmempty = false local qos_desc = "" sc = s:taboption("tab_qdisc", ListValue, "script", translate("Queue setup script")) for file in fs.dir(path) do if string.find(file, ".qos$") then sc:value(file) end if string.find(file, ".qos.help$") then fh = io.open(path .. "/" .. file, "r") qos_desc = qos_desc .. "<p><b>" .. file:gsub(".help$", "") .. ":</b><br />" .. fh:read("*a") .. "</p>" end end sc.default = "simple.qos" sc.rmempty = false sc.description = qos_desc ad = s:taboption("tab_qdisc", Flag, "qdisc_advanced", translate("Show Advanced Configuration")) ad.default = false ad.rmempty = true squash_dscp = s:taboption("tab_qdisc", ListValue, "squash_dscp", translate("Squash DSCP on inbound packets (ingress):")) squash_dscp:value("1", "SQUASH") squash_dscp:value("0", "DO NOT SQUASH") squash_dscp.default = "1" squash_dscp.rmempty = true squash_dscp:depends("qdisc_advanced", "1") squash_ingress = s:taboption("tab_qdisc", ListValue, "squash_ingress", translate("Ignore DSCP on ingress:")) squash_ingress:value("1", "Ignore") squash_ingress:value("0", "Allow") squash_ingress.default = "1" squash_ingress.rmempty = true squash_ingress:depends("qdisc_advanced", "1") iecn = s:taboption("tab_qdisc", ListValue, "ingress_ecn", translate("Explicit congestion notification (ECN) status on inbound packets (ingress):")) iecn:value("ECN", "ECN ("..translate("default")..")") iecn:value("NOECN") iecn.default = "ECN" iecn.rmempty = true iecn:depends("qdisc_advanced", "1") eecn = s:taboption("tab_qdisc", ListValue, "egress_ecn", translate("Explicit congestion notification (ECN) status on outbound packets (egress).")) eecn:value("NOECN", "NOECN ("..translate("default")..")") eecn:value("ECN") eecn.default = "NOECN" eecn.rmempty = true eecn:depends("qdisc_advanced", "1") ad2 = s:taboption("tab_qdisc", Flag, "qdisc_really_really_advanced", translate("Show Dangerous Configuration")) ad2.default = false ad2.rmempty = true ad2:depends("qdisc_advanced", "1") ilim = s:taboption("tab_qdisc", Value, "ilimit", translate("Hard limit on ingress queues; leave empty for default.")) -- ilim.default = 1000 ilim.isnumber = true ilim.datatype = "and(uinteger,min(0))" ilim.rmempty = true ilim:depends("qdisc_really_really_advanced", "1") elim = s:taboption("tab_qdisc", Value, "elimit", translate("Hard limit on egress queues; leave empty for default.")) -- elim.default = 1000 elim.datatype = "and(uinteger,min(0))" elim.rmempty = true elim:depends("qdisc_really_really_advanced", "1") itarg = s:taboption("tab_qdisc", Value, "itarget", translate("Latency target for ingress, e.g 5ms [units: s, ms, or us]; leave empty for default, or auto for automatic selection.")) itarg.datatype = "string" itarg.rmempty = true itarg:depends("qdisc_really_really_advanced", "1") etarg = s:taboption("tab_qdisc", Value, "etarget", translate("Latency target for egress, e.g. 5ms [units: s, ms, or us]; leave empty for default, or auto for automatic selection.")) etarg.datatype = "string" etarg.rmempty = true etarg:depends("qdisc_really_really_advanced", "1") iqdisc_opts = s:taboption("tab_qdisc", Value, "iqdisc_opts", translate("Advanced option string to pass to the ingress queueing disciplines; no error checking, use very carefully.")) iqdisc_opts.rmempty = true iqdisc_opts:depends("qdisc_really_really_advanced", "1") eqdisc_opts = s:taboption("tab_qdisc", Value, "eqdisc_opts", translate("Advanced option string to pass to the egress queueing disciplines; no error checking, use very carefully.")) eqdisc_opts.rmempty = true eqdisc_opts:depends("qdisc_really_really_advanced", "1") -- LINKLAYER ll = s:taboption("tab_linklayer", ListValue, "linklayer", translate("Which link layer to account for:")) ll:value("none", "none ("..translate("default")..")") ll:value("ethernet", "Ethernet with overhead: select for e.g. VDSL2.") ll:value("atm", "ATM: select for e.g. ADSL1, ADSL2, ADSL2+.") -- ll:value("adsl") -- reduce the options ll.default = "none" po = s:taboption("tab_linklayer", Value, "overhead", translate("Per Packet Overhead (byte):")) po.datatype = "and(integer,min(-1500))" po.default = 0 po.isnumber = true po.rmempty = true po:depends("linklayer", "ethernet") -- po:depends("linklayer", "adsl") po:depends("linklayer", "atm") adll = s:taboption("tab_linklayer", Flag, "linklayer_advanced", translate("Show Advanced Linklayer Options, (only needed if MTU > 1500)")) adll.rmempty = true adll:depends("linklayer", "ethernet") -- adll:depends("linklayer", "adsl") adll:depends("linklayer", "atm") smtu = s:taboption("tab_linklayer", Value, "tcMTU", translate("Maximal Size for size and rate calculations, tcMTU (byte); needs to be >= interface MTU + overhead:")) smtu.datatype = "and(uinteger,min(0))" smtu.default = 2047 smtu.isnumber = true smtu.rmempty = true smtu:depends("linklayer_advanced", "1") stsize = s:taboption("tab_linklayer", Value, "tcTSIZE", translate("Number of entries in size/rate tables, TSIZE; for ATM choose TSIZE = (tcMTU + 1) / 16:")) stsize.datatype = "and(uinteger,min(0))" stsize.default = 128 stsize.isnumber = true stsize.rmempty = true stsize:depends("linklayer_advanced", "1") smpu = s:taboption("tab_linklayer", Value, "tcMPU", translate("Minimal packet size, MPU (byte); needs to be > 0 for ethernet size tables:")) smpu.datatype = "and(uinteger,min(0))" smpu.default = 0 smpu.isnumber = true smpu.rmempty = true smpu:depends("linklayer_advanced", "1") lla = s:taboption("tab_linklayer", ListValue, "linklayer_adaptation_mechanism", translate("Which linklayer adaptation mechanism to use; for testing only")) lla:value("htb_private") lla:value("tc_stab", "tc_stab ("..translate("default")..")") lla.default = "tc_stab" lla.rmempty = true lla:depends("linklayer_advanced", "1") -- PRORITIES? return m
gpl-2.0
bayas/AutoRunner
Bin/Data/LuaScripts/24_Urho2DSprite.lua
1
6780
-- Urho2D sprite example. -- This sample demonstrates: -- - Creating a 2D scene with sprite -- - Displaying the scene using the Renderer subsystem -- - Handling keyboard to move and zoom 2D camera -- - Usage of Lua Closure to update scene require "LuaScripts/Utilities/Sample" local scene_ = nil local cameraNode = nil function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Hook up to the frame update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will -- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it -- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically -- optimizing manner scene_:CreateComponent("Octree") -- Create a scene node for the camera, which we will move around -- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically) cameraNode = scene_:CreateChild("Camera") -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 0.0, -10.0) local camera = cameraNode:CreateComponent("Camera") camera.orthographic = true local width = graphics.width * PIXEL_SIZE local height = graphics.height * PIXEL_SIZE camera:SetOrthoSize(Vector2(width, height)) local sprite = cache:GetResource("Sprite2D", "Urho2D/Aster.png") if sprite == nil then return end local spriteNodes = {} local NUM_SPRITES = 200 local halfWidth = width * 0.5 local halfHeight = height * 0.5 for i = 1, NUM_SPRITES do local spriteNode = scene_:CreateChild("StaticSprite2D") spriteNode.position = Vector3(Random(-halfWidth, halfWidth), Random(-halfHeight, halfHeight), 0.0) local staticSprite = spriteNode:CreateComponent("StaticSprite2D") -- Set color staticSprite.color = Color(Random(1.0), Random(1.0), Random(1.0), 1.0) -- Set blend mode staticSprite.blendMode = BLEND_ALPHA -- Set sprite staticSprite.sprite = sprite -- Set move speed spriteNode.moveSpeed = Vector3(Random(-2.0, 2.0), Random(-2.0, 2.0), 0.0) -- Set rotate speed spriteNode.rotateSpeed = Random(-90.0, 90.0) table.insert(spriteNodes, spriteNode) end scene_.Update = function(self, timeStep) for _, spriteNode in ipairs(spriteNodes) do local position = spriteNode.position local moveSpeed = spriteNode.moveSpeed local newPosition = position + moveSpeed * timeStep if newPosition.x < -halfWidth or newPosition.x > halfWidth then newPosition.x = position.x moveSpeed.x = -moveSpeed.x end if newPosition.y < -halfHeight or newPosition.y > halfHeight then newPosition.y = position.y moveSpeed.y = -moveSpeed.y end spriteNode.position = newPosition spriteNode:Roll(spriteNode.rotateSpeed * timeStep) end end local animation = cache:GetResource("Animation2D", "Urho2D/GoldIcon.anm") if animation == nil then return end local spriteNode = scene_:CreateChild("AnimatedSprite2D") spriteNode.position = Vector3(0.0, 0.0, -1.0) local animatedSprite = spriteNode:CreateComponent("AnimatedSprite2D") -- Set animation animatedSprite.animation = animation -- Set blend mode animatedSprite.blendMode = BLEND_ALPHA end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Use WASD keys and mouse to move, Use PageUp PageDown to zoom.") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera -- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to -- use, but now we just use full screen and default render path configured in the engine command line options local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 4.0 -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed -- Use the TranslateRelative() function to move relative to the node's orientation. Alternatively we could -- multiply the desired direction with the node's orientation quaternion, and use just Translate() if input:GetKeyDown(KEY_W) then cameraNode:TranslateRelative(Vector3.UP * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:TranslateRelative(Vector3.DOWN * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:TranslateRelative(Vector3.LEFT * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:TranslateRelative(Vector3.RIGHT * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_PAGEUP) then local camera = cameraNode:GetComponent("Camera") camera.zoom = camera.zoom * 1.01 end if input:GetKeyDown(KEY_PAGEDOWN) then local camera = cameraNode:GetComponent("Camera") camera.zoom = camera.zoom * 0.99 end end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData:GetFloat("TimeStep") -- Move the camera, scale movement with time step MoveCamera(timeStep) -- Update scene scene_:Update(timeStep) end
mit
xAleXXX007x/Witcher-RolePlay
witcherrp/schema/items/weapons/sh_mace_nlif.lua
1
1356
ITEM.name = "Имперская стальная булава" ITEM.desc = "Булава с характерным чёрным окрасом." ITEM.class = "nut_mace_nilf" ITEM.weaponCategory = "primary" ITEM.price = 250 ITEM.category = "Оружие" ITEM.model = "models/morrowind/ebony/mace/w_ebony_mace.mdl" ITEM.width = 4 ITEM.height = 1 ITEM.iconCam = { pos = Vector(-1.0090725421906, 53.753803253174, 5.0151271820068), ang = Angle(0, 270, -101.70430755615), fov = 45 } ITEM.damage = {1, 8} ITEM.permit = "melee" ITEM.pacData = {[1] = { ["children"] = { [1] = { ["children"] = { [1] = { ["children"] = { }, ["self"] = { ["Event"] = "weapon_class", ["Arguments"] = "nut_mace_nilf", ["UniqueID"] = "2195922949", ["ClassName"] = "event", }, }, }, ["self"] = { ["Angles"] = Angle(-63.254837036133, -66.692153930664, -52.068050384521), ["UniqueID"] = "73731660", ["Position"] = Vector(-1.28466796875, -3.9662475585938, 1.72412109375), ["EditorExpand"] = true, ["Bone"] = "left thigh", ["Model"] = "models/morrowind/ebony/mace/w_ebony_mace.mdl", ["ClassName"] = "model", }, }, }, ["self"] = { ["EditorExpand"] = true, ["UniqueID"] = "3888997461", ["ClassName"] = "group", ["Name"] = "my outfit", ["Description"] = "add parts to me!", }, }, }
mit
Blackdutchie/Zero-K
scripts/cornecro.lua
11
4986
-- original bos animation by Chris Mackey -- converted to lua by psimyn include 'constants.lua' local base, pelvis, torso = piece('base', 'pelvis', 'torso') local shield = piece 'shield' local lathe = piece 'lathe' local emit = piece 'emit' local centerpoint = piece 'centerpoint' local rthigh, ruppercalf, rlowercalf, rfoot = piece('rthigh', 'ruppercalf', 'rlowercalf', 'rfoot') local lthigh, luppercalf, llowercalf, lfoot = piece('lthigh', 'luppercalf', 'llowercalf', 'lfoot') local rightLeg = { thigh=piece('rthigh'), uppercalf=piece('ruppercalf'), lowercalf=piece('rlowercalf'), foot=piece('rfoot') } local leftLeg = { thigh=piece('lthigh'), uppercalf=piece('luppercalf'), lowercalf=piece('llowercalf'), foot=piece('lfoot') } local smokePiece = {torso} local nanoPieces = {emit} -- signals local SIG_BUILD = 1 local SIG_MOVE = 2 -- constants local PACE = 2 local function Step(front, back) Turn(front.thigh, x_axis, math.rad(-10), math.rad(36) * PACE) Turn(front.uppercalf, x_axis, math.rad(-68), math.rad(83) * PACE) Turn(front.foot, x_axis, math.rad(60), math.rad(90) * PACE) Move(front.lowercalf, z_axis, 0, 3 * PACE) Move(front.lowercalf, y_axis, 0, 3 * PACE) Turn(back.thigh, x_axis, math.rad(26), math.rad(36) * PACE) Turn(back.uppercalf, x_axis, math.rad(15), math.rad(83) * PACE) Turn(back.foot, x_axis, math.rad(-30), math.rad(90) * PACE) Move(back.lowercalf, z_axis, -1.1, 2.2 * PACE) Move(back.lowercalf, y_axis, -1.1, 2.2 * PACE) if front == leftLeg then Turn(pelvis, z_axis, math.rad(10), math.rad(15) * PACE) else Turn(pelvis, z_axis, math.rad(-10), math.rad(15) * PACE) end WaitForTurn(front.thigh, x_axis) WaitForTurn(front.uppercalf, x_axis) WaitForTurn(back.thigh, x_axis) WaitForTurn(back.uppercalf, x_axis) -- wait one gameframe Sleep(0) end local function Walk() Signal(SIG_MOVE) SetSignalMask(SIG_MOVE) Move(pelvis, y_axis, 2, 5) while true do Step(leftLeg, rightLeg) Step(rightLeg, leftLeg) end end function script.Create() StartThread(SmokeUnit, smokePiece) Spring.SetUnitNanoPieces(unitID, nanoPieces) end local function Stopping() Signal(SIG_MOVE) SetSignalMask(SIG_MOVE) Move(pelvis, y_axis, 0, 12) Turn(pelvis, z_axis, math.rad(0), math.rad(15) * PACE) Turn(rightLeg.thigh, x_axis, 0, math.rad(60) * PACE) Turn(leftLeg.thigh, x_axis, 0, math.rad(60) * PACE) Turn(rightLeg.uppercalf, x_axis, 0, math.rad(70) * PACE) Turn(leftLeg.uppercalf, x_axis, 0, math.rad(70) * PACE) Turn(rightLeg.foot, x_axis, 0, math.rad(60) * PACE) Turn(leftLeg.foot, x_axis, 0, math.rad(60) * PACE) Move(leftLeg.lowercalf, z_axis, 0, 3) Move(rightLeg.lowercalf, z_axis, 0, 2) Move(leftLeg.lowercalf, y_axis, 0, 3) Move(rightLeg.lowercalf, y_axis, 0, 2) end function script.StartMoving() StartThread(Walk) end function script.StopMoving() StartThread(Stopping) end function script.StartBuilding(heading, pitch) Signal(SIG_BUILD) SetSignalMask(SIG_BUILD) SetUnitValue(COB.INBUILDSTANCE, 1) -- aim at target location Turn(torso, y_axis, heading, math.rad(200) * PACE) Turn(torso, x_axis, -pitch, math.rad(200) * PACE) Turn(shield, x_axis, math.rad(-70), math.rad(100) * PACE) -- lower to ground. sit comfortably while you build Move(pelvis, y_axis, -6, 6 * PACE) Turn(leftLeg.uppercalf, x_axis, math.rad(40), math.rad(40) * PACE) Turn(leftLeg.foot, x_axis, math.rad(-40), math.rad(40) * PACE) Turn(rightLeg.uppercalf, x_axis, math.rad(40), math.rad(40) * PACE) Turn(rightLeg.foot, x_axis, math.rad(-40), math.rad(40) * PACE) WaitForTurn(torso, y_axis) end function script.StopBuilding() SetUnitValue(COB.INBUILDSTANCE, 0) Turn(torso, y_axis, 0, math.rad(40) * PACE) Turn(torso, x_axis, 0, math.rad(40) * PACE) Turn(shield, x_axis, 0, math.rad(40) * PACE) Turn(leftLeg.uppercalf, x_axis, 0, math.rad(40) * PACE) Turn(leftLeg.foot, x_axis, 0, math.rad(40) * PACE) Turn(rightLeg.uppercalf, x_axis, 0, math.rad(40) * PACE) Turn(rightLeg.foot, x_axis, 0, math.rad(40) * PACE) Move(pelvis, y_axis, 0, 6 * PACE) end function script.QueryNanoPiece() GG.LUPS.QueryNanoPiece(unitID,unitDefID,Spring.GetUnitTeam(unitID),emit) return emit end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity < 0.5 then Explode(torso, sfxFall) Explode(leftLeg.thigh, sfxNone) Explode(leftLeg.uppercalf, sfxNone) Explode(leftLeg.lowercalf, sfxNone) Explode(leftLeg.foot, sfxNone) Explode(rightLeg.thigh, sfxNone) Explode(rightLeg.uppercalf, sfxNone) Explode(rightLeg.lowercalf, sfxNone) Explode(rightLeg.foot, sfxNone) Explode(base, sfxFall) return 1 else Explode(torso, sfxShatter) Explode(leftLeg.thigh, sfxFall) Explode(leftLeg.uppercalf, sfxFall) Explode(leftLeg.lowercalf, sfxFall) Explode(leftLeg.foot, sfxFall) Explode(rightLeg.thigh, sfxFall) Explode(rightLeg.uppercalf, sfxFall) Explode(rightLeg.lowercalf, sfxFall) Explode(rightLeg.foot, sfxFall) Explode(base, sfxShatter) return 2 end end
gpl-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/tilesets/5x5/windy_tunnel.lua
1
1087
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org tiles = { {type="tunnel", [[##.##]], [[##.##]], [[##...]], [[#####]], [[#####]], }, {type="tunnel", [[#####]], [[#####]], [[...##]], [[##.##]], [[##.##]], }, {type="tunnel", [[##.##]], [[##.##]], [[...##]], [[#####]], [[#####]], }, {type="tunnel", [[#####]], [[#####]], [[##...]], [[##.##]], [[##.##]], }, }
gpl-3.0
electricpandafishstudios/Spoon
game/thirdparty/moonscript/compile.lua
5
13011
module("moonscript.compile", package.seeall) local util = require("moonscript.util") local data = require("moonscript.data") local dump = require("moonscript.dump") require("moonscript.compile.format") require("moonscript.compile.line") require("moonscript.compile.value") local ntype, Set = data.ntype, data.Set local concat, insert = table.concat, table.insert local pos_to_line, get_closest_line, trim = util.pos_to_line, util.get_closest_line, util.trim local bubble_names = { "has_varargs" } local Line Line = (function(_parent_0) local _base_0 = { _append_single = function(self, item) if util.moon.type(item) == Line then do local _item_0 = item for _index_0 = 1, #_item_0 do local value = _item_0[_index_0] self:_append_single(value) end end else insert(self, item) end return nil end, append_list = function(self, items, delim) for i = 1, #items do self:_append_single(items[i]) if i < #items then insert(self, delim) end end end, append = function(self, ...) do local _item_0 = { ... } for _index_0 = 1, #_item_0 do local item = _item_0[_index_0] self:_append_single(item) end end return nil end, render = function(self) local buff = { } for i = 1, #self do local c = self[i] insert(buff, (function() if util.moon.type(c) == Block then return c:render() else return c end end)()) end return concat(buff) end } _base_0.__index = _base_0 if _parent_0 then setmetatable(_base_0, getmetatable(_parent_0).__index) end local _class_0 = setmetatable({ __init = function(self, ...) if _parent_0 then return _parent_0.__init(self, ...) end end }, { __index = _base_0, __call = function(mt, ...) local self = setmetatable({}, _base_0) mt.__init(self, ...) return self end }) _base_0.__class = _class_0 return _class_0 end)() local Block_ Block_ = (function(_parent_0) local _base_0 = { header = "do", footer = "end", line_table = function(self) return self._posmap end, set = function(self, name, value) self._state[name] = value end, get = function(self, name) return self._state[name] end, declare = function(self, names) local undeclared = (function() local _accum_0 = { } local _len_0 = 0 do local _item_0 = names for _index_0 = 1, #_item_0 do local name = _item_0[_index_0] if type(name) == "string" and not self:has_name(name) then _len_0 = _len_0 + 1 _accum_0[_len_0] = name end end end return _accum_0 end)() do local _item_0 = undeclared for _index_0 = 1, #_item_0 do local name = _item_0[_index_0] self:put_name(name) end end return undeclared end, whitelist_names = function(self, names) self._name_whitelist = Set(names) end, put_name = function(self, name) self._names[name] = true end, has_name = function(self, name) local yes = self._names[name] if yes == nil and self.parent then if not self._name_whitelist or self._name_whitelist[name] then return self.parent:has_name(name) end else return yes end end, shadow_name = function(self, name) self._names[name] = false end, free_name = function(self, prefix, dont_put) prefix = prefix or "moon" local searching = true local name, i = nil, 0 while searching do name = concat({ "", prefix, i }, "_") i = i + 1 searching = self:has_name(name) end if not dont_put then self:put_name(name) end return name end, init_free_var = function(self, prefix, value) local name = self:free_name(prefix, true) self:stm({ "assign", { name }, { value } }) return name end, mark_pos = function(self, node) if node[-1] then self.last_pos = node[-1] if not self._posmap[self.current_line] then self._posmap[self.current_line] = self.last_pos end end end, add_line_text = function(self, text) return insert(self._lines, text) end, append_line_table = function(self, sub_table, offset) offset = offset + self.current_line for line, source in pairs(sub_table) do local line = line + offset if not self._posmap[line] then self._posmap[line] = source end end end, add_line_tables = function(self, line) do local _item_0 = line for _index_0 = 1, #_item_0 do local chunk = _item_0[_index_0] if util.moon.type(chunk) == Block then local current = chunk while current do if util.moon.type(current.header) == Line then self:add_line_tables(current.header) end self:append_line_table(current:line_table(), 0) self.current_line = self.current_line + current.current_line current = current.next end end end end end, add = function(self, line) local t = util.moon.type(line) if t == "string" then self:add_line_text(line) elseif t == Block then do local _item_0 = bubble_names for _index_0 = 1, #_item_0 do local name = _item_0[_index_0] if line[name] then self[name] = line.name end end end self:add(self:line(line)) elseif t == Line then self:add_line_tables(line) self:add_line_text(line:render()) self.current_line = self.current_line + 1 else error("Adding unknown item") end return nil end, _insert_breaks = function(self) for i = 1, #self._lines - 1 do local left, right = self._lines[i], self._lines[i + 1] if left:sub(-1) == ")" and right:sub(1, 1) == "(" then self._lines[i] = self._lines[i] .. ";" end end end, render = function(self) local flatten flatten = function(line) if type(line) == "string" then return line else return line:render() end end local header = flatten(self.header) if #self._lines == 0 then local footer = flatten(self.footer) return concat({ header, footer }, " ") end local indent = indent_char:rep(self.indent) if not self.delim then self:_insert_breaks() end local body = indent .. concat(self._lines, (self.delim or "") .. "\n" .. indent) return concat({ header, body, indent_char:rep(self.indent - 1) .. (function() if self.next then return self.next:render() else return flatten(self.footer) end end)() }, "\n") end, block = function(self, header, footer) return Block(self, header, footer) end, line = function(self, ...) do local _with_0 = Line() _with_0:append(...) return _with_0 end end, is_stm = function(self, node) return line_compile[ntype(node)] ~= nil end, is_value = function(self, node) local t = ntype(node) return value_compile[t] ~= nil or t == "value" end, name = function(self, node) return self:value(node) end, value = function(self, node, ...) local action if type(node) ~= "table" then action = "raw_value" else self:mark_pos(node) action = node[1] end local fn = value_compile[action] if not fn then error("Failed to compile value: " .. dump.value(node)) end return fn(self, node, ...) end, values = function(self, values, delim) delim = delim or ', ' do local _with_0 = Line() _with_0:append_list((function() local _accum_0 = { } local _len_0 = 0 do local _item_0 = values for _index_0 = 1, #_item_0 do local v = _item_0[_index_0] _len_0 = _len_0 + 1 _accum_0[_len_0] = self:value(v) end end return _accum_0 end)(), delim) return _with_0 end end, stm = function(self, node, ...) local fn = line_compile[ntype(node)] if not fn then if has_value(node) then return self:stm({ "assign", { "_" }, { node } }) else return self:add(self:value(node)) end else self:mark_pos(node) local out = fn(self, node, ...) if out then return self:add(out) end end end, ret_stms = function(self, stms, ret) if not ret then ret = default_return end local i = 1 while i < #stms do self:stm(stms[i]) i = i + 1 end local last_exp = stms[i] if last_exp then if cascading[ntype(last_exp)] then self:stm(last_exp, ret) elseif self:is_value(last_exp) then local line = ret(stms[i]) if self:is_stm(line) then self:stm(line) else error("got a value from implicit return") end else self:stm(last_exp) end end return nil end, stms = function(self, stms, ret) if ret then self:ret_stms(stms, ret) else do local _item_0 = stms for _index_0 = 1, #_item_0 do local stm = _item_0[_index_0] self:stm(stm) end end end return nil end } _base_0.__index = _base_0 if _parent_0 then setmetatable(_base_0, getmetatable(_parent_0).__index) end local _class_0 = setmetatable({ __init = function(self, parent, header, footer) self.parent, self.header, self.footer = parent, header, footer self.current_line = 1 self._lines = { } self._posmap = { } self._names = { } self._state = { } if self.parent then self.indent = self.parent.indent + 1 return setmetatable(self._state, { __index = self.parent._state }) else self.indent = 0 end end }, { __index = _base_0, __call = function(mt, ...) local self = setmetatable({}, _base_0) mt.__init(self, ...) return self end }) _base_0.__class = _class_0 return _class_0 end)() local RootBlock RootBlock = (function(_parent_0) local _base_0 = { render = function(self) self:_insert_breaks() return concat(self._lines, "\n") end } _base_0.__index = _base_0 if _parent_0 then setmetatable(_base_0, getmetatable(_parent_0).__index) end local _class_0 = setmetatable({ __init = function(self, ...) if _parent_0 then return _parent_0.__init(self, ...) end end }, { __index = _base_0, __call = function(mt, ...) local self = setmetatable({}, _base_0) mt.__init(self, ...) return self end }) _base_0.__class = _class_0 return _class_0 end)(Block_) Block = Block_ format_error = function(msg, pos, file_str) local line = pos_to_line(file_str, pos) local line_str line_str, line = get_closest_line(file_str, line) line_str = line_str or "" return concat({ "Compile error: " .. msg, (" [%d] >> %s"):format(line, trim(line_str)) }, "\n") end tree = function(tree) local scope = RootBlock() local runner = coroutine.create(function() do local _item_0 = tree for _index_0 = 1, #_item_0 do local line = _item_0[_index_0] scope:stm(line) end end return scope:render() end) local success, result = coroutine.resume(runner) if not success then local error_msg if type(result) == "table" then local error_type = result[1] if error_type == "user-error" then error_msg = result[2] else error_msg = error("Unknown error thrown", util.dump(error_msg)) end else error_msg = concat({ result, debug.traceback(runner) }, "\n") end return nil, error_msg, scope.last_pos else local tbl = scope:line_table() return result, tbl end end
gpl-3.0
electricpandafishstudios/Spoon
game/engines/te4-1.4.1/engine/ui/VariableList.lua
1
6617
-- TE4 - T-Engine 4 -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" local Base = require "engine.ui.Base" local Focusable = require "engine.ui.Focusable" local Slider = require "engine.ui.Slider" --- A generic UI variable list -- @classmod engine.ui.VariableList module(..., package.seeall, class.inherit(Base, Focusable)) function _M:init(t) self.list = assert(t.list, "no list list") self.w = assert(t.width, "no list width") self.max_h = t.max_height self.fct = t.fct self.select = t.select self.scrollbar = t.scrollbar self.min_items_shown = t.min_items_shown or 3 self.display_prop = t.display_prop or "name" Base.init(self, t) end function _M:generate() self.mouse:reset() self.key:reset() self.sel = 1 self.scroll = 1 self.max = #self.list local fw, fh = self.w, self.font_h self.fw, self.fh = fw, fh self.frame = self:makeFrame(nil, fw, fh) self.frame_sel = self:makeFrame("ui/selector-sel", fw, fh) self.frame_usel = self:makeFrame("ui/selector", fw, fh) -- Draw the list items local sh = 0 local minh = 0 for i, item in ipairs(self.list) do local color = item.color or {255,255,255} local width = fw - self.frame_sel.b4.w - self.frame_sel.b6.w local text = self.font:draw(item[self.display_prop], width, color[1], color[2], color[3]) local fh = fh * #text + self.frame_sel.b8.w / 3 * 2 local texs = {} for z, tex in ipairs(text) do texs[z] = {t=tex._tex, tw=tex._tex_w, th = tex._tex_h, w=tex.w, h=tex.h, y = (z - 1) * self.font_h + self.frame_sel.b8.w / 3} end item.start_h = sh item.fh = fh item._texs = texs sh = sh + fh if i <= self.min_items_shown then minh = sh end end self.h = math.max(minh, math.min(self.max_h or 1000000, sh)) if sh > self.h then self.scrollbar = true end self.scroll_inertia = 0 self.scroll = 0 if self.scrollbar then self.scrollbar = Slider.new{size=self.h, max=sh} end self.mouse:registerZone(0, 0, self.w, self.h, function(button, x, y, xrel, yrel, bx, by, event) self.last_input_was_keyboard = false if event == "button" and button == "wheelup" then if self.scrollbar then self.scroll_inertia = math.min(self.scroll_inertia, 0) - 5 end elseif event == "button" and button == "wheeldown" then if self.scrollbar then self.scroll_inertia = math.max(self.scroll_inertia, 0) + 5 end end for i = 1, #self.list do local item = self.list[i] if by + self.scroll >= item.start_h and by + self.scroll < item.start_h + item.fh then if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end self.sel = i self:onSelect() if button == "left" and event == "button" then self:onUse() end break end end end) -- Add UI controls self.key:addBinds{ ACCEPT = function() self:onUse() end, MOVE_UP = function() if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end self.sel = util.boundWrap(self.sel - 1, 1, self.max) self:onSelect() end, MOVE_DOWN = function() if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end self.sel = util.boundWrap(self.sel + 1, 1, self.max) self:onSelect() end, } end function _M:onUse() local item = self.list[self.sel] if not item then return end self:sound("button") if item.fct then item:fct() else self.fct(item, self.sel) end end function _M:onSelect() local item = self.list[self.sel] if not item then return end if self.scrollbar then local pos = 0 for i = 1, #self.list do local itm = self.list[i] pos = pos + itm.fh -- we've reached selected row if self.sel == i then -- check if it was visible if not go scroll over there if pos - itm.fh < self.scrollbar.pos then self.scrollbar.pos = util.minBound(pos - itm.fh, 0, self.scrollbar.max) elseif pos > self.scrollbar.pos + self.h then self.scrollbar.pos = util.minBound(pos - self.h, 0, self.scrollbar.max) end break end end end if rawget(self, "select") then self.select(item, self.sel) end end function _M:display(x, y, nb_keyframes, screen_x, screen_y) local by = y core.display.glScissor(true, screen_x, screen_y, self.w, self.h) if self.scrollbar then local tmp_pos = self.scrollbar.pos self.scrollbar.pos = util.minBound(self.scrollbar.pos + self.scroll_inertia, 0, self.scrollbar.max) if self.scroll_inertia > 0 then self.scroll_inertia = math.max(self.scroll_inertia - 1, 0) elseif self.scroll_inertia < 0 then self.scroll_inertia = math.min(self.scroll_inertia + 1, 0) end if self.scrollbar.pos == 0 or self.scrollbar.pos == self.scrollbar.max then self.scroll_inertia = 0 end y = y + (self.scrollbar and -self.scrollbar.pos or 0) self.scroll = self.scrollbar.pos end for i = 1, self.max do local item = self.list[i] if not item then break end self.frame.h = item.fh self.frame_sel.h = item.fh self.frame_usel.h = item.fh if self.sel == i then if self.focused then self:drawFrame(self.frame_sel, x, y) else self:drawFrame(self.frame_usel, x, y) end else self:drawFrame(self.frame, x, y) if item.focus_decay then if self.focused then self:drawFrame(self.frame_sel, x, y, 1, 1, 1, item.focus_decay / self.focus_decay_max_d) else self:drawFrame(self.frame_usel, x, y, 1, 1, 1, item.focus_decay / self.focus_decay_max_d) end item.focus_decay = item.focus_decay - nb_keyframes if item.focus_decay <= 0 then item.focus_decay = nil end end end for z, tex in pairs(item._texs) do if self.text_shadow then self:textureToScreen(tex, x+1 + self.frame_sel.b4.w, y+1 + tex.y, 0, 0, 0, self.text_shadow) end self:textureToScreen(tex, x + self.frame_sel.b4.w, y + tex.y) end y = y + item.fh end core.display.glScissor(false) if self.focused and self.scrollbar then self.scrollbar:display(x + self.w - self.scrollbar.w, by) self.last_scroll = self.scrollbar.pos end end
gpl-3.0
musenshen/SandBoxLua
src/framework/cc/Registry.lua
23
1841
local Registry = class("Registry") Registry.classes_ = {} Registry.objects_ = {} function Registry.add(cls, name) assert(type(cls) == "table" and cls.__cname ~= nil, "Registry.add() - invalid class") if not name then name = cls.__cname end assert(Registry.classes_[name] == nil, string.format("Registry.add() - class \"%s\" already exists", tostring(name))) Registry.classes_[name] = cls end function Registry.remove(name) assert(Registry.classes_[name] ~= nil, string.format("Registry.remove() - class \"%s\" not found", name)) Registry.classes_[name] = nil end function Registry.exists(name) return Registry.classes_[name] ~= nil end function Registry.newObject(name, ...) local cls = Registry.classes_[name] if not cls then -- auto load pcall(function() cls = require(name) Registry.add(cls, name) end) end assert(cls ~= nil, string.format("Registry.newObject() - invalid class \"%s\"", tostring(name))) return cls.new(...) end function Registry.setObject(object, name) assert(Registry.objects_[name] == nil, string.format("Registry.setObject() - object \"%s\" already exists", tostring(name))) assert(object ~= nil, "Registry.setObject() - object \"%s\" is nil", tostring(name)) Registry.objects_[name] = object end function Registry.getObject(name) assert(Registry.objects_[name] ~= nil, string.format("Registry.getObject() - object \"%s\" not exists", tostring(name))) return Registry.objects_[name] end function Registry.removeObject(name) assert(Registry.objects_[name] ~= nil, string.format("Registry.removeObject() - object \"%s\" not exists", tostring(name))) Registry.objects_[name] = nil end function Registry.isObjectExists(name) return Registry.objects_[name] ~= nil end return Registry
mit
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/maps/vaults/auto/greater/demon-nest-3.lua
1
2546
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org --demon nest 3 startx = 0 starty = 10 setStatusAll{no_teleport=true} rotates = {"default", "90", "180", "270", "flipx", "flipy"} defineTile('%', "WALL") defineTile('#', "HARDWALL") defineTile('+', "DOOR") defineTile('X', "DOOR_VAULT") defineTile('.', "LAVA_FLOOR") defineTile('-', "FLOOR") defineTile('$', "LAVA_FLOOR", {random_filter={add_levels=25, type="money"}}) defineTile('*', "LAVA_FLOOR", {random_filter={type="gem"}}) defineTile('/', "LAVA_FLOOR", {random_filter={add_levels=10, tome_mod="vault"}}) defineTile('L', "LAVA_FLOOR", {random_filter={add_levels=25, tome_mod="gvault"}}) defineTile('^', "FLOOR", nil, nil, {random_filter={add_levels=20}}) defineTile('u', "LAVA_FLOOR", nil, {random_filter={add_levels=20, type = "demon", subtype = "minor"}}) defineTile('h', "LAVA_FLOOR", nil, {random_filter={add_levels=10, type = "horror", subtype = "eldritch"}}) defineTile('U', "LAVA_FLOOR", {random_filter={add_levels=25, tome_mod="gvault"}}, {random_filter={add_levels=30, type = "demon", subtype = "major"}}) defineTile('D', "LAVA_FLOOR", {random_filter={add_levels=25, tome_mod="gvault"}}, {random_filter={add_levels=30, type = "dragon", subtype = "fire", name = "fire wyrm",}}) return { [[%%%%%%%%#####%%%%%%%%]], [[%%%%%%###-%*###%%%%%%]], [[%%%%###uu-%$*$###%%%%]], [[%%%##uuuuu%$$$$$##%%%]], [[%%###%#############%%]], [[%%#.h^.....h....+.#%%]], [[%##...h...h.-.h.#.##%]], [[%#U..-..h....h..#.L#%]], [[#################-.##]], [[#.U.$..*/.$../...$.D#]], [[X.U../$..-*../.$...L#]], [[#.U.$-*$./.$..*/..$D#]], [[#################..##]], [[%#U..h........h.#.L#%]], [[%##.h...h.-.h...#.##%]], [[%%#.--h......h..+.#%%]], [[%%###%#############%%]], [[%%%##uuuu-%$$$$$##%%%]], [[%%%%###uuu%$*$###%%%%]], [[%%%%%%###u%*###%%%%%%]], [[%%%%%%%%#####%%%%%%%%]], }
gpl-3.0
mwharris1313/AutoSheet
img/sheet48.lua
4
13136
local options = { frames = { {x=0,y=0,width=48,height=48,}, -- frame 1 {x=48,y=0,width=48,height=48,}, -- frame 2 {x=96,y=0,width=48,height=48,}, -- frame 3 {x=144,y=0,width=48,height=48,}, -- frame 4 {x=192,y=0,width=48,height=48,}, -- frame 5 {x=240,y=0,width=48,height=48,}, -- frame 6 {x=288,y=0,width=48,height=48,}, -- frame 7 {x=336,y=0,width=48,height=48,}, -- frame 8 {x=384,y=0,width=48,height=48,}, -- frame 9 {x=432,y=0,width=48,height=48,}, -- frame 10 {x=480,y=0,width=48,height=48,}, -- frame 11 {x=528,y=0,width=48,height=48,}, -- frame 12 {x=576,y=0,width=48,height=48,}, -- frame 13 {x=624,y=0,width=48,height=48,}, -- frame 14 {x=672,y=0,width=48,height=48,}, -- frame 15 {x=720,y=0,width=48,height=48,}, -- frame 16 {x=0,y=48,width=48,height=48,}, -- frame 17 {x=48,y=48,width=48,height=48,}, -- frame 18 {x=96,y=48,width=48,height=48,}, -- frame 19 {x=144,y=48,width=48,height=48,}, -- frame 20 {x=192,y=48,width=48,height=48,}, -- frame 21 {x=240,y=48,width=48,height=48,}, -- frame 22 {x=288,y=48,width=48,height=48,}, -- frame 23 {x=336,y=48,width=48,height=48,}, -- frame 24 {x=384,y=48,width=48,height=48,}, -- frame 25 {x=432,y=48,width=48,height=48,}, -- frame 26 {x=480,y=48,width=48,height=48,}, -- frame 27 {x=528,y=48,width=48,height=48,}, -- frame 28 {x=576,y=48,width=48,height=48,}, -- frame 29 {x=624,y=48,width=48,height=48,}, -- frame 30 {x=672,y=48,width=48,height=48,}, -- frame 31 {x=720,y=48,width=48,height=48,}, -- frame 32 {x=0,y=96,width=48,height=48,}, -- frame 33 {x=48,y=96,width=48,height=48,}, -- frame 34 {x=96,y=96,width=48,height=48,}, -- frame 35 {x=144,y=96,width=48,height=48,}, -- frame 36 {x=192,y=96,width=48,height=48,}, -- frame 37 {x=240,y=96,width=48,height=48,}, -- frame 38 {x=288,y=96,width=48,height=48,}, -- frame 39 {x=336,y=96,width=48,height=48,}, -- frame 40 {x=384,y=96,width=48,height=48,}, -- frame 41 {x=432,y=96,width=48,height=48,}, -- frame 42 {x=480,y=96,width=48,height=48,}, -- frame 43 {x=528,y=96,width=48,height=48,}, -- frame 44 {x=576,y=96,width=48,height=48,}, -- frame 45 {x=624,y=96,width=48,height=48,}, -- frame 46 {x=672,y=96,width=48,height=48,}, -- frame 47 {x=720,y=96,width=48,height=48,}, -- frame 48 {x=0,y=144,width=48,height=48,}, -- frame 49 {x=48,y=144,width=48,height=48,}, -- frame 50 {x=96,y=144,width=48,height=48,}, -- frame 51 {x=144,y=144,width=48,height=48,}, -- frame 52 {x=192,y=144,width=48,height=48,}, -- frame 53 {x=240,y=144,width=48,height=48,}, -- frame 54 {x=288,y=144,width=48,height=48,}, -- frame 55 {x=336,y=144,width=48,height=48,}, -- frame 56 {x=384,y=144,width=48,height=48,}, -- frame 57 {x=432,y=144,width=48,height=48,}, -- frame 58 {x=480,y=144,width=48,height=48,}, -- frame 59 {x=528,y=144,width=48,height=48,}, -- frame 60 {x=576,y=144,width=48,height=48,}, -- frame 61 {x=624,y=144,width=48,height=48,}, -- frame 62 {x=672,y=144,width=48,height=48,}, -- frame 63 {x=720,y=144,width=48,height=48,}, -- frame 64 {x=0,y=192,width=48,height=48,}, -- frame 65 {x=48,y=192,width=48,height=48,}, -- frame 66 {x=96,y=192,width=48,height=48,}, -- frame 67 {x=144,y=192,width=48,height=48,}, -- frame 68 {x=192,y=192,width=48,height=48,}, -- frame 69 {x=240,y=192,width=48,height=48,}, -- frame 70 {x=288,y=192,width=48,height=48,}, -- frame 71 {x=336,y=192,width=48,height=48,}, -- frame 72 {x=384,y=192,width=48,height=48,}, -- frame 73 {x=432,y=192,width=48,height=48,}, -- frame 74 {x=480,y=192,width=48,height=48,}, -- frame 75 {x=528,y=192,width=48,height=48,}, -- frame 76 {x=576,y=192,width=48,height=48,}, -- frame 77 {x=624,y=192,width=48,height=48,}, -- frame 78 {x=672,y=192,width=48,height=48,}, -- frame 79 {x=720,y=192,width=48,height=48,}, -- frame 80 {x=0,y=240,width=48,height=48,}, -- frame 81 {x=48,y=240,width=48,height=48,}, -- frame 82 {x=96,y=240,width=48,height=48,}, -- frame 83 {x=144,y=240,width=48,height=48,}, -- frame 84 {x=192,y=240,width=48,height=48,}, -- frame 85 {x=240,y=240,width=48,height=48,}, -- frame 86 {x=288,y=240,width=48,height=48,}, -- frame 87 {x=336,y=240,width=48,height=48,}, -- frame 88 {x=384,y=240,width=48,height=48,}, -- frame 89 {x=432,y=240,width=48,height=48,}, -- frame 90 {x=480,y=240,width=48,height=48,}, -- frame 91 {x=528,y=240,width=48,height=48,}, -- frame 92 {x=576,y=240,width=48,height=48,}, -- frame 93 {x=624,y=240,width=48,height=48,}, -- frame 94 {x=672,y=240,width=48,height=48,}, -- frame 95 {x=720,y=240,width=48,height=48,}, -- frame 96 {x=0,y=288,width=48,height=48,}, -- frame 97 {x=48,y=288,width=48,height=48,}, -- frame 98 {x=96,y=288,width=48,height=48,}, -- frame 99 {x=144,y=288,width=48,height=48,}, -- frame 100 {x=192,y=288,width=48,height=48,}, -- frame 101 {x=240,y=288,width=48,height=48,}, -- frame 102 {x=288,y=288,width=48,height=48,}, -- frame 103 {x=336,y=288,width=48,height=48,}, -- frame 104 {x=384,y=288,width=48,height=48,}, -- frame 105 {x=432,y=288,width=48,height=48,}, -- frame 106 {x=480,y=288,width=48,height=48,}, -- frame 107 {x=528,y=288,width=48,height=48,}, -- frame 108 {x=576,y=288,width=48,height=48,}, -- frame 109 {x=624,y=288,width=48,height=48,}, -- frame 110 {x=672,y=288,width=48,height=48,}, -- frame 111 {x=720,y=288,width=48,height=48,}, -- frame 112 {x=0,y=336,width=48,height=48,}, -- frame 113 {x=48,y=336,width=48,height=48,}, -- frame 114 {x=96,y=336,width=48,height=48,}, -- frame 115 {x=144,y=336,width=48,height=48,}, -- frame 116 {x=192,y=336,width=48,height=48,}, -- frame 117 {x=240,y=336,width=48,height=48,}, -- frame 118 {x=288,y=336,width=48,height=48,}, -- frame 119 {x=336,y=336,width=48,height=48,}, -- frame 120 {x=384,y=336,width=48,height=48,}, -- frame 121 {x=432,y=336,width=48,height=48,}, -- frame 122 {x=480,y=336,width=48,height=48,}, -- frame 123 {x=528,y=336,width=48,height=48,}, -- frame 124 {x=576,y=336,width=48,height=48,}, -- frame 125 {x=624,y=336,width=48,height=48,}, -- frame 126 {x=672,y=336,width=48,height=48,}, -- frame 127 {x=720,y=336,width=48,height=48,}, -- frame 128 {x=0,y=384,width=48,height=48,}, -- frame 129 {x=48,y=384,width=48,height=48,}, -- frame 130 {x=96,y=384,width=48,height=48,}, -- frame 131 {x=144,y=384,width=48,height=48,}, -- frame 132 {x=192,y=384,width=48,height=48,}, -- frame 133 {x=240,y=384,width=48,height=48,}, -- frame 134 {x=288,y=384,width=48,height=48,}, -- frame 135 {x=336,y=384,width=48,height=48,}, -- frame 136 {x=384,y=384,width=48,height=48,}, -- frame 137 {x=432,y=384,width=48,height=48,}, -- frame 138 {x=480,y=384,width=48,height=48,}, -- frame 139 {x=528,y=384,width=48,height=48,}, -- frame 140 {x=576,y=384,width=48,height=48,}, -- frame 141 {x=624,y=384,width=48,height=48,}, -- frame 142 {x=672,y=384,width=48,height=48,}, -- frame 143 {x=720,y=384,width=48,height=48,}, -- frame 144 {x=0,y=432,width=48,height=48,}, -- frame 145 {x=48,y=432,width=48,height=48,}, -- frame 146 {x=96,y=432,width=48,height=48,}, -- frame 147 {x=144,y=432,width=48,height=48,}, -- frame 148 {x=192,y=432,width=48,height=48,}, -- frame 149 {x=240,y=432,width=48,height=48,}, -- frame 150 {x=288,y=432,width=48,height=48,}, -- frame 151 {x=336,y=432,width=48,height=48,}, -- frame 152 {x=384,y=432,width=48,height=48,}, -- frame 153 {x=432,y=432,width=48,height=48,}, -- frame 154 {x=480,y=432,width=48,height=48,}, -- frame 155 {x=528,y=432,width=48,height=48,}, -- frame 156 {x=576,y=432,width=48,height=48,}, -- frame 157 {x=624,y=432,width=48,height=48,}, -- frame 158 {x=672,y=432,width=48,height=48,}, -- frame 159 {x=720,y=432,width=48,height=48,}, -- frame 160 {x=0,y=480,width=48,height=48,}, -- frame 161 {x=48,y=480,width=48,height=48,}, -- frame 162 {x=96,y=480,width=48,height=48,}, -- frame 163 {x=144,y=480,width=48,height=48,}, -- frame 164 {x=192,y=480,width=48,height=48,}, -- frame 165 {x=240,y=480,width=48,height=48,}, -- frame 166 {x=288,y=480,width=48,height=48,}, -- frame 167 {x=336,y=480,width=48,height=48,}, -- frame 168 {x=384,y=480,width=48,height=48,}, -- frame 169 {x=432,y=480,width=48,height=48,}, -- frame 170 {x=480,y=480,width=48,height=48,}, -- frame 171 {x=528,y=480,width=48,height=48,}, -- frame 172 {x=576,y=480,width=48,height=48,}, -- frame 173 {x=624,y=480,width=48,height=48,}, -- frame 174 {x=672,y=480,width=48,height=48,}, -- frame 175 {x=720,y=480,width=48,height=48,}, -- frame 176 {x=0,y=528,width=48,height=48,}, -- frame 177 {x=48,y=528,width=48,height=48,}, -- frame 178 {x=96,y=528,width=48,height=48,}, -- frame 179 {x=144,y=528,width=48,height=48,}, -- frame 180 {x=192,y=528,width=48,height=48,}, -- frame 181 {x=240,y=528,width=48,height=48,}, -- frame 182 {x=288,y=528,width=48,height=48,}, -- frame 183 {x=336,y=528,width=48,height=48,}, -- frame 184 {x=384,y=528,width=48,height=48,}, -- frame 185 {x=432,y=528,width=48,height=48,}, -- frame 186 {x=480,y=528,width=48,height=48,}, -- frame 187 {x=528,y=528,width=48,height=48,}, -- frame 188 {x=576,y=528,width=48,height=48,}, -- frame 189 {x=624,y=528,width=48,height=48,}, -- frame 190 {x=672,y=528,width=48,height=48,}, -- frame 191 {x=720,y=528,width=48,height=48,}, -- frame 192 {x=0,y=576,width=48,height=48,}, -- frame 193 {x=48,y=576,width=48,height=48,}, -- frame 194 {x=96,y=576,width=48,height=48,}, -- frame 195 {x=144,y=576,width=48,height=48,}, -- frame 196 {x=192,y=576,width=48,height=48,}, -- frame 197 {x=240,y=576,width=48,height=48,}, -- frame 198 {x=288,y=576,width=48,height=48,}, -- frame 199 {x=336,y=576,width=48,height=48,}, -- frame 200 {x=384,y=576,width=48,height=48,}, -- frame 201 {x=432,y=576,width=48,height=48,}, -- frame 202 {x=480,y=576,width=48,height=48,}, -- frame 203 {x=528,y=576,width=48,height=48,}, -- frame 204 {x=576,y=576,width=48,height=48,}, -- frame 205 {x=624,y=576,width=48,height=48,}, -- frame 206 {x=672,y=576,width=48,height=48,}, -- frame 207 {x=720,y=576,width=48,height=48,}, -- frame 208 {x=0,y=624,width=48,height=48,}, -- frame 209 {x=48,y=624,width=48,height=48,}, -- frame 210 {x=96,y=624,width=48,height=48,}, -- frame 211 {x=144,y=624,width=48,height=48,}, -- frame 212 {x=192,y=624,width=48,height=48,}, -- frame 213 {x=240,y=624,width=48,height=48,}, -- frame 214 {x=288,y=624,width=48,height=48,}, -- frame 215 {x=336,y=624,width=48,height=48,}, -- frame 216 {x=384,y=624,width=48,height=48,}, -- frame 217 {x=432,y=624,width=48,height=48,}, -- frame 218 {x=480,y=624,width=48,height=48,}, -- frame 219 {x=528,y=624,width=48,height=48,}, -- frame 220 {x=576,y=624,width=48,height=48,}, -- frame 221 {x=624,y=624,width=48,height=48,}, -- frame 222 {x=672,y=624,width=48,height=48,}, -- frame 223 {x=720,y=624,width=48,height=48,}, -- frame 224 {x=0,y=672,width=48,height=48,}, -- frame 225 {x=48,y=672,width=48,height=48,}, -- frame 226 {x=96,y=672,width=48,height=48,}, -- frame 227 {x=144,y=672,width=48,height=48,}, -- frame 228 {x=192,y=672,width=48,height=48,}, -- frame 229 {x=240,y=672,width=48,height=48,}, -- frame 230 {x=288,y=672,width=48,height=48,}, -- frame 231 {x=336,y=672,width=48,height=48,}, -- frame 232 {x=384,y=672,width=48,height=48,}, -- frame 233 {x=432,y=672,width=48,height=48,}, -- frame 234 {x=480,y=672,width=48,height=48,}, -- frame 235 {x=528,y=672,width=48,height=48,}, -- frame 236 {x=576,y=672,width=48,height=48,}, -- frame 237 {x=624,y=672,width=48,height=48,}, -- frame 238 {x=672,y=672,width=48,height=48,}, -- frame 239 {x=720,y=672,width=48,height=48,}, -- frame 240 {x=0,y=720,width=48,height=48,}, -- frame 241 {x=48,y=720,width=48,height=48,}, -- frame 242 {x=96,y=720,width=48,height=48,}, -- frame 243 {x=144,y=720,width=48,height=48,}, -- frame 244 {x=192,y=720,width=48,height=48,}, -- frame 245 {x=240,y=720,width=48,height=48,}, -- frame 246 {x=288,y=720,width=48,height=48,}, -- frame 247 {x=336,y=720,width=48,height=48,}, -- frame 248 {x=384,y=720,width=48,height=48,}, -- frame 249 {x=432,y=720,width=48,height=48,}, -- frame 250 {x=480,y=720,width=48,height=48,}, -- frame 251 {x=528,y=720,width=48,height=48,}, -- frame 252 {x=576,y=720,width=48,height=48,}, -- frame 253 {x=624,y=720,width=48,height=48,}, -- frame 254 {x=672,y=720,width=48,height=48,}, -- frame 255 {x=720,y=720,width=48,height=48,}, -- frame 256 } } return options
apache-2.0
clofresh/Paradigm_Shift
camera.lua
1
17482
--[[ CAMERA -- Description: Supplies an interface for scrolling, scaling, and rotating a scene. -- Contributors: Osuf Oboys -- Version:3d, April 24, 2009 -- This product is released under the Lovely Public Community License v. 1.0. -- Provided that you do not alter this file and call your project a new version of CAMERA, -- then you are free to do whatever you want, including removing this header and the -- accompanying license. Otherwise, see the accompanying license. --]] -- TODO: particle system scaling -- TODO: negative scales should substitute a position with the corner that is in the upper upper left after the scaling. -- TODO: camera = {love={graphics={},mouse={}}} camera.class = {} camera.class.__index = camera.class local twopi = math.pi + math.pi -- (screenox, screenoy): the position of (ox, oy) on the screen -- (0,0): upper left (until the next LÖVE version) -- (1,0): upper right, (0,1): lower left, (1,1): lower right -- (0.5, 0.5): center of screen -- TODO: rotation function camera.new(scalex, scaley, ox, oy, screenox, screenoy, rotation) local cam = {} setmetatable(cam, camera.class) cam.scalex = scalex or 1 cam.scaley = scaley or 1 cam.ox = ox or 0 cam.oy = oy or 0 cam.screenox = screenox or 0 cam.screenoy = screenoy or 0 cam.rotation = rotation or 0 cam.cosrot = 1 cam.sinrot = 0 return cam end function camera.stretchToResolution(fromwidth, fromheight, towidth, toheight, ox, oy, screenox, screenoy, rotation) fromwidth = fromwidth or love.graphics.getWindowWidth() fromheight = fromheight or love.graphics.getWindowHeight() towidth = towidth or love.graphics.getWindowWidth() toheight = toheight or love.graphics.getWindowHeight() return camera.new(towidth / fromwidth, toheight / fromheight, ox, oy, screenox, screenoy, rotation) end function camera.class:pos(x, y) x = x or 0 y = y or 0 x,y = ((x - self.ox) * self.cosrot - (y - self.oy) * self.sinrot) * self.scalex + love.graphics.getWindowWidth() * self.screenox, ((y - self.oy) * self.cosrot + (x - self.ox) * self.sinrot) * self.scaley + love.graphics.getWindowHeight() * self.screenoy return x, y end function camera.class:unpos(x, y) x = (x or 0) y = (y or 0) x = (x - love.graphics.getWindowWidth() * self.screenox) / self.scalex y = (y - love.graphics.getWindowHeight() * self.screenoy) / self.scaley return self.ox + x * self.cosrot + y * self.sinrot, self.oy + y * self.cosrot - x * self.sinrot end function camera.class:transformBox(x, y, w, h) x, y = self:pos(x,y) w = w * self.scalex h = h * self.scaley if w < 0 then x = x + w; w = -w; end if h < 0 then y = y + h; h = -h; end return x, y, w, h end function camera.class:untransformBox(x, y, w, h) x, y = self:unpos(x,y) w = w / self.scalex h = h / self.scaley if w < 0 then x = x + w; w = -w; end if h < 0 then y = y + h; h = -h; end return x, y, w, h end -- How should scaling work for rotations? function camera.class:scaleSym(s) return s * (self.scalex^2 / 2 + self.scaley^2 / 2)^0.5 end function camera.class:unscaleSym(s) return s / (self.scalex^2 / 2 + self.scaley^2 / 2)^0.5 end function camera.class:scale(x, y) return math.abs(x * self.scalex), math.abs(y * self.scaley) end function camera.class:getRotationSizeFactors(x,y) return math.abs(x * self.cosrot) + math.abs(y * self.sinrot), math.abs(y * self.cosrot) + math.abs(x * self.sinrot) end function camera.class:scaleWithRot(x, y) return math.abs(x * self.scalex * self.cosrot) + math.abs(y * self.scaley * self.sinrot), math.abs(y * self.scaley * self.cosrot) + math.abs(x * self.scalex * self.sinrot) end function camera.class:scaleX(x) return math.abs(x * self.scalex) end function camera.class:scaleY(y) return math.abs(y * self.scaley) end function camera.class:unscale(x, y) return math.abs(x / self.scalex), math.abs(y / self.scaley) end -- This cannot be determined if the rotation is 0.5pi or 1.5 pi. function camera.class:unscaleWithRot(x, y) local z = self.scalex * self.scaley * (self.cosrot^2 - self.sinrot^2) if z == 0 then -- Not a bug, should say 'x' on both sides. return self.scalex * x / (self.scalex + self.scaley), self.scaley * x / (self.scalex + self.scaley) end return (math.abs(x * self.cosrot * self.scaley) - math.abs(y * self.sinrot * self.scalex)) / z, (math.abs(y * self.cosrot * self.scalex) - math.abs(x * self.sinrot * self.scaley)) / z end function camera.class:unscaleX(x) return math.abs(x / self.scalex) end function camera.class:unscaleY(y) return math.abs(y / self.scaley) end function camera.class:setOrigin(ox,oy) self.ox = ox; self.oy = oy end function camera.class:getOrigin() return self.ox, self.oy end function camera.class:setRotation(rot) self.rotation = rot self.cosrot = math.cos(math.rad(self.rotation)) self.sinrot = math.sin(math.rad(self.rotation)) end function camera.class:rotateBy(rot, ox, oy) if ox then self.ox = self.ox + (ox - self.ox) * (1 - self.cosrot) + (oy - self.oy) * self.sinrot self.oy = self.oy + (oy - self.oy) * (1 - self.cosrot) - (ox - self.ox) * self.sinrot end self:setRotation((rot + self.rotation) % 360) end function camera.class:getRotation() return self.rotation end function camera.class:setScreenOrigin(ox,oy) self.screenox = ox; self.screenoy = oy end function camera.class:getScreenOrigin() return self.screenox, self.screenoy end function camera.class:setScaleFactor(sx, sy) self.scalex = sx; self.scaley = sy end function camera.class:scaleBy(sx, sy) sx = sx or 1 sy = sy or sx self.scalex = self.scalex * sx self.scaley = self.scaley * sy end function camera.class:scaleXToAspectRatio() --self.scalex = love.graphics.getWindowWidth() / love.graphics.getWindowHeight() * self.scaley self.scalex = self.scaley end function camera.class:scaleYToAspectRatio() --self.scaley = love.graphics.getWindowHeight() / love.graphics.getWindowWidth() * self.scalex self.scaley = self.scalex end function camera.class:getScaleFactor() return self.scalex, self.scaley end camera.present = camera.new() camera.mouseCamera = nil function setCamera(cam) if cam then camera.present = cam end end function getCamera() return camera.present end function setMouseCamera(cam) camera.mouseCamera = cam end function getMouseCamera() return camera.mouseCamera end ---- Superseding ---- camera.love.graphics.getWidth = love.graphics.getWidth love.graphics.getWindowWidth = love.graphics.getWidth function love.graphics.getWidth() return camera.present:unscaleX(love.graphics.getWindowWidth()) end function love.graphics.getWidthWithRot() end camera.love.graphics.getHeight = love.graphics.getHeight love.graphics.getWindowHeight = love.graphics.getHeight function love.graphics.getHeight() return camera.present:unscaleY(love.graphics.getWindowHeight()) end camera.love.graphics.setScissor = love.graphics.setScissor function love.graphics.setScissor(x, y, w, h) if x and y then x, y, w, h = camera.present:transformBox(x, y, w, h) camera.love.graphics.setScissor(x, y, math.ceil(w), math.ceil(h)) --needed by Leif GUI else camera.love.graphics.setScissor() end end camera.love.graphics.getScissor = love.graphics.getScissor function love.graphics.getScissor() local x, y, w, h = camera.love.graphics.getScissor() if not x then return nil; end x, y, w, h = camera.present:untransformBox(x, y, w, h) return x, y, w, h end -- TODO: count line CRs? function string.linecount(s) local count = 0 local lf = string.byte("\n", 1) for i=1,s:len() do if s:byte(i) == lf then count = count + 1; end end return count+1 end function string.lineiter(s) s = s.."\n" return s:gmatch("([^\r\n]*)\r*\n\r*") end function camera.isShapeVisible(shape) local minvisx, minvisy, maxvisx, maxvisy = camera.love.graphics.getScissor() if minvisx then maxvisx = minvisx + maxvisx maxvisy = minvisy + maxvisy else minvisx = 1; maxvisx = love.graphics.getWindowWidth() minvisy = 1; maxvisy = love.graphics.getWindowHeight() end local x1,y1,x2,y2,x3,y3,x4,y4 = shape:getBoundingBox() x1, y1 = getCamera():pos(x1, y1) x3, y3 = getCamera():pos(x3, y3) if getCamera().rotation ~= 0 then x2, y2 = getCamera():pos(x2, y2) x4, y4 = getCamera():pos(x4, y4) minx = math.min(x1, x2, x3, x4) miny = math.min(y1, y2, y3, y4) maxx = math.max(x1, x2, x3, x4) maxy = math.max(y1, y2, y3, y4) else minx = math.min(x1, x3) miny = math.min(y1, y3) maxx = math.max(x1, x3) maxy = math.max(y1, y3) end return maxx >= minvisx and minx <= maxvisx and maxy >= minvisy and miny <= maxvisy end -- Supports newlines function camera.getTextWidth(text, font) font = font or love.graphics.getFont() local maxwidth = 0 for line in string.lineiter(text) do maxwidth = math.max(maxwidth, font:getWidth(line)) end return maxwidth end function camera.getFontWidth(font, text) return camera.getTextWidth(text, font) end function camera.getTextHeight(text, limit, font) font = font or love.graphics.getFont() if limit then text = camera.splitTextByTextWidth(text, limit, font) end return text:linecount() * font:getHeight() * font:getLineHeight() end -- Height of text besides the first line. function camera.getTextTailHeight(text, limit, font) font = font or love.graphics.getFont() if limit then text = camera.splitTextByTextWidth(text, limit, font) end return (text:linecount() - 1) * font:getHeight() * font:getLineHeight() end function camera.splitTextByTextWidth(text, width, font) font = font or love.graphics.getFont() local s = "" for line in string.lineiter(text) do if camera.getTextWidth(line, font) <= width then s = s..line.."\n" else local tmps = "" for token in line:gmatch("%s*[^%s]+") do if tmps:len() == 0 or camera.getTextWidth(tmps..token, font) <= width then tmps = tmps..token else s = s..tmps.."\n" --TODO remove preceding whitespaces tmps = token end end s = s..tmps.."\n" end end return s:sub(1,s:len()-1) end --TODO: particle system camera.love.graphics.draw = love.graphics.draw function love.graphics.draw(elem, x, y, angle, sx, sy) x, y = camera.present:pos(x,y) angle = (angle or 0) + camera.present.rotation sx = sx or 1 sy = sy or sx sx = sx * (math.abs(math.cos(math.rad(angle))^2 * camera.present.scalex) + math.abs(math.sin(math.rad(angle))^2 * camera.present.scaley)) sy = sy * (math.abs(math.cos(math.rad(angle))^2 * camera.present.scaley) + math.abs(math.sin(math.rad(angle))^2 * camera.present.scalex)) if camera.present.scalex * camera.present.scaley < 0 then angle = -angle end local nextElem = elem if type(elem) == "string" then local c = love.graphics:getFont():getHeight() * love.graphics:getFont():getLineHeight() if camera.present.scaley < 0 then x = x - sx * c * math.sin(math.rad(angle)) y = y + sy * c * math.sin(math.rad(angle)) end for line in string.lineiter(elem) do camera.love.graphics.draw(line, x, y, angle, sx, sy) x = x - sx * c * math.sin(math.rad(angle)) y = y + sy * c * math.cos(math.rad(angle)) end else if not pcall(camera.love.graphics.draw, elem, x, y, angle, sx, sy) then camera.love.graphics.draw(elem, x, y) end end end function love.graphics.drawParticles(system, x, y) x, y = camera.present:pos(x,y) camera.love.graphics.draw(system, x, y) end camera.love.graphics.drawf = love.graphics.drawf function love.graphics.drawf(s, x, y, limit, align, sx, sy) x, y = camera.present:pos(x,y) align = align or love.align_left s = camera.splitTextByTextWidth(s, limit * math.abs(camera.present.scalex)) sx = sx or 1 sy = sy or sx sx = sx * math.abs(camera.present.scalex) sy = sy * math.abs(camera.present.scaley) local angle = camera.present.rotation local cosrot = camera.present.cosrot local sinrot = camera.present.sinrot if camera.present.scalex * camera.present.scaley < 0 then sinrot = -sinrot angle = -angle end limit = limit * math.abs(camera.present.scalex) local mul = align == love.align_center and 0.5 or align == love.align_right and 1 or 0 for line in string.lineiter(s) do local width = sx * camera.getTextWidth(line) camera.love.graphics.draw(line, x + (limit - width) * mul * cosrot, y + (limit - width) * mul * sinrot, angle, sx, sy) x = x - sx * love.graphics:getFont():getHeight() * love.graphics:getFont():getLineHeight() * sinrot y = y + sy * love.graphics:getFont():getHeight() * love.graphics:getFont():getLineHeight() * cosrot end end --TODO ox, oy local or not? camera.love.graphics.draws = love.graphics.draws function love.graphics.draws(image, x, y, cx, cy, w, h, angle, sx, sy, ox, oy) angle = (angle or 0) + camera.present.rotation sx = sx or 1 sy = sy or sx x, y = camera.present:pos(x,y) if ox and oy then ox, oy = camera.present:pos(ox,oy) end sx = sx * math.abs(camera.present.scalex) sy = sy * math.abs(camera.present.scaley) if camera.present.scalex * camera.present.scaley < 0 then angle = -angle end if ox and oy then camera.love.graphics.draws(image, x, y, cx, cy, w, h, angle, sx, sy, ox, oy) else camera.love.graphics.draws(image, x, y, cx, cy, w, h, angle, sx, sy) end end camera.love.graphics.point = love.graphics.point function love.graphics.point(x, y) x, y = camera.present:pos(x,y) camera.love.graphics.point(x, y) end camera.love.graphics.line = love.graphics.line function love.graphics.line(x1, y1, x2, y2) x1, y1 = camera.present:pos(x1, y1) x2, y2 = camera.present:pos(x2, y2) camera.love.graphics.line(x1, y1, x2, y2) end camera.love.graphics.triangle = love.graphics.triangle function love.graphics.triangle(t, x1, y1, x2, y2, x3, y3) x1, y1 = camera.present:pos(x1, y1) x2, y2 = camera.present:pos(x2, y2) x3, y3 = camera.present:pos(x3, y3) camera.love.graphics.triangle(t, x1, y1, x2, y2, x3, y3) end camera.love.graphics.rectangle = love.graphics.rectangle function love.graphics.rectangle(t, x, y, w, h) love.graphics.polygon(t, x, y, x + w, y, x + w, y + h, x, y + h) end camera.love.graphics.quad = love.graphics.quad function love.graphics.quad(t, x1, y1, x2, y2, x3, y3, x4, y4) x1, y1 = camera.present:pos(x1, y1) x2, y2 = camera.present:pos(x2, y2) x3, y3 = camera.present:pos(x3, y3) x4, y4 = camera.present:pos(x4, y4) camera.love.graphics.quad(t, x1, y1, x2, y2, x3, y3, x4, y4) end -- Ovals not supported camera.love.graphics.circle = love.graphics.circle function love.graphics.circle(t, x, y, r, points) x, y = camera.present:pos(x, y) r = camera.present:scaleSym(r) if points then camera.love.graphics.circle(t, x, y, r, points) else camera.love.graphics.circle(t, x, y, r) end end camera.love.graphics.polygon = love.graphics.polygon function love.graphics.polygon(t, ...) if #arg > 0 then if (type((arg[1])) == "table") then arg = arg[1] end if camera.present then for i=1,#arg/2 do arg[2*i-1],arg[2*i] = camera.present:pos(arg[2*i-1], arg[2*i]) end end camera.love.graphics.polygon(t, unpack(arg)) end end camera.love.graphics.setLineWidth = love.graphics.setLineWidth function love.graphics.setLineWidth(width) camera.love.graphics.setLineWidth(camera.present:scaleX(width)) end camera.love.graphics.setLine = love.graphics.setLine function love.graphics.setLine(width, ...) camera.love.graphics.setLine(camera.present:scaleX(width), ...) end camera.love.graphics.getLineWidth = love.graphics.getLineWidth function love.graphics.getLineWidth() return camera.present:unscaleX(camera.love.graphics.getLineWidth()) end camera.love.graphics.setPointSize = love.graphics.setPointSize function love.graphics.setPointSize(size) camera.love.graphics.setPointSize(camera.present:scaleSym(size)) end camera.love.graphics.setPoint = love.graphics.setPoint function love.graphics.setPoint(size, ...) camera.love.graphics.setPoint(camera.present:scaleSym(size), ...) end camera.love.graphics.getPointSize = love.graphics.getPointSize function love.graphics.getPointSize() return camera.present:unscaleSym(camera.love.graphics.getPointSize()) end camera.love.graphics.getMaxPointSize = love.graphics.getMaxPointSize function love.graphics.getMaxPointSize() return camera.present:unscaleSym(camera.love.graphics.getMaxPointSize()) end function camera.lateInit() camera.mousepressed_default = mousepressed or function() end camera.mousereleased_default = mousereleased or function() end camera.love.mouse.getX = love.mouse.getX camera.love.mouse.getY = love.mouse.getY camera.love.mouse.getPosition = love.mouse.getPosition camera.love.mouse.setPosition = love.mouse.setPosition function mousepressed(x, y, ...) local oldCamera = getCamera() if camera.mouseCamera then setCamera(camera.mouseCamera) end x, y = camera.present:unpos(x,y) setCamera(oldCamera) local ret = camera.mousepressed_default(x, y, ...) return ret end function mousereleased(x, y, ...) local oldCamera = getCamera() if camera.mouseCamera then setCamera(camera.mouseCamera) end x, y = camera.present:unpos(x, y) setCamera(oldCamera) local ret = camera.mousereleased_default(x, y, ...) return ret end function love.mouse.getX() local x, y = camera.present:unpos(camera.love.mouse.getX(), camera.love.mouse.getY()) return x end function love.mouse.getY() local x, y = camera.present:unpos(camera.love.mouse.getX(), camera.love.mouse.getY()) return y end function love.mouse.getPosition() return camera.present:unpos(camera.love.mouse.getPosition()) end function love.mouse.setPosition(x, y) return camera.love.mouse.setPosition(unpack(camera.present:scale(x,y))) end end
bsd-3-clause
kuoruan/lede-luci
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/network.lua
53
2738
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. m = Map("luci_statistics", translate("Network Plugin Configuration"), translate( "The network plugin provides network based communication between " .. "different collectd instances. Collectd can operate both in client " .. "and server mode. In client mode locally collected data is " .. "transferred to a collectd server instance, in server mode the " .. "local instance receives data from other hosts." )) -- collectd_network config section s = m:section( NamedSection, "collectd_network", "luci_statistics" ) -- collectd_network.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_network_listen config section (Listen) listen = m:section( TypedSection, "collectd_network_listen", translate("Listener interfaces"), translate( "This section defines on which interfaces collectd will wait " .. "for incoming connections." )) listen.addremove = true listen.anonymous = true -- collectd_network_listen.host listen_host = listen:option( Value, "host", translate("Listen host") ) listen_host.default = "0.0.0.0" -- collectd_network_listen.port listen_port = listen:option( Value, "port", translate("Listen port") ) listen_port.default = 25826 listen_port.isinteger = true listen_port.optional = true -- collectd_network_server config section (Server) server = m:section( TypedSection, "collectd_network_server", translate("server interfaces"), translate( "This section defines to which servers the locally collected " .. "data is sent to." )) server.addremove = true server.anonymous = true -- collectd_network_server.host server_host = server:option( Value, "host", translate("Server host") ) server_host.default = "0.0.0.0" -- collectd_network_server.port server_port = server:option( Value, "port", translate("Server port") ) server_port.default = 25826 server_port.isinteger = true server_port.optional = true -- collectd_network.timetolive (TimeToLive) ttl = s:option( Value, "TimeToLive", translate("TTL for network packets") ) ttl.default = 128 ttl.isinteger = true ttl.optional = true ttl:depends( "enable", 1 ) -- collectd_network.forward (Forward) forward = s:option( Flag, "Forward", translate("Forwarding between listen and server addresses") ) forward.default = 0 forward.optional = true forward:depends( "enable", 1 ) -- collectd_network.cacheflush (CacheFlush) cacheflush = s:option( Value, "CacheFlush", translate("Cache flush interval"), translate("Seconds") ) cacheflush.default = 86400 cacheflush.isinteger = true cacheflush.optional = true cacheflush:depends( "enable", 1 ) return m
apache-2.0
3scale/apicast
spec/policy/find_service/host_based_finder_spec.lua
2
1950
local HostBasedFinder = require('apicast.policy.find_service.host_based_finder') local ConfigurationStore = require('apicast.configuration_store') local Configuration = require('apicast.configuration') describe('HostBasedFinder', function() describe('.find_service', function() it('returns the service in the config for the given host', function() local host = 'example.com' local service_for_host = Configuration.parse_service({ id = 1, proxy = { hosts = { host }, proxy_rules = { { pattern = '/', http_method = 'GET', metric_system_name = 'hits', delta = 1 } } } }) local service_different_host = Configuration.parse_service({ id = 2, proxy = { hosts = { 'different_host.something' }, proxy_rules = { { pattern = '/', http_method = 'GET', metric_system_name = 'hits', delta = 1 } } } }) local services = { service_for_host, service_different_host } local config_store = ConfigurationStore.new() config_store:store({ services = services }) local found_service = HostBasedFinder.find_service(config_store, host) assert.same(service_for_host, found_service) end) it('returns nil if there is not a service for the host', function() local host = 'example.com' local service_different_host = Configuration.parse_service({ id = 1, proxy = { hosts = { 'different_host.something' }, proxy_rules = { { pattern = '/', http_method = 'GET', metric_system_name = 'hits', delta = 1 } } } }) local config_store = ConfigurationStore.new() config_store:store({ services = { service_different_host } }) local found_service = HostBasedFinder.find_service(config_store, host) assert.is_nil(found_service) end) end) end)
apache-2.0
liamneit/Cornucopia
Cornucopia/Libs/Sushi-3.0/Classes/TipOwner.lua
1
1643
--[[ Copyright 2008-2015 João Cardoso Sushi is distributed under the terms of the GNU General Public License (or the Lesser GPL). This file is part of Sushi. Sushi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Sushi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Sushi. If not, see <http://www.gnu.org/licenses/>. --]] local Owner = MakeSushi(1, nil, 'TipOwner', nil, nil, SushiCallHandler) if not Owner then return end --[[ Builder ]]-- function Owner:OnCreate () self:SetScript('OnEnter', self.OnEnter) self:SetScript('OnLeave', self.OnLeave) end function Owner:OnRelease () SushiCallHandler.OnRelease(self) self:SetTip(nil) end --[[ API ]]-- function Owner:SetTip (h1, p) self.h1, self.p = h1, p end function Owner:GetTip () return self.h1, self.p end --[[ Scripts ]]-- function Owner:OnEnter () local h1, p = self:GetTip() if h1 then GameTooltip:SetOwner(self, 'ANCHOR_RIGHT') GameTooltip:AddLine(h1, nil, nil, nil, true) if p then GameTooltip:AddLine(p, 1, 1, 1, true) end GameTooltip:Show() end end function Owner:OnLeave () if GameTooltip:GetOwner() == self then GameTooltip:Hide() end end Owner.SetTooltip = Owner.SetTip Owner.GetTooltip = Owner.GetTip
gpl-3.0
3scale/apicast
gateway/src/resty/openssl/base.lua
2
1889
local ffi = require('ffi') ffi.cdef([[ typedef long time_t; // https://github.com/openssl/openssl/blob/4ace4ccda2934d2628c3d63d41e79abe041621a7/include/openssl/ossl_typ.h typedef struct x509_store_st X509_STORE; typedef struct x509_st X509; typedef struct X509_crl_st X509_CRL; typedef struct X509_name_st X509_NAME; typedef struct bio_st BIO; typedef struct bio_method_st BIO_METHOD; typedef struct X509_VERIFY_PARAM_st X509_VERIFY_PARAM; typedef struct stack_st OPENSSL_STACK; typedef struct evp_md_st { int type; int pkey_type; int md_size; } EVP_MD; unsigned long ERR_get_error(void); const char *ERR_reason_error_string(unsigned long e); void ERR_clear_error(void); ]]) local C = ffi.C local _M = { } local error = error local function openssl_error() local code, reason while true do --[[ https://www.openssl.org/docs/man1.1.0/crypto/ERR_get_error.html ERR_get_error() returns the earliest error code from the thread's error queue and removes the entry. This function can be called repeatedly until there are no more error codes to return. ]]-- code = C.ERR_get_error() if code == 0 then break else reason = C.ERR_reason_error_string(code) end end C.ERR_clear_error() if reason then return ffi.string(reason) end end local function ffi_value(ret, expected) if ret == nil or ret == -1 or (expected and ret ~= expected) then return nil, openssl_error() or 'expected value, got nil' end return ret end local function ffi_assert(ret, expected) local value, err = ffi_value(ret, expected) if not value then error(err, 2) end return value end local function tocdata(obj) return obj and obj.cdata or obj end _M.ffi_assert = ffi_assert _M.ffi_value = ffi_value _M.openssl_error = openssl_error _M.tocdata = tocdata return _M
apache-2.0
RockySeven3161/SeedBot
bot/seedbot.lua
1
8640
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) -- mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite" }, sudo_users = {121189712,123064250,0,tonumber(our_id)},--Sudo users disabled_channels = {}, realm = {},--Realms Id moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v1 An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Admins @iwals [Founder] @imandaneshi [Developer] @seyedan25 [Manager] Special thanks to awkward_potato Siyanew topkecleon Vamptacus Our channels @teleseedch [English] ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id return group id or user id !help !lock [member|name] Locks [member|name] !unlock [member|name|photo] Unlocks [member|name|photo] !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !newlink create/revoke your group link !link returns group link !owner returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] <text> Save <text> as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] returns user id "!res @username" !log will return group logs !banlist will return group ban list **U can use both "/" and "!" *Only owner and mods can add bots in group *Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
amirilk1414/i4bot
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
3scale/apicast
gateway/src/apicast/policy/soap/soap.lua
1
3327
--- SOAP Policy -- This policy adds support for a very small subset of SOAP. -- This policy basically expects a SOAPAction URI in the SOAPAction header or -- the content-type header. -- The SOAPAction header is used in v1.1 of the SOAP standard: -- https://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528, whereas the -- Content-Type header is used in v1.2 of the SOAP standard: -- https://www.w3.org/TR/soap12-part2/#ActionFeature -- The SOAPAction URI is matched against the mapping rules defined in the -- policy and calculates a usage based on that so it can be authorized and -- reported against 3scale's backend. local ipairs = ipairs local insert = table.insert local MappingRule = require('apicast.mapping_rule') local Usage = require('apicast.usage') local mapping_rules_matcher = require('apicast.mapping_rules_matcher') local MimeType = require('resty.mime') local policy = require('apicast.policy') local _M = policy.new('SOAP policy') local soap_action_header = 'SOAPAction' local soap_action_ctype = 'application/soap+xml' local new = _M.new -- Extracts a SOAP action from the SOAPAction header. Returns nil when not -- present. local function soap_action_in_header(headers) return headers[soap_action_header] end -- Extracts a SOAP action from the Content-Type header. In SOAP, the -- type/subtype is application/soap+xml, and the action is specified as a -- param in that header. When there is no SOAP action, this method returns nil. local function soap_action_in_ctype(headers) local mime_type = MimeType.new(headers['Content-Type']) if mime_type.media_type == soap_action_ctype then return mime_type:parameter('action') else return nil end end -- Extracts a SOAP action URI from the SOAP Action and the Content-Type -- headers. When both contain a SOAP action, the Content-Type one takes -- precedence. local function extract_soap_uri() local headers = ngx.req.get_headers() or {} return soap_action_in_ctype(headers) or soap_action_in_header(headers) end local function usage_from_matching_rules(soap_action_uri, rules) return mapping_rules_matcher.get_usage_from_matches( nil, soap_action_uri, {}, rules) end local function mapping_rules_from_config(config) if not (config and config.mapping_rules) then return {} end local res = {} for _, config_rule in ipairs(config.mapping_rules) do local rule = MappingRule.from_proxy_rule(config_rule) insert(res, rule) end return res end --- Initialize a SOAP policy -- @tparam[opt] table config Configuration function _M.new(config) local self = new(config) self.mapping_rules = mapping_rules_from_config(config) return self end --- Rewrite phase -- When a SOAP Action is received via the SOAPAction or the Content-Type -- headers, the policy matches it against the mapping rules defined in the -- configuration of the policy and calculates the associated usage. -- This usage is merged with the one received in the shared context. -- @tparam table context Shared context between policies function _M:rewrite(context) local soap_action_uri = extract_soap_uri() if soap_action_uri then local soap_usage = usage_from_matching_rules( soap_action_uri, self.mapping_rules) context.usage = context.usage or Usage.new() context.usage:merge(soap_usage) end end return _M
apache-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/texts/tutorial/stats-tier/tier3.lua
1
1173
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org return [[ Have you determined what's causing those new timed effects? If not, then consider the following questions: 1) What #GOLD#combat stat#WHITE# are you using as the attacker, and what #GOLD#combat stat#WHITE# are the spiders using as the defenders? 2) What tiers are these #GOLD#combat stats#WHITE#? Feel free to go batter those spiders some more if you need further experimentation! ]]
gpl-3.0
Blackdutchie/Zero-K
scripts/mahlazor.lua
6
5101
include "constants.lua" local base = piece 'base' local imma_chargin = piece 'imma_chargin' local mah_lazer = piece 'mah_lazer' local downbeam = piece 'downbeam' local shoop_da_woop = piece 'shoop_da_woop' local flashpoint = piece 'flashpoint' local beam1 = piece 'beam1' local on = false local awake = false; local oldHeight = 0 local shooting = 0 local lazerDefID = WeaponDefNames["mahlazer_lazer"].id local Vector = Spring.Utilities.Vector local max = math.max local smokePiece = {base} local wantedDirection = 0 local ROTATION_SPEED = math.rad(3.5)/30 -- Signal definitions local SIG_AIM = 2 local TARGET_ALT = 143565270/2^16 local soundTime = 0 local spGetUnitIsStunned = Spring.GetUnitIsStunned function TargetingLaser() while on do awake = (not spGetUnitIsStunned(unitID)) and (Spring.GetUnitRulesParam(unitID,"disarmed") ~= 1); if awake then --// Aiming local dx, _, dz = Spring.GetUnitDirection(unitID) local currentHeading = Vector.Angle(dx, dz) local aimOff = (currentHeading - wantedDirection + math.pi)%(2*math.pi) - math.pi if aimOff < 0 then aimOff = math.max(-ROTATION_SPEED, aimOff) else aimOff = math.min(ROTATION_SPEED, aimOff) end Spring.SetUnitRotation(unitID, 0, currentHeading - aimOff - math.pi/2, 0) --// Relay range local _, flashY = Spring.GetUnitPiecePosition(unitID, flashpoint) local _, mah_lazerY = Spring.GetUnitPiecePosition(unitID, mah_lazer) newHeight = max(mah_lazerY-flashY, 1) if newHeight ~= oldHeight then Spring.SetUnitWeaponState(unitID, 3, "range", newHeight) Spring.SetUnitWeaponState(unitID, 5, "range", newHeight) oldHeight = newHeight end --// Sound effects if soundTime < 0 then local px, py, pz = Spring.GetUnitPosition(unitID) Spring.PlaySoundFile("sounds/weapon/laser/laser_burn6.wav", 10, px, (py + flashY)/2, pz) soundTime = 46 else soundTime = soundTime - 1 end --// Shooting if shooting ~= 0 then EmitSfx(mah_lazer, FIRE_W2) EmitSfx(flashpoint, FIRE_W3) shooting = shooting - 1 else EmitSfx(mah_lazer, FIRE_W4) EmitSfx(flashpoint, FIRE_W5) end end Sleep(30) end end function script.Activate() Move(shoop_da_woop, y_axis, TARGET_ALT, 30*4) on = true StartThread(TargetingLaser) end function script.Deactivate() Move(shoop_da_woop, y_axis, 0, 250*4) on = false Signal(SIG_AIM) end function script.Create() --Move(beam1, z_axis, 28) --Move(beam1, y_axis, -2) Spring.SetUnitWeaponState(unitID, 2, "range", 9300) Spring.SetUnitWeaponState(unitID, 4, "range", 9300) Turn(mah_lazer, x_axis, math.rad(90)) Turn(downbeam, x_axis, math.rad(90)) --Turn(shoop_da_woop, z_axis, math.rad(0.04)) Turn(flashpoint, x_axis, math.rad(-90)) --Turn(flashpoint, x_axis, math.rad(0)) Hide(mah_lazer) Hide(downbeam) StartThread(SmokeUnit, smokePiece) end -- Unused but good for testing. Perhaps needed if the unit breaks. local function DoAimFromBetterHeading() local cQueue = Spring.GetCommandQueue(unitID, 1) if not (cQueue and cQueue[1] and cQueue[1].id == CMD.ATTACK) then return false end local px, py, pz, dx, dy, dz = Spring.GetUnitPiecePosDir(unitID, shoop_da_woop) local ax, ay, az if cQueue[1].params[3] then ax, ay, az = cQueue[1].params[1], Spring.GetGroundHeight(cQueue[1].params[1], cQueue[1].params[3]), cQueue[1].params[3] elseif #cQueue[1].params == 1 then _,_,_, ax, ay, az = Spring.GetUnitPosition(cQueue[1].params[1], true) end if not ay then return false end local horVec = {ax - px, az - pz} local vertVec = {Vector.AbsVal(horVec), ay - py} local myHeading = Vector.Angle(horVec) - math.pi/2 local myPitch = Vector.Angle(vertVec) local fudge = -0.0091 local pitchFudge = 0 myHeading = myHeading + fudge myPitch = myPitch + pitchFudge Spring.Echo("My heading pitch", myHeading*180/math.pi, myPitch*180/math.pi) return myHeading, myPitch end function script.AimWeapon(num, heading, pitch) if on and awake and num == 1 then Signal(SIG_AIM) SetSignalMask(SIG_AIM) local dx, _, dz = Spring.GetUnitDirection(unitID) local currentHeading = Vector.Angle(dx, dz) wantedDirection = currentHeading - heading --Spring.Echo("Spring heading pitch", heading*180/math.pi, pitch*180/math.pi) --local newHeading, newPitch = DoAimFromBetterHeading() --if newHeading then -- heading = newHeading -- pitch = newPitch --end Turn(mah_lazer, y_axis, 0) Turn(mah_lazer, x_axis, -pitch, math.rad(1.2)) WaitForTurn(mah_lazer, x_axis) return true end return false end function script.QueryWeapon(num) return shoop_da_woop end function script.FireWeapon(num) shooting = 30 end function script.AimFromWeapon(num) return shoop_da_woop end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if (severity <= .25) then Explode(base, SFX.NONE) return 1 -- corpsetype elseif (severity <= .5) then Explode(base, SFX.NONE) return 1 -- corpsetype else Explode(base, SFX.SHATTER) return 2 -- corpsetype end end
gpl-2.0
saraedum/luci-packages-old
modules/admin-core/luasrc/controller/admin/servicectl.lua
9
1426
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.servicectl", package.seeall) function index() entry({"servicectl"}, alias("servicectl", "status")).sysauth = "root" entry({"servicectl", "status"}, call("action_status")).leaf = true entry({"servicectl", "restart"}, call("action_restart")).leaf = true end function action_status() local data = nixio.fs.readfile("/var/run/luci-reload-status") if data then luci.http.write("/etc/config/") luci.http.write(data) else luci.http.write("finish") end end function action_restart() local uci = require "luci.model.uci".cursor() local rqp = luci.dispatcher.context.requestpath if rqp[3] then local service local services = { } for service in rqp[3]:gmatch("[%w_-]+") do services[#services+1] = service end local command = uci:apply(services, true) if nixio.fork() == 0 then local i = nixio.open("/dev/null", "r") local o = nixio.open("/dev/null", "w") nixio.dup(i, nixio.stdin) nixio.dup(o, nixio.stdout) i:close() o:close() nixio.exec("/bin/sh", unpack(command)) else luci.http.write("OK") os.exit(0) end end end
apache-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/talents/corruptions/rot.lua
1
14447
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org newTalent{ name = "Infectious Bite", type = {"technique/other", 1}, points = 5, message = "@Source@ bites blight poison into @target@.", cooldown = 3, tactical = { ATTACK = {BLIGHT = 2}, }, requires_target = true, range = 1, getDamage = function(self, t) return self:combatTalentWeaponDamage(t, 1, 1.5) end, getPoisonDamage = function(self, t) return self:combatTalentSpellDamage(t, 22, 200) end, action = function(self, t) local tg = {type="hit", range=self:getTalentRange(t), talent=t} local x, y, target = self:getTarget(tg) if not x or not y or not target then return nil end if core.fov.distance(self.x, self.y, x, y) > 1 then return nil end local dam = t.getDamage(self,t) local poison = t.getPoisonDamage(self,t) -- Hit? local hitted = self:attackTarget(target, nil, dam, true) if hitted then self:project({type="hit"}, target.x, target.y, DamageType.BLIGHT_POISON, {dam=poison, power=0, poison=1, apply_power=self:combatSpellpower()}) end return true end, info = function(self, t) local damage = t.getDamage(self, t) * 100 local poison = t.getPoisonDamage(self, t) return ([[Bite the target, dealing %d%% melee damage If the attack hits you'll inject blight poison into the target, dealing %0.2f blight damage and a further %0.2f blight damage over 4 turns. The bonus damage improves with your Spellpower.]]) :format(damage, damDesc(self, DamageType.BLIGHT, poison/4), damDesc(self, DamageType.BLIGHT, poison) ) end } carrionworm = function(self, target, duration, x, y) local m = mod.class.NPC.new{ type = "vermin", subtype = "worms", display = "w", color=colors.SANDY_BROWN, image = "npc/vermin_worms_carrion_worm_mass.png", name = "carrion worm mass", faction = self.faction, desc = [[]], autolevel = "none", ai = "summoned", ai_real = "dumb_talented_simple", ai_state = { talent_in=1, }, stats = { str=10, dex=15, mag=3, con=3 }, level_range = {self.level, self.level}, exp_worth = 0, global_speed_base = 1.0, max_life = resolvers.rngavg(5,9), size_category = 1, cut_immune = 1, blind_immune = 1, life_rating = 6, disease_immune = 1, melee_project={[DamageType.PESTILENT_BLIGHT] = self:getTalentLevel(self.T_PESTILENT_BLIGHT)*4,}, resists = { [DamageType.PHYSICAL] = 50, [DamageType.ACID] = 100, [DamageType.BLIGHT] = 100, [DamageType.FIRE] = -50}, combat_armor = 1, combat_def = 1, combat = { dam=1, atk=100, apr=100 }, autolevel = "warriormage", resolvers.talents{ [Talents.T_INFECTIOUS_BITE]=math.floor(self:getTalentLevelRaw(self.T_INFESTATION)), }, combat_spellpower = self:combatSpellpower(), summoner = self, summoner_gain_exp=true, summon_time = 10, ai_target = {actor=target} } m.unused_stats = 0 m.unused_talents = 0 m.unused_generics = 0 m.unused_talents_types = 0 m.no_inventory_access = true m.no_points_on_levelup = true m.save_hotkeys = true m.ai_state = m.ai_state or {} m.ai_state.tactic_leash = 100 -- Try to use stored AI talents to preserve tweaking over multiple summons m.ai_talents = self.stored_ai_talents and self.stored_ai_talents[m.name] or {} local damincrease = self:getTalentLevel(self.T_INFESTATION)*5 m.inc_damage.all = 0 + (damincrease or 0) m.poolmult = (1 + self:getTalentLevel(self.T_WORM_WALK)*8/100 or 1) m.on_die = function(self, src) game.level.map:addEffect(self, self.x, self.y, 5, engine.DamageType.WORMBLIGHT, 0.6*self:combatSpellpower()*self.poolmult, 2, 5, nil, engine.MapEffect.new{color_br=150, color_bg=255, color_bb=150, effect_shader="shader_images/poison_effect.png"} ) game.logSeen(self, "%s exudes a corrupted gas as it dies.", self.name:capitalize()) end if game.party:hasMember(self) then m.remove_from_party_on_death = true end m:resolve() m:resolve(nil, true) m:forceLevelup(self.level) game.zone:addEntity(game.level, m, "actor", x, y) game.level.map:particleEmitter(x, y, 1, "summon") -- Summons never flee m.ai_tactic = m.ai_tactic or {} m.ai_tactic.escape = 0 m.summon_time = 10 mod.class.NPC.castAs(m) engine.interface.ActorAI.init(m, m) return m end newTalent{ name = "Infestation", type = {"corruption/rot", 1}, require = corrs_req_high1, points = 5, mode = "sustained", sustain_vim = 40, cooldown = 30, getDamageReduction = function(self, t) return self:combatTalentLimit(t, 1, 0.1, 0.22) end, getDamagePct = function(self, t) return self:combatTalentLimit(t, 0.11, 0.3, 0.15) end, getResist = function(self, t) return 5 * self:getTalentLevel(t) end, getAffinity = function(self, t) return 4 * self:getTalentLevel(t) end, activate = function(self, t) local resist = t.getResist(self,t) local affinity = t.getAffinity(self,t) local ret = { res = self:addTemporaryValue("resists", {[DamageType.BLIGHT]=resist, [DamageType.ACID]=resist}), aff = self:addTemporaryValue("damage_affinity", {[DamageType.BLIGHT]=affinity}), worm = self:addTemporaryValue("worm", 1), } return ret end, deactivate = function(self, t, p) self:removeTemporaryValue("resists", p.res) self:removeTemporaryValue("damage_affinity", p.aff) self:removeTemporaryValue("worm", p.worm) return true end, callbackOnHit = function(self, t, cb) if ( cb.value > (t.getDamagePct(self, t) * self.max_life) ) then local damageReduction = cb.value * t.getDamageReduction(self, t) cb.value = cb.value - damageReduction game.logPlayer(self, "#GREEN#A carrion worm mass bursts forth from your wounds, softening the blow and reducing damage taken by #ORCHID#" .. math.ceil(damageReduction) .. "#LAST#.") local x, y = util.findFreeGrid(self.x, self.y, 10, true, {[Map.ACTOR]=true}) if not x then return nil end local m = carrionworm(self, self, 10, x, y) end return cb.value end, info = function(self, t) local resist = t.getResist(self,t) local affinity = t.getAffinity(self,t) local cap = t.getDamagePct(self,t) local damage = t.getDamageReduction(self,t) return ([[Your body has become a mass of living corruption, increasing your blight and acid resistance by %d%%, blight affinity by %d%% and allowing you to heal from your carrion worm blight pools. On taking damage greater than %d%% of your maximum health, the damage will be reduced by %d%% and a carrion worm mass will burst forth onto an adjacent tile, attacking your foes for 10 turns. Also increases the damage dealt by your carrion worms by %d%% and grants them the Infectious Bite spell at level %d. Carrion worms fully inherit your Spellpower.]]): format(resist, affinity, cap*100, damage*100, self:getTalentLevel(t)*5, self:getTalentLevelRaw(t)) end, } newTalent{ name = "Worm Walk", type = {"corruption/rot", 2}, require = corrs_req_high2, points = 5, cooldown = function(self, t) return math.ceil(self:combatTalentLimit(t, 4, 20, 8)) -- Limit > 4 end, requires_target = true, direct_hit = true, range = function(self, t) return math.floor(self:combatTalentScale(t, 4, 9)) end, getHeal = function(self, t) return self:combatTalentSpellDamage(t, 20, 100, 0.75)/100 end, getVim = function(self, t) return 5 * self:getTalentLevel(t) end, getDam = function(self, t) return self:combatTalentLimit(t, 4, 20, 10) end, action = function(self, t) local tg = {type="hit", range=self:getTalentRange(t), talent=t} local tx, ty, target = self:getTarget(tg) if not tx or not ty then return nil end if target and target.summoner and target.summoner == self and target.name == "carrion worm mass" then local didcrit = self:spellCrit(1) self:incVim(didcrit * t.getVim(self, t)) self:attr("allow_on_heal", 1) self:heal(didcrit * (t.getHeal(self, t)) * self.max_life, self) self:attr("allow_on_heal", -1) game.level.map:remove(self.x, self.y, Map.ACTOR) target:die() game.level.map(target.x, target.y, Map.ACTOR, self) self.x, self.y, target.x, target.y = target.x, target.y, self.x, self.y game.level.map:particleEmitter(tx, ty, 3, "circle", {empty_start=8, oversize=1, a=80, appear=8, limit_life=11, speed=5, img="green_demon_fire_circle", radius=3}) game.level.map:particleEmitter(tx, ty, 3, "circle", {oversize=1, a=80, appear=8, limit_life=11, speed=5, img="demon_fire_circle", radius=3}) game:playSoundNear(self, "talents/teleport") else local dam = t.getDam(self, t) * self.life / 100 local x, y = util.findFreeGrid(tx, ty, 10, true, {[Map.ACTOR]=true}) if not x then return nil end local m = carrionworm(self, self, 10, x, y) self:takeHit(dam, self, {source_talent=t}) end return true end, info = function(self, t) local range = self:getTalentRange(t) local heal = t.getHeal(self, t) * 100 local vim = t.getVim(self, t) local dam = t.getDam(self,t) return ([[Gain the ability to merge and seperate carrion worm masses. If used on a worm mass, you merge with it, moving to it's location, healing you for %d%% of your maximum health, restoring %d vim, and destroying the mass. If used on another target, you sacrifice %d%% of your current health to create a worm mass at their location. Also increases the damage and healing of your carrion worm's blight pool by %d%%.]]): format (heal, vim, dam, self:getTalentLevel(t)*8) end, } newTalent{ name = "Pestilent Blight", type = {"corruption/rot",3}, require = corrs_req_high3, points = 5, mode = "passive", cooldown = 6, radius = function(self, t) return self:getTalentLevel(t) >= 4 and 1 or 0 end, getChance = function(self, t) return self:combatTalentSpellDamage(t, 10, 60) end, getDuration = function(self, t) return math.floor(self:combatTalentScale(t, 2, 4)) end, target = function(self, t) return {type="ball", range=self:getTalentRange(t), radius=self:getTalentRadius(t), friendlyfire=false, talent=t} end, do_rot = function(self, t, target, dam) local chance = t.getChance(self,t) local dur = t.getDuration(self,t) if not dam or type(dam) ~= "number" then return end if rng.percent(chance) and not self:isTalentCoolingDown(t.id) then local tg = self:getTalentTarget(t) self:project(tg, target.x, target.y, function(px, py, tg, self) local target = game.level.map(px, py, Map.ACTOR) if target then local eff = rng.table{"blind", "silence", "disarm", "pin", } if eff == "blind" and target:canBe("blind") then target:setEffect(target.EFF_BLINDED, dur, {apply_power=self:combatSpellpower(), no_ct_effect=true}) elseif eff == "silence" and target:canBe("silence") then target:setEffect(target.EFF_SILENCED, dur, {apply_power=self:combatSpellpower(), no_ct_effect=true}) elseif eff == "disarm" and target:canBe("disarm") then target:setEffect(target.EFF_DISARMED, dur, {apply_power=self:combatSpellpower(), no_ct_effect=true}) elseif eff == "pin" and target:canBe("pin") then target:setEffect(target.EFF_PINNED, dur, {apply_power=self:combatSpellpower(), no_ct_effect=true}) end end end) self:startTalentCooldown(t.id) end end, info = function(self, t) local chance = t.getChance(self,t) local duration = t.getDuration(self,t) return ([[You have a %d%% chance on dealing blight damage to cause the target to rot away, silencing, disarming, blinding or pinning them for %d turns. This effect has a cooldown. At talent level 4, this affects targets in a radius 1 ball. Your worms also have a %d%% chance to blind, silence, disarm or pin with their melee attacks, lasting 2 turns. The chance to apply this effect will increase with your Spellpower.]]): format(chance, duration, self:getTalentLevel(t)*4) end, } newTalent{ name = "Worm Rot", type = {"corruption/rot", 4}, require = corrs_req_high4, points = 5, cooldown = 8, vim = 10, range = 6, requires_target = true, tactical = { ATTACK = { ACID = 1, BLIGHT = 1 }, DISABLE = 4 }, getBurstDamage = function(self, t) return self:combatTalentSpellDamage(t, 10, 150) end, getDamage = function(self, t) return self:combatTalentSpellDamage(t, 10, 55) end, proj_speed = 6, spawn_carrion_worm = function (self, target, t) local x, y = util.findFreeGrid(target.x, target.y, 10, true, {[Map.ACTOR]=true}) if not x then return nil end local m = carrionworm(self, self, 10, x, y) end, action = function(self, t) local tg = {type="bolt", range=self:getTalentRange(t), talent=t, display={particle="bolt_slime"}} local x, y = self:getTarget(tg) if not x or not y then return nil end self:project(tg, x, y, function(px, py) local target = game.level.map(px, py, engine.Map.ACTOR) if not target then return end if target:canBe("disease") then target:setEffect(target.EFF_WORM_ROT, 5, {src=self, dam=t.getDamage(self, t), burst=t.getBurstDamage(self, t), rot_timer = 5, apply_power=self:combatSpellpower()}) else game.logSeen(target, "%s resists the worm rot!", target.name:capitalize()) end game.level.map:particleEmitter(px, py, 1, "slime") end) game:playSoundNear(self, "talents/slime") return true end, info = function(self, t) local damage = t.getDamage(self, t) local burst = t.getBurstDamage(self, t) return ([[Infects the target with parasitic carrion worm larvae for 5 turns. Each turn the disease will remove a beneficial physical effect and deal %0.2f acid and %0.2f blight damage. If not cleared after five turns it will inflict %0.2f blight damage as the larvae hatch, removing the effect but spawning a full grown carrion worm mass near the target's location. The damage dealt will increase with your Spellpower.]]): format(damDesc(self, DamageType.ACID, (damage/2)), damDesc(self, DamageType.BLIGHT, (damage/2)), damDesc(self, DamageType.ACID, (burst))) end, }
gpl-3.0
fusijie/ejoy2d
examples/ex01.lua
19
1027
local ej = require "ejoy2d" local fw = require "ejoy2d.framework" local pack = require "ejoy2d.simplepackage" pack.load { pattern = fw.WorkDir..[[examples/asset/?]], "sample", } local obj = ej.sprite("sample","cannon") local turret = obj.turret -- set position (-100,0) scale (0.5) obj:ps(-100,0,0.5) local obj2 = ej.sprite("sample","mine") obj2.resource.frame = 70 -- set position(100,0) scale(1.2) separately obj2:ps(100,0) obj2:ps(1.2) local game = {} local screencoord = { x = 512, y = 384, scale = 1.2 } local x1,y1,x2,y2 = obj2:aabb(screencoord) obj2.label.text = string.format("AABB\n%d x %d", x2-x1, y2-y1) function game.update() turret.frame = turret.frame + 3 obj2.frame = obj2.frame + 1 end function game.drawframe() ej.clear(0xff808080) -- clear (0.5,0.5,0.5,1) gray obj:draw(screencoord) obj2:draw(screencoord) end function game.touch(what, x, y) end function game.message(...) end function game.handle_error(...) end function game.on_resume() end function game.on_pause() end ej.start(game)
mit
musenshen/SandBoxLua
src/cocos/extension/DeprecatedExtensionEnum.lua
40
1369
_G.kCCControlStepperPartMinus = cc.CONTROL_STEPPER_PART_MINUS _G.kCCControlStepperPartPlus = cc.CONTROL_STEPPER_PART_PLUS _G.kCCControlStepperPartNone = cc.CONTROL_STEPPER_PART_NONE _G.CCControlEventTouchDown = cc.CONTROL_EVENTTYPE_TOUCH_DOWN _G.CCControlEventTouchDragInside = cc.CONTROL_EVENTTYPE_DRAG_INSIDE _G.CCControlEventTouchDragOutside = cc.CONTROL_EVENTTYPE_DRAG_OUTSIDE _G.CCControlEventTouchDragEnter = cc.CONTROL_EVENTTYPE_DRAG_ENTER _G.CCControlEventTouchDragExit = cc.CONTROL_EVENTTYPE_DRAG_EXIT _G.CCControlEventTouchUpInside = cc.CONTROL_EVENTTYPE_TOUCH_UP_INSIDE _G.CCControlEventTouchUpOutside = cc.CONTROL_EVENTTYPE_TOUCH_UP_OUTSIDE _G.CCControlEventTouchCancel = cc.CONTROL_EVENTTYPE_TOUCH_CANCEL _G.CCControlEventValueChanged = cc.CONTROL_EVENTTYPE_VALUE_CHANGED _G.CCControlStateNormal = cc.CONTROL_STATE_NORMAL _G.CCControlStateHighlighted = cc.CONTROL_STATE_HIGH_LIGHTED _G.CCControlStateDisabled = cc.CONTROL_STATE_DISABLED _G.CCControlStateSelected = cc.CONTROL_STATE_SELECTED _G.kCCScrollViewDirectionHorizontal = cc.SCROLLVIEW_DIRECTION_HORIZONTAL _G.kCCScrollViewDirectionVertical = cc.SCROLLVIEW_DIRECTION_VERTICAL _G.kCCTableViewFillTopDown = cc.TABLEVIEW_FILL_TOPDOWN _G.kCCTableViewFillBottomUp = cc.TABLEVIEW_FILL_BOTTOMUP
mit
khavnu/VLCLIB
share/lua/modules/simplexml.lua
103
3732
--[==========================================================================[ simplexml.lua: Lua simple xml parser wrapper --[==========================================================================[ Copyright (C) 2010 Antoine Cellerier $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]==========================================================================] module("simplexml",package.seeall) --[[ Returns the xml tree structure -- Each node is of one of the following types: -- { name (string), attributes (key->value map), children (node array) } -- text content (string) --]] local function parsexml(stream, errormsg) if not stream then return nil, errormsg end local xml = vlc.xml() local reader = xml:create_reader(stream) local tree local parents = {} local nodetype, nodename = reader:next_node() while nodetype > 0 do if nodetype == 1 then local node = { name= nodename, attributes= {}, children= {} } local attr, value = reader:next_attr() while attr ~= nil do node.attributes[attr] = value attr, value = reader:next_attr() end if tree then table.insert(tree.children, node) table.insert(parents, tree) end tree = node elseif nodetype == 2 then if #parents > 0 then local tmp = {} while nodename ~= tree.name do if #parents == 0 then error("XML parser error/faulty logic") end local child = tree tree = parents[#parents] table.remove(parents) table.remove(tree.children) table.insert(tmp, 1, child) for i, node in pairs(child.children) do table.insert(tmp, i+1, node) end child.children = {} end for _, node in pairs(tmp) do table.insert(tree.children, node) end tree = parents[#parents] table.remove(parents) end elseif nodetype == 3 then table.insert(tree.children, nodename) end nodetype, nodename = reader:next_node() end if #parents > 0 then error("XML parser error/Missing closing tags") end return tree end function parse_url(url) return parsexml(vlc.stream(url)) end function parse_string(str) return parsexml(vlc.memory_stream(str)) end function add_name_maps(tree) tree.children_map = {} for _, node in pairs(tree.children) do if type(node) == "table" then if not tree.children_map[node.name] then tree.children_map[node.name] = {} end table.insert(tree.children_map[node.name], node) add_name_maps(node) end end end
gpl-2.0
vaughamhong/vlc
share/lua/modules/simplexml.lua
103
3732
--[==========================================================================[ simplexml.lua: Lua simple xml parser wrapper --[==========================================================================[ Copyright (C) 2010 Antoine Cellerier $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]==========================================================================] module("simplexml",package.seeall) --[[ Returns the xml tree structure -- Each node is of one of the following types: -- { name (string), attributes (key->value map), children (node array) } -- text content (string) --]] local function parsexml(stream, errormsg) if not stream then return nil, errormsg end local xml = vlc.xml() local reader = xml:create_reader(stream) local tree local parents = {} local nodetype, nodename = reader:next_node() while nodetype > 0 do if nodetype == 1 then local node = { name= nodename, attributes= {}, children= {} } local attr, value = reader:next_attr() while attr ~= nil do node.attributes[attr] = value attr, value = reader:next_attr() end if tree then table.insert(tree.children, node) table.insert(parents, tree) end tree = node elseif nodetype == 2 then if #parents > 0 then local tmp = {} while nodename ~= tree.name do if #parents == 0 then error("XML parser error/faulty logic") end local child = tree tree = parents[#parents] table.remove(parents) table.remove(tree.children) table.insert(tmp, 1, child) for i, node in pairs(child.children) do table.insert(tmp, i+1, node) end child.children = {} end for _, node in pairs(tmp) do table.insert(tree.children, node) end tree = parents[#parents] table.remove(parents) end elseif nodetype == 3 then table.insert(tree.children, nodename) end nodetype, nodename = reader:next_node() end if #parents > 0 then error("XML parser error/Missing closing tags") end return tree end function parse_url(url) return parsexml(vlc.stream(url)) end function parse_string(str) return parsexml(vlc.memory_stream(str)) end function add_name_maps(tree) tree.children_map = {} for _, node in pairs(tree.children) do if type(node) == "table" then if not tree.children_map[node.name] then tree.children_map[node.name] = {} end table.insert(tree.children_map[node.name], node) add_name_maps(node) end end end
gpl-2.0
bayas/AutoRunner
Bin/Data/LuaScripts/18_CharacterDemo.lua
1
17162
-- Moving character example. -- This sample demonstrates: -- - Controlling a humanoid character through physics -- - Driving animations using the AnimationController component -- - Manual control of a bone scene node -- - Implementing 1st and 3rd person cameras, using raycasts to avoid the 3rd person camera clipping into scenery -- - Saving and loading the variables of a script object -- - Using touch inputs/gyroscope for iOS/Android (implemented through an external file) require "LuaScripts/Utilities/Sample" require "LuaScripts/Utilities/Touch" -- Variables used by external file are made global in order to be accessed CTRL_FORWARD = 1 CTRL_BACK = 2 CTRL_LEFT = 4 CTRL_RIGHT = 8 CTRL_JUMP = 16 local MOVE_FORCE = 0.8 local INAIR_MOVE_FORCE = 0.02 local BRAKE_FORCE = 0.2 local JUMP_FORCE = 7.0 local YAW_SENSITIVITY = 0.1 local INAIR_THRESHOLD_TIME = 0.1 scene_ = nil characterNode = nil function Start() -- Execute the common startup for samples SampleStart() -- Create static scene content CreateScene() -- Create the controllable character CreateCharacter() -- Create the UI content CreateInstructions() -- Activate mobile stuff only when appropriate if GetPlatform() == "Android" or GetPlatform() == "iOS" then SetLogoVisible(false) InitTouchInput() end -- Subscribe to necessary events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create scene subsystem components scene_:CreateComponent("Octree") scene_:CreateComponent("PhysicsWorld") -- Create camera and define viewport. Camera does not necessarily have to belong to the scene cameraNode = Node() local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 renderer:SetViewport(0, Viewport:new(scene_, camera)) -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(0.5, 0.5, 0.7) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) -- Create the floor object local floorNode = scene_:CreateChild("Floor") floorNode.position = Vector3(0.0, -0.5, 0.0) floorNode.scale = Vector3(200.0, 1.0, 200.0) local object = floorNode:CreateComponent("StaticModel") object.model = cache:GetResource("Model", "Models/Box.mdl") object.material = cache:GetResource("Material", "Materials/Stone.xml") local body = floorNode:CreateComponent("RigidBody") -- Use collision layer bit 2 to mark world scenery. This is what we will raycast against to prevent camera from going -- inside geometry body.collisionLayer = 2 local shape = floorNode:CreateComponent("CollisionShape") shape:SetBox(Vector3(1.0, 1.0, 1.0)) -- Create mushrooms of varying sizes local NUM_MUSHROOMS = 60 for i = 1, NUM_MUSHROOMS do local objectNode = scene_:CreateChild("Mushroom") objectNode.position = Vector3(Random(180.0) - 90.0, 0.0, Random(180.0) - 90.0) objectNode.rotation = Quaternion(0.0, Random(360.0), 0.0) objectNode:SetScale(2.0 + Random(5.0)) local object = objectNode:CreateComponent("StaticModel") object.model = cache:GetResource("Model", "Models/Mushroom.mdl") object.material = cache:GetResource("Material", "Materials/Mushroom.xml") object.castShadows = true local body = objectNode:CreateComponent("RigidBody") body.collisionLayer = 2 local shape = objectNode:CreateComponent("CollisionShape") shape:SetTriangleMesh(object.model, 0) end -- Create movable boxes. Let them fall from the sky at first local NUM_BOXES = 100 for i = 1, NUM_BOXES do local scale = Random(2.0) + 0.5 local objectNode = scene_:CreateChild("Box") objectNode.position = Vector3(Random(180.0) - 90.0, Random(10.0) + 10.0, Random(180.0) - 90.0) objectNode.rotation = Quaternion(Random(360.0), Random(360.0), Random(360.0)) objectNode:SetScale(scale) local object = objectNode:CreateComponent("StaticModel") object.model = cache:GetResource("Model", "Models/Box.mdl") object.material = cache:GetResource("Material", "Materials/Stone.xml") object.castShadows = true local body = objectNode:CreateComponent("RigidBody") body.collisionLayer = 2 -- Bigger boxes will be heavier and harder to move body.mass = scale * 2.0 local shape = objectNode:CreateComponent("CollisionShape") shape:SetBox(Vector3(1.0, 1.0, 1.0)) end end function CreateCharacter() characterNode = scene_:CreateChild("Jack") characterNode.position = Vector3(0.0, 1.0, 0.0) -- Create the rendering component + animation controller local object = characterNode:CreateComponent("AnimatedModel") object.model = cache:GetResource("Model", "Models/Jack.mdl") object.material = cache:GetResource("Material", "Materials/Jack.xml") object.castShadows = true characterNode:CreateComponent("AnimationController") -- Set the head bone for manual control object.skeleton:GetBone("Bip01_Head").animated = false; -- Create rigidbody, and set non-zero mass so that the body becomes dynamic local body = characterNode:CreateComponent("RigidBody") body.collisionLayer = 1 body.mass = 1.0 -- Set zero angular factor so that physics doesn't turn the character on its own. -- Instead we will control the character yaw manually body.angularFactor = Vector3(0.0, 0.0, 0.0) -- Set the rigidbody to signal collision also when in rest, so that we get ground collisions properly body.collisionEventMode = COLLISION_ALWAYS -- Set a capsule shape for collision local shape = characterNode:CreateComponent("CollisionShape") shape:SetCapsule(0.7, 1.8, Vector3(0.0, 0.9, 0.0)) -- Create the character logic object, which takes care of steering the rigidbody characterNode:CreateScriptObject("Character") end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText( "Use WASD keys and mouse to move\n".. "Space to jump, F to toggle 1st/3rd person\n".. "F5 to save scene, F7 to load") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SubscribeToEvents() -- Subscribe to Update event for setting the character controls before physics simulation SubscribeToEvent("Update", "HandleUpdate") -- Subscribe to PostUpdate event for updating the camera position after physics simulation SubscribeToEvent("PostUpdate", "HandlePostUpdate") -- Subscribe to mobile touch events if touchEnabled == true then SubscribeToTouchEvents() end end function HandleUpdate(eventType, eventData) if characterNode == nil then return end local character = characterNode:GetScriptObject() if character == nil then return end -- Clear previous controls character.controls:Set(CTRL_FORWARD + CTRL_BACK + CTRL_LEFT + CTRL_RIGHT + CTRL_JUMP, false) if touchEnabled == true then -- Update controls using touch (mobile) updateTouches() else -- Update controls using keys (desktop) if ui.focusElement == nil then if input:GetKeyDown(KEY_W) then character.controls:Set(CTRL_FORWARD, true) end if input:GetKeyDown(KEY_S) then character.controls:Set(CTRL_BACK, true) end if input:GetKeyDown(KEY_A) then character.controls:Set(CTRL_LEFT, true) end if input:GetKeyDown(KEY_D) then character.controls:Set(CTRL_RIGHT, true) end if input:GetKeyDown(KEY_SPACE) then character.controls:Set(CTRL_JUMP, true) end -- Add character yaw & pitch from the mouse motion character.controls.yaw = character.controls.yaw + input.mouseMoveX * YAW_SENSITIVITY character.controls.pitch = character.controls.pitch + input.mouseMoveY * YAW_SENSITIVITY -- Limit pitch character.controls.pitch = Clamp(character.controls.pitch, -80.0, 80.0) -- Switch between 1st and 3rd person if input:GetKeyPress(KEY_F) then firstPerson = not firstPerson newFirstPerson = firstPerson end -- Check for loading / saving the scene if input:GetKeyPress(KEY_F5) then scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/CharacterDemo.xml") end if input:GetKeyPress(KEY_F7) then scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/CharacterDemo.xml") -- After loading we have to reacquire the character scene node, as it has been recreated -- Simply find by name as there's only one of them characterNode = scene_:GetChild("Jack", true) if characterNode == nil then return end end else character.controls:Set(CTRL_FORWARD + CTRL_BACK + CTRL_LEFT + CTRL_RIGHT + CTRL_JUMP, false) end end -- Set rotation already here so that it's updated every rendering frame instead of every physics frame characterNode.rotation = Quaternion(character.controls.yaw, Vector3(0.0, 1.0, 0.0)) end function HandlePostUpdate(eventType, eventData) if characterNode == nil then return end local character = characterNode:GetScriptObject() if character == nil then return end -- Get camera lookat dir from character yaw + pitch local rot = characterNode.rotation local dir = rot * Quaternion(character.controls.pitch, Vector3(1.0, 0.0, 0.0)) -- Turn head to camera pitch, but limit to avoid unnatural animation local headNode = characterNode:GetChild("Bip01_Head", true) local limitPitch = Clamp(character.controls.pitch, -45.0, 45.0) local headDir = rot * Quaternion(limitPitch, Vector3(1.0, 0.0, 0.0)) -- This could be expanded to look at an arbitrary target, now just look at a point in front local headWorldTarget = headNode.worldPosition + headDir * Vector3(0.0, 0.0, 1.0) headNode:LookAt(headWorldTarget, Vector3(0.0, 1.0, 0.0)) -- Correct head orientation because LookAt assumes Z = forward, but the bone has been authored differently (Y = forward) headNode:Rotate(Quaternion(0.0, 90.0, 90.0)) if firstPerson then -- First person camera: position to the head bone + offset slightly forward & up cameraNode.position = headNode.worldPosition + rot * Vector3(0.0, 0.15, 0.2) cameraNode.rotation = dir else -- Third person camera: position behind the character local aimPoint = characterNode.position + rot * Vector3(0.0, 1.7, 0.0) -- You can modify x Vector3 value to translate the fixed character position (indicative range[-2;2]) -- Collide camera ray with static physics objects (layer bitmask 2) to ensure we see the character properly local rayDir = dir * Vector3(0.0, 0.0, -1.0) -- For indoor scenes you can use dir * Vector3(0.0, 0.0, -0.5) to prevent camera from crossing the walls local rayDistance = cameraDistance local result = scene_:GetComponent("PhysicsWorld"):RaycastSingle(Ray(aimPoint, rayDir), rayDistance, 2) if result.body ~= nil then rayDistance = Min(rayDistance, result.distance) end rayDistance = Clamp(rayDistance, CAMERA_MIN_DIST, cameraDistance) cameraNode.position = aimPoint + rayDir * rayDistance cameraNode.rotation = dir end end -- Character script object class Character = ScriptObject() function Character:Start() -- Character controls. self.controls = Controls() -- Grounded flag for movement. self.onGround = false -- Jump flag. self.okToJump = true -- In air timer. Due to possible physics inaccuracy, character can be off ground for max. 1/10 second and still be allowed to move. self.inAirTimer = 0.0 self:SubscribeToEvent(self.node, "NodeCollision", "Character:HandleNodeCollision") end function Character:Load(deserializer) self.onGround = deserializer:ReadBool() self.okToJump = deserializer:ReadBool() self.inAirTimer = deserializer:ReadFloat() self.controls.yaw = deserializer:ReadFloat() self.controls.pitch = deserializer:ReadFloat() end function Character:Save(serializer) serializer:WriteBool(self.onGround) serializer:WriteBool(self.okToJump) serializer:WriteFloat(self.inAirTimer) serializer:WriteFloat(self.controls.yaw) serializer:WriteFloat(self.controls.pitch) end function Character:HandleNodeCollision(eventType, eventData) local contacts = eventData:GetBuffer("Contacts") while not contacts.eof do local contactPosition = contacts:ReadVector3() local contactNormal = contacts:ReadVector3() local contactDistance = contacts:ReadFloat() local contactImpulse = contacts:ReadFloat() -- If contact is below node center and mostly vertical, assume it's a ground contact if contactPosition.y < self.node.position.y + 1.0 then local level = Abs(contactNormal.y) if level > 0.75 then self.onGround = true end end end end function Character:FixedUpdate(timeStep) -- Could cache the components for faster access instead of finding them each frame local body = self.node:GetComponent("RigidBody") local animCtrl = self.node:GetComponent("AnimationController") -- Update the in air timer. Reset if grounded if not self.onGround then self.inAirTimer = self.inAirTimer + timeStep else self.inAirTimer = 0.0 end -- When character has been in air less than 1/10 second, it's still interpreted as being on ground local softGrounded = self.inAirTimer < INAIR_THRESHOLD_TIME -- Update movement & animation local rot = self.node.rotation local moveDir = Vector3(0.0, 0.0, 0.0) local velocity = body.linearVelocity -- Velocity on the XZ plane local planeVelocity = Vector3(velocity.x, 0.0, velocity.z) if self.controls:IsDown(CTRL_FORWARD) then moveDir = moveDir + Vector3(0.0, 0.0, 1.0) end if self.controls:IsDown(CTRL_BACK) then moveDir = moveDir + Vector3(0.0, 0.0, -1.0) end if self.controls:IsDown(CTRL_LEFT) then moveDir = moveDir + Vector3(-1.0, 0.0, 0.0) end if self.controls:IsDown(CTRL_RIGHT) then moveDir = moveDir + Vector3(1.0, 0.0, 0.0) end -- Normalize move vector so that diagonal strafing is not faster if moveDir:LengthSquared() > 0.0 then moveDir:Normalize() end -- If in air, allow control, but slower than when on ground if softGrounded then body:ApplyImpulse(rot * moveDir * MOVE_FORCE) else body:ApplyImpulse(rot * moveDir * INAIR_MOVE_FORCE) end if softGrounded then -- When on ground, apply a braking force to limit maximum ground velocity local brakeForce = planeVelocity * -BRAKE_FORCE body:ApplyImpulse(brakeForce) -- Jump. Must release jump control inbetween jumps if self.controls:IsDown(CTRL_JUMP) then if self.okToJump then body:ApplyImpulse(Vector3(0.0, 1.0, 0.0) * JUMP_FORCE) self.okToJump = false end else self.okToJump = true end end -- Play walk animation if moving on ground, otherwise fade it out if softGrounded and not moveDir:Equals(Vector3(0.0, 0.0, 0.0)) then animCtrl:PlayExclusive("Models/Jack_Walk.ani", 0, true, 0.2) else animCtrl:Stop("Models/Jack_Walk.ani", 0.2) end -- Set walk animation speed proportional to velocity animCtrl:SetSpeed("Models/Jack_Walk.ani", planeVelocity:Length() * 0.3) -- Reset grounded flag for next frame self.onGround = false end
mit
Blackdutchie/Zero-K
LuaRules/Configs/cai/accessory/no_stuck_in_factory.lua
13
3079
-- function widget:GetInfo() -- return { -- name = "UnitNoStuckInFactory", -- desc = "Always move unit away from factory's build yard & Remove an accidental build unit command from unit from factory. Prevent case of unit stuck in factory & to make sure unit can complete their move queue.", -- author = "msafwan", -- date = "2 January 2014", -- license = "none", -- handler = false, -- layer = 1, -- enabled = true, -- loaded by default? -- } -- end --Note: Widget became less relevant for Spring 95+ because unit will always go out from factory in Spring 95+. include("LuaRules/Configs/customcmds.h.lua") local excludedFactory = { [UnitDefNames["factorygunship"].id] = true, [UnitDefNames["factoryplane"].id] = true } function MoveUnitOutOfFactory(unitID,factDefID) ---Order unit to move away from factory's build yard--- if (not excludedFactory[factDefID]) then local queue = Spring.GetCommandQueue(unitID, 1) local firstCommand = queue and queue[1] if firstCommand then if not (firstCommand.id == CMD.MOVE or firstCommand.id == CMD_JUMP) then --no rally behaviour?? (we leave unit with CMD.MOVE alone because we don't want to disturb factory's move command) local dx,_,dz = Spring.GetUnitDirection(unitID) local x,y,z = Spring.GetUnitPosition(unitID) dx = dx*100 --Note: don't need trigonometry here because factory direction is either {0+-,1+-} or {1+-,0+-} (1 or 0), so multiply both with 100 elmo is enough dz = dz*100 --note to self: CMD.OPT_META is spacebar, CMD.OPT_INTERNAL is widget. If we use CMD.OPT_INTERNAL Spring might return unit to where it originally started but the benefit is it don't effected by Repeat state (reference: cmd_retreat.lua widget by CarRepairer). if ( firstCommand.id < 0 ) and (not firstCommand.params[1] ) then --if build-unit-command (which can be accidentally given when you use Chili Integral Menu) Spring.GiveOrderArrayToUnitArray( {unitID},{ {CMD.REMOVE, {firstCommand.tag}, {}}, --remove build-unit command since its only valid for factory & it prevent idle status from being called for regular unit (it disturb other widget's logic) {CMD.INSERT, {0, CMD.MOVE, CMD.OPT_INTERNAL, x+dx, y, z+dz}, {"alt"}}, {CMD.INSERT, {1, CMD.STOP, CMD.OPT_INTERNAL,}, {"alt"}}, --stop unit at end of move command (else it will return to original position). })--insert move-stop command behind existing command else Spring.GiveOrderArrayToUnitArray( {unitID},{ {CMD.INSERT, {0, CMD.MOVE, CMD.OPT_INTERNAL, x+dx, y, z+dz}, {"alt"}}, {CMD.INSERT, {1, CMD.STOP, CMD.OPT_INTERNAL,}, {"alt"}}, }) --Spring.Echo(CMD[firstCommand.id]) end end else --no command at all? (happen when factory is at edge of map and engine ask unit to rally outside of map) local dx,_,dz = Spring.GetUnitDirection(unitID) local x,y,z = Spring.GetUnitPosition(unitID) dx = dx*100 dz = dz*100 Spring.GiveOrderToUnit( unitID, CMD.MOVE, {x+dx, y, z+dz}, {}) end ------ end end
gpl-2.0
nicoNaN/ludum-dare-33
lib/arc/navi.lua
1
19465
local draw = require(arc_path .. 'draw') local bool,calc,str,tab,misc = unpack(require(arc_path .. 'code')) local _,_,_choice = unpack(require(arc_path .. 'input')) -- shortcuts local lg = love.graphics local lt = love.timer -- a bloc is text of one color and with no line breaks. -- messages are played out in blocs to improve performance. local _bloc = {} _bloc.__index = _bloc function _bloc:new(s,x,y,c) local o = {} setmetatable(o,_bloc) o.s = str.unformat(s) o.nc = o.s:len() o.x,o.y = x,y o.c = c or arc.col.white local _,r,g,b,a,co local n,e = 0,1 -- parse out and set color if s:sub(1,2) == '|c' then _,_,r,g,b,a = s:find('(%x%x)(%x%x)(%x%x)(%x%x)',3) co = {tonumber(r,16),tonumber(g,16),tonumber(b,16),tonumber(a,16)} n = n+10 o.c = co end return o end -- draw first 'nc' characters of bloc function _bloc:draw(x,y,nc) local nc = nc or -1 -- if nc>s:len(), displays all of s, so don't worry about it draw.text(self.s:sub(1,nc),x+self.x,y+self.y,self.c) end -- message class local _navi = {} _navi.__index = _navi function _navi:new(s,opt) local o = {} setmetatable(o,_navi) -- a ton of options! local opt = opt or {} local w = opt.w -- text wrap width o.wbox = opt.wbox -- fixed box width o.x = opt.x or 10 -- x disp pos o.y = opt.y or 10 -- y disp pos o.alx = opt.alx or 'l' -- text x alignment o.alxb = opt.alxb or 'l' -- box x alignment o.alyb = opt.alyb or 't' -- box y alignment o.wait = opt.wait -- if nil, keypress ends msg, else wait opt.wait sec o.skip = misc.get_def(opt.skip,true) -- true = can skip msg with keypress o.msg_spd = opt.msg_spd or arc.cfg.msg_spd -- message speed o.instant = opt.instant -- true = show all text instantly o.box = misc.get_def(opt.box,true) -- true = message box o.box_open = misc.get_def(opt.box_open,false) -- true = box open animation o.box_close = misc.get_def(opt.box_close,false) -- true = box close animation o.box_anim = misc.get_def(opt.box_anim, -- true = box open/close animation not (o.box_open or o.box_close)) o.name = opt.name -- name o.face = opt.face -- face picture o.face_pos = opt.face_pos or 'l' -- face picture pos o.face_border = misc.get_def(opt.face_border,true) -- face border o.blinker = misc.get_def(opt.blinker,true) -- true = show blinker o.scroll = misc.get_def(opt.scroll,true) -- true = scroll message o.nrows = opt.nrows -- # rows in box if o.nrows and o.name then -- name takes up 1 row o.nrows = o.nrows-1 end o.chs = opt.choices -- list of choices if o.chs then if opt.nvchs then -- # views for choices o.nvchs = opt.nvchs else o.nvchs = #o.chs if o.nrows and (o.nvchs>o.nrows) then o.nvchs = o.nrows end end end o.dytext = (s=='' and -arc.fn.h) or 0 -- if message is '', move choices up one line o.dyname = (o.name and arc.fn.h) or 0 -- set face info if o.face then o.wface = o.face:getWidth() o.hface = o.face:getHeight() o.dxface = o.wface+10 if w then w = w-o.dxface end else o.dxface = 0 end -- if box width is set, set 'w' if o.wbox then w = o.wbox-o.dxface-20 o.wbox_fixed = true end -- choice cannot be longer than 'w' o.nchs = (o.chs and #o.chs) or 0 local lwchs if o.chs then lwchs,wcur = {},arc.img.cursor:getWidth()+3 for i = 1,o.nchs do lwchs[i] = arc.fn.w(o.chs[i])+wcur end local lwmaxchs = math.max(unpack(lwchs)) if w and lwmaxchs > w then w = lwmaxchs end end -- handle new message box formatting option s = _navi.repl_col(s) if o.nrows then local t = str.inbw(s,'|m') local m = {} if w then for i = 1,#t do m[i] = _navi.add_nls(t[i],w) if i~=#t then m[i] = _navi.add_nms(m[i],o.nrows) end end s = table.concat(m) end elseif w then s = _navi.add_nls(s,w) end if s:len() == 0 then s = s..' ' end -- prevent code crash -- adds pauses in a hackish way. it adds spaces before the pause command -- and adjusts the block display pos. n spaces = pause of n/msg_spd sec local ps = string.rep(' ',arc.cfg.msg_nc_short_pause) local pl = string.rep(' ',arc.cfg.msg_nc_long_pause) s = s:gsub('|,',ps..'|,') s = s:gsub('|:',pl..'|:') o.b = {} o.lw = {} -- line: widths o.lb = {} -- line: last bloc o.bl = {} -- block: liine # o.rnc = {} -- block: rolling total # chars o.lb[0] = 0 o.rnc[0] = 0 local i = 1 -- pos in 's' local j = 1 -- pos where last bloc ended local e = 1 -- current bloc # local cl = 1 -- current line # local xc,yc = 0,0 -- keeps track of block pos local dx,dy -- dx,dy shift for current bloc local cc = arc.col.white -- current text color local b -- current bloc string local z -- format command while true do -- parse all the information out! b = '' z = s:sub(i,i+1) -- start a new bloc when you see a formatting command if z == '|!' then b = s:sub(j,i-1) dx,dy = arc.fn.w(str.unformat(b)),0 elseif z == '|c' then b = s:sub(j,i-1) dx,dy = arc.fn.w(str.unformat(b)),0 elseif z == '|n' then b = s:sub(j,i-1) dx,dy = -xc,arc.fn.h elseif z == '|,' then b = s:sub(j,i-1) dx,dy = -arc.fn.w(ps)+arc.fn.w(str.unformat(b)),0 elseif z == '|:' then b = s:sub(j,i-1) dx,dy = -arc.fn.w(pl)+arc.fn.w(str.unformat(b)),0 end -- reached the end if i >= s:len() then b = s:sub(j,i) dx,dy = arc.fn.w(str.unformat(b)),0 o.lw[cl] = xc+dx o.lb[cl] = e -- if choices don't fit in same box, they will appear in next box -- so put in keypress to let player read current box if o.nrows and not o.wait and (o.chs and cl%o.nrows+o.nvchs>o.nrows) then z = '|!' end end -- create bloc if b ~= '' then o.b[e] = _bloc:new(b,xc,yc,cc) cc = o.b[e].c o.bl[e] = cl o.rnc[e] = o.rnc[e-1]+o.b[e].nc -- update line # if (z == '|n') then o.lw[cl] = xc+arc.fn.w(str.unformat(b)) o.lb[cl] = e -- if last line in box, add keypress to let player read current box if o.nrows and not o.wait and (cl%o.nrows==0) then z = '|!' end cl = cl+1 end -- keypress stuff o.b[e].inp = (z == '|!') xc,yc = xc+dx,yc+dy e,j = e+1,i end if i >= s:len() then break end i = i+1 end -- alignment o.nl = cl if o.chs then o.cchs = _choice:new(o.chs,o.nvchs) o.wll = math.max(math.max(unpack(o.lw)),math.max(unpack(lwchs))) else o.nchs = 0 o.wll = math.max(unpack(o.lw)) end -- total height of all lines (including choices) if o.nrows then o.hls = arc.fn.h*o.nrows else o.nrows = o.nl+o.nchs o.hls = arc.fn.h*o.nrows end -- dxm and dym are multipliers to align (i.e. center) text o.dxm = tab.index({l=0,m=.5,r=1},o.alx) o.dxmb = tab.index({l=0,m=.5,r=1},o.alxb) o.dymb = tab.index({t=0,m=.5,b=1},o.alyb) -- calculate x-shift of each bloc o.bdx = {} for i = 1,#o.b do o.bdx[i] = math.floor(-o.dxm*o.lw[o.bl[i]]) end o:set_pos() o:init() return o end -- set various positions and lengths function _navi:set_pos() if not self.wbox_fixed then self.wbox = self.wll+self.dxface+20 end -- margin = 20 px self.hbox = self.hls+arc.fn.h+self.dyname+6 self.xbox = -10-math.floor(self.dxmb*self.wbox) self.ybox = -10-math.floor(self.dymb*self.hbox) local x,y = self.xbox,self.ybox -- everything is wrt this self.xname = x+10+self.dxface self.yname = y+10 if self.face then self.xface = x+10 self.yface = y+math.floor(0.5*(self.hbox-self.hface)) end self.xtext = x+10+self.dxface+self.dxm*(self.wbox-20-self.dxface) self.ytext = y+10+self.dyname self.xchc = x+10+self.dxface self.ychc = y+10+self.dyname+arc.fn.h*self.nl+self.dytext+2 self.xblink = x+math.floor(0.5*(self.wbox-arc.img.blinker:getWidth())) self.yblink = y+self.hbox-math.floor(0.5*arc.img.blinker:getHeight()) self.clip = {self.xname,self.ytext,self.wll,self.hls} -- if face_pos is 'r', make some changes... if self.face_pos == 'r' then self.xname = self.xname-self.dxface self.xtext = self.xtext-self.dxface self.clip[1] = self.clip[1]-self.dxface self.xchc = self.xchc-self.dxface self.xface = self.xbox+self.wbox-self.dxface end -- choice bar if self.chs then -- when the choice is run, the pos is wrt self.xchc, do -- don't add that in here - or it will be wrong! self.cchs.xbar = self.wbox-self.dxface-24 end end -- init message function _navi:init() self.pos = 'made' self.ci = 1 self.view = 1 self.pick = nil if self.chs then self.cchs:reset() end -- handle keypresses and waits for i = 1,#self.b do self.b[i].done = nil self.b[i].tset = nil end end -- is the message done? function _navi:is_over() return self.pos == 'over' end -- what choice did the player pick? function _navi:get_pick() return self.pick end -- play message at (x,y) function _navi:play(x,y) if self.pos == 'over' then return end local i -- moving bloc # local dys -- adjusts text position local bf,bl -- first and last blocs in view local t1,t2 -- temp variables lg.push() x,y = x+self.x,y+self.y lg.translate(x,y) -- used for message auto-init if self.pos == 'made' then self.t0 = lt.getTime() self.pos = 'open' end -- play open or close animation local animo = self.pos=='open' and (self.box_anim or self.box_open) local animc = self.pos=='close' and (self.box_anim or self.box_close) if self.box and (animo or animc) then af = (lt.getTime()-self.t0)/arc.cfg.msg_tanim draw.win_anim(self.xbox, self.ybox, self.wbox, self.hbox, af, self.pos) if af > 1 then self.pos = (self.pos=='open' and 'show') or (self.pos=='close' and 'over') self.t0 = lt.getTime() end lg.pop() return end if not self.anim and self.pos == 'open' then self.pos = 'show' end local nc = (self.instant and math.huge) or math.floor(self.msg_spd*(lt.getTime()-self.t0)) -- draw stuff if self.box then draw.window(self.xbox, self.ybox, self.wbox, self.hbox) end if self.name then draw.text(self.name, self.xname, self.yname, arc.col.name) end if self.face then lg.setColor(arc.col.white) lg.draw(self.face, self.xface, self.yface) if self.face_border then lg.rectangle('line', self.xface, self.yface, self.wface, self.hface) end end -- scroll text if self.pos == 'scroll' and self.scroll then lg.setScissor(x+self.clip[1], y+self.clip[2], self.clip[3], self.clip[4]) dys = -(self.view-1)*arc.fn.h af = (lt.getTime()-self.sct0)/arc.cfg.msg_tscroll if af >= 1 then self.pos = self.scpos if self.pos == 'show' then self.view = self.view+self.nrows self.t0 = self.t0 + (lt.getTime()-self.b[self.sci].t0) elseif self.pos == 'choice' then self.t0 = lt.getTime() end else af = math.sin(math.pi/2*af) -- cooler than linear! for i = self.scbf,self.scbl do self.b[i]:draw(self.xtext+self.bdx[i], self.ytext+dys-af*arc.fn.h*self.nrows) end end lg.setScissor() lg.pop() return end dys = -(self.view-1)*arc.fn.h -- init some stuff for the choice... if self.pos == 'choice' then if self.chs then if self:chc_fits() then -- then -- start new screen self.dychs = (-self.nl+self.nl%self.nrows)*arc.fn.h else self.view = self.view+self.nrows self.dychs = -self.nl*arc.fn.h end end self.pos = 'choose' end -- display blocs if self.view <= self.nl then bf = self.lb[self.view-1]+1 bl = self.lb[math.min(self.view+self.nrows-1,self.nl)] for i = bf,bl do -- display everything and process any keypresses if self.pos == 'show' and nc <= self.rnc[i] then -- display the current bloc self.b[i]:draw(self.xtext+self.bdx[i], self.ytext+dys, nc-self.rnc[i-1]) self.ci = i break else self.b[i]:draw(self.xtext+self.bdx[i], self.ytext+dys) -- handle waits at end of view if self.wait and i == bl and not self.b[i].done then t1 = i==#self.b and self.chs and self:chc_fits() -- at end, choices fit, don't wait t2 = i==#self.b and not self.chs -- at end, no choices, don't wait (is handled later) if not (t1 or t2) then if self.b[i].tset then if lt.getTime()-self.b[i].waitt0 >= self.wait then self.b[i].done = true if self.scroll then self:set_scroll(i,bf,bl) else self:advance(i,bl) end end lg.pop() return else self.b[i].tset = true self.b[i].t0 = lt.getTime() self.b[i].waitt0 = lt.getTime() break end end end -- handle keypresses if self.b[i].inp and not self.b[i].done then self.ci = i if self.b[i].tset then self:show_blinker() if arc.btn.kp == arc.btn.ent then -- if player pressed input key self.b[i].done = true if i == bl and self.scroll then -- do scroll animation self:set_scroll(i,bf,bl) else self:advance(i,bl) end end lg.pop() return -- waiting for keypress, don't go further else -- store time when message paused for keypress. this is -- later used to adjust the initial time of the message. self.b[i].t0 = lt.getTime() self.b[i].tset = true break end end -- break out of loop if you reached the end if self.pos == 'show' and i == #self.b then self.pos = 'choice' self.t0 = lt.getTime() break end end end end -- press enter key to skip the message if self.pos == 'show' and arc.btn.kp == arc.btn.ent and self.skip and (not self.b[self.ci].inp or (self.b[self.ci].inp and (not self.b[self.ci].tset or self.b[self.ci].done))) then for i = bf,bl-1 do if self.b[i].inp then self.b[i].done = true end end self.t0 = lt.getTime()-self.rnc[self.lb[math.min(self.view+self.nrows-1,self.nl)]]/arc.cfg.msg_spd end -- if message is over, don't display if self.pos == 'choose' then if self.chs then if not self.cchs.done then self.cchs:run(self.xchc, self.ychc+self.dychs) else self.pos = 'close' self.t0 = lt.getTime() self.pick = self.cchs.pick end else if self.wait == nil then self:show_blinker() if arc.btn.kp == arc.btn.ent then self.pos = 'close' self.t0 = lt.getTime() end elseif (lt.getTime()-self.t0 > self.wait) then self.pos = 'close' self.t0 = lt.getTime() end end end if self.pos == 'close' and not (self.box and (self.box_anim or self.box_close)) then self.pos = 'over' end lg.pop() end -- show blinker function _navi:show_blinker() if ((lt.getTime()-self.t0)%arc.cfg.msg_tblink < 0.5*arc.cfg.msg_tblink) and self.blinker then lg.setColor(arc.col.white) lg.draw(arc.img.blinker, 285,30) end end -- will choices fit in same screen as last line? function _navi:chc_fits() return (self.nl%self.nrows)+self.nvchs <= self.nrows end -- advance to next box function _navi:advance(i,bl) if i == #self.b then self.pos = 'choice' self.t0 = lt.getTime() elseif i == bl then self.view = self.view+self.nrows end self.t0 = self.t0 + (lt.getTime()-self.b[i].t0) end -- set up scrolling function _navi:set_scroll(i,bf,bl) self.pos = 'scroll' self.scpos = (i==#self.b and 'choice') or 'show' self.scbf = bf self.scbl = bl self.sci = i self.sct0 = lt.getTime() end -- plays a list of messages sequentially function _navi.play_list(m,x,y) for i = 1,#m do if m[i].pos ~= 'over' then if m[i].pos == 'made' then m[i]:init() end m[i]:play(x,y) break end end end -- if width 'w' is specified, this adds newlines '|n' at the -- right places so that no line is greater than the specified width. function _navi.add_nls(s,w,opt) s = s .. ' ' local ss = '' local si,sj,t local bi,bj,i,j = 1,1,1,1 local t = {['|c']=10, ['|,']=2, ['|:']=2, ['|!']=2} b = str.unformat(s) -- i is current position in string -- j is current position minus formatting options for i = 1,s:len() do if s:sub(i,i) == ' ' or s:sub(i,i+1) == '|n' then if si and sj and arc.fn.w(b:sub(bj,j-1)) > w then -- there must be at least one ' ' before this ss = ss .. s:sub(bi,si-1) .. '|n' bi = si+1 bj = sj+1 end si = i -- pos of the last blank space in s sj = j -- pos of the last blank space in s minus formatting options end -- handle when there's already a newline if s:sub(i,i+1) == '|n' then ss = ss .. s:sub(bi,i+1) j = j-2 si = i+1 sj = j bi = si+1 bj = sj+1 end z = s:sub(i,i+1) -- subtract # chars in formatting options if not (t[z] == nil) then j = j-t[z] end j = j+1 end ss = ss .. s:sub(bi,s:len()) s = ss:sub(1,ss:len()-1) -- we added a ' ' at the beginning so remove it return s end -- replace the '|m' with '|n's to start new message box function _navi.add_nms(s,nrows) local n,nl,ns,ni nl = '|n' n = str.get_nmatch(s,nl) ni = nrows-n%nrows ns = #s if not (ni==nrows and ns>2 and s:sub(ns-1,ns) == '|n') then s = s .. nl:rep(ni) end return s end -- remove the '|!' if it's the last thing in the message function _navi.rem_kp(s) local sl = s:len() if s:sub(sl-1,sl) == '|!' then s = s:sub(1,sl-2) end return s end -- replace shortcuts for color changes function _navi.repl_col(s) local a,b,c,d,e while true do a,b,c,d = s:find('(|c{(%a+)})') if a == nil then break else d = arc.col[d] d = (#d==4 and d) or {d[1],d[2],d[3],255} s = s:gsub(c, string.format('|c%2x%2x%2x%2x',unpack(d))) end end return s end return _navi
gpl-2.0
gwash/ion-3
etc/cfg_statusbar.lua
3
2978
-- -- Ion statusbar module configuration file -- -- Create a statusbar mod_statusbar.create{ -- First screen, bottom left corner screen=0, pos='bl', -- Set this to true if you want a full-width statusbar fullsize=false, -- Swallow systray windows systray=true, -- Template. Tokens %string are replaced with the value of the -- corresponding meter. Currently supported meters are: -- date date -- load load average (1min, 5min, 15min) -- load_Nmin N minute load average (N=1, 5, 15) -- mail_new mail count (mbox format file $MAIL) -- mail_unread mail count -- mail_total mail count -- mail_*_new mail count (from an alternate mail folder, see below) -- mail_*_unread mail count -- mail_*_total mail count -- -- Space preceded by % adds stretchable space for alignment of variable -- meter value widths. > before meter name aligns right using this -- stretchable space , < left, and | centers. -- Meter values may be zero-padded to a width preceding the meter name. -- These alignment and padding specifiers and the meter name may be -- enclosed in braces {}. -- -- %filler causes things on the marker's sides to be aligned left and -- right, respectively, and %systray is a placeholder for system tray -- windows and icons. -- template="[ %date || load: %load ] %filler%systray", --template="[ %date || load:% %>load || mail:% %>mail_new/%>mail_total ] %filler%systray", --template="[ %date || load: %05load_1min || mail: %02mail_new/%02mail_total ] %filler%systray", } -- Launch ion-statusd. This must be done after creating any statusbars -- for necessary statusd modules to be parsed from the templates. mod_statusbar.launch_statusd{ -- Date meter date={ -- ISO-8601 date format with additional abbreviated day name date_format='%a %Y-%m-%d %H:%M', -- Finnish etc. date format --date_format='%a %d.%m.%Y %H:%M', -- Locale date format (usually shows seconds, which would require -- updating rather often and can be distracting) --date_format='%c', -- Additional date formats. --[[ formats={ time = '%H:%M', -- %date_time } --]] }, -- Load meter load={ --update_interval=10*1000, --important_threshold=1.5, --critical_threshold=4.0, }, -- Mail meter -- -- To monitor more mbox files, add them to the files table. For -- example, add mail_work_new and mail_junk_new to the template -- above, and define them in the files table: -- -- files = { work = "/path/to/work_email", junk = "/path/to/junk" } -- -- Don't use the keyword 'spool' as it's reserved for mbox. mail={ --update_interval=60*1000, --mbox=os.getenv("MAIL"), --files={}, }, }
lgpl-2.1
Facerafter/starcitizen-tools
extensions/Scribunto/engines/LuaCommon/lualib/mw.site.lua
6
2264
local site = {} function site.setupInterface( info ) -- Boilerplate site.setupInterface = nil local php = mw_interface mw_interface = nil site.siteName = info.siteName site.server = info.server site.scriptPath = info.scriptPath site.stylePath = info.stylePath site.currentVersion = info.currentVersion site.stats = info.stats site.stats.pagesInCategory = php.pagesInCategory site.stats.pagesInNamespace = php.pagesInNamespace site.stats.usersInGroup = php.usersInGroup site.interwikiMap = php.interwikiMap -- Process namespace list into more useful tables site.namespaces = {} local namespacesByName = {} site.subjectNamespaces = {} site.talkNamespaces = {} site.contentNamespaces = {} for ns, data in pairs( info.namespaces ) do data.subject = info.namespaces[data.subject] data.talk = info.namespaces[data.talk] data.associated = info.namespaces[data.associated] site.namespaces[ns] = data namespacesByName[data.name] = data if data.canonicalName then namespacesByName[data.canonicalName] = data end for i = 1, #data.aliases do namespacesByName[data.aliases[i]] = data end if data.isSubject then site.subjectNamespaces[ns] = data end if data.isTalk then site.talkNamespaces[ns] = data end if data.isContent then site.contentNamespaces[ns] = data end end -- Set __index for namespacesByName to handle names-with-underscores -- and non-standard case local getNsIndex = php.getNsIndex setmetatable( namespacesByName, { __index = function ( t, k ) if type( k ) == 'string' then -- Try with fixed underscores k = string.gsub( k, '_', ' ' ) if rawget( t, k ) then return rawget( t, k ) end -- Ask PHP, because names are case-insensitive local ns = getNsIndex( k ) if ns then rawset( t, k, site.namespaces[ns] ) end end return rawget( t, k ) end } ) -- Set namespacesByName as the lookup table for site.namespaces, so -- something like site.namespaces.Wikipedia works without having -- pairs( site.namespaces ) iterate all those names. setmetatable( site.namespaces, { __index = namespacesByName } ) -- Register this library in the "mw" global mw = mw or {} mw.site = site package.loaded['mw.site'] = site end return site
gpl-3.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/talents/cunning/survival.lua
1
4381
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org newTalent{ name = "Heightened Senses", type = {"cunning/survival", 1}, require = cuns_req1, mode = "passive", points = 5, sense = function(self, t) return math.floor(self:combatTalentScale(t, 5, 9)) end, trapPower = function(self, t) return self:combatScale(self:getTalentLevel(t) * self:getCun(25, true), 0, 0, 125, 125) end, passives = function(self, t, p) self:talentTemporaryValue(p, "heightened_senses", t.sense(self, t)) end, info = function(self, t) return ([[You notice the small things others do not notice, allowing you to "see" creatures in a %d radius even outside of light radius. This is not telepathy, however, and it is still limited to line of sight. Also, your attention to detail allows you to detect traps around you (%d detection 'power'). At level 3, you learn to disarm known traps (%d disarm 'power'). The trap detection and disarming ability improves with your Cunning.]]): format(t.sense(self,t),t.trapPower(self,t),t.trapPower(self,t)) end, } newTalent{ name = "Charm Mastery", type = {"cunning/survival", 2}, require = cuns_req2, mode = "passive", points = 5, cdReduc = function(tl) if tl <=0 then return 0 end return math.floor(100*tl/(tl+7.5)) -- Limit < 100% end, passives = function(self, t, p) self:talentTemporaryValue(p, "use_object_cooldown_reduce", t.cdReduc(self:getTalentLevel(t))) end, -- on_unlearn = function(self, t) -- end, info = function(self, t) return ([[Your cunning manipulations allow you to use charms (wands, totems and torques) more efficiently, reducing their cooldowns by %d%%.]]): format(t.cdReduc(self:getTalentLevel(t))) end, } newTalent{ name = "Piercing Sight", type = {"cunning/survival", 3}, require = cuns_req3, mode = "passive", points = 5, -- called by functions _M:combatSeeStealth and _M:combatSeeInvisible functions mod\class\interface\Combat.lua seePower = function(self, t) return self:combatScale(self:getCun(15, true)*self:getTalentLevel(t), 5, 0, 80, 75) end, --I5 info = function(self, t) return ([[You look at your surroundings with more intensity than most people, allowing you to see stealthed or invisible creatures. Increases stealth detection by %d and invisibility detection by %d. The detection power increases with your Cunning.]]): format(t.seePower(self,t), t.seePower(self,t)) end, } newTalent{ name = "Evasion", type = {"cunning/survival", 4}, points = 5, require = cuns_req4, random_ego = "defensive", tactical = { ESCAPE = 2, DEFEND = 2 }, cooldown = 30, getDur = function(self) return math.floor(self:combatStatLimit("wil", 30, 6, 15)) end, -- Limit < 30 getChanceDef = function(self, t) if self.perfect_evasion then return 100, 0 end return self:combatLimit(5*self:getTalentLevel(t) + self:getCun(25,true) + self:getDex(25,true), 50, 10, 10, 37.5, 75), self:combatScale(self:getTalentLevel(t) * (self:getCun(25, true) + self:getDex(25, true)), 0, 0, 55, 250, 0.75) -- Limit evasion chance < 50%, defense bonus ~= 55 at level 50 end, speed = "combat", action = function(self, t) local dur = t.getDur(self) local chance, def = t.getChanceDef(self,t) self:setEffect(self.EFF_EVASION, dur, {chance=chance, defense = def}) return true end, info = function(self, t) local chance, def = t.getChanceDef(self,t) return ([[Your quick wit allows you to see attacks before they land, granting you a %d%% chance to completely evade them and granting you %d defense for %d turns. Duration increases with Willpower, and chance to evade and defense with Cunning and Dexterity.]]): format(chance, def,t.getDur(self)) end, }
gpl-3.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/general/traps/annoy.lua
1
2184
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org newEntity{ define_as = "TRAP_ANNOY", type = "annoy", subtype="annoy", id_by_type=true, unided_name = "trap", display = '^', triggered = function() end, } newEntity{ base = "TRAP_ANNOY", name = "lethargy trap", auto_id = true, image = "trap/trap_lethargy_rune_01.png", detect_power = resolvers.clscale(20,50,8), disarm_power = resolvers.clscale(36,50,8), rarity = 3, level_range = {1, 50}, color=colors.BLUE, message = "@Target@ seems less active.", triggered = function(self, x, y, who) local tids = {} for tid, lev in pairs(who.talents) do local t = who:getTalentFromId(tid) if not who.talents_cd[tid] and t.mode == "activated" then tids[#tids+1] = tid end end for i = 1, 3 do local tid = rng.tableRemove(tids) if not tid then break end who.talents_cd[tid] = rng.range(4, 7) end who.changed = true return true, true end } newEntity{ base = "TRAP_ANNOY", name = "burning curse trap", auto_id = true, image = "trap/trap_burning_curse_01.png", detect_power = resolvers.clscale(50,50,8), disarm_power = resolvers.clscale(58,50,8), rarity = 3, level_range = {30, 50}, color=colors.ORCHID, message = "@Target@ triggers a burning curse!", dam = resolvers.clscale(60, 50, 15, 0.75, 25), pressure_trap = true, triggered = function(self, x, y, who) who:setEffect(who.EFF_BURNING_HEX, 7, {src=self, dam=self.dam, power=1+(self.dam/100)}) return true, true end }
gpl-3.0
khavnu/VLCLIB
share/lua/playlist/pluzz.lua
105
3740
--[[ $Id$ Copyright © 2011 VideoLAN Authors: Ludovic Fauvet <etix at l0cal dot com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "pluzz.fr/%w+" ) or string.match( vlc.path, "info.francetelevisions.fr/.+") or string.match( vlc.path, "france4.fr/%w+") end -- Helpers function key_match( line, key ) return string.match( line, "name=\"" .. key .. "\"" ) end function get_value( line ) local _,_,r = string.find( line, "content=\"(.*)\"" ) return r end -- Parse function. function parse() p = {} if string.match ( vlc.path, "www.pluzz.fr/%w+" ) then while true do line = vlc.readline() if not line then break end if string.match( line, "id=\"current_video\"" ) then _,_,redirect = string.find (line, "href=\"(.-)\"" ) print ("redirecting to: " .. redirect ) return { { path = redirect } } end end end if string.match ( vlc.path, "www.france4.fr/%w+" ) then while true do line = vlc.readline() if not line then break end -- maybe we should get id from tags having video/cappuccino type instead if string.match( line, "id=\"lavideo\"" ) then _,_,redirect = string.find (line, "href=\"(.-)\"" ) print ("redirecting to: " .. redirect ) return { { path = redirect } } end end end if string.match ( vlc.path, "info.francetelevisions.fr/.+" ) then title = "" arturl = "http://info.francetelevisions.fr/video-info/player_sl/Images/PNG/gene_ftv.png" while true do line = vlc.readline() if not line then break end -- Try to find the video's path if key_match( line, "urls--url--video" ) then video = get_value( line ) end -- Try to find the video's title if key_match( line, "vignette--titre--court" ) then title = get_value( line ) title = vlc.strings.resolve_xml_special_chars( title ) print ("playing: " .. title ) end -- Try to find the video's thumbnail if key_match( line, "vignette" ) then arturl = get_value( line ) if not string.match( line, "http://" ) then arturl = "http://info.francetelevisions.fr/" .. arturl end end end if video then -- base url is hardcoded inside a js source file -- see http://www.pluzz.fr/layoutftv/arches/common/javascripts/jquery.player-min.js base_url = "mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/" table.insert( p, { path = base_url .. video; name = title; arturl = arturl; } ) end end return p end
gpl-2.0
3scale/apicast
gateway/src/apicast/oauth/oidc.lua
2
6503
local JWT = require 'resty.jwt' local jwt_validators = require 'resty.jwt-validators' local lrucache = require 'resty.lrucache' local util = require 'apicast.util' local TemplateString = require 'apicast.template_string' local setmetatable = setmetatable local ngx_now = ngx.now local format = string.format local type = type local tostring = tostring local assert = assert local _M = { cache_size = 10000, } local default_claim_with_app_id = "azp" function _M.reset() _M.cache = lrucache.new(_M.cache_size) end _M.reset() local mt = { __index = _M, __tostring = function() return 'OpenID Connect' end } local empty = {} function _M.new(oidc_config) local oidc = oidc_config or empty local issuer = oidc.issuer local config = oidc.config or empty local alg_values = config.id_token_signing_alg_values_supported or empty local client_id_tmpl, client_id_tmpl_err, client_id_tmpl_type local err if oidc.claim_with_client_id then client_id_tmpl_type = oidc.claim_with_client_id_type client_id_tmpl, client_id_tmpl_err = TemplateString.new(oidc.claim_with_client_id, client_id_tmpl_type) if client_id_tmpl_err then err = 'Invalid client_id template string' end end if not issuer or #alg_values == 0 then err = 'missing OIDC configuration' end return setmetatable({ config = config, issuer = issuer, client_id_tmpl = client_id_tmpl, client_id_tmpl_type = client_id_tmpl_type, keys = oidc.keys or empty, clock = ngx_now, alg_whitelist = util.to_hash(alg_values), -- https://tools.ietf.org/html/rfc7523#section-3 jwt_claims = { -- 1. The JWT MUST contain an "iss" (issuer) claim that contains a -- unique identifier for the entity that issued the JWT. iss = jwt_validators.chain(jwt_validators.required(), issuer and jwt_validators.equals_any_of({ issuer })), -- 2. The JWT MUST contain a "sub" (subject) claim identifying the -- principal that is the subject of the JWT. sub = jwt_validators.required(), -- 3. The JWT MUST contain an "aud" (audience) claim containing a -- value that identifies the authorization server as an intended -- audience. aud = jwt_validators.required(), -- 4. The JWT MUST contain an "exp" (expiration time) claim that -- limits the time window during which the JWT can be used. exp = jwt_validators.is_not_expired(), -- 5. The JWT MAY contain an "nbf" (not before) claim that identifies -- the time before which the token MUST NOT be accepted for -- processing. nbf = jwt_validators.opt_is_not_before(), -- 6. The JWT MAY contain an "iat" (issued at) claim that identifies -- the time at which the JWT was issued. iat = jwt_validators.opt_greater_than(0), -- This is keycloak-specific. Its tokens have a 'typ' and we need to verify typ = jwt_validators.opt_equals_any_of({ 'Bearer' }), }, }, mt), err end local function timestamp_to_seconds_from_now(expiry, clock) local time_now = (clock or ngx_now)() local ttl = expiry and (expiry - time_now) or nil return ttl end local function find_public_key(jwt, keys) local jwk = keys and keys[jwt.header.kid] if jwk then return jwk.pem end end -- Parses the token - in this case we assume it's a JWT token -- Here we can extract authenticated user's claims or other information returned in the access_token -- or id_token by RH SSO local function parse_and_verify_token(self, namespace, jwt_token) local cache = self.cache if not cache then return nil, 'not initialized' end local cache_key = format('%s:%s', namespace or '<empty>', jwt_token) local jwt = self:parse(jwt_token, cache_key) if jwt.verified then return jwt end local _, err = self:verify(jwt, cache_key) return jwt, err end function _M:parse_and_verify(access_token, cache_key) local jwt_obj, err = parse_and_verify_token(self, assert(cache_key, 'missing cache key'), access_token) if err then if ngx.config.debug then ngx.log(ngx.DEBUG, 'JWT object: ', require('inspect')(jwt_obj), ' err: ', err, ' reason: ', jwt_obj.reason) end return nil, jwt_obj and jwt_obj.reason or err end return jwt_obj end local jwt_mt = { __tostring = function(jwt) return jwt.token end } local function load_jwt(token) local jwt = JWT:load_jwt(tostring(token)) jwt.token = token return setmetatable(jwt, jwt_mt) end function _M:parse(jwt, cache_key) local cached = cache_key and self.cache:get(cache_key) if cached then ngx.log(ngx.DEBUG, 'found JWT in cache for ', cache_key) return cached end return load_jwt(jwt) end function _M:verify(jwt, cache_key) if not jwt then return false, 'JWT missing' end if not jwt.valid then ngx.log(ngx.WARN, jwt.reason) return false, 'JWT not valid' end if not self.alg_whitelist[jwt.header.alg] then return false, '[jwt] invalid alg' end -- TODO: this should be able to use DER format instead of PEM local pubkey = find_public_key(jwt, self.keys) jwt = JWT:verify_jwt_obj(pubkey, jwt, self.jwt_claims) if not jwt.verified then ngx.log(ngx.DEBUG, "[jwt] failed verification for token, reason: ", jwt.reason) return false, "JWT not verified" end if cache_key then ngx.log(ngx.DEBUG, 'adding JWT to cache ', cache_key) local ttl = timestamp_to_seconds_from_now(jwt.payload.exp, self.clock) -- use the JWT itself in case there is no cache key self.cache:set(cache_key, jwt, ttl) end return true end function _M:transform_credentials(credentials, cache_key) local jwt_obj, err = self:parse_and_verify(credentials.access_token, cache_key or '<shared>') if err then return nil, nil, nil, err end local payload = jwt_obj.payload local app_id = self:get_client_id(payload) local ttl = timestamp_to_seconds_from_now(payload.exp) if type(app_id) == 'table' then app_id = app_id[1] end ------ -- OAuth2 credentials for OIDC -- @field app_id Client id -- @table credentials_oauth return { app_id = app_id }, ttl, payload end function _M:get_client_id(jwt_payload) if self.client_id_tmpl and self.client_id_tmpl_type == "liquid" then return self.client_id_tmpl:render(jwt_payload) end if self.client_id_tmpl and self.client_id_tmpl_type == "plain" then return jwt_payload[self.client_id_tmpl:render()] end return jwt_payload[default_claim_with_app_id] end return _M
apache-2.0
hexahedronic/basewars
basewars_free/entities/entities/bw_base_moneyprinter.lua
2
9219
--easylua.StartEntity("bw_base_moneyprinter") local fontName = "BaseWars.MoneyPrinter" ENT.Base = "bw_base_electronics" ENT.Model = "models/props_lab/reciever01a.mdl" ENT.Skin = 0 ENT.Capacity = 10000 ENT.Money = 0 ENT.MaxPaper = 2500 ENT.PrintInterval = 1.1 ENT.PrintAmount = 3 ENT.MaxLevel = 10 ENT.UpgradeCost = 1000 ENT.PrintName = "Basic Printer" ENT.IsPrinter = true ENT.IsValidRaidable = false local Clamp = math.Clamp function ENT:GSAT(slot, name, min, max) self:NetworkVar("Int", slot, name) local getVar = function(minMax) if self[minMax] and isfunction(self[minMax]) then return self[minMax](self) end if self[minMax] and isnumber(self[minMax]) then return self[minMax] end return minMax or 0 end self["Add" .. name] = function(_, var) local Val = self["Get" .. name](self) + var if min and max then Val = Clamp(tonumber(Val) or 0, getVar(min), getVar(max)) end self["Set" .. name](self, Val) end self["Take" .. name] = function(_, var) local Val = self["Get" .. name](self) - var if min and max then Val = Clamp(tonumber(Val) or 0, getVar(min), getVar(max)) end self["Set" .. name](self, Val) end end function ENT:StableNetwork() self:GSAT(2, "Capacity") self:GSAT(3, "Money", 0, "GetCapacity") self:GSAT(4, "Paper", 0, "MaxPaper") self:GSAT(5, "Level", 0, "MaxLevel") end if SERVER then AddCSLuaFile() function ENT:Init() self.time = CurTime() self.time_p = CurTime() self:SetCapacity(self.Capacity) self:SetPaper(self.MaxPaper) self:SetHealth(self.PresetMaxHealth or 100) self.rtb = 0 self.FontColor = color_white self.BackColor = color_black self:SetNWInt("UpgradeCost", self.UpgradeCost) self:SetLevel(1) end function ENT:SetUpgradeCost(val) self.UpgradeCost = val self:SetNWInt("UpgradeCost", val) end function ENT:Upgrade(ply) if ply then local lvl = self:GetLevel() local plyM = ply:GetMoney() local calcM = self:GetNWInt("UpgradeCost") * lvl if plyM < calcM then ply:Notify(BaseWars.LANG.UpgradeNoMoney, BASEWARS_NOTIFICATION_ERROR) return end if lvl >= self.MaxLevel then ply:Notify(BaseWars.LANG.UpgradeMaxLevel, BASEWARS_NOTIFICATION_ERROR) return end ply:TakeMoney(calcM) self.CurrentValue = (self.CurrentValue or 0) + calcM end self:AddLevel(1) self:EmitSound("replay/rendercomplete.wav") end function ENT:ThinkFunc() if self.Disabled or self:BadlyDamaged() then return end local added local level = self:GetLevel() ^ 1.3 if CurTime() >= self.PrintInterval + self.time and self:GetPaper() > 0 then local m = self:GetMoney() self:AddMoney(math.Round(self.PrintAmount * level)) self.time = CurTime() added = m ~= self:GetMoney() end if CurTime() >= self.PrintInterval * 2 + self.time_p and added then self.time_p = CurTime() self:TakePaper(1) end end function ENT:PlayerTakeMoney(ply) local money = self:GetMoney() local Res, Msg = hook.Run("BaseWars_PlayerCanEmptyPrinter", ply, self, money) if Res == false then if Msg then ply:Notify(Msg, BASEWARS_NOTIFICATION_ERROR) end return end self:TakeMoney(money) ply:GiveMoney(money) ply:EmitSound("mvm/mvm_money_pickup.wav") hook.Run("BaseWars_PlayerEmptyPrinter", ply, self, money) end function ENT:UseFuncBypass(activator, caller, usetype, value) if self.Disabled then return end if activator:IsPlayer() and caller:IsPlayer() and self:GetMoney() > 0 then self:PlayerTakeMoney(activator) end end function ENT:SetDisabled(a) self.Disabled = a and true or false self:SetNWBool("printer_disabled", a and true or false) end else function ENT:Initialize() if not self.FontColor then self.FontColor = color_white end if not self.BackColor then self.BackColor = color_black end end surface.CreateFont(fontName, { font = "Roboto", size = 20, weight = 800, }) surface.CreateFont(fontName .. ".Huge", { font = "Roboto", size = 64, weight = 800, }) surface.CreateFont(fontName .. ".Big", { font = "Roboto", size = 32, weight = 800, }) surface.CreateFont(fontName .. ".MedBig", { font = "Roboto", size = 24, weight = 800, }) surface.CreateFont(fontName .. ".Med", { font = "Roboto", size = 18, weight = 800, }) local WasPowered if CLIENT then function ENT:DrawDisplay(pos, ang, scale) local w, h = 216 * 2, 136 * 2 local disabled = self:GetNWBool("printer_disabled") local Pw = self:IsPowered() local Lv = self:GetLevel() local Cp = self:GetCapacity() draw.RoundedBox(4, 0, 0, w, h, Pw and self.BackColor or color_black) if not Pw then return end if disabled then draw.DrawText("This printer has been", fontName, w / 2, h / 2 - 48, self.FontColor, TEXT_ALIGN_CENTER) draw.DrawText("DISABLED", fontName .. ".Huge", w / 2, h / 2 - 32, Color(255,0,0), TEXT_ALIGN_CENTER) return end draw.DrawText(self.PrintName, fontName, w / 2, 4, self.FontColor, TEXT_ALIGN_CENTER) if disabled then return end --Level surface.SetDrawColor(self.FontColor) surface.DrawLine(0, 30, w, 30)--draw.RoundedBox(0, 0, 30, w, 1, self.FontColor) draw.DrawText("LEVEL: " .. Lv, fontName .. ".Big", 4, 32, self.FontColor, TEXT_ALIGN_LEFT) surface.DrawLine(0, 68, w, 68)--draw.RoundedBox(0, 0, 68, w, 1, self.FontColor) draw.DrawText("CASH", fontName .. ".Big", 4, 72, self.FontColor, TEXT_ALIGN_LEFT) -- draw.RoundedBox(0, 0, 72 + 32, w, 1, self.FontColor) local money = tonumber(self:GetMoney()) or 0 local cap = tonumber(Cp) or 0 local moneyPercentage = math.Round( money / cap * 100 ,1) --Percentage done draw.DrawText( moneyPercentage .."%" , fontName .. ".Big", w - 4, 71, self.FontColor, TEXT_ALIGN_RIGHT) --Money/Maxmoney local currentMoney = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(money) local maxMoney = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(cap) local font = fontName .. ".Big" if #currentMoney > 16 then font = fontName .. ".MedBig" end if #currentMoney > 20 then font = fontName .. ".Med" end local fh = draw.GetFontHeight(font) local StrW,StrH = surface.GetTextSize(" / ") draw.DrawText(" / " , font, w/2 - StrW/2 , (font == fontName .. ".Big" and 106 or 105 + fh / 4), self.FontColor, TEXT_ALIGN_LEFT) local moneyW,moneyH = surface.GetTextSize(currentMoney) draw.DrawText(currentMoney , font, w/2 - StrW/2 - moneyW , (font == fontName .. ".Big" and 106 or 105 + fh / 4), self.FontColor, TEXT_ALIGN_LEFT) draw.DrawText( maxMoney, font, w/2 + StrW/2 , (font == fontName .. ".Big" and 106 or 105 + fh / 4), self.FontColor, TEXT_ALIGN_Right) --Paper local paper = math.floor(self:GetPaper()) draw.DrawText("Paper: " .. paper .. " sheets", fontName .. ".MedBig", 4, 94 + 49, self.FontColor, TEXT_ALIGN_LEFT) --draw.RoundedBox(0, 0, 102 + 37, w, 1, self.FontColor) surface.DrawLine(0, 102 + 37, w, 102 + 37) local NextCost = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(self:GetLevel() * self:GetNWInt("UpgradeCost")) if self:GetLevel() >= self.MaxLevel then NextCost = "!Max Level!" end surface.DrawLine(0, 142 + 25, w, 142 + 25)--draw.RoundedBox(0, 0, 142 + 25, w, 1, self.FontColor) draw.DrawText("NEXT UPGRADE: " .. NextCost, fontName .. ".MedBig", 4, 84 + 78 + 10, self.FontColor, TEXT_ALIGN_LEFT) surface.DrawLine(0, 142 + 25, w, 142 + 25)--draw.RoundedBox(0, 0, 142 + 55, w, 1, self.FontColor) --Time remaining counter local timeRemaining = 0 timeRemaining = math.Round( (cap - money) / (self.PrintAmount * Lv / self.PrintInterval) ) if timeRemaining > 0 then local PrettyHours = math.floor(timeRemaining/3600) local PrettyMinutes = math.floor(timeRemaining/60) - PrettyHours*60 local PrettySeconds = timeRemaining - PrettyMinutes*60 - PrettyHours*3600 local PrettyTime = (PrettyHours > 0 and PrettyHours.."h" or "") .. (PrettyMinutes > 0 and PrettyMinutes.."m" or "") .. PrettySeconds .."s" draw.DrawText(PrettyTime .. " until full", fontName .. ".Big", w-4 , 32, self.FontColor, TEXT_ALIGN_RIGHT) else draw.DrawText("Full", fontName .. ".Big", w-4 , 32, self.FontColor, TEXT_ALIGN_RIGHT) end --Money bar BG local BoxX = 88 local BoxW = 265 draw.RoundedBox(0, BoxX, 74, BoxW , 24, self.FontColor) --Money bar gap if cap > 0 and cap ~= math.huge then local moneyRatio = money / cap local maxWidth = math.floor(BoxW - 6) local curWidth = maxWidth * (1-moneyRatio) draw.RoundedBox(0, w - BoxX - curWidth + 6 , 76, curWidth , 24 - 4, self.BackColor) end end function ENT:Calc3D2DParams() local pos = self:GetPos() local ang = self:GetAngles() pos = pos + ang:Up() * 3.09 pos = pos + ang:Forward() * -7.35 pos = pos + ang:Right() * 10.82 ang:RotateAroundAxis(ang:Up(), 90) return pos, ang, 0.1 / 2 end end function ENT:Draw() self:DrawModel() if CLIENT then local pos, ang, scale = self:Calc3D2DParams() cam.Start3D2D(pos, ang, scale) pcall(self.DrawDisplay, self, pos, ang, scale) cam.End3D2D() end end end --easylua.EndEntity()
mit
3scale/apicast
benchmark/ips.lua
2
8544
local function to_i(str) return tonumber(str:gsub('[^%d]', ''), 10) end local NANOSECONDS_PER_SECOND = to_i('1 000 000 000') local NANOSECONDS_PER_100MS = to_i('100 000 000') local Timing = { } local ffi = require 'ffi' local tab_new = require "table.new" ffi.cdef [[ typedef int clockid_t; typedef long time_t; struct timespec { time_t tv_sec; long tv_nsec; }; int clock_gettime(clockid_t clk_id, struct timespec *tp); char *strerror(int errnum); ]] local C = ffi.C local CLOCK = { REALTIME = 0, MONOTONIC = 1, PROCESS_CPUTIME_ID = 2, THREAD_CPUTIME_ID = 3, MONOTONIC_RAW = 4, REALTIME_COARSE = 5, MONOTONIC_COARSE = 6, } local ts = ffi.new("struct timespec[1]") local function ffi_error() return C.strerror(ffi.errno()) end -- Get an object that represents now in nanoseconds function Timing.now() if C.clock_gettime(CLOCK.MONOTONIC_RAW, ts) ~= 0 then return nil, ffi_error() end return tonumber(ts[0].tv_sec * 1e9 + ts[0].tv_nsec) end -- Recycle used objects by starting Garbage Collector. function Timing.clean_env() collectgarbage('collect') end -- Return the number of microseconds between the 2 moments function Timing.time_ns(before, after) return after - before end -- Add number of seconds second to the time represenetation function Timing.add_second(t, s) return t + (s * NANOSECONDS_PER_SECOND) end local Report = {} local ReportEntry = {} local Entry = {} local Stats = {} local function _just(str, width, char) local delta = width - #str if delta > 0 then return (char or ' '):rep(delta) else return '' end end local function rjust(str, width, char) return _just(str, width, char) .. str end local function ljust(str, width, char) return str .. _just(str, width, char) end -- Add padding to label's right if label's length < 20, Otherwise add a new line and 20 whitespaces. local function rjust_label(label) local delta = 20 - #label if delta > 0 then return rjust(label, 20) else return label .. "\n" .. rjust('', 20) end end local IPS = { time = 5, warmup = 2, iterations = 1, hooks = { start_warming = { function() print('Warming up --------------------------------------') end, }, warming = { function(label) print(rjust_label(label)) end, }, warmup_stats = { function(_, timing) print(("%10d i/100ms\n"):format(timing)) end, }, start_running = { function() print('Calculating -------------------------------------') end, }, running = {}, report_entry = { function(report) print(" ", report:body()) end, }, done = {}, }, } local IPS_mt = { __index = IPS, __newindex = function(_, k) error("unknown property: " .. k) end, } function IPS:call(f) local ips = self:new() f(ips) ips:run() return end function IPS:new() local m = { time = self.time, warmup = self.warmup, iterations = self.iterations, full_report = Report:new(), items = {}, timing = {}, hooks = self.hooks, } return setmetatable(m, IPS_mt) end function IPS:notify(name, ...) for _, fun in ipairs(self.hooks[name]) do fun(...) end end function IPS:report(label, fun) table.insert(self.items, Entry:new(label, fun)) end function IPS:compare() if #self.items < 1 then error("no items to test") end end local floor = math.floor -- Calculate the cycles needed to run for approx 100ms, -- given the number of iterations to run the given time. -- @tparam Float time_nsec Each iteration's time in ns. -- @tparam Integer iters Iterations. -- @treturn Integer Cycles per 100ms. local function cycles_per_100ms(time_nsec, iters) local cycles = floor((NANOSECONDS_PER_100MS / time_nsec) * iters) if cycles <= 0 then return 1 else return cycles end end -- Calculate the interations per second given the number -- of cycles run and the time in microseconds that elapsed. -- @tparam Integer cycles Cycles. -- @tparam Integer time_ns Time in microsecond. -- @treturn Float Iteration per second. local function iterations_per_sec(cycles, time_ns) return NANOSECONDS_PER_SECOND * (cycles / time_ns) end function IPS:run_warmup() for _,item in ipairs(self.items) do self:notify('warming', item.label, self.warmup) Timing:clean_env() local before = Timing.now() local target = Timing.add_second(before, self.warmup) local warmup_iter = 0 while Timing.now() < target do item:call_times(1) warmup_iter = warmup_iter + 1 end local after = Timing.now() local warmup_time_ns = Timing.time_ns(before, after) self.timing[item] = cycles_per_100ms(warmup_time_ns, warmup_iter) self:notify('warmup_stats', warmup_time_ns, self.timing[item]) end end local insert = table.insert local sum = function(t) local total = 0 for _, n in ipairs(t) do total = total + n end return total end local function stats_samples(measurements_ns, cycles) local samples = tab_new(#measurements_ns, 0) for i, time_ns in ipairs(measurements_ns) do samples[i] = iterations_per_sec(cycles, time_ns) end return samples end function IPS:run_benchmark() for _,item in ipairs(self.items) do self:notify('running', item.label, self.time) Timing:clean_env() local iter = 0 local measurements_ns = {} -- Running this number of cycles should take around 100ms. local cycles = self.timing[item] local after local before = Timing.now() local target = Timing.add_second(before, self.time) while before < target do item:call_times(cycles) after = Timing.now() -- If for some reason the timing said this took no time (O_o) -- then error out. local iter_ns = Timing.time_ns(before, after) if iter_ns <= 0 then error('impossible happened') end before = after iter = iter + cycles insert(measurements_ns, iter_ns) end local measured_ns = sum(measurements_ns) local samples = stats_samples(measurements_ns, cycles) local rep = self.full_report:add_entry(item.label, measured_ns, iter, Stats:new(samples), cycles) self:notify('report_entry', rep) end end function IPS:run() if self.warmup and self.warmup > 0 then for _=1, self.iterations do self:notify('start_warming') self:run_warmup() end end self:notify('start_running') for _=1, self.iterations do self:run_benchmark() end self:notify('done') end function Entry:new(label, action) local entry = { label = label, action = action } return setmetatable(entry, { __index = self }) end function Entry:call_times(n) local action = self.action for _=1, n do action() end end function Report:new() return setmetatable({ entries = {}, }, { __index = self }) end function Report:add_entry(label, nanoseconds, iters, stats, measurement_cycle) local entry = ReportEntry:new(label, nanoseconds, iters, stats, measurement_cycle) table.insert(self.entries, entry) return entry end function Report.body(_) end function ReportEntry:new(label, nanoseconds, iterations, stats, measurement_cycle) return setmetatable({ label = label, nanoseconds = nanoseconds, iterations = iterations, stats = stats, measurement_cycle = measurement_cycle, }, { __index = self }) end function ReportEntry:error_percentage() return 100.0 * (self.stats.error / self.stats.central_tendency) end function ReportEntry:body() local left = ("%10.1f (±%.1f%%) i/s"):format(self.stats.central_tendency, self:error_percentage()) return ljust(left, 20) .. (" - %10d in %10.6fs"):format(self.iterations, self:runtime()) end function ReportEntry:runtime() return self.nanoseconds / NANOSECONDS_PER_SECOND end local function stat_mean(samples) local total = sum(samples) return total / #samples end local function stat_variance(samples, m) local mean = m or stat_mean(samples) local total = 0 for _,n in ipairs(samples) do total = total + math.pow(n - mean, 2) end return total / #samples end local function stat_stddev(samples, m) return math.sqrt(stat_variance(samples, m)) end function Stats:new(samples) local mean = stat_mean(samples) local error = stat_stddev(samples, mean) return setmetatable({ central_tendency = mean, error = error, }, { __index = self }) end return setmetatable(IPS, { __call = function(_, f) return IPS:call(f) end, __newindex = IPS_mt.__newindex, })
apache-2.0
protomech/epgp-dkp-reloaded
libs/AceEvent-3.0/AceEvent-3.0.lua
50
4772
--- AceEvent-3.0 provides event registration and secure dispatching. -- All dispatching is done using **CallbackHandler-1.0**. AceEvent is a simple wrapper around -- CallbackHandler, and dispatches all game events or addon message to the registrees. -- -- **AceEvent-3.0** can be embeded into your addon, either explicitly by calling AceEvent:Embed(MyAddon) or by -- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object -- and can be accessed directly, without having to explicitly call AceEvent itself.\\ -- It is recommended to embed AceEvent, otherwise you'll have to specify a custom `self` on all calls you -- make into AceEvent. -- @class file -- @name AceEvent-3.0 -- @release $Id: AceEvent-3.0.lua 975 2010-10-23 11:26:18Z nevcairiel $ local MAJOR, MINOR = "AceEvent-3.0", 3 local AceEvent = LibStub:NewLibrary(MAJOR, MINOR) if not AceEvent then return end -- Lua APIs local pairs = pairs local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0") AceEvent.frame = AceEvent.frame or CreateFrame("Frame", "AceEvent30Frame") -- our event frame AceEvent.embeds = AceEvent.embeds or {} -- what objects embed this lib -- APIs and registry for blizzard events, using CallbackHandler lib if not AceEvent.events then AceEvent.events = CallbackHandler:New(AceEvent, "RegisterEvent", "UnregisterEvent", "UnregisterAllEvents") end function AceEvent.events:OnUsed(target, eventname) AceEvent.frame:RegisterEvent(eventname) end function AceEvent.events:OnUnused(target, eventname) AceEvent.frame:UnregisterEvent(eventname) end -- APIs and registry for IPC messages, using CallbackHandler lib if not AceEvent.messages then AceEvent.messages = CallbackHandler:New(AceEvent, "RegisterMessage", "UnregisterMessage", "UnregisterAllMessages" ) AceEvent.SendMessage = AceEvent.messages.Fire end --- embedding and embed handling local mixins = { "RegisterEvent", "UnregisterEvent", "RegisterMessage", "UnregisterMessage", "SendMessage", "UnregisterAllEvents", "UnregisterAllMessages", } --- Register for a Blizzard Event. -- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied) -- Any arguments to the event will be passed on after that. -- @name AceEvent:RegisterEvent -- @class function -- @paramsig event[, callback [, arg]] -- @param event The event to register for -- @param callback The callback function to call when the event is triggered (funcref or method, defaults to a method with the event name) -- @param arg An optional argument to pass to the callback function --- Unregister an event. -- @name AceEvent:UnregisterEvent -- @class function -- @paramsig event -- @param event The event to unregister --- Register for a custom AceEvent-internal message. -- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied) -- Any arguments to the event will be passed on after that. -- @name AceEvent:RegisterMessage -- @class function -- @paramsig message[, callback [, arg]] -- @param message The message to register for -- @param callback The callback function to call when the message is triggered (funcref or method, defaults to a method with the event name) -- @param arg An optional argument to pass to the callback function --- Unregister a message -- @name AceEvent:UnregisterMessage -- @class function -- @paramsig message -- @param message The message to unregister --- Send a message over the AceEvent-3.0 internal message system to other addons registered for this message. -- @name AceEvent:SendMessage -- @class function -- @paramsig message, ... -- @param message The message to send -- @param ... Any arguments to the message -- Embeds AceEvent into the target object making the functions from the mixins list available on target:.. -- @param target target object to embed AceEvent in function AceEvent:Embed(target) for k, v in pairs(mixins) do target[v] = self[v] end self.embeds[target] = true return target end -- AceEvent:OnEmbedDisable( target ) -- target (object) - target object that is being disabled -- -- Unregister all events messages etc when the target disables. -- this method should be called by the target manually or by an addon framework function AceEvent:OnEmbedDisable(target) target:UnregisterAllEvents() target:UnregisterAllMessages() end -- Script to fire blizzard events into the event listeners local events = AceEvent.events AceEvent.frame:SetScript("OnEvent", function(this, event, ...) events:Fire(event, ...) end) --- Finally: upgrade our old embeds for target, v in pairs(AceEvent.embeds) do AceEvent:Embed(target) end
bsd-3-clause
isdriven/tsvloader
tsvloader.lua
1
4409
--[[ ---------------------- tsvloader ---------------------- Author: isdriven Licence: MIT ]]-- module("tsvloader", package.seeall) FETCHNG_TITLE = 1 FETCHNG_BODY = 2 FETCHNG_MULTI = 3 local mode = FETCHNG_TITLE local delimiter = "\t" local rows = {} local line = {} local titles = {} local column = 1 local pos = 1 local after_delimiter = false local tmp_body = "" function seek(text, titles, rows) from = pos local text_len = #text if from >= #text then if titles[column] ~= nil then line[titles[column]] = refine(table.concat({tmp_body,ret_body},"")) end table.insert(rows, line) return false end local q = string.find(text, '"', from, true) local d = string.find(text,delimiter, from) local n = string.find(text,"\n", from) if q == nil then q = text_len end if d == nil then d = text_len end if n == nil then n = text_len end local positions = {q,d,n} table.sort(positions) local f = positions[1] local ret_body = "" if f == nil then f = #text end pos = f + 1 ret_body = string.sub(text,from,f-1) if mode == FETCHNG_TITLE then -- in title, no '"' if f == d then table.insert(titles, ret_body) elseif f == n then table.insert(titles, ret_body) mode = FETCHNG_BODY end elseif mode == FETCHNG_BODY then if f == d then if titles[column] ~= nil then line[titles[column]] = refine(table.concat({tmp_body,ret_body},"")) tmp_body = "" column = column + 1 if f + 1 == q then pos = pos + 1 mode = FETCHNG_MULTI end end elseif f == n then if column == 1 then -- expect nil rows return false end if titles[column] ~= nil then line[titles[column]] = refine(table.concat({tmp_body,ret_body},"")) end tmp_body = "" column = 1 table.insert(rows, line) line = {} elseif f == q then tmp_body = tmp_body..string.sub(text, from, q) pos = f + 1 end elseif mode == FETCHNG_MULTI then -- see next quote with next delimiter next_d = string.find(text,delimiter,q) next_n = string.find(text,"\n",q) if (q + 1 == next_d ) or ( q + 1 == next_n ) then f = q tmp_body = tmp_body..string.sub(text, from, q-1) mode = FETCHNG_BODY pos = f + 1 else tmp_body = tmp_body..string.sub(text, from, q) pos = f + 1 end end end function refine(text) return string.gsub(text,'""', '"') end function dump(self) local rows = self.rows local ret = {} for _,v in ipairs( rows ) do for _,key in pairs(self.keys) do table.insert(ret,string.format(" %s=%s", key, v[key])) end table.insert(ret,"----\n") end return table.concat(ret,"\n") end function wrap(row, keys) local t = { rows={row}, keys=keys, dump=dump } local mt = { __index = row } setmetatable(t,mt) return t end function find_by(self, name, key) local ret = {} if self.index_sorted[name] == nil then for k,v in pairs(self.rows) do ret[tostring(v.id)] = v end self.index_sorted[name] = ret end local ret2 = self.index_sorted[name][tostring(key)] if ret2 == nil then return nil else return wrap(ret2,self.keys) end end function index(self, index) return wrap(self.rows[index], self.keys) end function first(self) return self:index(1) end function last(self) return self:index(self.length) end function rewind(self) self.pos = 0 end function has_next(self) if self.pos + 1 <= self.length then self.pos = self.pos + 1 return true else self:rewind() return false end end function value(self) return self:index(self.pos) end function load_from_file(file_name) local f = io.open(file_name) if f == nil then io.write("Error: no sush file:"..file_name.."\n") return false end local text = f:read("*a") return load(text) end function load( text ) -- initialize mode = FETCHNG_TITLE local rows = {} local titles = {} line = {} column = 1 pos = 1 after_delimiter = false tmp_body = "" while true do if seek(text, titles, rows) == false then break end end return { rows=rows, dump=dump, keys=titles, length=#rows, index_sorted={}, find_by=find_by, first=first, last=last, index=index, has_next=has_next, value=value, rewind=rewind, pos=0, } end
mit
lmangani/ntopng
scripts/lua/modules/dkjson.lua
17
25626
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.3* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.3"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local concat = table.concat local json = { version = "dkjson 2.3" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = tostring (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = tonumber (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") local pegmatch = g.match local P, S, R, V = g.P, g.S, g.R, g.V local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/tonumber local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-3.0
Blackdutchie/Zero-K
units/neebcomm.lua
8
2422
unitDef = { unitname = [[neebcomm]], name = [[Neeb Comm]], description = [[Ugly Turkey]], acceleration = 0.2, brakeRate = 0.205, buildCostEnergy = 1200, buildCostMetal = 1200, buildDistance = 120, builder = true, buildoptions = { }, buildPic = [[chickenbroodqueen.png]], buildTime = 1200, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canSubmerge = true, cantBeTransported = true, category = [[LAND UNARMED]], commander = true, customParams = { description_pl = [[Karny kurczak]], helptext = [[This fat chicken is presented to you as a reward for your misdeeds. Behave next time!]], helptext_pl = [[Karny kurczak za zle zachowanie. Popraw sie!]], level = [[1]], }, energyMake = 2, explodeAs = [[SMALL_UNITEX]], footprintX = 4, footprintZ = 4, iconType = [[chickenc]], idleAutoHeal = 0, idleTime = 300, leaveTracks = true, mass = 712, maxDamage = 2000, maxSlope = 36, maxVelocity = 1.2, maxWaterDepth = 22, metalMake = 2, minCloakDistance = 75, movementClass = [[AKBOT3]], noAutoFire = false, noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK TURRET]], objectName = [[chickenbroodqueen.s3o]], power = 2500, reclaimable = false, script = [[chickenbroodqueen.cob]], seismicSignature = 4, selfDestructAs = [[SMALL_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:blood_spray]], [[custom:blood_explode]], [[custom:dirt]], }, }, showNanoSpray = false, showPlayerName = true, side = [[THUNDERBIRDS]], sightDistance = 500, smoothAnim = true, sonarDistance = 300, trackOffset = 8, trackStrength = 8, trackStretch = 1, trackType = [[ChickenTrack]], trackWidth = 40, turnRate = 573, upright = false, workerTime = 7.5, } return lowerkeys({ neebcomm = unitDef })
gpl-2.0
3scale/apicast
gateway/src/apicast/upstream.lua
1
4701
--- @classmod Upstream -- Abstracts how to forward traffic to upstream server. --- @usage --- local upstream = Upstream.new('http://example.com') --- upstream:rewrite_request() -- set Host header to 'example.com' --- -- store itself in `context` table for later use in balancer phase and call `ngx.exec`. --- upstream:call(context) local setmetatable = setmetatable local tonumber = tonumber local str_format = string.format local resty_resolver = require('resty.resolver') local resty_url = require('resty.url') local core_base = require('resty.core.base') local http_proxy = require('apicast.http_proxy') local str_find = string.find local str_sub = string.sub local format = string.format local new_tab = core_base.new_tab local _M = { } local function proxy_pass(upstream) return str_format('%s://%s', upstream.uri.scheme, upstream.upstream_name) end local mt = { __index = _M } local function split_path(path) if not path then return end local start = str_find(path, '?', 1, true) if start then return str_sub(path, 1, start - 1), str_sub(path, start + 1) else return path end end local function parse_url(url) local parsed, err = resty_url.split(url) if err then return nil, err end local uri = new_tab(0, 6) uri.scheme = parsed[1] uri.user = parsed[2] uri.password = parsed[3] uri.host = parsed[4] uri.port = tonumber(parsed[5]) uri.path, uri.query = split_path(parsed[6]) return uri end --- Create new Upstream instance. --- @tparam string url --- @treturn Upstream|nil upstream instance --- @treturn nil|string error when upstream can't be initialized --- @static function _M.new(url) local uri, err = parse_url(url) if err then return nil, 'invalid upstream' end return setmetatable({ uri = uri, resolver = resty_resolver, -- @upstream location is defined in apicast.conf location_name = '@upstream', -- upstream is defined in upstream.conf upstream_name = 'upstream', }, mt) end --- Resolve upstream servers. --- @treturn {...}|nil resolved servers returned by the resolver --- @treturn nil|string error in case resolving fails function _M:resolve() local resolver = self.resolver local uri = self.uri if self.servers then return self.servers end if not resolver or not uri then return nil, 'not initialized' end local res, err = resolver:instance():get_servers(uri.host, uri) if err then return nil, err end self.servers = res return res end --- Return port to use when connecting to upstream. --- @treturn number port number function _M:port() if not self or not self.uri then return nil, 'not initialized' end return self.uri.port or resty_url.default_port(self.uri.scheme) end local root_uri = { ['/'] = true, [''] = true, } local function prefix_path(prefix) local uri = ngx.var.uri or '' if root_uri[uri] then return prefix end uri = resty_url.join(prefix, uri) return uri end local function host_header(uri) local port = uri.port local default_port = resty_url.default_port(uri.scheme) if port and port ~= default_port then return format('%s:%s', uri.host, port) else return uri.host end end function _M:use_host_header(host) self.host = host end --- Rewrite request Host header to what is provided in the argument or in the URL. function _M:rewrite_request() local uri = self.uri if not uri then return nil, 'not initialized' end ngx.req.set_header('Host', self.host or host_header(uri)) if uri.path then ngx.req.set_uri(prefix_path(uri.path)) end if uri.query then ngx.req.set_uri_args(uri.query) end end local function exec(self) ngx.var.proxy_pass = proxy_pass(self) -- the caller can unset the location_name to do own exec/location.capture if self.location_name then ngx.exec(self.location_name) end end --- Execute the upstream. --- @tparam table context any table (policy context, ngx.ctx) to store the upstream for later use by balancer function _M:call(context) if ngx.headers_sent then return nil, 'response sent already' end local proxy_uri = http_proxy.find(self) if proxy_uri then ngx.log(ngx.DEBUG, 'using proxy: ', proxy_uri) -- https requests will be terminated, http will be rewritten and sent to a proxy http_proxy.request(self, proxy_uri) else self:rewrite_request() end if not self.servers then self:resolve() end context[self.upstream_name] = self return exec(self) end return _M
apache-2.0
Maxsteam/HHHHLLLL
plugins/stats.lua
458
4098
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
saraedum/luci-packages-old
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_mini.lua
141
1031
--[[ smap_devinfo - SIP Device Information (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.smap_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.smap_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug) luci.controller.luci_diag.smap_common.action_links(m, true) return m
apache-2.0
froggatt/openwrt-luci
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_mini.lua
141
1031
--[[ smap_devinfo - SIP Device Information (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.smap_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.smap_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug) luci.controller.luci_diag.smap_common.action_links(m, true) return m
apache-2.0
ld-test/luasocket-unix
src/http.lua
121
12193
----------------------------------------------------------------------------- -- HTTP/1.1 client support for the Lua language. -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: http.lua,v 1.71 2007/10/13 23:55:20 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ------------------------------------------------------------------------------- local socket = require("socket") local url = require("socket.url") local ltn12 = require("ltn12") local mime = require("mime") local string = require("string") local base = _G local table = require("table") module("socket.http") ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- -- connection timeout in seconds TIMEOUT = 60 -- default port for document retrieval PORT = 80 -- user agent field sent in request USERAGENT = socket._VERSION ----------------------------------------------------------------------------- -- Reads MIME headers from a connection, unfolding where needed ----------------------------------------------------------------------------- local function receiveheaders(sock, headers) local line, name, value, err headers = headers or {} -- get first line line, err = sock:receive() if err then return nil, err end -- headers go until a blank line is found while line ~= "" do -- get field-name and value name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)")) if not (name and value) then return nil, "malformed reponse headers" end name = string.lower(name) -- get next line (value might be folded) line, err = sock:receive() if err then return nil, err end -- unfold any folded values while string.find(line, "^%s") do value = value .. line line = sock:receive() if err then return nil, err end end -- save pair in table if headers[name] then headers[name] = headers[name] .. ", " .. value else headers[name] = value end end return headers end ----------------------------------------------------------------------------- -- Extra sources and sinks ----------------------------------------------------------------------------- socket.sourcet["http-chunked"] = function(sock, headers) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function() -- get chunk size, skip extention local line, err = sock:receive() if err then return nil, err end local size = base.tonumber(string.gsub(line, ";.*", ""), 16) if not size then return nil, "invalid chunk size" end -- was it the last chunk? if size > 0 then -- if not, get chunk and skip terminating CRLF local chunk, err, part = sock:receive(size) if chunk then sock:receive() end return chunk, err else -- if it was, read trailers into headers table headers, err = receiveheaders(sock, headers) if not headers then return nil, err end end end }) end socket.sinkt["http-chunked"] = function(sock) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function(self, chunk, err) if not chunk then return sock:send("0\r\n\r\n") end local size = string.format("%X\r\n", string.len(chunk)) return sock:send(size .. chunk .. "\r\n") end }) end ----------------------------------------------------------------------------- -- Low level HTTP API ----------------------------------------------------------------------------- local metat = { __index = {} } function open(host, port, create) -- create socket with user connect function, or with default local c = socket.try((create or socket.tcp)()) local h = base.setmetatable({ c = c }, metat) -- create finalized try h.try = socket.newtry(function() h:close() end) -- set timeout before connecting h.try(c:settimeout(TIMEOUT)) h.try(c:connect(host, port or PORT)) -- here everything worked return h end function metat.__index:sendrequestline(method, uri) local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri) return self.try(self.c:send(reqline)) end function metat.__index:sendheaders(headers) local h = "\r\n" for i, v in base.pairs(headers) do h = i .. ": " .. v .. "\r\n" .. h end self.try(self.c:send(h)) return 1 end function metat.__index:sendbody(headers, source, step) source = source or ltn12.source.empty() step = step or ltn12.pump.step -- if we don't know the size in advance, send chunked and hope for the best local mode = "http-chunked" if headers["content-length"] then mode = "keep-open" end return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step)) end function metat.__index:receivestatusline() local status = self.try(self.c:receive(5)) -- identify HTTP/0.9 responses, which do not contain a status line -- this is just a heuristic, but is what the RFC recommends if status ~= "HTTP/" then return nil, status end -- otherwise proceed reading a status line status = self.try(self.c:receive("*l", status)) local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)")) return self.try(base.tonumber(code), status) end function metat.__index:receiveheaders() return self.try(receiveheaders(self.c)) end function metat.__index:receivebody(headers, sink, step) sink = sink or ltn12.sink.null() step = step or ltn12.pump.step local length = base.tonumber(headers["content-length"]) local t = headers["transfer-encoding"] -- shortcut local mode = "default" -- connection close if t and t ~= "identity" then mode = "http-chunked" elseif base.tonumber(headers["content-length"]) then mode = "by-length" end return self.try(ltn12.pump.all(socket.source(mode, self.c, length), sink, step)) end function metat.__index:receive09body(status, sink, step) local source = ltn12.source.rewind(socket.source("until-closed", self.c)) source(status) return self.try(ltn12.pump.all(source, sink, step)) end function metat.__index:close() return self.c:close() end ----------------------------------------------------------------------------- -- High level HTTP API ----------------------------------------------------------------------------- local function adjusturi(reqt) local u = reqt -- if there is a proxy, we need the full url. otherwise, just a part. if not reqt.proxy and not PROXY then u = { path = socket.try(reqt.path, "invalid path 'nil'"), params = reqt.params, query = reqt.query, fragment = reqt.fragment } end return url.build(u) end local function adjustproxy(reqt) local proxy = reqt.proxy or PROXY if proxy then proxy = url.parse(proxy) return proxy.host, proxy.port or 3128 else return reqt.host, reqt.port end end local function adjustheaders(reqt) -- default headers local lower = { ["user-agent"] = USERAGENT, ["host"] = reqt.host, ["connection"] = "close, TE", ["te"] = "trailers" } -- if we have authentication information, pass it along if reqt.user and reqt.password then lower["authorization"] = "Basic " .. (mime.b64(reqt.user .. ":" .. reqt.password)) end -- override with user headers for i,v in base.pairs(reqt.headers or lower) do lower[string.lower(i)] = v end return lower end -- default url parts local default = { host = "", port = PORT, path ="/", scheme = "http" } local function adjustrequest(reqt) -- parse url if provided local nreqt = reqt.url and url.parse(reqt.url, default) or {} -- explicit components override url for i,v in base.pairs(reqt) do nreqt[i] = v end if nreqt.port == "" then nreqt.port = 80 end socket.try(nreqt.host and nreqt.host ~= "", "invalid host '" .. base.tostring(nreqt.host) .. "'") -- compute uri if user hasn't overriden nreqt.uri = reqt.uri or adjusturi(nreqt) -- ajust host and port if there is a proxy nreqt.host, nreqt.port = adjustproxy(nreqt) -- adjust headers in request nreqt.headers = adjustheaders(nreqt) return nreqt end local function shouldredirect(reqt, code, headers) return headers.location and string.gsub(headers.location, "%s", "") ~= "" and (reqt.redirect ~= false) and (code == 301 or code == 302) and (not reqt.method or reqt.method == "GET" or reqt.method == "HEAD") and (not reqt.nredirects or reqt.nredirects < 5) end local function shouldreceivebody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 then return nil end if code >= 100 and code < 200 then return nil end return 1 end -- forward declarations local trequest, tredirect function tredirect(reqt, location) local result, code, headers, status = trequest { -- the RFC says the redirect URL has to be absolute, but some -- servers do not respect that url = url.absolute(reqt.url, location), source = reqt.source, sink = reqt.sink, headers = reqt.headers, proxy = reqt.proxy, nredirects = (reqt.nredirects or 0) + 1, create = reqt.create } -- pass location header back as a hint we redirected headers = headers or {} headers.location = headers.location or location return result, code, headers, status end function trequest(reqt) -- we loop until we get what we want, or -- until we are sure there is no way to get it local nreqt = adjustrequest(reqt) local h = open(nreqt.host, nreqt.port, nreqt.create) -- send request line and headers h:sendrequestline(nreqt.method, nreqt.uri) h:sendheaders(nreqt.headers) -- if there is a body, send it if nreqt.source then h:sendbody(nreqt.headers, nreqt.source, nreqt.step) end local code, status = h:receivestatusline() -- if it is an HTTP/0.9 server, simply get the body and we are done if not code then h:receive09body(status, nreqt.sink, nreqt.step) return 1, 200 end local headers -- ignore any 100-continue messages while code == 100 do headers = h:receiveheaders() code, status = h:receivestatusline() end headers = h:receiveheaders() -- at this point we should have a honest reply from the server -- we can't redirect if we already used the source, so we report the error if shouldredirect(nreqt, code, headers) and not nreqt.source then h:close() return tredirect(reqt, headers.location) end -- here we are finally done if shouldreceivebody(nreqt, code) then h:receivebody(headers, nreqt.sink, nreqt.step) end h:close() return 1, code, headers, status end local function srequest(u, b) local t = {} local reqt = { url = u, sink = ltn12.sink.table(t) } if b then reqt.source = ltn12.source.string(b) reqt.headers = { ["content-length"] = string.len(b), ["content-type"] = "application/x-www-form-urlencoded" } reqt.method = "POST" end local code, headers, status = socket.skip(1, trequest(reqt)) return table.concat(t), code, headers, status end request = socket.protect(function(reqt, body) if base.type(reqt) == "string" then return srequest(reqt, body) else return trequest(reqt) end end)
mit