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
wcjscm/JackGame
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/EaseQuadraticActionInOut.lua
2
1291
-------------------------------- -- @module EaseQuadraticActionInOut -- @extend ActionEase -- @parent_module cc -------------------------------- -- -- @function [parent=#EaseQuadraticActionInOut] create -- @param self -- @param #cc.ActionInterval action -- @return EaseQuadraticActionInOut#EaseQuadraticActionInOut ret (return value: cc.EaseQuadraticActionInOut) -------------------------------- -- -- @function [parent=#EaseQuadraticActionInOut] clone -- @param self -- @return EaseQuadraticActionInOut#EaseQuadraticActionInOut ret (return value: cc.EaseQuadraticActionInOut) -------------------------------- -- -- @function [parent=#EaseQuadraticActionInOut] update -- @param self -- @param #float time -- @return EaseQuadraticActionInOut#EaseQuadraticActionInOut self (return value: cc.EaseQuadraticActionInOut) -------------------------------- -- -- @function [parent=#EaseQuadraticActionInOut] reverse -- @param self -- @return ActionEase#ActionEase ret (return value: cc.ActionEase) -------------------------------- -- -- @function [parent=#EaseQuadraticActionInOut] EaseQuadraticActionInOut -- @param self -- @return EaseQuadraticActionInOut#EaseQuadraticActionInOut self (return value: cc.EaseQuadraticActionInOut) return nil
gpl-3.0
dmccuskey/dmc-gestures
examples/gesture-pan-basic/dmc_corona/dmc_states_mix.lua
29
3816
--====================================================================-- -- dmc_corona/dmc_states_mix.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2015 David McCuskey 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. --]] --====================================================================-- --== DMC Corona Library : DMC States Mix --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== DMC Corona Library Config --====================================================================-- --====================================================================-- --== Support Functions local Utils = {} -- make copying from Utils easier --== Start: copy from lua_utils ==-- -- extend() -- Copy key/values from one table to another -- Will deep copy any value from first table which is itself a table. -- -- @param fromTable the table (object) from which to take key/value pairs -- @param toTable the table (object) in which to copy key/value pairs -- @return table the table (object) that received the copied items -- function Utils.extend( fromTable, toTable ) if not fromTable or not toTable then error( "table can't be nil" ) end function _extend( fT, tT ) for k,v in pairs( fT ) do if type( fT[ k ] ) == "table" and type( tT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], tT[ k ] ) elseif type( fT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], {} ) else tT[ k ] = v end end return tT end return _extend( fromTable, toTable ) end --== End: copy from lua_utils ==-- --====================================================================-- --== Configuration local dmc_lib_data -- boot dmc_corona with boot script or -- setup basic defaults if it doesn't exist -- if false == pcall( function() require( 'dmc_corona_boot' ) end ) then _G.__dmc_corona = { dmc_corona={}, } end dmc_lib_data = _G.__dmc_corona --====================================================================-- --== DMC States Mix --====================================================================-- --====================================================================-- --== Configuration dmc_lib_data.dmc_states_mix = dmc_lib_data.dmc_states_mix or {} local DMC_STATES_MIX_DEFAULTS = { } local dmc_states_mix_data = Utils.extend( dmc_lib_data.dmc_states_mix, DMC_STATES_MIX_DEFAULTS ) --====================================================================-- --== Imports local StatesMixModule = require 'lib.dmc_lua.lua_states_mix' return StatesMixModule
mit
heysion/prosody-modules
mod_limit_auth/mod_limit_auth.lua
31
1377
-- mod_limit_auth local st = require"util.stanza"; local new_throttle = require "util.throttle".create; local period = math.max(module:get_option_number(module.name.."_period", 30), 0); local max = math.max(module:get_option_number(module.name.."_max", 5), 1); local tarpit_delay = module:get_option_number(module.name.."_tarpit_delay", nil); if tarpit_delay then local waiter = require "util.async".waiter; local delay = tarpit_delay; function tarpit_delay() local wait, done = waiter(); module:add_timer(delay, done); wait(); end else function tarpit_delay() end end local throttles = module:shared"throttles"; local reply = st.stanza("failure", { xmlns = "urn:ietf:params:xml:ns:xmpp-sasl" }):tag("temporary-auth-failure"); local function get_throttle(ip) local throttle = throttles[ip]; if not throttle then throttle = new_throttle(max, period); throttles[ip] = throttle; end return throttle; end module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:auth", function (event) local origin = event.origin; if not get_throttle(origin.ip):peek(1) then origin.log("warn", "Too many authentication attepmts for ip %s", origin.ip); tarpit_delay(); origin.send(reply); return true; end end, 10); module:hook("authentication-failure", function (event) get_throttle(event.session.ip):poll(1); end); -- TODO remove old throttles after some time
mit
m2fan/ss
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
badboyam/crazy_bot
plugins/time.lua
771
2865
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run }
gpl-2.0
Djabbz/nn
SpatialDivisiveNormalization.lua
39
5171
local SpatialDivisiveNormalization, parent = torch.class('nn.SpatialDivisiveNormalization','nn.Module') function SpatialDivisiveNormalization:__init(nInputPlane, kernel, threshold, thresval) parent.__init(self) -- get args self.nInputPlane = nInputPlane or 1 self.kernel = kernel or torch.Tensor(9,9):fill(1) self.threshold = threshold or 1e-4 self.thresval = thresval or threshold or 1e-4 local kdim = self.kernel:nDimension() -- check args if kdim ~= 2 and kdim ~= 1 then error('<SpatialDivisiveNormalization> averaging kernel must be 2D or 1D') end if (self.kernel:size(1) % 2) == 0 or (kdim == 2 and (self.kernel:size(2) % 2) == 0) then error('<SpatialDivisiveNormalization> averaging kernel must have ODD dimensions') end -- padding values local padH = math.floor(self.kernel:size(1)/2) local padW = padH if kdim == 2 then padW = math.floor(self.kernel:size(2)/2) end -- create convolutional mean estimator self.meanestimator = nn.Sequential() self.meanestimator:add(nn.SpatialZeroPadding(padW, padW, padH, padH)) if kdim == 2 then self.meanestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, self.kernel:size(2), self.kernel:size(1))) else self.meanestimator:add(nn.SpatialConvolutionMap(nn.tables.oneToOne(self.nInputPlane), self.kernel:size(1), 1)) self.meanestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, 1, self.kernel:size(1))) end self.meanestimator:add(nn.Replicate(self.nInputPlane,1,3)) -- create convolutional std estimator self.stdestimator = nn.Sequential() self.stdestimator:add(nn.Square()) self.stdestimator:add(nn.SpatialZeroPadding(padW, padW, padH, padH)) if kdim == 2 then self.stdestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, self.kernel:size(2), self.kernel:size(1))) else self.stdestimator:add(nn.SpatialConvolutionMap(nn.tables.oneToOne(self.nInputPlane), self.kernel:size(1), 1)) self.stdestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, 1, self.kernel:size(1))) end self.stdestimator:add(nn.Replicate(self.nInputPlane,1,3)) self.stdestimator:add(nn.Sqrt()) -- set kernel and bias if kdim == 2 then self.kernel:div(self.kernel:sum() * self.nInputPlane) for i = 1,self.nInputPlane do self.meanestimator.modules[2].weight[1][i] = self.kernel self.stdestimator.modules[3].weight[1][i] = self.kernel end self.meanestimator.modules[2].bias:zero() self.stdestimator.modules[3].bias:zero() else self.kernel:div(self.kernel:sum() * math.sqrt(self.nInputPlane)) for i = 1,self.nInputPlane do self.meanestimator.modules[2].weight[i]:copy(self.kernel) self.meanestimator.modules[3].weight[1][i]:copy(self.kernel) self.stdestimator.modules[3].weight[i]:copy(self.kernel) self.stdestimator.modules[4].weight[1][i]:copy(self.kernel) end self.meanestimator.modules[2].bias:zero() self.meanestimator.modules[3].bias:zero() self.stdestimator.modules[3].bias:zero() self.stdestimator.modules[4].bias:zero() end -- other operation self.normalizer = nn.CDivTable() self.divider = nn.CDivTable() self.thresholder = nn.Threshold(self.threshold, self.thresval) -- coefficient array, to adjust side effects self.coef = torch.Tensor(1,1,1) end function SpatialDivisiveNormalization:updateOutput(input) self.localstds = self.stdestimator:updateOutput(input) -- compute side coefficients local dim = input:dim() if self.localstds:dim() ~= self.coef:dim() or (input:size(dim) ~= self.coef:size(dim)) or (input:size(dim-1) ~= self.coef:size(dim-1)) then self.ones = self.ones or input.new() if dim == 4 then -- batch mode self.ones:resizeAs(input[1]):fill(1) local coef = self.meanestimator:updateOutput(self.ones) self._coef = self._coef or input.new() self._coef:resizeAs(coef):copy(coef) -- make contiguous for view self.coef = self._coef:view(1,table.unpack(self._coef:size():totable())):expandAs(self.localstds) else self.ones:resizeAs(input):fill(1) self.coef = self.meanestimator:updateOutput(self.ones) end end -- normalize std dev self.adjustedstds = self.divider:updateOutput{self.localstds, self.coef} self.thresholdedstds = self.thresholder:updateOutput(self.adjustedstds) self.output = self.normalizer:updateOutput{input, self.thresholdedstds} -- done return self.output end function SpatialDivisiveNormalization:updateGradInput(input, gradOutput) -- resize grad self.gradInput:resizeAs(input):zero() -- backprop through all modules local gradnorm = self.normalizer:updateGradInput({input, self.thresholdedstds}, gradOutput) local gradadj = self.thresholder:updateGradInput(self.adjustedstds, gradnorm[2]) local graddiv = self.divider:updateGradInput({self.localstds, self.coef}, gradadj) self.gradInput:add(self.stdestimator:updateGradInput(input, graddiv[1])) self.gradInput:add(gradnorm[1]) -- done return self.gradInput end
bsd-3-clause
MrCerealGuy/Stonecraft
games/stonecraft_game/mods/technic/technic/init.lua
1
1424
-- Minetest 0.4.7 mod: technic -- namespace: technic -- (c) 2012-2013 by RealBadAngel <mk@realbadangel.pl> --[[ 2017-01-06 modified by MrCerealGuy <mrcerealguy@gmx.de> exit if mod is deactivated --]] if core.skip_mod("technic") then return end local load_start = os.clock() technic = rawget(_G, "technic") or {} technic.creative_mode = minetest.settings:get_bool("creative_mode") local modpath = minetest.get_modpath("technic") technic.modpath = modpath -- Boilerplate to support intllib if rawget(_G, "intllib") then technic.getter = intllib.Getter() else technic.getter = function(s,a,...)if a==nil then return s end a={a,...}return s:gsub("(@?)@(%(?)(%d+)(%)?)",function(e,o,n,c)if e==""then return a[tonumber(n)]..(o==""and c or"")else return"@"..o..n..c end end) end end local S = technic.getter -- Read configuration file dofile(modpath.."/config.lua") -- Helper functions dofile(modpath.."/helpers.lua") -- Items dofile(modpath.."/items.lua") -- Craft recipes for items dofile(modpath.."/crafts.lua") -- Register functions dofile(modpath.."/register.lua") -- Radiation dofile(modpath.."/radiation.lua") -- Machines dofile(modpath.."/machines/init.lua") -- Tools dofile(modpath.."/tools/init.lua") -- Aliases for legacy node/item names dofile(modpath.."/legacy.lua") if minetest.settings:get_bool("log_mods") then print(S("[Technic] Loaded in %f seconds"):format(os.clock() - load_start)) end
gpl-3.0
heysion/prosody-modules
mod_storage_ldap/ldap/vcard.lib.lua
40
5035
-- vim:sts=4 sw=4 -- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- Copyright (C) 2012 Rob Hoelz -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require 'util.stanza'; local VCARD_NS = 'vcard-temp'; local builder_methods = {}; local base64_encode = require('util.encodings').base64.encode; function builder_methods:addvalue(key, value) self.vcard:tag(key):text(value):up(); end function builder_methods:addphotofield(tagname, format_section) local record = self.record; local format = self.format; local vcard = self.vcard; local config = format[format_section]; if not config then return; end if config.extval then if record[config.extval] then local tag = vcard:tag(tagname); tag:tag('EXTVAL'):text(record[config.extval]):up(); end elseif config.type and config.binval then if record[config.binval] then local tag = vcard:tag(tagname); tag:tag('TYPE'):text(config.type):up(); tag:tag('BINVAL'):text(base64_encode(record[config.binval])):up(); end else module:log('error', 'You have an invalid %s config section', tagname); return; end vcard:up(); end function builder_methods:addregularfield(tagname, format_section) local record = self.record; local format = self.format; local vcard = self.vcard; if not format[format_section] then return; end local tag = vcard:tag(tagname); for k, v in pairs(format[format_section]) do tag:tag(string.upper(k)):text(record[v]):up(); end vcard:up(); end function builder_methods:addmultisectionedfield(tagname, format_section) local record = self.record; local format = self.format; local vcard = self.vcard; if not format[format_section] then return; end for k, v in pairs(format[format_section]) do local tag = vcard:tag(tagname); if type(k) == 'string' then tag:tag(string.upper(k)):up(); end for k2, v2 in pairs(v) do if type(v2) == 'boolean' then tag:tag(string.upper(k2)):up(); else tag:tag(string.upper(k2)):text(record[v2]):up(); end end vcard:up(); end end function builder_methods:build() local record = self.record; local format = self.format; self:addvalue( 'VERSION', '2.0'); self:addvalue( 'FN', record[format.displayname]); self:addregularfield( 'N', 'name'); self:addvalue( 'NICKNAME', record[format.nickname]); self:addphotofield( 'PHOTO', 'photo'); self:addvalue( 'BDAY', record[format.birthday]); self:addmultisectionedfield('ADR', 'address'); self:addvalue( 'LABEL', nil); -- we don't support LABEL...yet. self:addmultisectionedfield('TEL', 'telephone'); self:addmultisectionedfield('EMAIL', 'email'); self:addvalue( 'JABBERID', record.jid); self:addvalue( 'MAILER', record[format.mailer]); self:addvalue( 'TZ', record[format.timezone]); self:addregularfield( 'GEO', 'geo'); self:addvalue( 'TITLE', record[format.title]); self:addvalue( 'ROLE', record[format.role]); self:addphotofield( 'LOGO', 'logo'); self:addvalue( 'AGENT', nil); -- we don't support AGENT...yet. self:addregularfield( 'ORG', 'org'); self:addvalue( 'CATEGORIES', nil); -- we don't support CATEGORIES...yet. self:addvalue( 'NOTE', record[format.note]); self:addvalue( 'PRODID', nil); -- we don't support PRODID...yet. self:addvalue( 'REV', record[format.rev]); self:addvalue( 'SORT-STRING', record[format.sortstring]); self:addregularfield( 'SOUND', 'sound'); self:addvalue( 'UID', record[format.uid]); self:addvalue( 'URL', record[format.url]); self:addvalue( 'CLASS', nil); -- we don't support CLASS...yet. self:addregularfield( 'KEY', 'key'); self:addvalue( 'DESC', record[format.description]); return self.vcard; end local function new_builder(params) local vcard_tag = st.stanza('vCard', { xmlns = VCARD_NS }); local object = { vcard = vcard_tag, __index = builder_methods, }; for k, v in pairs(params) do object[k] = v; end setmetatable(object, object); return object; end local _M = {}; function _M.create(params) local builder = new_builder(params); return builder:build(); end return _M;
mit
mahdisudo/best
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
gpl-2.0
xing634325131/Luci-0.11.1
libs/nixio/docsrc/nixio.lua
151
15824
--- General POSIX IO library. module "nixio" --- Look up a hostname and service via DNS. -- @class function -- @name nixio.getaddrinfo -- @param host hostname to lookup (optional) -- @param family address family [<strong>"any"</strong>, "inet", "inet6"] -- @param service service name or port (optional) -- @return Table containing one or more tables containing: <ul> -- <li>family = ["inet", "inet6"]</li> -- <li>socktype = ["stream", "dgram", "raw"]</li> -- <li>address = Resolved IP-Address</li> -- <li>port = Resolved Port (if service was given)</li> -- </ul> --- Reverse look up an IP-Address via DNS. -- @class function -- @name nixio.getnameinfo -- @param ipaddr IPv4 or IPv6-Address -- @return FQDN --- (Linux, BSD) Get a list of available network interfaces and their addresses. -- @class function -- @name nixio.getifaddrs -- @return Table containing one or more tables containing: <ul> -- <li>name = Interface Name</li> -- <li>family = ["inet", "inet6", "packet"]</li> -- <li>addr = Interface Address (IPv4, IPv6, MAC, ...)</li> -- <li>broadaddr = Broadcast Address</li> -- <li>dstaddr = Destination Address (Point-to-Point)</li> -- <li>netmask = Netmask (if available)</li> -- <li>prefix = Prefix (if available)</li> -- <li>flags = Table of interface flags (up, multicast, loopback, ...)</li> -- <li>data = Statistics (Linux, "packet"-family)</li> -- <li>hatype = Hardware Type Identifier (Linix, "packet"-family)</li> -- <li>ifindex = Interface Index (Linux, "packet"-family)</li> -- </ul> --- Get protocol entry by name. -- @usage This function returns nil if the given protocol is unknown. -- @class function -- @name nixio.getprotobyname -- @param name protocol name to lookup -- @return Table containing the following fields: <ul> -- <li>name = Protocol Name</li> -- <li>proto = Protocol Number</li> -- <li>aliases = Table of alias names</li> -- </ul> --- Get protocol entry by number. -- @usage This function returns nil if the given protocol is unknown. -- @class function -- @name nixio.getprotobynumber -- @param proto protocol number to lookup -- @return Table containing the following fields: <ul> -- <li>name = Protocol Name</li> -- <li>proto = Protocol Number</li> -- <li>aliases = Table of alias names</li> -- </ul> --- Get all or a specifc proto entry. -- @class function -- @name nixio.getproto -- @param proto protocol number or name to lookup (optional) -- @return Table (or if no parameter is given, a table of tables) -- containing the following fields: <ul> -- <li>name = Protocol Name</li> -- <li>proto = Protocol Number</li> -- <li>aliases = Table of alias names</li> -- </ul> --- Create a new socket and bind it to a network address. -- This function is a shortcut for calling nixio.socket and then bind() -- on the socket object. -- @usage This functions calls getaddrinfo(), socket(), -- setsockopt() and bind() but NOT listen(). -- @usage The <em>reuseaddr</em>-option is automatically set before binding. -- @class function -- @name nixio.bind -- @param host Hostname or IP-Address (optional, default: all addresses) -- @param port Port or service description -- @param family Address family [<strong>"any"</strong>, "inet", "inet6"] -- @param socktype Socket Type [<strong>"stream"</strong>, "dgram"] -- @return Socket Object --- Create a new socket and connect to a network address. -- This function is a shortcut for calling nixio.socket and then connect() -- on the socket object. -- @usage This functions calls getaddrinfo(), socket() and connect(). -- @class function -- @name nixio.connect -- @param host Hostname or IP-Address (optional, default: localhost) -- @param port Port or service description -- @param family Address family [<strong>"any"</strong>, "inet", "inet6"] -- @param socktype Socket Type [<strong>"stream"</strong>, "dgram"] -- @return Socket Object --- Open a file. -- @class function -- @name nixio.open -- @usage Although this function also supports the traditional fopen() -- file flags it does not create a file stream but uses the open() syscall. -- @param path Filesystem path to open -- @param flags Flag string or number (see open_flags). -- [<strong>"r"</strong>, "r+", "w", "w+", "a", "a+"] -- @param mode File mode for newly created files (see chmod, umask). -- @see nixio.umask -- @see nixio.open_flags -- @return File Object --- Generate flags for a call to open(). -- @class function -- @name nixio.open_flags -- @usage This function cannot fail and will never return nil. -- @usage The "nonblock" and "ndelay" flags are aliases. -- @usage The "nonblock", "ndelay" and "sync" flags are no-ops on Windows. -- @param flag1 First Flag ["append", "creat", "excl", "nonblock", "ndelay", -- "sync", "trunc", "rdonly", "wronly", "rdwr"] -- @param ... More Flags [-"-] -- @return flag to be used as second paramter to open --- Duplicate a file descriptor. -- @class function -- @name nixio.dup -- @usage This funcation calls dup2() if <em>newfd</em> is set, otherwise dup(). -- @param oldfd Old descriptor [File Object, Socket Object (POSIX only)] -- @param newfd New descriptor to serve as copy (optional) -- @return File Object of new descriptor --- Create a pipe. -- @class function -- @name nixio.pipe -- @return File Object of the read end -- @return File Object of the write end --- Get the last system error code. -- @class function -- @name nixio.errno -- @return Error code --- Get the error message for the corresponding error code. -- @class function -- @name nixio.strerror -- @param errno System error code -- @return Error message --- Sleep for a specified amount of time. -- @class function -- @usage Not all systems support nanosecond precision but you can expect -- to have at least maillisecond precision. -- @usage This function is not signal-protected and may fail with EINTR. -- @param seconds Seconds to wait (optional) -- @param nanoseconds Nanoseconds to wait (optional) -- @name nixio.nanosleep -- @return true --- Generate events-bitfield or parse revents-bitfield for poll. -- @class function -- @name nixio.poll_flags -- @param mode1 revents-Flag bitfield returned from poll to parse OR -- ["in", "out", "err", "pri" (POSIX), "hup" (POSIX), "nval" (POSIX)] -- @param ... More mode strings for generating the flag [-"-] -- @see nixio.poll -- @return table with boolean fields reflecting the mode parameter -- <strong>OR</strong> bitfield to use for the events-Flag field --- Wait for some event on a file descriptor. -- poll() sets the revents-field of the tables provided by fds to a bitfield -- indicating the events that occured. -- @class function -- @usage This function works in-place on the provided table and only -- writes the revents field, you can use other fields on your demand. -- @usage All metamethods on the tables provided as fds are ignored. -- @usage The revents-fields are not reset when the call times out. -- You have to check the first return value to be 0 to handle this case. -- @usage If you want to wait on a TLS-Socket you have to use the underlying -- socket instead. -- @usage On Windows poll is emulated through select(), can only be used -- on socket descriptors and cannot take more than 64 descriptors per call. -- @usage This function is not signal-protected and may fail with EINTR. -- @param fds Table containing one or more tables containing <ul> -- <li> fd = I/O Descriptor [Socket Object, File Object (POSIX)]</li> -- <li> events = events to wait for (bitfield generated with poll_flags)</li> -- </ul> -- @param timeout Timeout in milliseconds -- @name nixio.poll -- @see nixio.poll_flags -- @return number of ready IO descriptors -- @return the fds-table with revents-fields set --- (POSIX) Clone the current process. -- @class function -- @name nixio.fork -- @return the child process id for the parent process, 0 for the child process --- (POSIX) Send a signal to one or more processes. -- @class function -- @name nixio.kill -- @param target Target process of process group. -- @param signal Signal to send -- @return true --- (POSIX) Get the parent process id of the current process. -- @class function -- @name nixio.getppid -- @return parent process id --- (POSIX) Get the user id of the current process. -- @class function -- @name nixio.getuid -- @return process user id --- (POSIX) Get the group id of the current process. -- @class function -- @name nixio.getgid -- @return process group id --- (POSIX) Set the group id of the current process. -- @class function -- @name nixio.setgid -- @param gid New Group ID -- @return true --- (POSIX) Set the user id of the current process. -- @class function -- @name nixio.setuid -- @param gid New User ID -- @return true --- (POSIX) Change priority of current process. -- @class function -- @name nixio.nice -- @param nice Nice Value -- @return true --- (POSIX) Create a new session and set the process group ID. -- @class function -- @name nixio.setsid -- @return session id --- (POSIX) Wait for a process to change state. -- @class function -- @name nixio.waitpid -- @usage If the "nohang" is given this function becomes non-blocking. -- @param pid Process ID (optional, default: any childprocess) -- @param flag1 Flag (optional) ["nohang", "untraced", "continued"] -- @param ... More Flags [-"-] -- @return process id of child or 0 if no child has changed state -- @return ["exited", "signaled", "stopped"] -- @return [exit code, terminate signal, stop signal] --- (POSIX) Get process times. -- @class function -- @name nixio.times -- @return Table containing: <ul> -- <li>utime = user time</li> -- <li>utime = system time</li> -- <li>cutime = children user time</li> -- <li>cstime = children system time</li> -- </ul> --- (POSIX) Get information about current system and kernel. -- @class function -- @name nixio.uname -- @return Table containing: <ul> -- <li>sysname = operating system</li> -- <li>nodename = network name (usually hostname)</li> -- <li>release = OS release</li> -- <li>version = OS version</li> -- <li>machine = hardware identifier</li> -- </ul> --- Change the working directory. -- @class function -- @name nixio.chdir -- @param path New working directory -- @return true --- Ignore or use set the default handler for a signal. -- @class function -- @name nixio.signal -- @param signal Signal -- @param handler ["ign", "dfl"] -- @return true --- Get the ID of the current process. -- @class function -- @name nixio.getpid -- @return process id --- Get the current working directory. -- @class function -- @name nixio.getcwd -- @return workign directory --- Get the current environment table or a specific environment variable. -- @class function -- @name nixio.getenv -- @param variable Variable (optional) -- @return environment table or single environment variable --- Set or unset a environment variable. -- @class function -- @name nixio.setenv -- @usage The environment variable will be unset if value is ommited. -- @param variable Variable -- @param value Value (optional) -- @return true --- Execute a file to replace the current process. -- @class function -- @name nixio.exec -- @usage The name of the executable is automatically passed as argv[0] -- @usage This function does not return on success. -- @param executable Executable -- @param ... Parameters --- Invoke the shell and execute a file to replace the current process. -- @class function -- @name nixio.execp -- @usage The name of the executable is automatically passed as argv[0] -- @usage This function does not return on success. -- @param executable Executable -- @param ... Parameters --- Execute a file with a custom environment to replace the current process. -- @class function -- @name nixio.exece -- @usage The name of the executable is automatically passed as argv[0] -- @usage This function does not return on success. -- @param executable Executable -- @param arguments Argument Table -- @param environment Environment Table (optional) --- Sets the file mode creation mask. -- @class function -- @name nixio.umask -- @param mask New creation mask (see chmod for format specifications) -- @return the old umask as decimal mode number -- @return the old umask as mode string --- (Linux) Get overall system statistics. -- @class function -- @name nixio.sysinfo -- @return Table containing: <ul> -- <li>uptime = system uptime in seconds</li> -- <li>loads = {loadavg1, loadavg5, loadavg15}</li> -- <li>totalram = total RAM</li> -- <li>freeram = free RAM</li> -- <li>sharedram = shared RAM</li> -- <li>bufferram = buffered RAM</li> -- <li>totalswap = total SWAP</li> -- <li>freeswap = free SWAP</li> -- <li>procs = number of running processes</li> -- </ul> --- Create a new socket. -- @class function -- @name nixio.socket -- @param domain Domain ["inet", "inet6", "unix"] -- @param type Type ["stream", "dgram", "raw"] -- @return Socket Object --- (POSIX) Send data from a file to a socket in kernel-space. -- @class function -- @name nixio.sendfile -- @param socket Socket Object -- @param file File Object -- @param length Amount of data to send (in Bytes). -- @return bytes sent --- (Linux) Send data from / to a pipe in kernel-space. -- @class function -- @name nixio.splice -- @param fdin Input I/O descriptor -- @param fdout Output I/O descriptor -- @param length Amount of data to send (in Bytes). -- @param flags (optional, bitfield generated by splice_flags) -- @see nixio.splice_flags -- @return bytes sent --- (Linux) Generate a flag bitfield for a call to splice. -- @class function -- @name nixio.splice_flags -- @param flag1 First Flag ["move", "nonblock", "more"] -- @param ... More flags [-"-] -- @see nixio.splice -- @return Flag bitfield --- (POSIX) Open a connection to the system logger. -- @class function -- @name nixio.openlog -- @param ident Identifier -- @param flag1 Flag 1 ["cons", "nowait", "pid", "perror", "ndelay", "odelay"] -- @param ... More flags [-"-] --- (POSIX) Close the connection to the system logger. -- @class function -- @name nixio.closelog --- (POSIX) Write a message to the system logger. -- @class function -- @name nixio.syslog -- @param priority Priority ["emerg", "alert", "crit", "err", "warning", -- "notice", "info", "debug"] -- @param message --- (POSIX) Set the logmask of the system logger for current process. -- @class function -- @name nixio.setlogmask -- @param priority Priority ["emerg", "alert", "crit", "err", "warning", -- "notice", "info", "debug"] --- (POSIX) Encrypt a user password. -- @class function -- @name nixio.crypt -- @param key Key -- @param salt Salt -- @return password hash --- (POSIX) Get all or a specific user group. -- @class function -- @name nixio.getgr -- @param group Group ID or groupname (optional) -- @return Table containing: <ul> -- <li>name = Group Name</li> -- <li>gid = Group ID</li> -- <li>passwd = Password</li> -- <li>mem = {Member #1, Member #2, ...}</li> -- </ul> --- (POSIX) Get all or a specific user account. -- @class function -- @name nixio.getpw -- @param user User ID or username (optional) -- @return Table containing: <ul> -- <li>name = Name</li> -- <li>uid = ID</li> -- <li>gid = Group ID</li> -- <li>passwd = Password</li> -- <li>dir = Home directory</li> -- <li>gecos = Information</li> -- <li>shell = Shell</li> -- </ul> --- (Linux, Solaris) Get all or a specific shadow password entry. -- @class function -- @name nixio.getsp -- @param user username (optional) -- @return Table containing: <ul> -- <li>namp = Name</li> -- <li>expire = Expiration Date</li> -- <li>flag = Flags</li> -- <li>inact = Inactivity Date</li> -- <li>lstchg = Last change</li> -- <li>max = Maximum</li> -- <li>min = Minimum</li> -- <li>warn = Warning</li> -- <li>pwdp = Password Hash</li> -- </ul> --- Create a new TLS context. -- @class function -- @name nixio.tls -- @param mode TLS-Mode ["client", "server"] -- @return TLSContext Object
apache-2.0
xingshuo/frame_sync_model
server/globaldefines.lua
1
2378
local Skynet = require "lualib.local_skynet" GAME_FIGHTER_WAR = 1001 GGameConfig = { [GAME_FIGHTER_WAR] = { frame_rate = 50, --times of per second ping_interval = 1000, --ms }, } ACTION_ENTER = 1 ACTION_LEAVE = 2 ACTION_ATTACK = 3 ACTION_MOVE = 4 local ostime = os.time function GetSecond() return ostime() end function GetCSecond() return Skynet.now() end local mathrand = math.random function RandomList(lst) if #lst == 0 then return nil end return lst[mathrand(1,#lst)] end function IsValueInList(value, list) for _,v in ipairs(list) do if value == v then return true end end return false end function skynet_call(service, cmd, ...) return Skynet.call(service, "lua", cmd, ...) end function skynet_send(service, cmd, ...) Skynet.send(service, "lua", cmd, ...) end -- ti: 执行间隔,单位百分之一秒(10ms) -- count:0表示无限次数, >0 有限次 -- handle : 自定义(int,string等常量key)或系统分配 local timer_no = 0 local timer_list = {} local timer_default_hdl = 0 function AddTimer(ti, func, handle, count) assert(ti >= 0) count = count or 0 count = (count>0) and count or true if handle == nil then handle = timer_default_hdl timer_default_hdl = timer_default_hdl + 1 end local tno = timer_no timer_no = timer_no + 1 timer_list[handle] = {tno, count} local f f = function () if not timer_list[handle] then return end if timer_list[handle][1] ~= tno then return end if timer_list[handle][2] == true then Skynet.timeout(ti, f) else timer_list[handle][2] = timer_list[handle][2] - 1 if timer_list[handle][2] > 0 then Skynet.timeout(ti, f) else timer_list[handle] = nil end end func() end Skynet.timeout(ti, f) return handle end function RemoveTimer(handle) timer_list[handle] = nil end function RemoveAllTimers() timer_list = {} end function FindTimer(handle) return timer_list[handle] end local UniqIDList = {} function NewServiceUniqID(sType) if not UniqIDList[sType] then UniqIDList[sType] = 0 end UniqIDList[sType] = UniqIDList[sType] + 1 return UniqIDList[sType] end
mit
ahmadreza5251/terojanbot
plugins/id.lua
355
2795
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 local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver --local chat_id = "chat#id"..result.id local chat_id = result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local text = 'User '..qusername..' not found in this group!' for k,v in pairs(result.members) do vusername = v.username if vusername == qusername then text = 'ID for username\n'..vusername..' : '..v.id end end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end else if not is_chat_msg(msg) then return "Only works in group" end local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) chat_info(chat, username_id, {receiver=receiver, qusername=qusername}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id <username> : Return the id from username given." }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
gpl-2.0
McGlaspie/mvm
lua/mvm/Hud/GUIShotgunDisplay.lua
1
4853
// ======= Copyright (c) 2003-2011, Unknown Worlds Entertainment, Inc. All rights reserved. ======= // // lua\GUIShotgunDisplay.lua // // Created by: Max McGuire (max@unknownworlds.com) // // Displays the ammo counter for the shotgun. // // ========= For more information, visit us at http://www.unknownworlds.com ===================== Script.Load("lua/GUIScript.lua") Script.Load("lua/Utility.lua") Script.Load("lua/mvm/GUIColorGlobals.lua") // Global state that can be externally set to adjust the display. weaponClip = 0 weaponAmmo = 0 weaponAuxClip = 0 teamNumber = 0 bulletDisplay = nil class 'GUIShotgunDisplay' function GUIShotgunDisplay:Initialize() self.weaponClip = 0 self.weaponAmmo = 0 self.weaponClipSize = 50 self.teamNumber = 0 self.flashInDelay = 1.2 self.background = GUIManager:CreateGraphicItem() self.background:SetSize( Vector(256, 128, 0) ) self.background:SetPosition( Vector(0, 0, 0)) self.background:SetTexture("ui/ShotgunDisplay.dds") self.background:SetShader("shaders/GUI_TeamThemed.surface_shader") self.clipText, self.clipTextBg = self:CreateItem(52, 66) self.ammoText, self.ammoTextBg = self:CreateItem(177, 66) local slash, slashBg = self:CreateItem(100, 66) slash:SetFontName("fonts/AgencyFB_large_bold.fnt") slash:SetText("/") slashBg:SetFontName("fonts/AgencyFB_large_bold.fnt") slashBg:SetText("/") self.flashInOverlay = GUIManager:CreateGraphicItem() self.flashInOverlay:SetSize( Vector(256, 128, 0) ) self.flashInOverlay:SetPosition( Vector(0, 0, 0)) self.flashInOverlay:SetColor(Color(1,1,1,0.0)) self.background:AddChild(self.flashInOverlay) // Force an update so our initial state is correct. self:Update(0) end function GUIShotgunDisplay:CreateItem(x, y) local textBg = GUIManager:CreateTextItem() textBg:SetFontName("fonts/MicrogrammaDMedExt_medium.fnt") textBg:SetFontSize(85) textBg:SetTextAlignmentX(GUIItem.Align_Center) textBg:SetTextAlignmentY(GUIItem.Align_Center) textBg:SetPosition(Vector(x, y, 0)) textBg:SetColor(Color(0.88, 0.98, 1, 0.25)) //### // Text displaying the amount of reserve ammo local text = GUIManager:CreateTextItem() text:SetFontName("fonts/MicrogrammaDMedExt_medium2.fnt") text:SetFontSize(75) text:SetTextAlignmentX(GUIItem.Align_Center) text:SetTextAlignmentY(GUIItem.Align_Center) text:SetPosition(Vector(x, y, 0)) text:SetColor(Color(0.88, 0.98, 1)) //### return text, textBg end function GUIShotgunDisplay:UpdateTeamColors() local ui_color = kGUI_Team1_BaseColor if self.teamNumber == 2 then ui_color = kGUI_Team2_BaseColor end self.background:SetFloatParameter( "teamBaseColorR", ui_color.r ) self.background:SetFloatParameter( "teamBaseColorG", ui_color.g ) self.background:SetFloatParameter( "teamBaseColorB", ui_color.b ) end function GUIShotgunDisplay:Update(deltaTime) PROFILE("GUIShotgunDisplay:Update") self:UpdateTeamColors() // Update the ammo counter. local clipFormat = string.format("%d", self.weaponClip) local ammoFormat = string.format("%02d", self.weaponAmmo) self.clipText:SetText( clipFormat ) self.clipTextBg:SetText( clipFormat ) self.ammoText:SetText( ammoFormat ) self.ammoTextBg:SetText( ammoFormat ) if self.flashInDelay > 0 then self.flashInDelay = Clamp(self.flashInDelay - deltaTime, 0, 5) if self.flashInDelay == 0 then self.flashInOverlay:SetColor(Color(1,1,1,0.7)) end else local flashInAlpha = self.flashInOverlay:GetColor().a if flashInAlpha > 0 then local alphaPerSecond = .5 flashInAlpha = Clamp(flashInAlpha - alphaPerSecond * deltaTime, 0, 1) self.flashInOverlay:SetColor(Color(1, 1, 1, flashInAlpha)) end end end function GUIShotgunDisplay:SetTeamNumber(team) self.teamNumber = team end function GUIShotgunDisplay:SetClip(weaponClip) self.weaponClip = weaponClip end function GUIShotgunDisplay:SetClipSize(weaponClipSize) self.weaponClipSize = weaponClipSize end function GUIShotgunDisplay:SetAmmo(weaponAmmo) self.weaponAmmo = weaponAmmo end /** * Called by the player to update the components. */ function Update(deltaTime) bulletDisplay:SetClip(weaponClip) bulletDisplay:SetAmmo(weaponAmmo) bulletDisplay:SetTeamNumber(teamNumber) bulletDisplay:Update(deltaTime) end /** * Initializes the player components. */ function Initialize() GUI.SetSize( 256, 128 ) bulletDisplay = GUIShotgunDisplay() bulletDisplay:Initialize() bulletDisplay:SetClipSize(50) end Initialize()
gpl-3.0
coronalabs/plugins-source-gamenetwork-google
Corona-gemwars/sprites-1x.lua
1
1906
-- -- created with TexturePacker (http://www.codeandweb.com/texturepacker) -- -- $TexturePacker:SmartUpdate:ceb5655d19921868929dae6efaa35799$ -- -- local sheetInfo = require("mysheet") -- local myImageSheet = graphics.newImageSheet( "mysheet.png", sheetInfo:getSheet() ) -- local sprite = display.newSprite( myImageSheet , {frames={sheetInfo:getFrameIndex("sprite")}} ) -- local SheetInfo = {} SheetInfo.sheet = { frames = { { -- bg x=2, y=2, width=320, height=480, }, { -- blueball x=428, y=52, width=50, height=48, sourceX = 0, sourceY = 2, sourceWidth = 50, sourceHeight = 50 }, { -- greenball x=428, y=2, width=50, height=48, sourceX = 0, sourceY = 2, sourceWidth = 50, sourceHeight = 50 }, { -- redball x=376, y=2, width=50, height=50, }, { -- yellowball x=324, y=2, width=50, height=50, }, { -- logo x=2, y=484, width=279, height=178, sourceX = 8, sourceY = 12, sourceWidth = 295, sourceHeight = 190 }, }, sheetContentWidth = 512, sheetContentHeight = 1024 } SheetInfo.frameIndex = { ["bg"] = 1, ["blueball"] = 2, ["greenball"] = 3, ["redball"] = 4, ["yellowball"] = 5, ["logo"] = 6, } function SheetInfo:getSheet() return self.sheet; end function SheetInfo:getFrameIndex(name) return self.frameIndex[name]; end return SheetInfo
mit
ananay/vice-players
Vendor/CEGUI/cegui/src/ScriptingModules/LuaScriptModule/support/tolua++bin/lua/module.lua
7
1526
-- tolua: module class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id: module.lua 1004 2006-02-27 13:03:20Z lindquist $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Module class -- Represents module. -- The following fields are stored: -- {i} = list of objects in the module. classModule = { classtype = 'module' } classModule.__index = classModule setmetatable(classModule,classContainer) -- register module function classModule:register (pre) pre = pre or '' push(self) output(pre..'tolua_module(tolua_S,"'..self.name..'",',self:hasvar(),');') output(pre..'tolua_beginmodule(tolua_S,"'..self.name..'");') local i=1 while self[i] do self[i]:register(pre..' ') i = i+1 end output(pre..'tolua_endmodule(tolua_S);') pop() end -- Print method function classModule:print (ident,close) print(ident.."Module{") print(ident.." name = '"..self.name.."';") local i=1 while self[i] do self[i]:print(ident.." ",",") i = i+1 end print(ident.."}"..close) end -- Internal constructor function _Module (t) setmetatable(t,classModule) append(t) return t end -- Constructor -- Expects two string representing the module name and body. function Module (n,b) local t = _Module(_Container{name=n}) push(t) t:parse(strsub(b,2,strlen(b)-1)) -- eliminate braces pop() return t end
gpl-3.0
MrCerealGuy/Stonecraft
games/stonecraft_game/mods/drops/init.lua
1
3748
--[[ 2017-06-11 modified by MrCerealGuy <mrcerealguy@gmx.de> exit if mod is deactivated --]] if core.skip_mod("itemdrop") then return end local age = 1 --how old an item has to be before collecting local radius_magnet = 2.5 --radius of item magnet local player_collect_height = 1.3 --added to their pos y value local adjuster_collect = 0.01 --Delay before collecting to visualize moveme --Item collection minetest.register_globalstep(function(dtime) --collection for _,player in ipairs(minetest.get_connected_players()) do --don't magnetize to dead players if player:get_hp() > 0 then local pos = player:getpos() local inv = player:get_inventory() --radial detection for _,object in ipairs(minetest.env:get_objects_inside_radius({x=pos.x,y=pos.y + player_collect_height,z=pos.z}, radius_magnet)) do if not object:is_player() and object:get_luaentity() and object:get_luaentity().name == "__builtin:item" then if object:get_luaentity().age > age then if inv and inv:room_for_item("main", ItemStack(object:get_luaentity().itemstring)) then --collect if object:get_luaentity().collectioner == true and object:get_luaentity().age > age and object:get_luaentity().age > object:get_luaentity().age_stamp + adjuster_collect then if object:get_luaentity().itemstring ~= "" then inv:add_item("main", ItemStack(object:get_luaentity().itemstring)) minetest.sound_play("item_drop_pickup", { pos = pos, max_hear_distance = 15, gain = 0.1, }) object:get_luaentity().itemstring = "" object:remove() end --magnet else --moveto for extreme speed boost local pos1 = pos pos1.y = pos1.y + player_collect_height object:moveto(pos1) object:get_luaentity().collectioner = true object:get_luaentity().age_stamp = object:get_luaentity().age end end end end end end end end) --Drop items on dig function minetest.handle_node_drops(pos, drops, digger) for _,item in ipairs(drops) do local count, name if type(item) == "string" then count = 1 name = item else count = item:get_count() name = item:get_name() end --if not inv or not inv:contains_item("main", ItemStack(name)) then for i=1,count do local obj = minetest.add_item(pos, name) if obj ~= nil then obj:get_luaentity().collect = true obj:get_luaentity().age = age obj:setvelocity({x=math.random(-3,3), y=math.random(2,5), z=math.random(-3,3)}) end end --end end end --Throw items using player's velocity function minetest.item_drop(itemstack, dropper, pos) --if player then do modified item drop if dropper and minetest.get_player_information(dropper:get_player_name()) then local v = dropper:get_look_dir() local vel = dropper:get_player_velocity() local p = {x=pos.x, y=pos.y+player_collect_height, z=pos.z} local item = itemstack:to_string() local obj = core.add_item(p, item) if obj then v.x = (v.x*5)+vel.x v.y = ((v.y*5)+2)+vel.y v.z = (v.z*5)+vel.z obj:setvelocity(v) obj:get_luaentity().dropped_by = dropper:get_player_name() itemstack:clear() return itemstack end --machine else local v = dropper:get_look_dir() local item = itemstack:to_string() local obj = minetest.add_item({x=pos.x,y=pos.y+1.5,z=pos.z}, item) --{x=pos.x+v.x,y=pos.y+v.y+1.5,z=pos.z+v.z} if obj then v.x = (v.x*5) v.y = (v.y*5) v.z = (v.z*5) obj:setvelocity(v) obj:get_luaentity().dropped_by = nil itemstack:clear() return itemstack end end end if minetest.settings:get_bool("log_mods") then minetest.log("action", "Drops loaded") end
gpl-3.0
cod3hulk/dotfiles
nvim/lua/user/which-key.lua
1
9922
-- local wk = require("which-key") -- wk.register({ -- f = { -- name = "find", -- f = { "<cmd>Telescope find_files<cr>", "Find File" }, -- b = { "<cmd>Telescope buffers<cr>", "Find Buffers" }, -- r = { "<cmd>Telescope oldfiles<cr>", "Open Recent File"}, -- g = { "<cmd>Telescope live_grep<cr>", "Grep File"}, -- n = { "<cmd>:new<cr>", "New File" }, -- }, -- l = { -- name = "LanguageServer", -- i = { "<cmd>LspInstallInfo<cr>", "Install LanguageServer"}, -- }, -- w = { "<cmd>:w<cr>", "Write File" }, -- x = { "<cmd>:x<cr>", "Write And Close File" }, -- q = { "<cmd>:q<cr>", "Close File" }, -- e = { "<cmd>:NvimTreeToggle<cr>", "Toggle File Explorer" }, -- } -- local status_ok, which_key = pcall(require, "which-key") if not status_ok then print("which-key not found") return end local setup = { plugins = { marks = true, -- shows a list of your marks on ' and ` registers = true, -- shows your registers on " in NORMAL or <C-r> in INSERT mode spelling = { enabled = true, -- enabling this will show WhichKey when pressing z= to select spelling suggestions suggestions = 20, -- how many suggestions should be shown in the list? }, -- the presets plugin, adds help for a bunch of default keybindings in Neovim -- No actual key bindings are created presets = { operators = false, -- adds help for operators like d, y, ... and registers them for motion / text object completion motions = false, -- adds help for motions text_objects = false, -- help for text objects triggered after entering an operator windows = false, -- default bindings on <c-w> nav = true, -- misc bindings to work with windows z = true, -- bindings for folds, spelling and others prefixed with z g = true, -- bindings for prefixed with g }, }, -- add operators that will trigger motion and text object completion -- to enable all native operators, set the preset / operators plugin above -- operators = { gc = "Comments" }, key_labels = { -- override the label used to display some keys. It doesn't effect WK in any other way. -- For example: -- ["<space>"] = "SPC", -- ["<cr>"] = "RET", -- ["<tab>"] = "TAB", }, icons = { breadcrumb = "»", -- symbol used in the command line area that shows your active key combo separator = "➜", -- symbol used between a key and it's label group = "+", -- symbol prepended to a group }, popup_mappings = { scroll_down = "<c-d>", -- binding to scroll down inside the popup scroll_up = "<c-u>", -- binding to scroll up inside the popup }, window = { border = "rounded", -- none, single, double, shadow position = "bottom", -- bottom, top margin = { 1, 0, 1, 0 }, -- extra window margin [top, right, bottom, left] padding = { 2, 2, 2, 2 }, -- extra window padding [top, right, bottom, left] winblend = 0, }, layout = { height = { min = 4, max = 25 }, -- min and max height of the columns width = { min = 20, max = 50 }, -- min and max width of the columns spacing = 3, -- spacing between columns align = "left", -- align columns left, center or right }, ignore_missing = true, -- enable this to hide mappings for which you didn't specify a label hidden = { "<silent>", "<cmd>", "<Cmd>", "<CR>", "call", "lua", "^:", "^ " }, -- hide mapping boilerplate show_help = true, -- show help message on the command line when the popup is visible triggers = "auto", -- automatically setup triggers -- triggers = {"<leader>"} -- or specify a list manually triggers_blacklist = { -- list of mode / prefixes that should never be hooked by WhichKey -- this is mostly relevant for key maps that start with a native binding -- most people should not need to change this i = { "f", "d" }, v = { "f", "d" }, }, } local opts = { mode = "n", -- NORMAL mode prefix = "<leader>", buffer = nil, -- Global mappings. Specify a buffer number for buffer local mappings silent = true, -- use `silent` when creating keymaps noremap = true, -- use `noremap` when creating keymaps nowait = true, -- use `nowait` when creating keymaps } local mappings = { -- ["/"] = { "<cmd>lua require(\"Comment.api\").toggle_current_linewise()<CR>", "Comment" }, -- ["a"] = { "<cmd>Alpha<cr>", "Alpha" }, -- ["b"] = { -- "<cmd>lua require('telescope.builtin').buffers(require('telescope.themes').get_dropdown{previewer = false})<cr>", -- "Buffers", -- }, -- ["e"] = { "<cmd>NvimTreeToggle<cr>", "Explorer" }, -- ["w"] = { "<cmd>w!<CR>", "Save" }, -- ["q"] = { "<cmd>q!<CR>", "Quit" }, -- ["c"] = { "<cmd>Bdelete!<CR>", "Close Buffer" }, -- ["h"] = { "<cmd>nohlsearch<CR>", "No Highlight" }, -- ["f"] = { -- "<cmd>lua require('telescope.builtin').find_files(require('telescope.themes').get_dropdown{previewer = false})<cr>", -- "Find files", -- }, -- ["F"] = { "<cmd>Telescope live_grep theme=ivy<cr>", "Find Text" }, -- ["P"] = { "<cmd>Telescope projects<cr>", "Projects" }, -- -- p = { -- name = "Packer", -- c = { "<cmd>PackerCompile<cr>", "Compile" }, -- i = { "<cmd>PackerInstall<cr>", "Install" }, -- s = { "<cmd>PackerSync<cr>", "Sync" }, -- S = { "<cmd>PackerStatus<cr>", "Status" }, -- u = { "<cmd>PackerUpdate<cr>", "Update" }, -- }, -- -- g = { -- name = "Git", -- g = { "<cmd>lua _LAZYGIT_TOGGLE()<CR>", "Lazygit" }, -- j = { "<cmd>lua require 'gitsigns'.next_hunk()<cr>", "Next Hunk" }, -- k = { "<cmd>lua require 'gitsigns'.prev_hunk()<cr>", "Prev Hunk" }, -- l = { "<cmd>lua require 'gitsigns'.blame_line()<cr>", "Blame" }, -- p = { "<cmd>lua require 'gitsigns'.preview_hunk()<cr>", "Preview Hunk" }, -- r = { "<cmd>lua require 'gitsigns'.reset_hunk()<cr>", "Reset Hunk" }, -- R = { "<cmd>lua require 'gitsigns'.reset_buffer()<cr>", "Reset Buffer" }, -- s = { "<cmd>lua require 'gitsigns'.stage_hunk()<cr>", "Stage Hunk" }, -- u = { -- "<cmd>lua require 'gitsigns'.undo_stage_hunk()<cr>", -- "Undo Stage Hunk", -- }, -- o = { "<cmd>Telescope git_status<cr>", "Open changed file" }, -- b = { "<cmd>Telescope git_branches<cr>", "Checkout branch" }, -- c = { "<cmd>Telescope git_commits<cr>", "Checkout commit" }, -- d = { -- "<cmd>Gitsigns diffthis HEAD<cr>", -- "Diff", -- }, -- }, -- -- l = { -- name = "LSP", -- a = { "<cmd>lua vim.lsp.buf.code_action()<cr>", "Code Action" }, -- d = { -- "<cmd>Telescope lsp_document_diagnostics<cr>", -- "Document Diagnostics", -- }, -- w = { -- "<cmd>Telescope lsp_workspace_diagnostics<cr>", -- "Workspace Diagnostics", -- }, -- f = { "<cmd>lua vim.lsp.buf.formatting()<cr>", "Format" }, -- i = { "<cmd>LspInfo<cr>", "Info" }, -- I = { "<cmd>LspInstallInfo<cr>", "Installer Info" }, -- j = { -- "<cmd>lua vim.lsp.diagnostic.goto_next()<CR>", -- "Next Diagnostic", -- }, -- k = { -- "<cmd>lua vim.lsp.diagnostic.goto_prev()<cr>", -- "Prev Diagnostic", -- }, -- l = { "<cmd>lua vim.lsp.codelens.run()<cr>", "CodeLens Action" }, -- q = { "<cmd>lua vim.lsp.diagnostic.set_loclist()<cr>", "Quickfix" }, -- r = { "<cmd>lua vim.lsp.buf.rename()<cr>", "Rename" }, -- s = { "<cmd>Telescope lsp_document_symbols<cr>", "Document Symbols" }, -- S = { -- "<cmd>Telescope lsp_dynamic_workspace_symbols<cr>", -- "Workspace Symbols", -- }, -- }, -- s = { -- name = "Search", -- b = { "<cmd>Telescope git_branches<cr>", "Checkout branch" }, -- c = { "<cmd>Telescope colorscheme<cr>", "Colorscheme" }, -- h = { "<cmd>Telescope help_tags<cr>", "Find Help" }, -- M = { "<cmd>Telescope man_pages<cr>", "Man Pages" }, -- r = { "<cmd>Telescope oldfiles<cr>", "Open Recent File" }, -- R = { "<cmd>Telescope registers<cr>", "Registers" }, -- k = { "<cmd>Telescope keymaps<cr>", "Keymaps" }, -- C = { "<cmd>Telescope commands<cr>", "Commands" }, -- }, -- -- t = { -- name = "Terminal", -- n = { "<cmd>lua _NODE_TOGGLE()<cr>", "Node" }, -- u = { "<cmd>lua _NCDU_TOGGLE()<cr>", "NCDU" }, -- t = { "<cmd>lua _HTOP_TOGGLE()<cr>", "Htop" }, -- p = { "<cmd>lua _PYTHON_TOGGLE()<cr>", "Python" }, -- f = { "<cmd>ToggleTerm direction=float<cr>", "Float" }, -- h = { "<cmd>ToggleTerm size=10 direction=horizontal<cr>", "Horizontal" }, -- v = { "<cmd>ToggleTerm size=80 direction=vertical<cr>", "Vertical" }, -- }, -- f = { name = "find", f = { "<cmd>Telescope find_files<cr>", "Find File" }, b = { "<cmd>Telescope buffers<cr>", "Find Buffers" }, r = { "<cmd>Telescope oldfiles<cr>", "Open Recent File" }, g = { "<cmd>Telescope live_grep<cr>", "Grep File" }, n = { "<cmd>:new<cr>", "New File" }, }, j = { name = "jump", w = { "<cmd>HopWord<cr>", "Jump Word" }, j = { "<cmd>HopChar1<cr>", "Jump Char" }, }, l = { name = "LSP", i = { "<cmd>LspInstallInfo<cr>", "Install LanguageServer" }, f = { "<cmd>lua vim.lsp.buf.format({async = true})<cr>", "Format" }, }, w = { "<cmd>:w<cr>", "Write File" }, x = { "<cmd>:x<cr>", "Write And Close File" }, q = { "<cmd>:q<cr>", "Close File" }, e = { "<cmd>:NvimTreeToggle<cr>", "Toggle File Explorer" }, } local vopts = { mode = "v", -- VISUAL mode prefix = "<leader>", buffer = nil, -- Global mappings. Specify a buffer number for buffer local mappings silent = true, -- use `silent` when creating keymaps noremap = true, -- use `noremap` when creating keymaps nowait = true, -- use `nowait` when creating keymaps } local vmappings = { ["/"] = { "<ESC><CMD>lua require(\"Comment.api\").toggle_linewise_op(vim.fn.visualmode())<CR>", "Comment" }, } which_key.setup(setup) which_key.register(mappings, opts) which_key.register(vmappings, vopts)
gpl-2.0
coronalabs/plugins-source-gamenetwork-google
Corona-gemwars/game-logic.lua
1
9365
local self = {} local json = require "json" -- class variables self._spriteSheet = nil self._displayGroup = nil self._listener = nil -- localized variables local DW = display.contentWidth local DH = display.contentHeight self.overlay = nil local globalScale = 1 if display.contentScaleX <= 0.6 then globalScale = 0.5 end self.achievedScore = 0 self.receivedTable = nil self.event = nil self.gemsTable = {} self.gemsTable.moveContent = {} self.gemsTable.moveContent.moves = {} for i = 1, 8 do self.gemsTable.moveContent.moves[ i ] = {} end local numberOfMarkedToDestroy = 0 local gemToBeDestroyed -- used as a placeholder local isGemTouchEnabled = true -- blocker for double touching gems -- forward declaration local onGemTouch self.init = function( iSheet, displayGroup, listener ) self._displayGroup = displayGroup self._spriteSheet = iSheet local screenWidth = display.contentWidth - (display.screenOriginX*2) local screenRealWidth = screenWidth / display.contentScaleX local screenHeight = display.contentHeight - (display.screenOriginY*2) local screenRealHeight = screenHeight / display.contentScaleY local bg = display.newImage( iSheet ,1) bg:setReferencePoint( display.CenterReferencePoint ) bg.x = display.contentWidth * 0.5 bg.y = display.contentHeight * 0.5 bg.xScale, bg.yScale = globalScale, globalScale displayGroup:insert( bg ) self.overlay = display.newRect( 0, 0, display.contentWidth, display.contentHeight ) self.overlay.alpha = 0.01 displayGroup:insert ( self.overlay ) -- prevent propagation of touch events self.overlay:addEventListener("touch", function() return true end) self.overlay:addEventListener("tap", function() return true end) self._listener = listener end self.newGem = function( i, j ) local newGem local R = math.random( 2,5 ) newGem = display.newImage( self._spriteSheet ,R) newGem:setReferencePoint( display.CenterReferencePoint ) newGem.x = i*40-20 newGem.y = j*40+60 newGem.xScale, newGem.yScale = 0.1, 0.1 newGem.rotation = 45 newGem.i = i newGem.j = j newGem.isMarkedToDestroy = false if R == 4 then newGem.gemType = "red" self.gemsTable.moveContent.moves[i][j] = "red" elseif R == 3 then newGem.gemType = "green" self.gemsTable.moveContent.moves[i][j] = "green" elseif R == 2 then newGem.gemType = "blue" self.gemsTable.moveContent.moves[i][j] = "blue" elseif R == 5 then newGem.gemType = "yellow" self.gemsTable.moveContent.moves[i][j] = "yellow" end --new gem falling animation transition.to( newGem, { time=100, xScale = globalScale * 0.8, yScale = globalScale * 0.8} ) self._displayGroup:insert( newGem ) newGem.touch = onGemTouch newGem:addEventListener( "touch", newGem ) return newGem end self.gatherTableState = function() for i = 1, 8, 1 do for j = 1, 8, 1 do self.gemsTable.moveContent.moves[i][j] = self.gemsTable[i][j].gemType end end end self.newMoveGem = function( i, j, color ) local newGem local R = 0 if color == "red" then R = 4 elseif color == "green" then R = 3 elseif color == "blue" then R = 2 elseif color == "yellow" then R = 5 end newGem = display.newImage( self._spriteSheet ,R) newGem:setReferencePoint( display.CenterReferencePoint ) newGem.x = i*40-20 newGem.y = j*40+60 newGem.xScale, newGem.yScale = 0.1, 0.1 newGem.rotation = 45 newGem.i = i newGem.j = j newGem.isMarkedToDestroy = false newGem.gemType = color self.gemsTable.moveContent.moves[i][j] = color --new gem falling animation transition.to( newGem, { time=100, xScale = globalScale * 0.8, yScale = globalScale * 0.8} ) self._displayGroup:insert( newGem ) newGem.touch = onGemTouch newGem:addEventListener( "touch", newGem ) return newGem end self.initTable = function( content ) for i = 1, 8, 1 do self.gemsTable[i] = {} for j = 1, 8, 1 do --print("Move: ", content.moves[i][j]) self.gemsTable[i][j] = self.newMoveGem( i,j, content.moves[ i ][ j ] ) end end self.overlay:toFront() end self.redrawTable = function() for i = 1, 8, 1 do for j = 1, 8, 1 do --print("Move: ", self.receivedTable[i][j]) if (self.gemsTable[i][j].gemType ~= self.receivedTable[i][j]) then self.gemsTable[i][j]:removeSelf() self.gemsTable[i][j] = self.newMoveGem( i,j, self.receivedTable[ i ][ j ] ) end end end self.receivedTable = nil self.overlay:toFront() end self.shiftGems = function() print ("Shifting Gems") --print("generated table: ", json.encode( self.gemsTable.moveContent.moves ) ) -- first roww for i = 1, 8, 1 do if self.gemsTable[i][1].isMarkedToDestroy then -- current gem must go to a 'gemToBeDestroyed' variable holder to prevent memory leaks -- cannot destroy it now as gemsTable will be sorted and elements moved down gemToBeDestroyed = self.gemsTable[i][1] self.gemsTable[i][1] = self.newGem(i,1, self._spriteSheet, self._displayGroup) -- destroy old gem gemToBeDestroyed:removeSelf() gemToBeDestroyed = nil end end -- rest of the rows for j = 2, 8, 1 do -- j = row number - need to do like this it needs to be checked row by row for i = 1, 8, 1 do if self.gemsTable[i][j].isMarkedToDestroy then --if you find and empty hole then shift down all gems in column gemToBeDestroyed = self.gemsTable[i][j] -- shiftin whole column down, element by element in one column for k = j, 2, -1 do -- starting from bottom - finishing at the second row -- curent markedToDestroy Gem is replaced by the one above in the gemsTable self.gemsTable[i][k] = self.gemsTable[i][k-1] self.gemsTable[i][k].y = self.gemsTable[i][k].y +40 transition.to( self.gemsTable[i][k], { time=0, y= self.gemsTable[i][k].y} ) -- we change its j value as it has been 'moved down' in the gemsTable self.gemsTable[i][k].j = self.gemsTable[i][k].j + 1 end -- create a new gem at the first row as there is en ampty space due to gems -- that have been moved in the column self.gemsTable[i][1] = self.newGem(i,1, self._spriteSheet, self._displayGroup) -- destroy the old gem (the one that was invisible and placed in gemToBeDestroyed holder) gemToBeDestroyed:removeSelf() gemToBeDestroyed = nil end end end self.gatherTableState() --print("generated table after switching: ", json.encode( self.gemsTable.moveContent.moves ) ) self.overlay:toFront() end --shiftGems() self.markToDestroy = function( gem ) gem.isMarkedToDestroy = true numberOfMarkedToDestroy = numberOfMarkedToDestroy + 1 -- check on the left if gem.i>1 then if (self.gemsTable[gem.i-1][gem.j]).isMarkedToDestroy == false then if (self.gemsTable[gem.i-1][gem.j]).gemType == gem.gemType then self.markToDestroy( self.gemsTable[gem.i-1][gem.j] ) end end end -- check on the right if gem.i<8 then if (self.gemsTable[gem.i+1][gem.j]).isMarkedToDestroy == false then if (self.gemsTable[gem.i+1][gem.j]).gemType == gem.gemType then self.markToDestroy( self.gemsTable[gem.i+1][gem.j] ) end end end -- check above if gem.j>1 then if (self.gemsTable[gem.i][gem.j-1]).isMarkedToDestroy == false then if (self.gemsTable[gem.i][gem.j-1]).gemType == gem.gemType then self.markToDestroy( self.gemsTable[gem.i][gem.j-1] ) end end end -- check below if gem.j<8 then if (self.gemsTable[gem.i][gem.j+1]).isMarkedToDestroy== false then if (self.gemsTable[gem.i][gem.j+1]).gemType == gem.gemType then self.markToDestroy( self.gemsTable[gem.i][gem.j+1] ) end end end end local function sendData() self._listener( self.event ) self.event = nil print("triggered") end local function sendEvent() print("start event") timer.performWithDelay(600, sendData) end function onGemTouch( gem, event ) -- was pre-declared if event.phase == "began" and isGemTouchEnabled then print("Gem touched i= "..gem.i.." j= "..gem.j) self.markToDestroy(gem) if numberOfMarkedToDestroy >= 3 then self.destroyGems() self.event = {} self.event.name = "gemTapped" self.event.params = { gem.i, gem.j, self.achievedScore } sendEvent() self.achievedScore = 0 else self.cleanUpGems() end end return true end self.enableGemTouch = function() isGemTouchEnabled = true end self.destroyGems = function() print ("Destroying Gems. Marked to Destroy = "..numberOfMarkedToDestroy) for i = 1, 8, 1 do for j = 1, 8, 1 do isGemTouchEnabled = false if self.gemsTable[i][j].isMarkedToDestroy then transition.to( self.gemsTable[i][j], { time=250, alpha=0, xScale=0.1, onComplete=self.enableGemTouch } ) -- update score self.achievedScore = self.achievedScore + 50 end end end numberOfMarkedToDestroy = 0 timer.performWithDelay( 300, self.shiftGems ) end self.cleanUpGems = function() print("Cleaning Up Gems") numberOfMarkedToDestroy = 0 for i = 1, 8, 1 do for j = 1, 8, 1 do -- show that there is not enough if self.gemsTable[i][j].isMarkedToDestroy then transition.to( self.gemsTable[i][j], { time=100, xScale=globalScale, yScale = globalScale } ) transition.to( self.gemsTable[i][j], { time=100, delay=100, xScale=globalScale * 0.8, yScale = globalScale * 0.8} ) end self.gemsTable[i][j].isMarkedToDestroy = false end end end return self
mit
SLAPaper/MCGC
MCGC/ygoLib.lua
2
78200
-- =====debug类===== Debug = { } function Debug.AddCard(code, owner, player, location, seq, pos, proc) -- 添加卡片,将卡号为code的卡片的持有者设置为owner,以表示形式pos放置在player的场上位于location上序号为seq的格子处 -- 【必须】 --[[ int code int owner int player int location int seq int pos --]] -- 【可选】 --[[ bool proc = false proc = true则解除苏生限制 --]] -- 【返回】添加的Card对象 end function Debug.Message(any) -- 输出调试信息 end function Debug.PreAddCounter(c, counter_type, count) -- 为c添加count个counter_type的指示物 -- 【必须】 --[[ Card c int counter_type int count --]] end function Debug.PreEquip(equip_card, target) -- 为target添加装备equip_card -- 【必须】 --[[ Card equip_card Card target --]] -- 【返回】bool类型(?) end function Debug.PreSetTarget(c, target) -- 把target选为c的永续对象 -- 【必须】 --[[ Card c Card target --]] end function Debug.ReloadFieldBegin(flag) -- 以选项flag开始布局 -- 【必须】 --[[ int flag flag of 残局:DUEL_ATTACK_FIRST_TURN + DUEL_SIMPLE_AI --]] end function Debug.ReloadFieldEnd() -- 布局结束 end function Debug.SetAIName(name) -- 设置AI的名字 -- 【必须】 --[[ string name --]] end function Debug.SetPlayerInfo(playerid, lp, startcount, drawcount) -- 设置玩家信息,基本分为lp,初始手卡为startcount张,每回合抽drawcount张 -- 【必须】 --[[ int playerid playerid 下方 0,上方 1 int lp int startcount int drawcount --]] end function Debug.PreSummon(c, sum_type, sum_location) -- 设置卡片c的召唤信息:以sum_type方法(通常召唤、特殊召唤等)[从sum_location]出场 -- 【必须】 --[[ Card c int sum_type --]] -- 【可选】 --[[ int sum_location = 0 ]] end function Debug.ShowHint(msg) -- 显示提示窗口 -- 【必须】 --[[ string msg --]] end -- =====bit类===== bit = { } function bit.band(a, b) -- a与b的位与 end function bit.bor(a, b) -- a与b的位或 end function bit.bxor(a, b) -- a与b的位异或 end function bit.lshift(a, b) -- a左移b end function bit.rshift(a, b) -- a右移b end -- =====Card类===== Card = { } -- 属性 Card.material_count = 0 -- 融合素材的数量 Card.material = 0 -- 融合素材的数组,内容为卡片ID -- 方法 function Card.GetCode(c) -- 返回c的当前代号(可能因为效果改变) -- 【返回】 --[[ int int --]] end function Card.GetOriginalCode(c) -- 返回c的卡片记载的代号 end function Card.GetOriginalCodeRule(c) -- 返回c规则上的代号(这张卡规则上当作...使用) -- 【返回】 --[[ int int --]] end function Card.GetFusionCode(c) -- 返回c作为融合素材时的卡号(包括c原本的卡号) -- 【返回】 --[[ int int ... --]] end function Card.IsFusionCode(c, code) -- 检查c作为融合素材时能否当作卡号为code的卡 end function Card.IsSetCard(c, setname) -- 检查c是否是名字含有setname的卡 end function Card.IsPreviousSetCard(c, setname) -- 检查c位置变化之前是否是名字含有setname的卡 end function Card.IsFusionSetCard(c, setname) -- 检查c作为融合素材时能否当作名字含有setname的卡 end function Card.GetType(c) -- 返回c的当前类型。 end function Card.GetOriginalType(c) -- 返回c的卡片记载的类型。 end function Card.GetLevel(c) -- 返回c的当前等级 end function Card.GetRank(c) -- 返回c的当前阶级 end function Card.GetSynchroLevel(c, sc) -- 返回c在用于同调召唤sc时的同调用等级。此函数除了某些特定卡如调节支援士,返回值与Card.GetLevel(c)相同 end function Card.GetRitualLevel(c, rc) -- 返回c在用于仪式召唤rc时的仪式解放等级。此函数除了某些特定卡如仪式供物,返回值与Card.GetLevel(c)相同 end function Card.GetOriginalLevel(c) -- 返回c的卡片记载的等级 end function Card.GetOriginalRank(c) -- 返回c的卡片记载的阶级 end function Card.IsXyzLevel(c, xyzc, lv) -- 检查c对于超量怪兽xyzc的超量用等级是否是lv end function Card.GetLeftScale(c) -- 返回c的左灵摆刻度 end function Card.GetOriginalLeftScale(c) -- 返回c的原本的左灵摆刻度 end function Card.GetRightScale(c) -- 返回c的右灵摆刻度 end function Card.GetOriginalRightScale(c) -- 返回c的原本的右灵摆刻度 end function Card.GetAttribute(c) -- 返回c的当前属性。注:对某些多属性怪物如光与暗之龙,此函数的返回值可能是几个属性的组合值。 end function Card.GetOriginalAttribute(c) -- 返回c的卡片记载的属性 end function Card.GetRace(c) -- 返回c的当前种族。注:对某些多种族怪物如动画效果的魔术猿,此函数的返回值可能是几个种族的组合值。 end function Card.GetOriginalRace(c) -- 返回c的卡片记载的种族 end function Card.GetAttack(c) -- 返回c的当前攻击力,返回值是负数表示是"?" end function Card.GetBaseAttack(c) -- 返回c的原本攻击力 end function Card.GetTextAttack(c) -- 返回c的卡片记载的攻击力 end function Card.GetDefense(c) -- 返回c的当前守备力,返回值是负数表示是"?" end function Card.GetBaseDefense(c) -- 返回c的原本守备力 end function Card.GetTextDefense(c) -- 返回c的卡片记载的守备力 end function Card.GetPreviousCodeOnField(c) -- 返回c位置变化之前的卡号 end function Card.GetPreviousTypeOnField(c) -- 返回c位置变化之前的类型 end function Card.GetPreviousLevelOnField(c) -- 返回c位置变化之前的等级 end function Card.GetPreviousRankOnField(c) -- 返回c位置变化之前的阶级 end function Card.GetPreviousAttributeOnField(c) -- 返回c位置变化之前的属性 end function Card.GetPreviousRaceOnField(c) -- 返回c位置变化之前的种族 end function Card.GetPreviousAttackOnField(c) -- 返回c位置变化之前的攻击力 end function Card.GetPreviousDefenseOnField(c) -- 返回c位置变化之前的守备力 end function Card.GetOwner(c) -- 返回c的持有者 end function Card.GetControler(c) -- 返回c的当前控制者 end function Card.GetPreviousControler(c) -- 返回c的位置变化之前的控制者 end function Card.GetReason(c) -- 返回c的位置变化原因 end function Card.GetReasonCard(c) -- 返回导致c的位置变化的卡。此函数仅在某卡被战斗破坏时,因为上级召唤被解放,或者成为特殊召唤使用的素材时有效。 end function Card.GetReasonPlayer(c) -- 返回导致c的位置变化的玩家 end function Card.GetReasonEffect(c) -- 返回导致c的位置变化的效果。 end function Card.GetPosition(c) -- 返回c当前的表示形式 end function Card.GetPreviousPosition(c) -- 返回c位置变化前的表示形式 end function Card.GetBattlePosition(c) -- 返回c在本次战斗发生之前的表示形式 end function Card.GetLocation(c) -- 返回c当前的所在位置 end function Card.GetPreviousLocation(c) -- 返回c位置变化前的所在的位置 end function Card.GetSequence(c) --[[返回c在当前位置的序号 在场上时,序号代表所在的格子,从左往右分别是0-4,场地魔法格的序号为5 在其它地方时,序号表示的是第几张卡。最底下的卡的序号为0]] end function Card.GetPreviousSequence(c) -- 返回c位置变化前的序号 end function Card.GetSummonType(c) -- 返回c上场的方式。 end function Card.GetSummonLocation(c) -- 返回c的召唤位置 end function Card.GetSummonPlayer(c) -- 返回召唤,特殊召唤c上场的玩家 end function Card.GetDestination(c) -- 返回c位置变化的目的地。此函数仅在处理位置转移代替效果时有效。 end function Card.GetLeaveFieldDest(c) -- 返回c离场时因改变去向的效果(如大宇宙)的目的地 end function Card.GetTurnID(c) -- 返回c转移到当前位置的回合 end function Card.GetFieldID(c) -- 返回c转移到当前位置的时间标识。此数值唯一,越小表示c是越早出现在那个位置。 end function Card.GetRealFieldID(c) -- 返回c转移到当前位置的真实的时间标识 end function Card.IsCode(c, code1, code2) -- 检查c的代号是否是code1[或者为code2]。 end function Card.IsType(c, type) -- 检查c是否属于类型type。 end function Card.IsRace(c, race) -- 检查c是否属于种族race。 end function Card.IsAttribute(c, attribute) -- 检查c是否属于属性attribute。 end function Card.IsReason(c, reason) -- 检查c是否包含原因reason。 end function Card.IsStatus(c, status) -- 检查c是否包含某个状态码。 end function Card.IsNotTuner(c) -- 检查c是否可以当成非调整来使用。 end function Card.SetStatus(c, state, enable) -- 给c设置或者取消状态码。除非妳清楚的了解每个状态码的含意,否则不要轻易使用此函数。 end function Card.IsDualState(c) -- 检查c属否处于再召唤状态。 end function Card.EnableDualState(c) -- 把c设置成再召唤状态。 end function Card.SetTurnCounter(c, counter) -- 设置c的回合计数器(光之护封剑等) end function Card.GetTurnCounter(c) -- 返回c的回合计数器 end function Card.SetCustomValue(c, tag, object) -- 以tag作为标签为c设置一个自定义值object end function Card.GetCustomValue(c, tag) -- 返回c的以tag作为标签的自定义值 end function Card.SetMaterial(c, g) -- 把g中的所有卡作为c的素材(上级召唤,特殊召唤) end function Card.GetMaterial(c) -- 返回c出场使用的素材 end function Card.GetMaterialCount(c) -- 返回c出场使用的素材数量 end function Card.GetEquipGroup(c) -- 返回c当前装备着的卡片组 end function Card.GetEquipCount(c) -- 返回c当前装备着的卡片数量 end function Card.GetEquipTarget(c) -- 返回c当前的装备对象 end function Card.CheckEquipTarget(c1, c2) -- 检查c2是否是c1的正确的装备对象 end function Card.GetUnionCount(c) -- 返回c当前装备的同盟卡数量 end function Card.GetOverlayGroup(c) -- 返回c当前叠放着的卡片组 end function Card.GetOverlayCount(c) -- 返回c当前叠放着的卡片数量 end function Card.GetOverlayTarget(c) -- 返回以c为超量素材的卡 end function Card.CheckRemoveOverlayCard(c, player, count, reason) -- 检查玩家player能否以reason为原因,至少移除c叠放的count张卡 end function Card.RemoveOverlayCard(c, player, min, max, reason) -- 以reason为原因,让玩家player移除c叠放的min-max张卡,返回值表示是否成功 end function Card.GetAttackedGroup(c) -- 返回c本回合攻击过的卡片组 end function Card.GetAttackedGroupCount(c) -- 返回c本回合攻击过的卡片数量 end function Card.GetAttackedCount(c) -- 返回c本回合攻击过的次数 -- 注:如果此值与上一个函数的返回值不同,那么说明此卡本回合进行过直接攻击 end function Card.GetBattledGroup(c) -- 返回与c本回合进行过战斗的卡片组 -- 进行过战斗指发生过伤害的计算。用于剑斗兽等卡的判定。 end function Card.GetBattledGroupCount(c) -- 返回与c本回合进行过战斗的的卡片数量 end function Card.GetAttackAnnouncedCount(c) -- 返回c本回合攻击宣言的次数 -- 注:攻击被无效不会被计入攻击过的次数,但是会计入攻击宣言的次数。 end function Card.IsDirectAttacked(c) -- 检查c是否直接攻击过 end function Card.SetCardTarget(c1, c2) -- 把c2作为c1的永续对象。 -- c1和c2的联系会在c1活c2任意一卡离场或变成里侧表示时reset。 end function Card.GetCardTarget(c) -- 返回c当前所有的永续对象 end function Card.GetFirstCardTarget(c) -- 返回c当前第一个永续对象 end function Card.GetCardTargetCount(c) -- 返回c当前的永续对象的数量 end function Card.IsHasCardTarget(c1, c2) -- 检查c1是否取c2为永续对象 end function Card.CancelCardTarget(c1, c2) -- 取消c2为c1的永续对象 end function Card.GetOwnerTarget(c) -- 返回取c作为永续对象的所有卡 end function Card.GetOwnerTargetCount(c) -- 返回取c作为永续对象的卡的数量 end function Card.GetActivateEffect(c) -- 返回c的“卡片发动”的效果。仅对魔法和陷阱有效。 end function Card.CheckActivateEffect(c, neglect_con, neglect_cost, copy_info) -- 返回c的可以发动时机正确的“卡的发动”的效果,neglect_con=true则无视发动条件,neglect_cost=true则无视发动cost -- copy_info=false或者自由时点的效果则只返回这个效果 -- 否则还返回这个效果的时点为code的触发时点的信息 eg,ep,ev,re,r,rp end function Card.RegisterEffect(c, e, forced) -- 把效果e注册给c,返回效果的全局id。 -- 默认情况下注册时如果c带有免疫e的效果那么注册会失败。如果forced为true则不会检查c对e的免疫效果。 end function Card.IsHasEffect(c, code) -- 检查c是否受到效果种类是code的效果的影响 end function Card.ResetEffect(c, id, reset_type) -- 以重置类型为reset_type、重置种类为id手动重置c受到的效果的影响 -- 重置类型只能是以下类型,对应的重置种类为 -- RESET_EVENT 发生事件重置 id为事件 -- RESET_PHASE 阶段结束重置 id为阶段 -- RESET_CODE 重置指定code的效果 id为效果的种类code,只能重置EFFECT_TYPE_SINGLE的永续型效果 -- RESET_COPY 重置复制的效果 id为copy_id -- RESET_CARD 重置卡片的效果 id为效果owner的卡号 end function Card.GetEffectCount(c, code) -- 返回c受到影响的种类是code的效果的数量 end function Card.RegisterFlagEffect(c, code, reset_flag, property, reset_count) -- 为c注册一个标识用效果。 -- 注:注册给卡的标识用效果不会用于系统,即使code与内置效果code重合也不会影响,并且类型总是EFFECT_TYPE_SINGLE。reset方法,property和一般的效果相同,并且不会无效化,不受卡的免疫效果影响。 end function Card.GetFlagEffect(c, code) -- 返回c的种类是code的标识效果的数量。 end function Card.ResetFlagEffect(c, code) -- 手动清除c的种类是code的标识效果。 end function Card.SetFlagEffectLabel(c, code, label) -- 返回c是否存在种类为code的标识效果,并设置其Label属性为label end function Card.GetFlagEffectLabel(c, code) -- 返回c的种类为code的标识效果的Label,没有此效果则返回nil end function Card.CreateRelation(c1, c2, reset_flag) -- 为c1建立于c2的联系。此联系仅会由于RESET_EVENT的事件reset。 end function Card.ReleaseRelation(c1, c2) -- 手动释放c1对于c2的联系 end function Card.CreateEffectRelation(c, e) -- 为卡片c和效果e建立联系 end function Card.ReleaseEffectRelation(c, e) -- 手动释放c与效果e的联系 end function Card.ClearEffectRelation(c) -- 清空c所有联系的效果 end function Card.IsRelateToEffect(c, e) -- 检查c是否和效果e有联系。 -- 注:每次发动进入连锁的效果时,发动效果的卡,以及发动效果时指定的对象(用Duel.SetTargetCard或者Duel.SelectTarget指定的,包括取对象和不取对象)会自动与那个效果建立联系。一旦离场,联系会重置。 end function Card.IsRelateToChain(c, chainc) -- 检查c是否和连锁chainc有联系 -- 注:每次发动进入连锁的效果时,发动效果的卡,以及发动效果时指定的对象(用Duel.SetTargetCard或者Duel.SelectTarget指定的,包括取对象和不取对象)会自动与那个效果建立联系。一旦离场,联系会重置。 end function Card.IsRelateToCard(c1, c2) -- 检查c1是否和c2有联系。 end function Card.IsRelateToBattle(c) -- 检查c是否和本次战斗关联。 -- 注:此效果通常用于伤害计算后伤害阶段结束前,用于检查战斗的卡是否离场过。 end function Card.CopyEffect(c, code, reset_flag, reset_count) -- 为c添加代号是code的卡的可复制的效果,并且添加额外的reset条件。 -- 返回值是表示复制效果的代号id。 end function Card.ReplaceEffect(c, code, reset_flag, reset_count) -- 把c的效果替换为卡号是code的卡的效果,并且添加额外的reset条件 -- 返回值是表示替换效果的代号id end function Card.EnableUnsummonable(c) -- 将c设置为不可通常召唤的怪兽 -- 实际上是个不可复制、不会被无效的EFFECT_UNSUMMONABLE_CARD效果 end function Card.EnableReviveLimit(c) -- 为c添加苏生限制。 -- 实际上是不可复制、不会被无效的EFFECT_UNSUMMONABLE_CARD和EFFECT_REVIVE_LIMIT效果 end function Card.CompleteProcedure(c) -- 使c完成正规的召唤手续。此函数也可通过Card.SetStatus实现。 end function Card.IsDisabled(c) -- 检查c是否处于无效状态 end function Card.IsDestructable(c) -- 检查c是否是可破坏的。 -- 注:不可破坏指的是类似场地护罩,宫廷的规矩等“破壊できない”的效果 end function Card.IsSummonableCard(c) -- 检查c是否是可通常召唤的卡。 end function Card.IsSpecialSummonable(c) -- 检查是否可以对c进行特殊召唤手续。 end function Card.IsSynchroSummonable(c, tuner) -- 检查是否可以以tuner作为调整对c进行同调召唤手续。如果tuner是nil,此函数与上一个函数作用相同。 end function Card.IsXyzSummonable(c, mg, min, max) -- 检查是否可以在mg中选出[min-max个]超量素材对c进行超量召唤手续 -- 如果mg为nil,此函数与Card.IsSpecialSummonable作用相同 end function Card.IsSummonable(c, ignore_count, e, minc) -- 检查c是否进行通常召唤(不包含通常召唤的set),ignore_count=true则不检查召唤次数限制 -- e~=nil则检查c是否可以以效果e进行通常召唤,minc表示至少需要的祭品数(用于区分妥协召唤与上级召唤) end function Card.IsMSetable(c, ignore_count, e, minc) -- 检查c是否可进行通常召唤的set,ignore_count=true则不检查召唤次数限制 -- e~=nil则检查c是否可以以效果e进行通常召唤的set,minc表示至少需要的祭品数(用于区分妥协召唤set与上级召唤set) end function Card.IsSSetable(c, ignore_field) -- 检查c是否可以set到魔法陷阱区,ignore_field=true则无视魔陷区格子限制 end function Card.IsCanBeSpecialSummoned(c, e, sumtype, sumplayer, nocheck, nolimit, sumpos, target_player) -- 检查c是否可以被玩家sumplayer用效果e以sumtype方式和sumpos表示形式特殊召唤到target_player场上 -- 如果nocheck是true则不检查c的召唤条件,如果nolimit是true则不检查c的苏生限制 -- sumpos默认为POS_FACEUP, target_player默认为sumplayer end function Card.IsAbleToHand(c) -- 检查c是否可以送去手牌。 -- 注:仅当卡片或者玩家受到“不能加入手牌”的效果的影响时(如雷王)此函数才返回false。以下几个函数类似。 end function Card.IsAbleToDeck(c) -- 检查c是否可以送去卡组。 end function Card.IsAbleToExtra(c) -- 检查c是否可以送去额外卡组。 -- 对于非融合,同调,超量卡此函数均返回false。 end function Card.IsAbleToGrave(c) -- 检查c是否可以送去墓地。 end function Card.IsAbleToRemove(c, player) -- 检查c是否可以被玩家player除外 end function Card.IsAbleToHandAsCost(c) -- 检查c是否可以作为cost送去手牌。 -- 注:此函数会在Card.IsAbleToHand的基础上追加检测c的实际目的地。 -- 当c送往手牌会被送去其它地方时(如缩退回路适用中,或者c是融合,同调和超量怪的一种),此函数返回false。 -- 以下几个函数类似。 end function Card.IsAbleToDeckAsCost(c) -- 检查c是否可以作为cost送去卡组。 end function Card.IsAbleToExtraAsCost(c) -- 检查c是否可以作为cost送去额外卡组。 end function Card.IsAbleToDeckOrExtraAsCost(c) -- 检查c是否可以作为cost送去卡组或额外卡组(用于接触融合的召唤手续检测) end function Card.IsAbleToGraveAsCost(c) -- 检查c是否可以作为cost送去墓地。 end function Card.IsAbleToRemoveAsCost(c) -- 检查c是否可以作为cost除外。 end function Card.IsReleaseable(c) -- 检查c是否可以解放(非上级召唤用) end function Card.IsReleasableByEffect(c) -- 检查c是否可以被效果解放 end function Card.IsDiscardable(c) -- 检查c是否可以丢弃 -- 注:此函数仅用于检测,以REASON_DISCARD作为原因把一张手卡送墓并不会导致那张卡不能丢弃。 end function Card.IsAttackable(c) -- 检查c是否可以攻击 end function Card.IsChainAttackable(c) -- 检查c是否可以连续攻击 -- 注:当c因为闪光之双剑等效果进行过多次攻击之后此函数返回false。 end function Card.IsFaceup(c) -- 检查c是否是表侧表示 end function Card.IsAttackPos(c) -- 检查c是否是攻击表示 end function Card.IsFacedown(c) -- 检查c是否是里侧表示 end function Card.IsDefensePos(c) -- 检查c是否是守备表示 end function Card.IsPosition(c, pos) -- 检查c是否是表示形式pos end function Card.IsPreviousPosition(c, pos) -- 检查c位置变化之前是否是表示形式pos end function Card.IsControler(c, controler) -- 检查c的当前控制着是否是controler end function Card.IsOnField(c) -- 检查c是否在场。 -- 注:当怪物召唤,反转召唤,特殊召唤时召唤成功之前,此函数返回false end function Card.IsLocation(c, location) -- 检查c当前位置是否是location。 -- 注:当怪物召唤,反转召唤,特殊召唤时召唤成功之前,并且loc=LOCATION_MZONE时,此函数返回false end function Card.IsPreviousLocation(c, location) -- 检查c之前的位置是否是location end function Card.IsLevelBelow(c, level) -- 检查c是否是等级level以下(至少为1) end function Card.IsLevelAbove(c, level) -- 检查c是否是等级level以上 end function Card.IsRankBelow(c, rank) -- 检查c是否是阶级rank以下(至少为1) end function Card.IsRankAbove(c, rank) -- 检查c是否是阶级rank以上 end function Card.IsAttackBelow(c, atk) -- 检查c是否是攻击力atk以下(至少为0) end function Card.IsAttackAbove(c, atk) -- 检查c是否是攻击力atk以上 end function Card.IsDefenseBelow(c, def) -- 检查c是否是守备力def以下(至少为0) end function Card.IsDefenseAbove(c, def) -- 检查c是否是守备力def以上 end function Card.IsPublic(c) -- 检查c是否处于公开状态 end function Card.IsForbidden(c) -- 检查c是否处于被宣言禁止状态 end function Card.IsAbleToChangeControler(c) -- 检查c是否可以改变控制权 -- 注:仅当卡收到了“不能改变控制权”的效果的影响时,此函数返回false end function Card.IsControlerCanBeChanged(c) -- 检查c的控制权是否可以改变 -- 注:此函数会在上一个函数的基础上追加检测场上的空格位 end function Card.AddCounter(c, countertype, count, singly) -- 为c放置count个countertype类型的指示物 -- singly为true表示逐个添加至上限为止 end function Card.RemoveCounter(c, player, countertype, count, reason) -- 让玩家player以原因reason移除c上的count个countertype类型的指示物 end function Card.GetCounter(c, countertype) -- 返回c上的countertype类型的指示物的数量 end function Card.EnableCounterPermit(c, countertype, location) -- 允许c[在位置location]放置那个需要"可以放置"才能放置的指示物countertype -- location的默认值与c的种类有关,灵摆怪兽需要指定能否在怪兽区域或灵摆区域放置指示物 end function Card.SetCounterLimit(c, countertype, count) -- 设定c放置countertype类型指示物的上限 end function Card.IsCanTurnSet(c) -- 检查c是否可以转成里侧表示。 end function Card.IsCanAddCounter(c, countertype, count, singly) -- 检查c是否可以[逐个(singly=true)]放置count个countertype类型的指示物 end function Card.IsCanRemoveCounter(c, player, countertype, count, reason) -- 检查玩家player是否可以以原因reason移除c上的count个countertype类型的指示物 end function Card.IsCanBeFusionMaterial(c, fc, ignore_mon) -- 检查c是否可以成为[融合怪兽fc的]融合素材,ignore_mon=true则不检查c是否是怪兽 end function Card.IsCanBeSynchroMaterial(c, sc, tuner) -- 检查c是否可以成为同调怪兽sc的同调素材 end function Card.IsCanBeRitualMaterial(c, sc) -- 检查c是否能作为仪式怪兽sc的祭品 end function Card.IsCanBeXyzMaterial(c, sc) -- 检查c是否可以成为超量怪兽sc的超量素材 end function Card.CheckFusionMaterial(c, g, gc, chkf) -- 检查g是否包含了c需要[必须包含gc在内]的一组融合素材 -- 根据c的种类为EFFECT_FUSION_MATERIAL的效果的Condition函数检查 end function Card.CheckFusionSubstitute(c, fc) -- 检查c能否代替融合怪兽fc的记述卡名的素材 end function Card.IsImmuneToEffect(c, e) -- 检查c是否免疫效果e(即不受效果e的影响) end function Card.IsCanBeEffectTarget(c, e) -- 检查c是否可以成为效果e的对象 end function Card.IsCanBeBattleTarget(c1, c2) -- 检查c1是否可以成为c2的攻击目标 end function Card.AddTrapMonsterAttribute(c, attribute, race, level, atk, def) -- 为魔陷卡c添加怪兽数值 -- 在数据库中有记录的数值视为原本数值,此处设置为0 end function Card.TrapMonsterComplete(c, extra_type) -- 使陷阱怪兽c占用一个魔法陷阱格子,并添加extra_type怪兽类型 -- 注:陷阱怪兽属性指的是同时作为怪兽和陷阱,并且额外使一个魔法陷阱的格子不能使用 end function Card.CancelToGrave(c, cancel) -- 取消送墓确定状态,cancel=false则重新设置送墓确定状态 --[[注:送墓确定状态指的是在场上发动的不留场的魔法和陷阱后,这些卡片的状态。 送墓确定状态中的卡无法返回手牌和卡组,并且连锁结束时送去墓地。 此函数的作用是取消此状态使其留场。用于光之护封剑和废铁稻草人等卡。]] end function Card.GetTributeRequirement(c) -- 返回通常召唤c所需要的祭品的最小和最大数量 end function Card.GetBattleTarget(c) -- 返回与c进行战斗的卡 end function Card.GetAttackableTarget(c) -- 返回c可攻击的卡片组g和能否直接攻击的布尔值b end function Card.SetHint(c, type, value) -- 为c设置类型为type的卡片提示信息 -- type只能为以下值,对应的value类型为 -- CHINT_TURN 回合数 -- CHINT_CARD 卡片id -- CHINT_RACE 种族 -- CHINT_ATTRIBUTE 属性 -- CHINT_NUMBER 数字 -- CHINT_DESC 描述 end function Card.ReverseInDeck(c) -- 设置c在卡组中正面表示 end function Card.SetUniqueOnField(c, s, o, unique_code, unique_location) -- 设置c以unique_code只能在场上[或怪兽区域或魔陷区域,由unique_location决定]只能存在1张 -- s不为0会检查自己场上的唯一性,o不为0则检查对方场上的唯一性 -- unique_location默认为 LOCATION_ONFIELD end function Card.CheckUniqueOnField(c, check_player) -- 检查c在check_player场上的唯一性 end function Card.ResetNegateEffect(c, code1, ...) -- 重置c受到的卡号为code1, code2...的卡片的效果的影响 end function Card.AssumeProperty(c, assume_type, assume_value) -- 把c的assume_type的数值当作assume_value使用(基因组斗士) -- assume_type为以下类型 -- ASSUME_CODE 卡号 -- ASSUME_TYPE 类型 -- ASSUME_LEVEL 等级 -- ASSUME_RANK 阶级 -- ASSUME_ATTRIBUTE 属性 -- ASSUME_RACE 种族 -- ASSUME_ATTACK 攻击力 -- ASSUME_DEFENSE 守备力 end function Card.SetSPSummonOnce(c, spsummon_code) -- 设置c一回合只能进行1次特殊召唤(灵兽,波动龙) -- 相同的spsummon_code共用1个次数 end -- =====Effect类===== Effect = { } function Effect.CreateEffect(c) -- 新建一个空效果,并且效果的拥有者为c end function Effect.GlobalEffect() -- 新建一个全局效果 end function Effect.Clone(e) -- 新建一个效果e的副本 end function Effect.Reset(e) -- 把效果e重置。重置之后不可以再使用此效果 end function Effect.GetFieldID(e) -- 获取效果e的id end function Effect.SetDescription(e, desc) -- 为效果e设置效果描述 end function Effect.SetCategory(e, cate) -- 设置Category属性 end function Effect.SetCode(e, code) -- 为效果e设置Code属性 end function Effect.SetProperty(e, prop1, prop2) -- 设置Property属性 -- prop2 不是必须的 end function Effect.SetRange(e, range) -- 为效果e设置Range属性 end function Effect.SetAbsoluteRange(e, playerid, s_range, o_range) -- 设置target range属性并设置EFFECT_FLAG_ABSOLUTE_RANGE标志 -- playerid != 0 s_range和o_range反转 end function Effect.SetCountLimit(e, count, code) -- 设置一回合可以发动的次数(仅触发型效果有效) -- 设置一回合可以发动的次数count(仅触发型效果有效),相同的code(不等于0或1时)共用1个次数 -- code包含以下数值具有特殊的性质 -- EFFECT_COUNT_CODE_OATH 誓约使用次数 -- EFFECT_COUNT_CODE_DUEL 决斗中使用次数 -- EFFECT_COUNT_CODE_SINGLE 同一张卡多个效果公共使用次数(不限制同名卡) end function Effect.SetReset(e, reset_flag, reset_count) -- 设置reset参数 -- 默认reset_count = 1 end function Effect.SetLabel(e, label) -- 设置Label属性 end function Effect.SetLabelObject(e, labelobject) -- 设置LabelObject属性 end function Effect.SetHintTiming(e, s_time, o_time) -- 设置提示时点 end function Effect.SetCondition(e, con_func) -- 设置Condition属性 end function Effect.SetCost(e, cost_func) -- 设置Cost属性 end function Effect.SetTarget(e, targ_func) -- 设置Target属性 end function Effect.SetTargetRange(e, s_range, o_range) -- 为效果e设置Target Range属性 --[[s_range指影响的我方区域。o_range值影响的对方区域。 如果property属性中指定了EFFECT_FLAG_ABSOLUTE_RANGE标志,那么s_range指玩家1收到影响的区域,o_range指玩家2受到影响的区域。 如果这是一个特殊召唤手续(EFFECT_SPSUMMON_PROC)的效果,并且property指定了EFFECT_FLAG_SPSUM_PARAM标志, 那么s_range表示特殊召唤到的哪个玩家的场地,o_range表示可选择的表示形式。]] end function Effect.SetValue(e, val) -- 设置Value属性 end function Effect.SetOperation(e, op_func) -- 设置Operation属性 end function Effect.SetOwnerPlayer(e, player) -- 设置Owner player属性 end function Effect.GetDescription(e) -- 返回效果描述 end function Effect.GetCode(e) -- 返回code属性 end function Effect.GetType(e) -- 返回Type属性 end function Effect.GetProperty(e) -- 返回Property属性 end function Effect.GetLabel(e) -- 返回Label属性 -- 【返回】 --[[ int int --]] end function Effect.GetLabelObject(e) -- 返回LabelObject属性 end function Effect.GetCategory(e) -- 返回Category属性 end function Effect.GetOwner(e) -- 返回效果拥有者 end function Effect.GetHandler(e) -- 返回效果在哪一张卡上生效(通常是注册该效果的卡) end function Effect.GetCondition(e) -- 返回condition属性 end function Effect.GetTarget(e) -- 返回target属性 end function Effect.GetCost(e) -- 返回cost属性 end function Effect.GetValue(e) -- 返回value属性 end function Effect.GetOperation(e) -- 返回operation属性 end function Effect.GetActiveType(e) -- 返回e的效果类型(怪兽·魔法·陷阱) -- 与发动该效果的卡的类型不一定相同,比如灵摆效果视为魔法卡的效果 end function Effect.IsActiveType(e, type) -- 检查e的效果类型(怪兽·魔法·陷阱)是否有type end function Effect.GetOwnerPlayer(e) -- 返回OwnerPlayer属性,一般是Owner的控制者 end function Effect.GetHandlerPlayer(e) -- 返回当前者,一般是Handle的控制者 end function Effect.IsHasProperty(e, prop1, prop2) -- 检查效果是否含有标志prop1[和prop2] end function Effect.IsHasCategory(e, cate) -- 检查效果是否含有效果分类cate end function Effect.IsHasType(e, type) -- 检查效果是否属于类型type end function Effect.IsActivatable(e, player) -- 检查效果e能否由player发动 end function Effect.IsActivated(e) -- 检查效果e能否是发动的效果(机壳) end function Effect.GetActivateLocation(e) -- 返回效果e的发动区域 end -- =====Group类===== Group = { } function Group.CreateGroup() -- 新建一个空的卡片组 end function Group.KeepAlive(g) -- 让卡片组持续,把卡片组设置为效果的LabelObject需要设置 end function Group.DeleteGroup(g) -- 删除卡片组g end function Group.Clone(g) -- 新建卡片组g的副本 end function Group.FromCards(c, ...) -- 不定参数,把传入的所有卡组合成一个卡片组并返回 end function Group.Clear(g) -- 清空卡片组 end function Group.AddCard(g, c) -- 往g中增加c end function Group.RemoveCard(g, c) -- 把c从g中移除 end function Group.GetFirst(g) -- 返回g中第一张卡,并重置当前指针到g中第一张卡。如果g中不存在卡则返回nil end function Group.GetNext(g) -- 返回并使指针指向下一张卡。如果g中不存在卡则返回nil end function Group.GetCount(g) -- 返回g中卡的数量 end function Group.ForEach(g, f) -- 以g中的每一张卡作为参数调用一次f end function Group.Filter(g, f, ex, ...) -- 过滤函数。从g中筛选满足筛选条件f并且不等于ex的卡。从第4个参数开始为额外参数。 end function Group.FilterCount(g, f, ex, ...) -- 过滤函数。和Group.Filter基本相同,不同之处在于此函数只返回满足条件的卡的数量 end function Group.FilterSelect(g, player, f, min, max, ex, ...) -- 过滤函数。让玩家player从g中选择min-max张满足筛选条件f并且不等于ex的卡。从第7个参数开始为额外参数。 end function Group.Select(g, player, min, max, ex) -- 让玩家player从g中选择min-max张不等于ex的卡。 end function Group.RandomSelect(g, player, count) -- 让玩家player从g中随机选择count张卡。因为是随机算则,所以参数player基本无用,由系统随机选取。 end function Group.IsExists(g, f, count, ex, ...) -- 过滤函数。检查g中是否存在至少count张满足筛选条件f并且不等于ex的卡。从第5个参数开始为额外参数。 end function Group.CheckWithSumEqual(g, f, sum, min, max, ...) -- 子集求和判定函数。f为返回一个interger值的函数(通常用于同调判定)。 -- 检查g中是否存在一个数量为min-max的子集满足以f对子集的每一个元素求值的和等于sum,从第6个参数开始为额外参数 -- 比如:g:CheckWithSumEqual(Card.GetSynchroLevel,7,2)检查g中是否存在一个子集满足子集的同调用等级之和等于7 end function Group.SelectWithSumEqual(g, player, f, sum, min, max, ...) -- 让玩家player从g中选取一个数量为min-max的子集使子集的特定函数的和等于sum,从第7个参数开始为额外参数 end function Group.CheckWithSumGreater(g, f, sum, ...) -- 子集求和判定函数之二。f为返回一个interger值的函数(通常用于仪式判定)。 -- 检查g中是否存在一个子集满足以f对子集的每一个元素求值的和刚好大于或者等于sum,从第4个参数开始为额外参数 -- 比如:g:CheckWithSumGreater(Card.GetRitualLevel,8)检查g中是否存在一个子集满足子集的仪式用等级之和大于等于8 -- 注:判定必须是“刚好”大于或者等于。以等级为例,要使等级合计大于等于8,可以选择LV1+LV7而不可以选择LV1+LV4+LV4 end function Group.SelectWithSumGreater(g, player, f, sum, ...) -- 让玩家player从g中选取一个子集使子集的特定函数的和大于等于sum,从第5个参数开始为额外参数 end function Group.GetMinGroup(g, f, ...) -- f为返回一个interger值的函数。从g中筛选出具有最小的f的值的卡。用于地裂等卡。 -- 第2个返回值为这个最小值,从第3个参数开始为额外参数 end function Group.GetMaxGroup(g, f, ...) -- f为返回一个interger值的函数。从g中筛选出具有最大的f的值的卡。用于地碎等卡。 -- 第2个返回值为这个最大值,从第3个参数开始为额外参数 end function Group.GetSum(g, f, ...) -- 计算g中所有卡的取值的总和。f为为每张卡的取值函数。 end function Group.GetClassCount(g, f, ...) -- 计算g中所有卡的种类数量,f为分类的依据,返回相同的值视为同一种类,从第3个参数开始为额外参数 end function Group.Remove(g, f, ex, ...) -- 从g中移除满足筛选条件f并且不等于ex的所有卡,第4个参数开始是额外参数 end function Group.Merge(g1, g2) -- 把g2中的所有卡合并到g1。 -- 注:g2本身不会发生变化。 end function Group.Sub(g1, g2) -- 从g1中移除属于g2中的卡 -- 注:g2本身不会发生变化 end function Group.IsContains(g, c) -- 检查g中是否存在卡片c end function Group.SearchCard(g, f, ...) -- 过滤函数。返回g中满足筛选条件f的第一张卡。第三个参数为额外参数。 end -- =====Duel类===== Duel = { } function Duel.EnableGlobalFlag(global_flag) -- 设置全局标记global_flag end function Duel.GetLP(player) -- 返回玩家player的当前LP end function Duel.SetLP(player, lp) -- 设置玩家player的当前LP为lp end function Duel.GetTurnPlayer() -- 返回当前的回合玩家 end function Duel.GetTurnCount() -- 返回当前的回合数 end function Duel.GetDrawCount(player) -- 返回玩家player每回合的规则抽卡数量 end function Duel.RegisterEffect(e, player) -- 把效果作为玩家player的效果注册给全局环境。 end function Duel.RegisterFlagEffect(player, code, reset_flag, property, reset_count) -- 此函数为玩家player注册全局环境下的标识效果。 -- 此效果总是影响玩家的(EFFECT_FLAG_PLAYER_TARGET)并且不会被无效化。 -- 其余部分与Card.RegisterFlagEffect相同 end function Duel.GetFlagEffect(player, code) -- 返回玩家player的特定的标识效果的数量 end function Duel.ResetFlagEffect(player, code) -- 手动reset玩家player的特定的标识效果 end function Duel.Destroy(targets, reason, dest) -- 以reason原因破坏targets去dest。返回值是实际被破坏的数量。 -- 如果reason包含REASON_RULE,则破坏事件将不会检查卡片是否免疫效果,不会触发代破效果并且无视“不能破坏”。 end function Duel.Remove(targets, pos, reason) -- 以reason原因,pos表示形式除外targets。返回值是实际被操作的数量。 -- 如果reason包含REASON_TEMPORARY,那么视为是暂时除外,可以通过Duel.ReturnToField返回到场上 end function Duel.SendtoGrave(targets, reason) -- 以reason原因把targets送去墓地。返回值是实际被操作的数量。 end function Duel.SendtoHand(targets, player, reason) -- 以reason原因把targets送去玩家player的手牌。返回值是实际被操作的数量。 -- 如果player是nil则返回卡的持有者的手牌。 end function Duel.SendtoDeck(targets, player, seq, reason) -- 以reason原因把targets送去玩家player的卡组。返回值是实际被操作的数量。 -- 如果player是nil则返回卡的持有者的卡组。 -- 如果seq=0,则是返回卡组最顶端;seq=1则是返回卡组最低端;其余情况则是返回最顶端并且标记需要洗卡组。 end function Duel.PSendtoExtra(targets, player, reason) -- 以reason原因把灵摆卡targets送去玩家player的额外卡组 -- 【必须】 --[[ Card/Group targets int player int reason --]] -- 如果player是nil则返回卡的持有者的额外卡组 -- 【返回】实际被操作的数量 end function Duel.GetOperatedGroup() -- 此函数返回之前一次卡片操作实际操作的卡片组。包括Duel.Destroy, Duel.Remove, Duel.SendtoGrave, Duel.SendtoHand, Duel.SendtoDeck, Duel.PSendtoExtra, Duel.Release, Duel.ChangePosition, Duel.SpecialSummon, Duel.DiscardDeck end function Duel.Summon(player, c, ignore_count, e, minc) -- 让玩家以效果e对c进行通常召唤(非set),至少使用minc个祭品。 -- 如果e=nil,那么就按照一般的通常召唤规则进行通常召唤。 -- 如果ignore_count=true,则忽略每回合的通常召唤次数限制。 end function Duel.SpecialSummonRule(player, c) -- 让玩家player对c进行特殊召唤手续。 end function Duel.SynchroSummon(player, c, tuner, mg) -- 让玩家player以tuner作为调整[mg为素材]对c进行同调召唤手续。 end function Duel.XyzSummon(player, c, mg, min, max) -- 让玩家player[从mg中][选min-max个素材]对c进行超量召唤手续 -- mg非空且min为0则直接把mg全部作为超量素材 end function Duel.MSet(player, c, ignore_count, e, minc) -- 让玩家以效果e对c进行通常召唤的Set,至少使用minc个祭品。 -- 如果e=nil,那么就按照一般的通常召唤规则进行通常召唤。 -- 如果ignore_count=true,则忽略每回合的通常召唤次数限制。 end function Duel.SSet(player, c, target_player) -- 让玩家player把targets放置到target_player的魔法陷阱区 -- 若targets为Group,则返回成功操作的数量 end function Duel.CreateToken(player, code, cardsetCode, attack, defense, level, race, attribute) -- 以传入的参数数值新建一个Token并返回 end function Duel.SpecialSummon(targets, sumtype, player, target_player, nocheck, nolimit, pos) -- 让玩家player以sumtype方式,pos表示形式把targets特殊召唤到target_player场上。 -- 如果nocheck为true则无视卡的召唤条件。如果nolimit为true则无视卡的苏生限制。 -- 返回值是特殊召唤成功的卡的数量。 end function Duel.SpecialSummonStep(c, sumtype, sumplayer, target_player, nocheck, nolimit, pos) -- 此函数是Duel.SpecialSummon的分解过程,只特殊召唤一张卡c。 -- 此函数用于一个效果同时特殊召唤多张参数不同的卡。 -- 此函数必须和Duel.SpecialSummonComplete一起使用。 -- 返回值表示是否特殊召唤成功。 end function Duel.SpecialSummonComplete() -- 此函数在确定复数个Duel.SpecialSummonStep调用完毕之后调用。用于触发事件。 end function Duel.IsCanAddCounter(player, countertype, count, c) -- 检查玩家player能否向卡片c添加count个countertype类型的指示物 --! require --[[ int player int countertype int count Card c ]] --! return --[[ bool ]] end function Duel.RemoveCounter(player, s, o, countertype, count, reason) -- 让玩家player移除场上存在的countertype类型的count个指示物。 -- 表示对player来说的己方的可移除指示物的位置,o表示对player来说的对方的可移除指示物的位置 end function Duel.IsCanRemoveCounter(player, s, o, countertype, count, reason) -- 检查玩家player是否能移除场上的countertype类型的count个指示物。s和o参数作用同上。 end function Duel.GetCounter(player, s, o, countertype) -- 返回场上存在的countertype类型的指示物的数量。s和o参数作用同上。 end function Duel.ChangePosition(targets, au, ad, du, dd, noflip, setavailable) -- 改变targets的表示形式并返回实际操作的数量。 -- 表侧攻击表示的变成au,里侧攻击表示的变成ad,表侧守备表示变成du,里侧守备表示变成dd -- 如果noflip=true则不触发翻转效果(但会触发反转时的诱发效果) -- 如果setavailable=true则对象之后变成里侧也发动反转效果 end function Duel.Release(targets, reason) -- 以reason原因解放targets。返回值是实际解放的数量。 -- 如果reason含有REASON_COST,则不会检查卡片是否不受效果影响 end function Duel.MoveToField(c, move_player, target_player, dest, pos, enabled) -- 让玩家move_player把c移动的target_player的场上。dest只能是LOCATION_MZONE或者LOCATION_SZONE。 -- pos表示可选表示形式。enable表示是否立刻适用c的效果。 end function Duel.ReturnToField(c, pos) -- 把c返回到场上,pos默认值是离场前的表示形式,返回值表示是否成功。 -- c必须是以REASON_TEMPORARY原因离场,并且离场后没有离开过那个位置。 end function Duel.MoveSequence(c, seq) -- 移动c的序号。通常用于在场上换格子或者在卡组中移动到最上方或者最下方。 end function Duel.SetChainLimit(f) -- 设定连锁条件,f的函数原型为 bool f(e,ep,tp) -- e表示要限制连锁的效果,ep表示要限制连锁的玩家,tp表示发动该效果的玩家 -- 在cost或者target处理中调用此函数可以限制可以连锁的效果的种类(如超融合)。 -- 如果f返回false表示不能连锁。一旦设置连锁条件后发生了新的连锁那么连锁条件将会解除。 end function Duel.SetChainLimitTillChainEnd(f) -- 功能同Duel.SetChainLimit,但是此函数设定的连锁条件直到连锁结束才会解除。 end function Duel.GetChainMaterial(player) -- 返回玩家player受到的连锁素材的效果。此函数仅用于融合类卡的效果。 end function Duel.ConfirmDeckTop(player, count) -- 确认玩家player卡组最上方的count张卡。双方均可确认。 end function Duel.ConfirmCards(player, targets) -- 给玩家player确认targets end function Duel.SortDecktop(sort_player, target_player, count) -- 让玩家sort_player对玩家target_player的卡组最上方count张卡进行排序 end function Duel.CheckEvent(event, get_info) -- 检查当前是否是event时点 -- 若get_info=true并且是正确的时点则还返回触发时点的信息 eg,ep,ev,re,r,rp end function Duel.RaiseEvent(eg, code, re, r, rp, ep, ev) -- 以eg,ep,ev,re,r,rp触发一个时点 end function Duel.RaiseSingleEvent(ec, code, re, r, rp, ep, ev) -- 以eg,ep,ev,re,r,rp为卡片ec触发一个单体时点 end function Duel.CheckTiming(timing) -- 检查当前是否是timing提示时点 end function Duel.GetEnvironment() -- 返回两个值,表示当前场地代号,以及当前场地效果的来源玩家。 -- 场地代号指当前生效的场地卡的代号,或者海神的巫女把场地变化效果的值。 -- 来源玩家指当前生效的场地卡的控制者,或者海神的巫女等卡的控制者。 end function Duel.IsEnvironment(code, player) -- 检查玩家player是否为场地代号code的来源玩家 -- 场地代号指当前生效的场地卡的代号,或者海神的巫女把场地变化效果的值 -- 来源玩家指当前生效的场地卡的控制者,或者海神的巫女等卡的控制者 end function Duel.Win(player, reason) -- 当前效果处理完令player以win_reason决斗胜利 end function Duel.Draw(player, count, reason) -- 让玩家player以原因reason抽count张卡。返回实际抽的卡的数量。 -- 如果reason含有REASON_RULE则此次抽卡不受“不能抽卡”的效果的影响。 end function Duel.Damage(player, value, reason, is_step) -- 以reason原因给与玩家player造成value的伤害。返回实际收到的伤害值。 -- 如果受到伤害变成回复等效果的影响时,返回值为0. -- is_step为true则是伤害/恢复LP过程的分解,需要调用Duel.RDComplete()触发时点 --! require --[[ int player int value int reason ]] --! optional --[[ bool is_step = false ]] --! return --[[ int ]] end function Duel.Recover(player, value, reason, is_step) -- 以reason原因使玩家player回复value的LP。返回实际的回复值。 -- 如果受到回复变成伤害等效果的影响时,返回值为0. -- is_step为true则是伤害/恢复LP过程的分解,需要调用Duel.RDComplete()触发时点 --! require --[[ int player int value int reason ]] --! optional --[[ bool is_step = false ]] --! return --[[ int ]] end function Duel.RDComplete() -- 在调用Duel.Damage/Duel.Recover时,若is_step参数为true,则需调用此函数触发时点 end function Duel.Equip(player, c1, c2, up, is_step) -- 把c1作为玩家player的装备卡装备给c2。返回值表示是否成功。 -- up=false则保持装备卡之前的表示形式 -- is_step=true则是装备过程的分解,需要配合Duel.EquipComplete使用 end function Duel.EquipComplete() -- 在调用Duel.Equip时,若is_step参数为true,则需调用此函数触发时点 end function Duel.GetControl(targets, player, reset_phase, reset_count) -- 让玩家player得到targets的控制权,返回值表示是否成功 --! require --[[ Card|Group targets Player player ]] --! optional --[[ RESET reset_phase = 0 int reset_count = 0 ]] --! return --[[ bool ]] end function Duel.SwapControl(c1, c2, reset_phase, reset_count) -- 交换c1和c2的控制权。返回值表示是否成功。 end function Duel.CheckLPCost(player, cost) -- 检查玩家player是否能支付cost点lp end function Duel.PayLPCost(player, cost) -- 让玩家player支付cost点lp end function Duel.DiscardDeck(player, count, reason) -- 以原因reason把玩家player的卡组最上端count张卡送去墓地.返回实际转移的数量。 end function Duel.DiscardHand(player, f, min, max, reason, ex, ...) -- 过滤函数。让玩家player选择并丢弃满足筛选条件f并不等于ex的min-max张手卡。 -- 第7个参数开始为额外参数。 end function Duel.DisableShuffleCheck() -- 使下一个操作不检查是否需要洗卡组或者洗手卡。 -- 注:如果不调用此函数,除了调用Duel.DiscardDeck和Duel.Draw之外, -- 从卡组中取出卡或者把卡加入手卡或者把卡加入卡组(非最上端或最底端)时, -- 系统会自动在效果处理结束时洗卡组或手卡。 -- 如果不希望如此,比如从卡组顶端除外一张卡等操作,那么需要调用此函数。 -- 此函数仅保证紧接着的一次操作不会进行洗卡检测。 end function Duel.ShuffleDeck(player) -- 手动洗玩家player的卡组 -- 注:会重置洗卡检测的状态 end function Duel.ShuffleHand(player) -- 手动洗玩家player的手卡 -- 注:会重置洗卡检测的状态 end function Duel.ShuffleSetCard(g) -- 洗切覆盖在怪兽区域的卡(魔术礼帽) end function Duel.ChangeAttacker(c) -- 把当前的攻击卡替换成c进行攻击 -- 注:此函数会使原来的攻击怪兽视为攻击过 end function Duel.ReplaceAttacker(c) -- 用c代替当前攻击的卡进行伤害阶段 end function Duel.ChangeAttackTarget(c) -- 将攻击对象变为c,c为nil表示直接攻击,返回值表示是否成功转移攻击对象 --! optional --[[ Card c = nil ]] --! return --[[ bool ]] end function Duel.ReplaceAttackTarget(c) -- (预留) end function Duel.CalculateDamage(c1, c2) -- 令c1与c2进行战斗伤害计算 end function Duel.GetBattleDamage(player) -- 返回玩家player在本次战斗中收到的伤害 end function Duel.ChangeBattleDamage(player, value, check) -- 把玩家player在本次战斗中收到的伤害变成value -- heck为false则原本战斗伤害为0也改变伤害 end function Duel.ChangeTargetCard(chainc, g) -- 把连锁chainc的对象换成g end function Duel.ChangeTargetPlayer(chainc, player) -- 把连锁chainc的对象玩家换成player end function Duel.ChangeTargetParam(chainc, param) -- 把连锁chainc的对象参数换成param end function Duel.BreakEffect() -- 中断当前效果,使之后的效果处理视为不同时处理。 -- 此函数会造成错时点。 end function Duel.ChangeChainOperation(chainc, f) -- 把连锁chainc的效果的处理函数换成f。用于实现“把效果变成”等的效果 end function Duel.NegateActivation(chainc) -- 使连锁chainc的发动无效,返回值表示是否成功 end function Duel.NegateEffect(chainc) -- 使连锁chainc的效果无效,返回值表示是否成功 end function Duel.NegateRelatedChain(c, reset) -- 使卡片c的已经发动的连锁都无效化,发生reset事件则重置 end function Duel.NegateSummon(targets) -- 使正在召唤,反转召唤,特殊召唤的targets的召唤无效 end function Duel.IncreaseSummonedCount(c) -- 手动消耗1次玩家[对于卡片c]的通常召唤的次数 end function Duel.CheckSummonCount(c) -- 检查回合玩家本回合是否还能通常召唤[卡片c] end function Duel.GetLocationCount(player, location, use_player, reason) -- 返回玩家player的场上location可用的空格数 -- location只能是LOCATION_MZONE或者LOCATION_SZONE -- reason为LOCATION_REASON_TOFIELD或LOCATION_REASON_CONTROL,默认为前者 -- 额外参数与凯撒斗技场的效果有关 end function Duel.GetFieldCard(player, location, sequence) -- 返回玩家player的场上位于location序号为sequence的卡,常用于获得场地区域·灵摆区域的卡 end function Duel.CheckLocation(player, location, seq) -- 检查玩家player的场上位于location序号为seq的空格是否可用 end function Duel.GetCurrentChain() -- 返回当前正在处理的连锁序号 end function Duel.GetChainInfo(chainc, ...) --[[ 返回连锁chainc的信息。如果chainc=0,则返回当前正在处理的连锁的信息。 此函数根据传入的参数个数按顺序返回相应数量的返回值。参数可以是: CHAININFO_CHAIN_COUNT 连锁序号 CHAININFO_TRIGGERING_EFFECT 连锁的效果 CHAININFO_TRIGGERING_PLAYER 连锁的玩家 CHAININFO_TRIGGERING_CONTROLER 连锁发生位置所属玩家 CHAININFO_TRIGGERING_LOCATION 连锁发生位置 CHAININFO_TRIGGERING_SEQUENCE 连锁发生的位置的序号 CHAININFO_TARGET_CARDS 连锁的对象卡片组 CHAININFO_TARGET_PLAYER 连锁的对象玩家 CHAININFO_TARGET_PARAM 连锁的对象参数 CHAININFO_DISABLE_REASON 连锁被无效的原因效果 CHAININFO_DISABLE_PLAYER 连锁被无效的原因玩家 CHAININFO_CHAIN_ID 连锁的唯一标识 举例:Duel.GetChainInfo(0, CHAININFO_TRIGGERING_LOCATION, CHAININFO_TARGET_CARDS) 将会返回当前连锁发生的位置和对象卡。 ]] end function Duel.GetFirstTarget() -- 返回连锁的所有的对象卡,一般只有一个对象时使用 end function Duel.GetCurrentPhase() -- 返回当前的阶段 end function Duel.SkipPhase(player, phase, reset_flag, reset_count, value) -- 跳过玩家player的phase阶段,并在特定的阶段后reset。reset参数和效果相同。 -- value只对phase=PHASE_BATTLE才有用,value=1跳过战斗阶段的结束步骤,用于“变成回合结束阶段”等(招财猫王,闪光弹) end function Duel.IsDamageCalculated() -- 用于在伤害阶段检查是否已经计算了战斗伤害。 end function Duel.GetAttacker() -- 返回此次战斗攻击的卡 end function Duel.GetAttackTarget() -- 返回此次战斗被攻击的卡。如果返回nil表示是直接攻击。 end function Duel.NegateAttack() -- 使本次攻击无效,返回值表示是否成功 -- 此次攻击已经被其他效果无效或导致攻击的卡不能攻击则返回false end function Duel.ChainAttack(c) -- 使攻击卡[或卡片c]再进行1次攻击(开辟,破灭的女王) end function Duel.Readjust() -- 刷新场上的卡的信息。 -- 非特定情况或者不清楚原理请勿使用此函数以免形成死循环。 end function Duel.AdjustInstantly(c) -- 似乎是处理场上的卡[或卡片c相关的卡]效果相互无效 end function Duel.GetFieldGroup(player, s, o) -- 返回指定位置的卡。s指对玩家player来说的己方的位置,o指对玩家player来说的对方的位置。 -- 下面提到的指定位置均为此意。 -- 比如Duel.GetFieldGroup(0,LOCATION_GRAVE,LOCATION_MZONE) -- 返回玩家1墓地和玩家2的怪兽区的所有卡 end function Duel.GetFieldGroupCount(player, s, o) -- 返回指定位置的卡的数量 end function Duel.GetDecktopGroup(player, count) -- 返回玩家player的卡组最上方的count张卡 end function Duel.GetMatchingGroup(f, player, s, o, ex, ...) -- 过滤函数,返回指定位置满足过滤条件f并且不等于ex的卡。 -- 第6个参数开始为额外参数。 end function Duel.GetMatchingGroupCount(f, player, s, o, ex, ...) -- 过滤函数,返回指定位置满足过滤条件f并且不等于ex的卡的数量 end function Duel.GetFirstMatchingCard(f, player, s, o, ex, ...) -- 过滤函数,返回指定位置满足过滤条件f并且不等于ex的第一张卡。 -- 第6个参数开始为额外参数。 end function Duel.IsExistingMatchingCard(f, player, s, o, count, ex, ...) -- 过滤函数,检查指定位置是否存在至少count张满足过滤条件f并且不等于ex的卡。 -- 第7个参数开始为额外参数。 end function Duel.SelectMatchingCard(sel_player, f, player, s, o, min, max, ex, ...) -- 过滤函数,让玩家sel_player选择指定位置满足过滤条件f并且不等于ex的min-max张卡。 -- 第9个参数开始为额外参数。 end function Duel.GetReleaseGroup(player, use_hand) -- 返回玩家player可解放(非上级召唤用)的卡片组,use_hand为true则包括手卡 end function Duel.GetReleaseGroupCount(player, use_hand) -- 返回玩家player可解放(非上级召唤用)的卡片数量,use_hand为true则包括手卡 end function Duel.ChecktReleaseGroup(player, f, count, ex, ...) -- 过滤函数,检查玩家player场上是否存在至少count张不等于ex的满足条件f的可解放的卡(非上级召唤用) -- 第5个参数开始为额外参数 end function Duel.SelectReleaseGroup(player, f, min, max, ex, ...) -- 过滤函数,让玩家player选择min-max张不等于ex的满足条件f的可解放的卡(非上级召唤用) end function Duel.CheckReleaseGroupEx(player, f, count, ex, ...) -- 检查玩家player场上·手卡是否存在至少count张满足过滤条件f并且不等于ex的可解放的卡(非上级召唤用) end function Duel.SelectReleaseGroupEx(player, f, min, max, ex, ...) -- 过滤函数,让玩家player从场上·手卡选择min-max张不等于ex的满足条件f的可解放的卡(非上级召唤用) end function Duel.GetTributeGroup(c) -- 返回用于通常召唤c可解放(上级召唤用)的卡片组 end function Duel.GetTributeCount(c, mg, ex) -- 返回[mg中]用于通常召唤c的祭品数量,ex=true则允许对方场上的怪兽(太阳神之翼神龙-球体形) -- 此数量不一定等于Duel.GetTributeGroup的返回值中的卡片数量 -- 因为某些卡可以作为两个祭品来使用 end function Duel.SelectTribute(player, c, min, max, mg, ex) -- 让玩家player[从mg中]选择用于通常召唤c的min-max个祭品,ex=true则允许对方场上的怪兽(太阳神之翼神龙-球体形) end function Duel.GetTargetCount(f, player, s, o, ex, ...) -- 基本同Duel.GetMatchingGroupCount,不同之处在于需要追加判定卡片是否能成为当前正在处理的效果的对象。 end function Duel.IsExistingTarget(f, player, s, o, count, ex, ...) -- 过滤函数,检查指定位置是否存在至少count张满足过滤条件f并且不等于ex并且可以成为当前正在处理的效果的对象的卡。 -- 第7个参数开始为额外参数。 end function Duel.SelectTarget(sel_player, f, player, s, o, min, max, ex, ...) -- 过滤函数,让玩家sel_player选择指定位置满足过滤条件f并且不等于ex并且可以成为当前正在处理的效果的对象的min-max张卡。 -- 第9个参数开始为额外参数。 -- 此函数会同时将当前正在处理的连锁的对象设置成选择的卡 end function Duel.SelectFusionMaterial(player, c, g, gc, chkf) -- 让玩家player从g中选择一组[必须包含gc在内的]融合怪兽c的融合素材 -- 根据c的种类为EFFECT_FUSION_MATERIAL的效果的Operation操作 end function Duel.SetFusionMaterial(g) -- 设置g为需要使用的融合素材 end function Duel.SetSynchroMaterial(g) -- 设置g为需要使用的同调素材 end function Duel.SelectSynchroMaterial(player, c, f1, f2, min, max, smat, mg) -- 让玩家player[从mg中]选择用于同调c需要的[必须包含smat在内(如果有mg~=nil则忽略此参数)]满足条件的数量为min-max的一组素材。 -- f1是调整需要满足的过滤条件。f2是调整以外的部分需要满足的过滤条件。 end function Duel.CheckSynchroMaterial(c, f1, f2, min, max, smat, mg) -- 检查[mg中]是否存在一组[必须包括smat在内的]满足条件的min-max张卡作为同调召唤c的素材 -- f1是调整需要满足的过滤条件,f2是调整以外的部分需要满足的过滤条件 end function Duel.SelectTunerMaterial(player, c, tuner, f1, f2, min, max, mg) -- 让玩家[从mg中]选择用于同调c需要的满足条件的以tuner作为调整的min-max张卡的一组素材 -- f1是调整需要满足的过滤条件,f2是调整以外的部分需要满足的过滤条件 end function Duel.CheckTunerMaterial(c, tuner, f1, f2, min, max, mg) -- 检查以tuner作为调整[在mg中]是否存在一组满足条件的min-max张卡作为同调召唤c的素材 -- f1是调整需要满足的过滤条件,f2是调整以外的部分需要满足的过滤条件 end function Duel.GetRitualMaterial(player) -- 返回玩家player可用的用于仪式召唤素材的卡片组。 -- 包含手上,场上可解放的以及墓地的仪式魔人等卡。 end function Duel.ReleaseRitualMaterial(g) -- 解放仪式用的素材g。如果是墓地的仪式魔人等卡则除外。 end function Duel.SetSelectedCard(cards) -- 将cards设置为Group.SelectWithSumEqual或Group.SelectWithSumGreater已选择的卡片, end function Duel.SetTargetCard(g) -- 把当前正在处理的连锁的对象设置成g。 -- 注,这里的对象指的的广义的对象,包括不取对象的效果可能要处理的对象。 end function Duel.ClearTargetCard() -- 把当前正在处理的连锁的对象全部清除 end function Duel.SetTargetPlayer(player) -- 把当前正在处理的连锁的对象玩家设置成player。 end function Duel.SetTargetParam(param) -- 把当前正在处理的连锁的对象参数设置成param。 end function Duel.SetOperationInfo(chainc, category, targets, count, target_player, target_param) -- 设置当前处理的连锁的操作信息。此操作信息包含了效果处理中确定要处理的效果分类。 -- 比如潜行狙击手需要设置CATEGORY_DICE,但是不能设置CATEGORY_DESTROY,因为不确定。 -- 对于破坏效果,targets需要设置成发动时可能成为连锁的影响对象的卡,并设置count为发动时确定的要处理的卡的数量。 -- 比如黑洞发动时,targets需要设定为场上的所有怪物,count设置成场上的怪的数量。 -- 对于CATEGORY_SPECIAL_SUMMON,CATEGORY_TOHAND,CATEGORY_TODECK等分类,如果取对象则设置targets为对象,count为对象的数量; -- 如果不取对象则设置targets为nil,count为预计要处理的卡的数量,并设置target_param为预计要处理的卡的位置。 -- 例如增援:SetOperationInfo(0,CATEGORY_TOHAND,nil,1,0,LOCATION_DECK)。 -- 操作信息用于很多效果的发动的检测,例如星尘龙,王家沉眠之谷等。 end function Duel.GetOperationInfo(chainc, category) -- 返回连锁chainc的category分类的操作信息。返回值为5个,第一个返回值是false的话表示不存在该分类。 -- 后4个返回值对应Duel.SetOperationInfo的后4个参数。 end function Duel.GetOperationCount(chainc) -- 返回连锁chainc包含的操作分类的数量 end function Duel.CheckXyzMaterial(c, f, lv, min, max, mg) -- 检查场上或mg中是否存在超量召唤c的超量用等级为lv的min-max个满足条件f的叠放素材 end function Duel.SelectXyzMaterial(player, c, f, lv, min, max, mg) -- 让玩家player为超量怪兽c[从mg中]选择超量用等级为lv的min-max个满足条件f的叠放素材 end function Duel.GetExceedMaterial(c) -- 返回c的超量素材 end function Duel.Overlay(c, ocard) -- 把ocard作为c的叠放卡叠放 end function Duel.GetOverlayGroup(player, s, o) -- 返回指定位置的所有叠放的卡 end function Duel.GetOverlayCount(player, s, o) -- 返回指定位置的所有叠放的卡的数量 end function Duel.CheckRemoveOverlayCard(player, s, o, count, reason) -- 检查player能否以原因reason移除指定位置至少count张卡 end function Duel.RemoveOverlayCard(player, s, o, min, max, reason) -- 以reason原因移除指定位置的min-max张叠放卡 end function Duel.Hint(hint_type, player, desc) -- 给玩家player发送hint_type类型的消息提示,提示内容为desc --[[ hint_type只能为以下类型: HINT_SELECTMSG将提示内容写入缓存,用于选择卡片的提示,例如Duel.SelectMatchingCard等 HINT_OPSELECTED向player提示"对方选择了:...",常用于向对方玩家提示选择发动了什么效果 HINT_CARD此时desc应为卡号,手动显示卡片发动的动画,常用于提示不入连锁的处理 HINT_RACE此时desc应为种族,向player提示"对方宣言了:..."种族 HINT_ATTRIB此时desc应为属性,向player提示"对方宣言了:..."属性 HINT_CODE此时desc应为卡号,向player提示"对方宣言了:..."卡片 HINT_NUMBER此时desc视为单纯的数字,向player提示"对方选择了:..."数字 HINT_MESSAGE弹出一个对话框显示信息 HINT_EVENT将提示内容写入缓存,用于时点的提示信息(诱发即时效果的提示) HINT_EFFECT同HINT_CARD --]] end function Duel.HintSelection(g) -- 手动为g显示被选为对象的动画效果 end function Duel.SelectEffectYesNo(player, c) -- 让玩家选择是否发动卡片C的效果 end function Duel.SelectYesNo(player, desc) -- 让玩家选择是或否 end function Duel.SelectOption(player, ...) -- 让玩家选择选项。从第二个参数开始,每一个参数代表一条选项。 -- 返回选择的选项的序号。 end function Duel.SelectSequence() -- (预留) end function Duel.SelectPosition(player, c, pos) -- 让玩家player选择c的表示形式并返回 end function Duel.SelectDisableField(player, count, s, o, filter) -- 让玩家player选择指定位置满足标记条件filter的count个可用的空格并返回选择位置的标记 -- 常用于选择区域不能使用或移动怪兽格子 -- 位置标记的定义如下 -- flag = 0; -- seq为在玩家p,位置l中选择的格子序号 -- for(int32 i = 0; i < count; ++i) { -- flag |= 1 << (seq[i] + (p[i] == player ? 0 : 16) + (l[i] == LOCATION_MZONE ? 0 : 8)); -- } end function Duel.AnnounceRace(player, count, available) -- 让玩家player从可选的种族中宣言count个种族。available是所有可选种族的组合值。 end function Duel.AnnounceAttribute(player, count, available) -- 让玩家player从可选的属性中宣言count个属性。available是所有可选属性的组合值。 end -- function Duel.AnnounceLevel(player) -- 【废弃】已经不能正常使用 -- 让玩家player宣言一个等级 -- end function Duel.AnnounceCard(player, type) -- 让玩家player宣言一个[type类型的]卡片代号 -- 默认情况下type=TYPE_MONSTER+TYPE_SPELL+TYPE_TRAP end function Duel.AnnounceType(player) -- 让玩家player宣言一个卡片类型。 end function Duel.AnnounceNumber(player, ...) -- 让玩家player宣言一个数字。从第二个参数开始,每一个参数代表一个可宣言的数字。 -- 第一个返回值的宣言的数字,第二个返回值是宣言数字在所有选项中的位置。 end function Duel.AnnounceCoin(player) -- 让玩家player宣言硬币的正反面。 end function Duel.TossCoin(player, count) -- 让玩家player投count(<=5)次硬币,返回值为count个结果,0或者1. end function Duel.TossDice(player, count1, count2) -- 让玩家player投count1次骰子[,1-player投count2次骰子](count1+count2<=5), -- 返回值为count1+count2个结果,结果是1-6. end function Duel.GetCoinResult() -- 返回当前投硬币的结果 end function Duel.GetDiceResult() -- 返回当前掷骰子的结果 end function Duel.SetCoinResult(...) -- 强行修改投硬币的结果。此函数用于永续的EVENT_TOSS_COIN事件中 end function Duel.SetDiceResult(...) -- 强行修改投骰子的结果。此函数用于永续的EVENT_TOSS_DICE事件中 end function Duel.IsPlayerAffectedByEffect(player, code) -- 检查player是否受到种类为code的效果影响,如果有就返回该效果 end function Duel.IsPlayerCanDraw(player, count) -- 检查玩家player是否可以效果抽[count张]卡 end function Duel.IsPlayerCanDiscardDeck(player, count) -- 检查玩家player是否可以把卡组顶端的卡送去墓地 end function Duel.IsPlayerCanDiscardDeckAdCost(player, count) -- 检查玩家player是否可以把卡组顶端的卡送去墓地作为cost。 -- 当卡组没有足够数量的卡,或者当卡组中的卡受到送墓转移效果的影响时 -- (如大宇宙,次元裂缝,即使不是全部)此函数会返回false end function Duel.IsPlayerCanSummon(player, sumtype, c) -- 检查玩家player是否可以通常召唤[c,以sumtype方式] -- 如果需要可选参数,则必须全部使用 -- 仅当玩家收到"不能上级召唤"等效果的影响时返回false end function Duel.IsPlayerCanSpecialSummon(player, sumtype, sumpos, target_player, c) -- 检查玩家player能否特殊召唤[c到target_player场上,以sumtype召唤方式,sumpos表示形式] -- 如果需要可选参数,则必须全部使用 end function Duel.IsPlayerCanFlipSummon(player, c) -- 检查玩家player是否可以反转召唤c。 end function Duel.IsPlayerCanSpecialSummonMonster(player, code, cardsetCode, type, atk, def, level, race, attribute, pos, target_player) -- 检查玩家player是否可以以pos的表示形式特殊召唤特定属性值的怪物到target_player场上。此函数通常用于判定是否可以特招token和陷阱怪物。 end function Duel.IsPlayerCanSpecialSummonCount(player, count) -- 检查玩家player能否特殊召唤count次 end function Duel.IsPlayerCanRelease(player, c) -- 检查玩家是否能解放c end function Duel.IsPlayerCanRemove(player, c) -- 检查玩家是否能除外c end function Duel.IsPlayerCanSendtoHand(player, c) -- 检查玩家是否能把c送去手牌 end function Duel.IsPlayerCanSendtoGrave(player, c) -- 检查玩家是否能把c送去墓地 end function Duel.IsPlayerCanSendtoDeck(player, c) -- 检查玩家是否能把c送去卡组 end function Duel.IsChainNegatable(chainc) -- 检查连锁chainc的发动是否可以被无效化 end function Duel.IsChainDisablable(chainc) -- 检查连锁chainc的效果是否可以被无效化 end function Duel.CheckChainTarget(chainc, c) -- 检查c是否是连锁chainc的正确的对象 end function Duel.CheckChainUniqueness() -- 检查当前连锁中是否存在同名卡的发动。true表示无同名卡。 end function Duel.GetActivityCount(player, activity_type, ...) -- 返回player进行对应的activity_type操作的次数 -- activity_type为以下类型 -- ACTIVITY_SUMMON 召唤(不包括通常召唤的放置) -- ACTIVITY_NORMALSUMMON 通常召唤(包括通常召唤的放置) -- ACTIVITY_SPSUMMON 特殊召唤 -- ACTIVITY_FLIPSUMMON 反转召唤 -- ACTIVITY_ATTACK 攻击 -- ACTIVITY_BATTLE_PHASE 进入战斗阶段 end function CheckPhaseActivity() -- 检查玩家在当前阶段是否有操作(是否处于阶段开始时,如七皇之剑) end function Duel.AddCustomActivityCounter(counter_id, activity_type, f) -- 设置操作类型为activity_type、代号为counter_id的计数器,放在initial_effect函数内 -- f为过滤函数,以Card类型为参数,返回值为false的卡片进行以下类型的操作,计数器增加1(目前最多为1) -- activity_type为以下类型 -- ACTIVITY_SUMMON 召唤(不包括通常召唤的set) -- ACTIVITY_NORMALSUMMON 通常召唤(包括通常召唤的set) -- ACTIVITY_SPSUMMON 特殊召唤 -- ACTIVITY_FLIPSUMMON 反转召唤 -- ACTIVITY_CHAIN 发动效果 end function Duel.GetCustomActivityCount(counter_id, player, activity_type) -- 代号为counter_id的计数器的计数,返回player进行以下操作的次数(目前最多为1) -- activity_type为以下类型 -- ACTIVITY_SUMMON 召唤(不包括通常召唤的set) -- ACTIVITY_NORMALSUMMON 通常召唤(包括通常召唤的set) -- ACTIVITY_SPSUMMON 特殊召唤 -- ACTIVITY_FLIPSUMMON 反转召唤 -- ACTIVITY_CHAIN 发动效果 end function Duel.GetBattledCount(player) -- 返回玩家player这回合战斗过的次数 --! require --[[ Player player ]] --! return -- int end function Duel.IsAbleToEnterBP() -- 检查回合玩家能否进入战斗阶段 end function Duel.VenomSwampCheck(e, c) -- 蛇毒沼泽专用。把攻击力被其效果变成0的卡片破坏 end function Duel.SwapDeckAndGrave(player) -- 现世与冥界的逆转专用。把玩家player的卡组和墓地交换 end function Duel.MajesticCopy(c1, c2) -- 救世星龙专用。把c2记述的效果复制给c1 -- 强制发动的效果可以选择是否发动 end function Duel.CheckSummonActivity(player) -- 检查玩家player本回合有没有进行过召唤的行为。召唤被无效视作进行过召唤行为。 end function Duel.CheckNormalSummonActivity(player) -- 检查玩家player本回合有没有进行过通常召唤的行为。包括召唤和set end function Duel.CheckFlipSummonActivity(player) -- 检查玩家player本回合有没有进行过反转召唤的行为。 end function Duel.CheckFlipSummonActivity(player) -- 检查玩家player本回合有没有进行过特殊召唤的行为。 -- 特殊召唤的行为包括:进行了入连锁和不入连锁的特殊召唤;发动了确定要特殊召唤的效果但是效果被无效 -- 不包括:发动了确定要特殊召唤的效果但是发动被无效 end function Duel.CheckAttackActivity(player) -- 检查玩家player本回合有没有进行过攻击。 end
mit
judos/robotMiningSite
source/control/migration_0_2_3.lua
1
1076
function migration_0_2_3() -- migrate data to new variables -- Entities are invalid since type has changed -> search them and replace again in schedule -- Current relevant data: -- global.robotMiningSite.schedule[tick][idEntity] = $entity -- global.robotMiningSite.entityData[idEntity] = { name=$name, ... } info(serpent.block(global.robotMiningSite.schedule)) for tick,arr in pairs(global.robotMiningSite.schedule) do for idEntity,entity in pairs(arr) do if not entity.valid then local data = global.robotMiningSite.entityData[idEntity] local entity = entityOfId_v21(idEntity,data.name) if entity then arr[idEntity] = entity local chestInv = data.providerChest.get_inventory(defines.inventory.chest) local entityInv = entity.get_inventory(defines.inventory.chest) if not moveInventoryToInventory(chestInv,entityInv) then spillInventory(chestInv,entity.surface,entity.position) end data.providerChest.destroy() data.providerChest = nil end end end end global.robotMiningSite.version = "0.2.3" end
gpl-3.0
neg-serg/notion
ioncore/ioncore_misc.lua
7
2578
-- -- ion/share/ioncore_misc.lua -- -- Copyright (c) Tuomo Valkonen 2004-2009. -- -- See the included file LICENSE for details. -- local group_tmpl = { type="WGroupWS" } local default_tmpl = { switchto=true } local empty = { type="WGroupWS", managed={} } local layouts={ empty = empty, default = empty, } --DOC -- Define a new workspace layout with name \var{name}, and -- attach/creation parameters given in \var{tab}. The layout -- "empty" may not be defined. function ioncore.deflayout(name, tab) assert(name ~= "empty") if name=="default" and not tab then layouts[name] = empty else layouts[name] = table.join(tab, group_tmpl) end end --DOC -- Get named layout (or all of the latter parameter is set, -- but this is for internal use only). function ioncore.getlayout(name, all) if all then return layouts else return layouts[name] end end ioncore.set{_get_layout=ioncore.getlayout} --DOC -- Create new workspace on screen \var{scr}. The table \var{tmpl} -- may be used to override parts of the layout named with \code{layout}. -- If no \var{layout} is given, "default" is used. function ioncore.create_ws(scr, tmpl, layout) local lo=ioncore.getlayout(layout or "default") assert(lo, TR("Unknown layout")) return scr:attach_new(table.join(tmpl or default_tmpl, lo)) end --DOC -- Find an object with type name \var{t} managing \var{obj} or one of -- its managers. function ioncore.find_manager(obj, t) while obj~=nil do if obj_is(obj, t) then return obj end obj=obj:manager() end end --DOC -- gettext+string.format function ioncore.TR(s, ...) return string.format(ioncore.gettext(s), ...) end --DOC -- Attach tagged regions to \var{reg}. The method of attach -- depends on the types of attached regions and whether \var{reg} -- implements \code{attach_framed} and \code{attach}. If \var{param} -- is not set, the default of \verb!{switchto=true}! is used. -- The function returns \code{true} if all tagged regions were -- succesfully attached, and \code{false} otherwisse. function ioncore.tagged_attach(reg, param) local errors=false if not param then param={switchto=true} end local tagged=function() return ioncore.tagged_first(true) end for r in tagged do local fn=((not obj_is(r, "WWindow") and reg.attach_framed) or reg.attach) if not (fn and fn(reg, r, param)) then errors=true end end return not errors end
lgpl-2.1
logzero/ValyriaTear
dat/battles/desert_cave_battle_anim.lua
3
3539
-- Desert cave scripted animation local ns = {} setmetatable(ns, {__index = _G}) desert_cave_battle_anim = ns; setfenv(1, ns); -- Animation members local rock_id = -1; local fog_id = -1; local anim_ids = {}; -- Fog related members local fog_x_position = 300.0; local fog_origin_x_position = 300.0; local fog_y_position = 500.0; local fog_alpha = 0.0; local fog_timer; local fog_time_length = 8000; local Battle = {}; local Script = {}; function Initialize(battle_instance) Battle = battle_instance; Script = Battle:GetScriptSupervisor(); -- Load the creatures animated background anim_ids[0] = Script:AddAnimation("img/backdrops/battle/desert_cave/desert_cave_creatures.lua"); -- Load small eyes animations anim_ids[1] = Script:AddAnimation("img/backdrops/battle/desert_cave/desert_cave_eyes1.lua"); anim_ids[2] = Script:AddAnimation("img/backdrops/battle/desert_cave/desert_cave_eyes2.lua"); -- Load the water drop animation anim_ids[3] = Script:AddAnimation("img/backdrops/battle/desert_cave/desert_cave_waterdrop.lua"); -- Load the water underground river animation anim_ids[4] = Script:AddAnimation("img/backdrops/battle/desert_cave/desert_cave_water.lua"); -- Construct a timer used to display the fog with a custom alpha value and position fog_timer = vt_system.SystemTimer(fog_time_length, 0); -- Load a fog image used later to be displayed dynamically on the battle ground fog_id = Script:AddImage("img/ambient/fog.png", 320.0, 256.0); -- Load a rock displayed in the foreground rock_id = Script:AddImage("img/backdrops/battle/rock.png", 54.0, 54.0); end function Update() -- fog -- Start the timer only at normal battle stage if ((fog_timer:IsRunning() == false) and (Battle:GetState() ~= vt_battle.BattleMode.BATTLE_STATE_INITIAL)) then fog_timer:Run(); end if (fog_timer:IsFinished()) then fog_timer:Initialize(fog_time_length, 0); fog_timer:Run(); -- Make the fog appear at random position fog_x_position = math.random(100.0, 700.0); fog_y_position = math.random(218.0, 568.0); fog_origin_x_position = fog_x_position; fog_alpha = 0.0; end fog_timer:Update(); -- update fog position and alpha fog_x_position = fog_origin_x_position - (100 * fog_timer:PercentComplete()); if (fog_timer:PercentComplete() <= 0.5) then -- fade in fog_alpha = fog_timer:PercentComplete() * 0.3 / 0.5; else -- fade out fog_alpha = 0.3 - (0.3 * (fog_timer:PercentComplete() - 0.5) / 0.5); end end local white_color = vt_video.Color(1.0, 1.0, 1.0, 1.0); function DrawBackground() -- Draw background main animations -- Creatures Script:DrawAnimation(anim_ids[0], 814.0, 9.0); -- Eyes 1 Script:DrawAnimation(anim_ids[1], 28.0, 112.0); -- Eyes 2 Script:DrawAnimation(anim_ids[2], 503.0, 21.0); -- Water drop Script:DrawAnimation(anim_ids[3], 200.0, 63.0); -- Water Script:DrawAnimation(anim_ids[4], 235.0, 110.0); -- Draw a rock in the background Script:DrawImage(rock_id, 800.0, 248.0, white_color); end local fog_color = vt_video.Color(1.0, 1.0, 1.0, 1.0); function DrawForeground() -- Draw the rock in the foreground Script:DrawImage(rock_id, 300.0, 618.0, white_color); -- Draw a random fog effect fog_color:SetAlpha(fog_alpha); Script:DrawImage(fog_id, fog_x_position, fog_y_position, fog_color); end
gpl-2.0
MrCerealGuy/Stonecraft
games/stonecraft_game/mods/ethereal/strawberry.lua
1
3321
local S = ethereal.intllib -- Strawberry (can also be planted as seed) minetest.register_craftitem("ethereal:strawberry", { description = S("Strawberry"), inventory_image = "strawberry.png", wield_image = "strawberry.png", groups = {food_strawberry = 1, food_berry = 1, flammable = 2}, on_place = function(itemstack, placer, pointed_thing) return farming.place_seed(itemstack, placer, pointed_thing, "ethereal:strawberry_1") end, on_use = minetest.item_eat(1), }) -- Define Strawberry Bush growth stages local crop_def = { drawtype = "plantlike", tiles = {"strawberry_1.png"}, paramtype = "light", sunlight_propagates = true, waving = 1, walkable = false, buildable_to = true, drop = "", selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5} }, groups = { snappy = 3, flammable = 2, plant = 1, attached_node = 1, not_in_creative_inventory = 1, growing = 1 }, sounds = default.node_sound_leaves_defaults(), } --stage 1 minetest.register_node("ethereal:strawberry_1", table.copy(crop_def)) -- stage 2 crop_def.tiles = {"strawberry_2.png"} minetest.register_node("ethereal:strawberry_2", table.copy(crop_def)) -- stage 3 crop_def.tiles = {"strawberry_3.png"} minetest.register_node("ethereal:strawberry_3", table.copy(crop_def)) -- stage 4 crop_def.tiles = {"strawberry_4.png"} minetest.register_node("ethereal:strawberry_4", table.copy(crop_def)) -- stage 5 crop_def.tiles = {"strawberry_5.png"} minetest.register_node("ethereal:strawberry_5", table.copy(crop_def)) -- stage 6 crop_def.tiles = {"strawberry_6.png"} crop_def.drop = { items = { {items = {"ethereal:strawberry 1"},rarity = 2}, {items = {"ethereal:strawberry 2"},rarity = 3}, } } minetest.register_node("ethereal:strawberry_6", table.copy(crop_def)) -- stage 7 crop_def.tiles = {"strawberry_7.png"} crop_def.drop = { items = { {items = {"ethereal:strawberry 1"},rarity = 1}, {items = {"ethereal:strawberry 2"},rarity = 3}, } } minetest.register_node("ethereal:strawberry_7", table.copy(crop_def)) -- stage 8 crop_def.tiles = {"strawberry_8.png"} crop_def.groups.growing = 0 crop_def.drop = { items = { {items = {"ethereal:strawberry 2"},rarity = 1}, {items = {"ethereal:strawberry 3"},rarity = 3}, } } minetest.register_node("ethereal:strawberry_8", table.copy(crop_def)) -- growing routine if farming redo isn't present if not farming or not farming.mod or farming.mod ~= "redo" then minetest.register_abm({ label = "Ethereal grow strawberry", nodenames = { "ethereal:strawberry_1", "ethereal:strawberry_2", "ethereal:strawberry_3", "ethereal:strawberry_4", "ethereal:strawberry_5", "ethereal:strawberry_6", "ethereal:strawberry_7" }, neighbors = {"farming:soil_wet"}, interval = 9, chance = 20, catch_up = false, action = function(pos, node) if not abm_allowed.yes then return end -- are we on wet soil? pos.y = pos.y - 1 if minetest.get_item_group(minetest.get_node(pos).name, "soil") < 3 then return end pos.y = pos.y + 1 -- do we have enough light? local light = minetest.get_node_light(pos) if not light or light < 13 then return end -- grow to next stage local num = node.name:split("_")[2] node.name = "ethereal:strawberry_" .. tonumber(num + 1) minetest.swap_node(pos, node) end }) end -- END IF
gpl-3.0
spixi/wesnoth
data/lua/functional.lua
4
2431
-- This file implements equivalents of various higher-order WFL functions local functional = {} function functional.filter(input, condition) local filtered_table = {} for _,v in ipairs(input) do if condition(v) then table.insert(filtered_table, v) end end return filtered_table end function functional.filter_map(input, condition) local filtered_table = {} for k,v in pairs(input) do if condition(k, v) then filtered_table[k] = v end end return filtered_table end function functional.find(input, condition) for _,v in ipairs(input) do if condition(v) then return v end end end function functional.find_map(input, condition) for k,v in pairs(input) do if condition(k,v) then return k, v end end end function functional.choose(input, value) -- Equivalent of choose() function in Formula AI -- Returns element of a table with the largest @value (a function) -- Also returns the max value and the index local max_value, best_input, best_key = -9e99 for k,v in ipairs(input) do local v2 = value(v) if v2 > max_value then max_value, best_input, best_key = v2, v, k end end return best_input, max_value, best_key end function functional.choose_map(input, value) -- Equivalent of choose() function in Formula AI -- Returns element of a table with the largest @value (a function) -- Also returns the max value and the index local max_value, best_input, best_key = -9e99 for k,v in pairs(input) do local v2 = value(k, v) if v2 > max_value then max_value, best_input, best_key = v2, v, k end end return {key = best_key, value = best_input}, max_value end function functional.map(input, formula) local mapped_table = {} for k,v in pairs(input) do if type(k) == 'number' then table.insert(mapped_table, formula(v)) else mapped_table[k] = formula(v, k) end end return mapped_table end function functional.reduce(input, operator, identity) local result = identity or 0 for _, v in ipairs(input) do result = operator(result, v) end return result end function functional.take_while(input, condition) local truncated_table = {} for _,v in ipairs(input) do if not condition(v) then break end table.insert(truncated_table, v) end return truncated_table end return functional
gpl-2.0
khanasbot/Avatar_Bot
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
parsa13881/serverbot
plugins/location.lua
93
1704
-- Implement a command !loc [area] which uses -- the static map API to get a location image -- Not sure if this is the proper way -- Intent: get_latlong is in time.lua, we need it here -- loadfile "time.lua" -- Globals -- If you have a google api key for the geocoding/timezone api do local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" function get_staticmap(area) local api = base_api .. "/staticmap?" -- Get a sense of scale local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale=="locality" then zoom=8 elseif scale=="country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~=nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end function run(msg, matches) local receiver = get_receiver(msg) local lat,lng,url = get_staticmap(matches[1]) -- Send the actual location, is a google maps link send_location(receiver, lat, lng, ok_cb, false) -- Send a picture of the map, which takes scale into account send_photo_from_url(receiver, url) -- Return a link to the google maps stuff is now not needed anymore return nil end return { description = "Gets information about a location, maplink and overview", usage = "!loc (location): Gets information about a location, maplink and overview", patterns = {"^!loc (.*)$"}, run = run } end --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
crazyboy11/bot122
plugins/cpu.lua
244
1893
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!$ uptime') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!$ uptime", patterns = {"^!$ uptime", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
dmccuskey/dmc-gestures
examples/gesture-memtest/dmc_corona/lib/dmc_lua/lua_patch.lua
44
7239
--====================================================================-- -- lua_patch.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 David McCuskey 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. --]] --====================================================================-- --== DMC Lua Library : Lua Patch --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.3.0" --====================================================================-- --== Imports local Utils = {} -- make copying easier --====================================================================-- --== Setup, Constants local lua_patch_data = { string_format_active = false, table_pop_active = false, print_output_active = false } local PATCH_TABLE_POP = 'table-pop' local PATCH_STRING_FORMAT = 'string-format' local PATCH_PRINT_OUTPUT = 'print-output' local addTablePopPatch, removeTablePopPatch local addStringFormatPatch, removeStringFormatPatch local addPrintOutputPatch, removePrintOutputPatch local sfmt = string.format local tstr = tostring --====================================================================-- --== Support Functions --== Start: copy from lua_utils ==-- -- stringFormatting() -- implement Python-style string replacement -- http://lua-users.org/wiki/StringInterpolation -- function Utils.stringFormatting( a, b ) if not b then return a elseif type(b) == "table" then return string.format(a, unpack(b)) else return string.format(a, b) end end --== End: copy from lua_utils ==-- local function addLuaPatch( input ) -- print( "Patch.addLuaPatch" ) if type(input)=='table' then -- pass elseif type(input)=='string' then input = { input } elseif type(input)=='nil' then input = { PATCH_TABLE_POP, PATCH_STRING_FORMAT, PATCH_PRINT_OUTPUT } else error( sfmt( "Lua Patch:: unknown patch type '%s'", type(input) ) ) end for i, patch_name in ipairs( input ) do if patch_name == PATCH_TABLE_POP then addTablePopPatch() elseif patch_name == PATCH_STRING_FORMAT then addStringFormatPatch() elseif patch_name == PATCH_PRINT_OUTPUT then addPrintOutputPatch() else error( sfmt( "Lua Patch:: unknown patch name '%s'", tostring( patch ) ) ) end end end local function addAllLuaPatches() addLuaPatch( nil ) end local function removeLuaPatch( input ) -- print( "Patch.removeLuaPatch", input ) if type(input)=='table' then -- pass elseif type(input)=='string' then input = { input } elseif type(input)=='nil' then input = { PATCH_TABLE_POP, PATCH_STRING_FORMAT } else error( "Lua Patch:: unknown patch type '" .. type(input) .. "'" ) end for i, patch_name in ipairs( input ) do if patch_name == PATCH_TABLE_POP then removeTablePopPatch() elseif patch_name == PATCH_STRING_FORMAT then removeStringFormatPatch() elseif patch_name == PATCH_PRINT_OUTPUT then removePrintOutputPatch() else error( "Lua Patch:: unknown patch name '" .. tostring( patch ) .. "'" ) end end end local function removeAllLuaPatches() addAllLuaPatches( nil ) end --====================================================================-- --== Setup Patches --====================================================================-- --======================================================-- -- Python-style string formatting addStringFormatPatch = function() if lua_patch_data.string_format_active == false then print( "Lua Patch::activating patch '" .. PATCH_STRING_FORMAT .. "'" ) getmetatable("").__mod = Utils.stringFormatting lua_patch_data.string_format_active = true end end removeStringFormatPatch = function() if lua_patch_data.string_format_active == true then print( "Lua Patch::deactivating patch '" .. PATCH_STRING_FORMAT .. "'" ) getmetatable("").__mod = nil lua_patch_data.string_format_active = false end end --======================================================-- -- Python-style table pop() method -- tablePop() -- local function tablePop( t, v ) assert( type(t)=='table', "Patch:tablePop, expected table arg for pop()") assert( v, "Patch:tablePop, expected key" ) local res = t[v] t[v] = nil return res end addTablePopPatch = function() if lua_patch_data.table_pop_active == false then print( "Lua Patch::activating patch '" .. PATCH_TABLE_POP .. "'" ) table.pop = tablePop lua_patch_data.table_pop_active = true end end removeTablePopPatch = function() if lua_patch_data.table_pop_active == true then print( "Lua Patch::deactivating patch '" .. PATCH_TABLE_POP .. "'" ) table.pop = nil lua_patch_data.table_pop_active = false end end --======================================================-- -- Print Output functions local function printNotice( str, params ) params = params or {} if params.newline==nil then params.newline=true end --==-- local prefix = "NOTICE" local nlstr = "\n\n" if not params.newline then nlstr='' end print( sfmt( "%s[%s] %s%s", nlstr, prefix, tstr(str), nlstr ) ) end local function printWarning( str, params ) params = params or {} if params.newline==nil then params.newline=true end --==-- local prefix = "WARNING" local nlstr = "\n\n" if not params.newline then nlstr='' end print( sfmt( "%s[%s] %s%s", nlstr, prefix, tstr(str), nlstr ) ) end addPrintOutputPatch = function() if lua_patch_data.print_output_active == false then _G.pnotice = printNotice _G.pwarn = printWarning lua_patch_data.print_output_active = true end end removePrintOutputPatch = function() if lua_patch_data.print_output_active == true then _G.pnotice = nil _G.pwarn = nil lua_patch_data.print_output_active = false end end --====================================================================-- --== Patch Facade --====================================================================-- return { PATCH_TABLE_POP=PATCH_TABLE_POP, PATCH_STRING_FORMAT=PATCH_STRING_FORMAT, PATCH_PRINT_OUTPUT=PATCH_PRINT_OUTPUT, addPatch = addLuaPatch, addAllPatches=addAllLuaPatches, removePatch=removeLuaPatch, removeAllPatches=removeAllLuaPatch, }
mit
dmccuskey/dmc-gestures
examples/gesture-pinch-basic/dmc_corona/lib/dmc_lua/lua_patch.lua
44
7239
--====================================================================-- -- lua_patch.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 David McCuskey 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. --]] --====================================================================-- --== DMC Lua Library : Lua Patch --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.3.0" --====================================================================-- --== Imports local Utils = {} -- make copying easier --====================================================================-- --== Setup, Constants local lua_patch_data = { string_format_active = false, table_pop_active = false, print_output_active = false } local PATCH_TABLE_POP = 'table-pop' local PATCH_STRING_FORMAT = 'string-format' local PATCH_PRINT_OUTPUT = 'print-output' local addTablePopPatch, removeTablePopPatch local addStringFormatPatch, removeStringFormatPatch local addPrintOutputPatch, removePrintOutputPatch local sfmt = string.format local tstr = tostring --====================================================================-- --== Support Functions --== Start: copy from lua_utils ==-- -- stringFormatting() -- implement Python-style string replacement -- http://lua-users.org/wiki/StringInterpolation -- function Utils.stringFormatting( a, b ) if not b then return a elseif type(b) == "table" then return string.format(a, unpack(b)) else return string.format(a, b) end end --== End: copy from lua_utils ==-- local function addLuaPatch( input ) -- print( "Patch.addLuaPatch" ) if type(input)=='table' then -- pass elseif type(input)=='string' then input = { input } elseif type(input)=='nil' then input = { PATCH_TABLE_POP, PATCH_STRING_FORMAT, PATCH_PRINT_OUTPUT } else error( sfmt( "Lua Patch:: unknown patch type '%s'", type(input) ) ) end for i, patch_name in ipairs( input ) do if patch_name == PATCH_TABLE_POP then addTablePopPatch() elseif patch_name == PATCH_STRING_FORMAT then addStringFormatPatch() elseif patch_name == PATCH_PRINT_OUTPUT then addPrintOutputPatch() else error( sfmt( "Lua Patch:: unknown patch name '%s'", tostring( patch ) ) ) end end end local function addAllLuaPatches() addLuaPatch( nil ) end local function removeLuaPatch( input ) -- print( "Patch.removeLuaPatch", input ) if type(input)=='table' then -- pass elseif type(input)=='string' then input = { input } elseif type(input)=='nil' then input = { PATCH_TABLE_POP, PATCH_STRING_FORMAT } else error( "Lua Patch:: unknown patch type '" .. type(input) .. "'" ) end for i, patch_name in ipairs( input ) do if patch_name == PATCH_TABLE_POP then removeTablePopPatch() elseif patch_name == PATCH_STRING_FORMAT then removeStringFormatPatch() elseif patch_name == PATCH_PRINT_OUTPUT then removePrintOutputPatch() else error( "Lua Patch:: unknown patch name '" .. tostring( patch ) .. "'" ) end end end local function removeAllLuaPatches() addAllLuaPatches( nil ) end --====================================================================-- --== Setup Patches --====================================================================-- --======================================================-- -- Python-style string formatting addStringFormatPatch = function() if lua_patch_data.string_format_active == false then print( "Lua Patch::activating patch '" .. PATCH_STRING_FORMAT .. "'" ) getmetatable("").__mod = Utils.stringFormatting lua_patch_data.string_format_active = true end end removeStringFormatPatch = function() if lua_patch_data.string_format_active == true then print( "Lua Patch::deactivating patch '" .. PATCH_STRING_FORMAT .. "'" ) getmetatable("").__mod = nil lua_patch_data.string_format_active = false end end --======================================================-- -- Python-style table pop() method -- tablePop() -- local function tablePop( t, v ) assert( type(t)=='table', "Patch:tablePop, expected table arg for pop()") assert( v, "Patch:tablePop, expected key" ) local res = t[v] t[v] = nil return res end addTablePopPatch = function() if lua_patch_data.table_pop_active == false then print( "Lua Patch::activating patch '" .. PATCH_TABLE_POP .. "'" ) table.pop = tablePop lua_patch_data.table_pop_active = true end end removeTablePopPatch = function() if lua_patch_data.table_pop_active == true then print( "Lua Patch::deactivating patch '" .. PATCH_TABLE_POP .. "'" ) table.pop = nil lua_patch_data.table_pop_active = false end end --======================================================-- -- Print Output functions local function printNotice( str, params ) params = params or {} if params.newline==nil then params.newline=true end --==-- local prefix = "NOTICE" local nlstr = "\n\n" if not params.newline then nlstr='' end print( sfmt( "%s[%s] %s%s", nlstr, prefix, tstr(str), nlstr ) ) end local function printWarning( str, params ) params = params or {} if params.newline==nil then params.newline=true end --==-- local prefix = "WARNING" local nlstr = "\n\n" if not params.newline then nlstr='' end print( sfmt( "%s[%s] %s%s", nlstr, prefix, tstr(str), nlstr ) ) end addPrintOutputPatch = function() if lua_patch_data.print_output_active == false then _G.pnotice = printNotice _G.pwarn = printWarning lua_patch_data.print_output_active = true end end removePrintOutputPatch = function() if lua_patch_data.print_output_active == true then _G.pnotice = nil _G.pwarn = nil lua_patch_data.print_output_active = false end end --====================================================================-- --== Patch Facade --====================================================================-- return { PATCH_TABLE_POP=PATCH_TABLE_POP, PATCH_STRING_FORMAT=PATCH_STRING_FORMAT, PATCH_PRINT_OUTPUT=PATCH_PRINT_OUTPUT, addPatch = addLuaPatch, addAllPatches=addAllLuaPatches, removePatch=removeLuaPatch, removeAllPatches=removeAllLuaPatch, }
mit
hfjgjfg/persianguard75
plugins/cpu.lua
244
1893
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!$ uptime') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!$ uptime", patterns = {"^!$ uptime", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
Spesiel/LuckysDashboard
@Resources/VarFileInit.lua
1
2925
------- Metadata -------------------------------------------------------------- -- VarFileInit -- Author: Lucky Penny -- Description: Creates all variables files with default values. -- License: Creative Commons BY-NC-SA 3.0 -- Version: 0.0.3 -- -- Initialize(): As described ------------------------------------------------------------------------------- -- Create the files for the variables unless it already exists function Initialize() -- variables.var local doRefreshForVariables = GenerateVarsFile("variables", "TemplateVariablesDefault", "Variables", "") -- clocks.var local doRefreshForClocks = GenerateVarsFile("clocks", "TemplateClocksDefault", "ClocksSettings", "") -- disks.var local doRefreshForDisks = GenerateVarsFile("disks", "TemplateDisksDefault", "DisksSettings", "Disk1") -- network.var local doRefreshForNetwork = GenerateVarsFile("network", "TemplateNetworkDefault", "NetworkSettings", "") -- fortune.var local doRefreshForFortune = GenerateVarsFile("fortune", "TemplateFortuneDefault", "FortuneSettings", "") -- gpus.var local doRefreshForGpus = GenerateVarsFile("gpus", "TemplateGpusDefault", "GpusSettings", "Gpu1") -- cpu.var local doRefreshForCpu = GenerateVarsFile("cpu", "TemplateCpuDefault", "CpuSettings", "Cpu1") if doRefreshForVariables or doRefreshForClocks or doRefreshForDisks or doRefreshForNetwork or doRefreshForFortune or doRefreshForGpus or doRefreshForCpu then SKIN:Bang("!Refresh") end end -- Generator for var files function GenerateVarsFile(varFileName,templateFileName,name,substitute) dofile(SKIN:ReplaceVariables("#@#").."FileHelper.lua") if next(ReadIni(SKIN:ReplaceVariables("#@#")..varFileName..".var")) then return false end local variables = {} local templateFileVars = ReadFile(SKIN:ReplaceVariables("#@#").."Templates\\"..templateFileName..".inc") variables = GenerateMetadata(variables,name,"Lucky Penny","Variables for the "..varFileName,"0.0.3") table.insert(variables,"[Variables]") for _,value in ipairs(templateFileVars) do local str = "" if value:find("|") then str = value:gsub("|",substitute) else str = value end table.insert(variables,str) end WriteFile(table.concat(variables,"\n"),SKIN:ReplaceVariables("#@#")..varFileName..".var") return true end function GenerateMetadata(inputtable,name,author,information,version) table.insert(inputtable,"[Metadata]") table.insert(inputtable,"Name="..name) table.insert(inputtable,"Author="..author) table.insert(inputtable,"Information="..information) table.insert(inputtable,"License=Creative Commons BY-NC-SA 3.0") table.insert(inputtable,"Version="..version.."\n") return inputtable end
unlicense
T3hArco/skeyler-gamemodes
Sassilization/entities/effects/paralyze/init.lua
1
2224
local matLight = Material( "models/shiny" ) local matRefract = Material( "models/spawn_effect" ) function EFFECT:Init( data ) local ent = Unit:Unit(data:GetScale()) if ( ent == NULL ) then return end self.Time = data:GetMagnitude() self.LifeTime = CurTime() + self.Time self.ParentEntity = ent ent.healing = nil ent.effecttime = self.Time ent.paralyzed = self.LifeTime self:SetModel(ent:GetModel()) self:SetPos(ent:GetPos()) self:SetAngles(ent:GetAngles()) self:SetParent(ent:GetEntity()) self:SetMaterial( matLight ) local sequence = ent:GetSequence() if sequence then self:ResetSequence( sequence ) end end function EFFECT:Think() if (!self.ParentEntity or !self.ParentEntity:IsValid()) then return false end if (self.ParentEntity.healing) then self.ParentEntity.paralyzed = nil return false elseif CurTime() > self.LifeTime then self.ParentEntity.paralyzed = nil return false end local sequence = self.ParentEntity:GetSequence() if self.Entity:GetSequence() ~= sequence then self.Entity:ResetSequence( sequence ) end return true end function EFFECT:Render() if self.ParentEntity == NULL then return end if self.Entity == NULL then return end self:SetPos( self.Entity:GetPos() ) local Fraction = (self.LifeTime - CurTime()) / self.Time Fraction = math.Clamp( Fraction, 0, 1 ) self.Entity:SetColor( Color( 0, 255, 0, 1 + math.sin( Fraction * math.pi ) * 100 ) ) local EyeNormal = self.Entity:GetPos() - EyePos() local Distance = EyeNormal:Length() EyeNormal:Normalize() local Pos = EyePos() + EyeNormal * Distance * 0.01 cam.Start3D( Pos, EyeAngles() ) render.MaterialOverride( matLight ) self:DrawModel() render.MaterialOverride( 0 ) -- If our card is DX8 or above draw the refraction effect if ( render.GetDXLevel() >= 80 ) then -- Update the refraction texture with whatever is drawn right now render.UpdateRefractTexture() matRefract:SetFloat( "$refractamount", Fraction ^ 2 * 0.05 ) render.MaterialOverride( matRefract ) self.Entity:DrawModel() render.MaterialOverride( 0 ) end cam.End3D() end
bsd-3-clause
McGlaspie/mvm
lua/mvm/bots/CommanderBrain.lua
1
6283
//---------------------------------------- // //---------------------------------------- Script.Load("lua/mvm/bots/PlayerBrain.lua") local gDebug = false //---------------------------------------- // Utility funcs //---------------------------------------- function GetRandomBuildPosition(techId, aroundPos, maxDist) local extents = GetExtents(techId) local validationFunc = LookupTechData(techId, kTechDataRequiresInfestation, nil) and GetIsPointOnInfestation or nil local randPos = GetRandomSpawnForCapsule(extents.y, extents.x, aroundPos, 0.01, maxDist, EntityFilterAll(), validationFunc) return randPos end //---------------------------------------- // //---------------------------------------- class 'CommanderBrain' (PlayerBrain) function CommanderBrain:GetShouldDebug(bot) //return true return gDebug end //---------------------------------------- // This enumerates EVERYTHING that the commander can do right now - EVERYTHING // The result is a hash table with techId as keys and an array of units as values. These are the units that you can perform the tech on (it may just be com) //---------------------------------------- function CommanderBrain:GetDoableTechIds(com) local teamNum = self:GetExpectedTeamNumber() local tree = GetTechTree(teamNum) local doables = {} local function GetIsActionButton(techNode) return not techNode:GetIsPassive() and not techNode:GetIsMenu() end local function HandleUnitActionButton(unit, techNode) assert( techNode ~= nil ) assert( GetIsActionButton(techNode) ) local techId = techNode:GetTechId() if techNode:GetAvailable() then // check cool down if com:GetIsTechOnCooldown(techId) then return end local allowed, canAfford = unit:GetTechAllowed( techId, techNode, com ) if self.debug then Print("%s-%d.%s = %s (%s^%s)", unit:GetClassName(), unit:GetId(), EnumToString(kTechId, techId), ToString( allowed and canAfford ), ToString(allowed), ToString(canAfford) ) end if allowed and canAfford then if doables[techId] == nil then doables[techId] = {} end table.insert( doables[techId], unit ) end end end //---------------------------------------- // Go through all units, gather all the things we can do with them //---------------------------------------- local function CollectUnitDoableTechIds( unit, menuTechId, doables, visitedMenus ) // Very important. Menus are naturally cyclic, since there is always a "back" button visitedMenus[menuTechId] = true local techIds = unit:GetTechButtons( menuTechId ) or {} for _, techId in ipairs(techIds) do if techId ~= kTechId.None then local techNode = tree:GetTechNode(techId) assert(techNode ~= nil) if techNode:GetIsMenu() and visitedMenus[techId] == nil then CollectUnitDoableTechIds( unit, techId, doables, visitedMenus ) elseif GetIsActionButton(techNode) then HandleUnitActionButton( unit, techNode ) end end end end for _, unit in ipairs(GetEntitiesForTeam("ScriptActor", teamNum)) do CollectUnitDoableTechIds( unit, kTechId.RootMenu, doables, {} ) end //---------------------------------------- // Now do commander buttons. They are all in a two-level table, so no need to recurse. //---------------------------------------- // Now do commander buttons - all of them for _,menu in pairs( com:GetButtonTable() ) do for _,techId in ipairs(menu) do if techId ~= kTechId.None then local techNode = tree:GetTechNode(techId) assert( techNode ~= nil ) if GetIsActionButton(techNode) then HandleUnitActionButton( com, techNode ) end end end end return doables end //---------------------------------------- // Helper function for subclasses //---------------------------------------- function CommanderBrain:ExecuteTechId( commander, techId, position, hostEntity ) DebugPrint("Combrain executing %s at %s on %s", EnumToString(kTechId, techId), ToString(position), hostEntity == nil and "<no target>" or hostEntity:GetClassName()) local techNode = commander:GetTechTree():GetTechNode( techId ) local allowed, canAfford = hostEntity:GetTechAllowed( techId, techNode, commander ) assert( allowed and canAfford ) // We should probably use ProcessTechTreeAction instead here... commander.isBotRequestedAction = true // Hackapalooza... local success, keepGoing = commander:ProcessTechTreeActionForEntity( techNode, position, Vector(0,1,0), // normal true, // isCommanderPicked 0, // orientation hostEntity, nil // trace ) if success then // set cooldown local cooldown = LookupTechData(techId, kTechDataCooldown, 0) if cooldown ~= 0 then commander:SetTechCooldown(techId, cooldown, Shared.GetTime()) end else DebugPrint("COM BOT ERROR: Failed to perform action %s", EnumToString(kTechId, techId)) end return success end //---------------------------------------- // //---------------------------------------- function CommanderBrain:Update( bot, move ) PlayerBrain.Update( self, bot, move ) // Move a little bit to avoid AFK kick bot:GetMotion():SetDesiredMoveDirection( Vector( math.random(), math.random(), math.random() ) ) end //---------------------------------------- // //---------------------------------------- Event.Hook("Console_bot_com", function() gDebug = not gDebug Print("CommanderBrain debug = %s", ToString(gDebug)) end)
gpl-3.0
T3hArco/skeyler-gamemodes
Sassilization/gamemode/server/buildings.lua
1
12087
-------------------- -- Sassilization -- By Sassafrass / Spacetech / LuaPineapple -------------------- local HULL_BUILDER hook.Add( "InitPostEntity", "Load_queryphys", function() HULL_BUILDER = ents.Create("prop_physics") HULL_BUILDER:SetSolid( SOLID_NONE ) HULL_BUILDER:SetCollisionGroup( COLLISION_GROUP_NONE ) HULL_BUILDER:SetMoveType( MOVETYPE_NONE ) HULL_BUILDER:EnableCustomCollisions(false) local phys = HULL_BUILDER:GetPhysicsObject() if( phys:IsValid() ) then phys:EnableCollisions( false ) phys:EnableMotion( false ) end end ) function SA.CreateConvexMeshBox( mins, maxs ) HULL_BUILDER:PhysicsInitBox( mins, maxs ) local phys = HULL_BUILDER:GetPhysicsObject() HULL_BUILDER:SetSolid( SOLID_NONE ) HULL_BUILDER:SetCollisionGroup( COLLISION_GROUP_NONE ) HULL_BUILDER:SetMoveType( MOVETYPE_NONE ) if( phys:IsValid() ) then phys:EnableCollisions( false ) phys:EnableMotion( false ) return phys:GetMesh() end end function GM:SpawnBuilding(Name, Pos, Ang, Empire, NoTable) local Building = ents.Create("building_" .. Name) Building.dt.bBuilt = false Building:SetControl(Empire) Building:SetPos(Pos) Building:SetAngles(Ang) Building:Spawn() Building:Activate() Building.CachedType = Name return Building end function GM:SpawnWall( Empire, WallTower1, WallTower2, Positions ) local Building = ents.Create("building_wall") Building:SetControl( Empire ) Building:Spawn() Building:Activate() Building:SetTowers( WallTower1, WallTower2, Positions ) --Sets Position and Angle return Building end concommand.Add("sa_buildwall", function(ply, cmd, args) if(ply.NextBuildBuilding and ply.NextBuildBuilding > CurTime()) then return end ply.NextBuildBuilding = CurTime() + 0.1; local Empire = ply:GetEmpire() if( not Empire ) then return end if( GAMEMODE:MaxEntLimitReached() ) then ply:ChatPrint( "Map has reached Max Entity Limit" ) return end if #args < 4 then return end local Building = building.GetBuilding("walltower") if(not Building) then return end if(not building.CanBuild(Empire, "walltower")) then return end local aimVec = Vector( tonumber(args[1]), tonumber(args[2]), tonumber(args[3]) ) local tower1 = Entity( args[4] ) local tower2 = NULL if args[5] then tower2 = Entity( args[5] ) end --MsgN("T1: ", tower1) --MsgN("T2: ", tower2) if( tower1 ~= NULL ) then if( not (IsValid( tower1 ) and tower1:IsWallTower() and tower1:GetEmpire() == Empire) ) then print( "Invalid tower1\n" ) return end else return end if( tower2 ~= NULL ) then if( not (IsValid( tower2 ) and tower2:IsWallTower() and tower2:GetEmpire() == Empire) ) then print( "Invalid tower2\n" ) return end else tower2 = nil end local trace = {} trace.start = ply:EyePos() trace.endpos = trace.start + aimVec * 2048; trace.filter = ply; trace.mask = MASK_SHOT_HULL local tr = util.TraceLine( trace ); local Positions, Cost; if( tower1 and tower2 ) then local pos1 = tower1:GetPos() local pos2 = tower2:GetPos() local midpos = pos1:MidPoint(pos2) --Is it feasible that the player can create the wall at this position? if( tr.HitPos:Distance( (pos1 + pos2)*0.5 ) >= 10 ) then return end --Can this wall be built here? if( not ( GAMEMODE:NoInbetweenWall( tower1, tower2 ) and GAMEMODE:ValidWallAngle( tower1, midpos ) and GAMEMODE:ValidWallAngle( tower2, midpos ) ) ) then ply:ChatPrint( "Couldn't make wall here" ) return end Positions, Cost = GAMEMODE:CalculateWallPositions( pos1, pos2, {tower1, tower2} ) if( Positions ) then if( Empire:GetFood() >= Building.Food*Cost and Empire:GetIron() >= Building.Iron*Cost and Empire:GetGold() >= Building.Gold*Cost ) then Empire:AddFood(-Building.Food*Cost or 0) Empire:AddIron(-Building.Iron*Cost or 0) Empire:AddGold(-Building.Gold*Cost or 0) GAMEMODE:SpawnWall( Empire, tower1, tower2, Positions ) ply:ChatPrint( "Successfully linked two Wall Towers." ) end end elseif( tower1 ) then local CanFit, Pos, Ang = GAMEMODE:CanFit(tr, Building.OBBMins, Building.OBBMaxs, Angle(0, 0, 0), false, false) if( not GAMEMODE:IsPosInTerritory( Pos, ply:GetEmpire():GetID() ) ) then return end if( Pos:Distance( tower1:GetPos() ) < 10 ) then ply:ChatPrint( "Wall too close to another" ) return end if( not ( GAMEMODE:ValidWallAngle( tower1, Pos ) ) ) then ply:ChatPrint( "Couldn't make wall here" ) return end Positions, Cost = GAMEMODE:CalculateWallPositions( Pos, tower1:GetPos(), tower1 ) if( Positions ) then if( Empire:GetFood() >= Building.Food*Cost and Empire:GetIron() >= Building.Iron*Cost and Empire:GetGold() >= Building.Gold*Cost ) then if Empire.spawns[Building.id] != nil then Empire.spawns[Building.id] = Empire.spawns[Building.id] + 1 else Empire.spawns[Building.id] = 1 end Empire:AddFood(-Building.Food*Cost or 0) Empire:AddIron(-Building.Iron*Cost or 0) Empire:AddGold(-Building.Gold*Cost or 0) local tower = GAMEMODE:SpawnBuilding("walltower", Pos, Ang, Empire) GAMEMODE:SpawnWall( Empire, tower1, tower, Positions ) ply:ChatPrint( "You created a new Connected Wall" ) end else ply:ChatPrint( "Failed to create Connected Wall" ) end end end ) util.AddNetworkString( "NetworkConnectedGates" ) concommand.Add("sa_buildbuilding", function(ply, cmd, args) if(ply.NextBuildBuilding and ply.NextBuildBuilding > CurTime()) then return end ply.NextBuildBuilding = CurTime() + 0.05 local Empire = ply:GetEmpire() if( not Empire ) then return end if( GAMEMODE:MaxEntLimitReached() ) then ply:ChatPrint( "Map has reached Max Entity Limit" ) return end if(table.Count(args) ~= 13) then ply:ChatPrint( "Incorrect argument count for " .. tostring( cmd ) ) return end local Name = args[1] local x = tonumber(args[2]) local y = tonumber(args[3]) local z = tonumber(args[4]) local Pitch = tonumber(args[5]) local Yaw = tonumber(args[6]) local Roll = tonumber(args[7]) local obbsMins = Vector(args[8], args[9], args[10]) local obbsMaxs = Vector(args[11], args[12], args[13]) local Building = building.GetBuilding(Name) if(not Building) then return end if(not building.CanBuild(Empire, Name)) then return end local trace = {} trace.start = ply:EyePos() trace.endpos = trace.start + Vector(tonumber(x), tonumber(y), tonumber(z)) * 2048 trace.filter = ply trace.mask = MASK_SHOT_HULL local tr = util.TraceLine( trace ) if Name == "gate" then closest = nil vecPos = Vector(tonumber(x), tonumber(y), tonumber(z)) for _, e in pairs(ents.FindByClass("building_wall")) do if e:GetEmpire() == Empire then if closest == nil then closest = e end if closest:GetPos():Distance(vecPos) > e:GetPos():Distance(vecPos) then closest = e end end end end if Name == "walltower" or Name == "shieldmono" then --I do these seperately because for some reason CanFit returns false on either of these if they're on a displacement CanFit, Pos, Ang = GAMEMODE:CanFit(tr, obbsMins, obbsMaxs, Angle(Pitch, Yaw, Roll), "wall", Building.Foundation) else CanFit, Pos, Ang = GAMEMODE:CanFit(tr, obbsMins, obbsMaxs, Angle(Pitch, Yaw, Roll), true, Building.Foundation) end if(not CanFit and Name ~= "gate") then return end if Building.Require and Building.Require["city"] then if( not GAMEMODE:IsPosInTerritory( Pos, ply:GetEmpire():GetID() ) and Name ~= "gate" ) then return end else if( not GAMEMODE:IsPosInTerritory( Pos, 0 ) and Name ~= "gate" ) then return end end if(Name == "gate") then if(closest and closest:IsWall()) then local Valid, Walls, Guards = GAMEMODE:CalculateGate(Empire, closest, vecPos) if (Valid) then Empire:AddFood( -Building.Food or 0) Empire:AddIron( -Building.Iron or 0) Empire:AddGold( -Building.Gold or 0) Pos = vecPos + GATE_OFFSET Ang = Walls[1]:GetAngles() local Ent = GAMEMODE:SpawnBuilding(Name, Pos, Ang, Empire) Ent:Materialize() Ent.HiddenWalls = {} local LeftTower = GAMEMODE:SpawnBuilding(Name, Pos + (Ang:Right() * 26), Ang, Empire) LeftTower:ChangeSettings("Wall", "models/mrgiggles/sassilization/walltower.mdl", true) LeftTower:Materialize() Ent:AddConnected(LeftTower) LeftTower:AddConnected(Ent) LeftTower.HiddenWalls = {} local RightTower = GAMEMODE:SpawnBuilding(Name, Pos + (Ang:Right() * -26), Ang, Empire) RightTower:ChangeSettings("Wall", "models/mrgiggles/sassilization/walltower.mdl", true) RightTower:Materialize() Ent:AddConnected(RightTower) RightTower:AddConnected(Ent) RightTower.HiddenWalls = {} LeftTower:AddConnected(RightTower) RightTower:AddConnected(LeftTower) for k,v in pairs(Walls) do v.gate = Ent closest:HideWallSegment(v) table.insert(LeftTower.HiddenWalls, v) table.insert(Ent.HiddenWalls, v) table.insert(RightTower.HiddenWalls, v) end for k,v in pairs(Guards) do table.insert(v.ConnectedGates, Ent) for i,d in pairs(player.GetAll()) do timer.Simple(0.1, function() net.Start("NetworkConnectedGates") net.WriteEntity(v) net.WriteEntity(Ent) net.Send(d) net.Start("NetworkConnectedGates") net.WriteEntity(v) net.WriteEntity(LeftTower) net.Send(d) net.Start("NetworkConnectedGates") net.WriteEntity(v) net.WriteEntity(RightTower) net.Send(d) end) end end if Empire.spawns[Building.id] != nil then Empire.spawns[Building.id] = Empire.spawns[Building.id] + 1 else Empire.spawns[Building.id] = 1 end return end else ply:ChatPrint( "Gate too close to another" ) return end elseif(Name == "walltower") then local towers = GAMEMODE:GetWallTowersInSphere( Pos, 128, Empire ) for _, tower in pairs( towers ) do if( Pos:Distance( tower:GetPos() ) < SA.MIN_WALL_DISTANCE ) then ply:ChatPrint( "Wall too close to another" ) return end end end if Name != "tower" && Name != "workshop" then if Empire.spawns[Building.id] != nil then Empire.spawns[Building.id] = Empire.spawns[Building.id] + 1 else Empire.spawns[Building.id] = 1 end else if Empire.spawns[Building.id[1]] != nil then Empire.spawns[Building.id[1]] = Empire.spawns[Building.id[1]] + 1 else Empire.spawns[Building.id[1]] = 1 end end Empire:AddFood(-Building.Food or 0) Empire:AddIron(-Building.Iron or 0) Empire:AddGold(-Building.Gold or 0) GAMEMODE:SpawnBuilding(Name, Pos, Ang, Empire) end) concommand.Add("sa_upgradebuilding", function(ply, cmd, args) local Name = args[1] local EntIndex = args[2] if(table.Count(args) ~= 2) then return end local Empire = ply:GetEmpire() if( not Empire ) then return end local Building = building.GetBuilding(Name) if(not Building) then return end if(not building.CanBuild(Empire, Name)) then return end local Ent = Entity(EntIndex) if(not IsValid(Ent)) then return end if(not building.CanUpgrade(Empire, Name, Ent:GetLevel() + 1)) then return end if(not Ent:IsUpgradeable()) then return end if Empire.spawns[Building.id[Ent:GetLevel() + 1]] != nil then Empire.spawns[Building.id[Ent:GetLevel() + 1]] = Empire.spawns[Building.id[Ent:GetLevel() + 1]] + 1 else Empire.spawns[Building.id[Ent:GetLevel() + 1]] = 1 end Empire:AddFood(-Building.Food or 0) Empire:AddIron(-Building.Iron or 0) Empire:AddGold(-Building.Gold or 0) Ent:Upgrade() end)
bsd-3-clause
pydsigner/naev
dat/snd/music.lua
10
6708
--[[ -- music will get called with a string parameter indicating status -- valid parameters: -- load - game is loading -- land - player landed -- takeoff - player took off -- combat - player just got a hostile onscreen -- idle - current playing music ran out ]]-- last = "idle" -- Faction-specific songs. factional = { Collective = { "collective1", "collective2", "automat" }, Empire = { "empire1", "empire2" }, Sirius = { "sirius1", "sirius2" }, Dvaered = { "dvaered1", "dvaered2" }, ["Za'lek"] = { "zalek1", "zalek2" } } function choose( str ) -- Stores all the available sound types and their functions choose_table = { ["load"] = choose_load, ["intro"] = choose_intro, ["credits"] = choose_credits, ["land"] = choose_land, ["takeoff"] = choose_takeoff, ["ambient"] = choose_ambient, ["combat"] = choose_combat } -- Means to only change song if needed if str == nil then str = "ambient" end -- If we are over idling then we do weird stuff local changed = false if str == "idle" and last ~= "idle" then -- We'll play the same as last unless it was takeoff if last == "takeoff" then changed = choose_ambient() else changed = choose(last) end -- Normal case else changed = choose_table[ str ]() end if changed and str ~= "idle" then last = str -- save the last string so we can use it end end --[[ -- @brief Checks to see if a song is being played, if it is it stops it. -- -- @return true if music is playing. --]] function checkIfPlayingOrStop( song ) if music.isPlaying() then if music.current() ~= song then music.stop() end return true end return false end --[[ -- @brief Play a song if it's not currently playing. --]] function playIfNotPlaying( song ) if checkIfPlayingOrStop( song ) then return true end music.load( song ) music.play() return true end --[[ -- @brief Chooses Loading songs. --]] function choose_load () return playIfNotPlaying( "machina" ) end --[[ -- @brief Chooses Intro songs. --]] function choose_intro () return playIfNotPlaying( "intro" ) end --[[ -- @brief Chooses Credit songs. --]] function choose_credits () return playIfNotPlaying( "empire1" ) end --[[ -- @brief Chooses landing songs. --]] function choose_land () local pnt = planet.cur() local class = pnt:class() if class == "M" then mus = { "agriculture" } elseif class == "O" then mus = { "ocean" } elseif class == "P" then mus = { "snow" } else if pnt:services()["inhabited"] then mus = { "cosmostation", "upbeat" } else mus = { "agriculture" } end end music.load( mus[ rnd.rnd(1, #mus) ] ) music.play() return true end -- Takeoff songs function choose_takeoff () -- No need to restart if last == "takeoff" and music.isPlaying() then return true end takeoff = { "liftoff", "launch2", "launch3chatstart" } music.load( takeoff[ rnd.rnd(1,#takeoff) ]) music.play() return true end -- Save old data last_sysFaction = nil last_sysNebuDens = nil last_sysNebuVol = nil ambient_neutral = { "ambient2", "mission", "peace1", "peace2", "peace4", "peace6", "void_sensor", "ambiphonic", "ambient4", "terminal", "eureka", "ambient2_5" } --[[ -- @brief Chooses ambient songs. --]] function choose_ambient () local force = true -- Check to see if we want to update if music.isPlaying() then if last == "takeoff" then return true elseif last == "ambient" then force = false end -- Get music information. local songname, songpos = music.current() -- Do not change songs so soon if songpos < 10. then music.delay( "ambient", 10. - songpos ) return false end end -- Get information about the current system local sys = system.cur() local factions = sys:presences() local faction = sys:faction() if faction then faction = faction:name() end local nebu_dens, nebu_vol = sys:nebula() -- Check to see if changing faction zone if faction ~= last_sysFaction then -- Table must not be empty if next(factions) ~= nil then force = true end if force then last_sysFaction = faction end end -- Check to see if entering nebula local nebu = nebu_dens > 0 if nebu ~= last_sysNebuDens then force = true last_sysNebuDens = nebu end -- Must be forced if force then -- Choose the music, bias by faction first local add_neutral = false local neutral_prob = 0.6 if factional[faction] then ambient = factional[faction] if faction ~= "Collective" then add_neutral = true end elseif nebu then ambient = { "ambient1", "ambient3" } add_neutral = true else ambient = ambient_neutral end -- Clobber array with generic songs if allowed. if add_neutral and rnd.rnd() < neutral_prob then ambient = ambient_neutral end -- Make sure it's not already in the list or that we have to stop the -- currently playing song. if music.isPlaying() then local cur = music.current() for k,v in pairs(ambient) do if cur == v then return false end end music.stop() return true end -- Load music and play music.load( ambient[ rnd.rnd(1,#ambient) ] ) music.play() return true end return false end --[[ -- @brief Chooses battle songs. --]] function choose_combat () -- Get some data about the system local sys = system.cur() local nebu_dens, nebu_vol = sys:nebula() local nebu = nebu_dens > 0 if nebu then combat = { "nebu_battle1", "nebu_battle2", "battlesomething1", "battlesomething2", "combat1", "combat2" } else combat = { "galacticbattle", "flf_battle1", "battlesomething1", "battlesomething2", "combat3", "combat1", "combat2" } end -- Make sure it's not already in the list or that we have to stop the -- currently playing song. if music.isPlaying() then local cur = music.current() for k,v in pairs(combat) do if cur == v then return false end end music.stop() return true end music.load( combat[ rnd.rnd(1,#combat) ] ) music.play() return true end
gpl-3.0
pirate/snabbswitch
src/lib/json.lua
29
10286
-- JSON4Lua: JSON encoding / decoding support for the Lua language. -- json Module. -- Author: Craig Mason-Jones -- Homepage: http://json.luaforge.net/ -- Version: 0.9.40 -- This module is released under the MIT License (MIT). -- -- NOTE: This is only the decode functionality ripped out from JSON4Lua. -- See: https://github.com/craigmj/json4lua module(..., package.seeall) local math = require('math') local string = require("string") local table = require("table") local base = _G -- Private functions local decode_scanArray local decode_scanComment local decode_scanConstant local decode_scanNumber local decode_scanObject local decode_scanString local decode_scanWhitespace --- Decodes a JSON string and returns the decoded value as a Lua data structure / value. -- @param s The string to scan. -- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1. -- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil, -- and the position of the first character after -- the scanned JSON object. function decode(s, startPos) startPos = startPos and startPos or 1 startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']') local curChar = string.sub(s,startPos,startPos) -- Object if curChar=='{' then return decode_scanObject(s,startPos) end -- Array if curChar=='[' then return decode_scanArray(s,startPos) end -- Number if string.find("+-0123456789.e", curChar, 1, true) then return decode_scanNumber(s,startPos) end -- String if curChar==[["]] or curChar==[[']] then return decode_scanString(s,startPos) end if string.sub(s,startPos,startPos+1)=='/*' then return decode(s, decode_scanComment(s,startPos)) end -- Otherwise, it must be a constant return decode_scanConstant(s,startPos) end --- The null function allows one to specify a null value in an associative array (which is otherwise -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null } function null() return null -- so json.null() will also return null ;-) end ----------------------------------------------------------------------------- -- Internal, PRIVATE functions. -- Following a Python-like convention, I have prefixed all these 'PRIVATE' -- functions with an underscore. ----------------------------------------------------------------------------- --- Scans an array from JSON into a Lua object -- startPos begins at the start of the array. -- Returns the array and the next starting position -- @param s The string being scanned. -- @param startPos The starting position for the scan. -- @return table, int The scanned array as a table, and the position of the next character to scan. function decode_scanArray(s,startPos) local array = {} -- The return value local stringLen = string.len(s) base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s ) startPos = startPos + 1 -- Infinite loop for array elements repeat startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.') local curChar = string.sub(s,startPos,startPos) if (curChar==']') then return array, startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.') object, startPos = decode(s,startPos) table.insert(array,object) until false end --- Scans a comment and discards the comment. -- Returns the position of the next character following the comment. -- @param string s The JSON string to scan. -- @param int startPos The starting position of the comment function decode_scanComment(s, startPos) base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos) local endPos = string.find(s,'*/',startPos+2) base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos) return endPos+2 end --- Scans for given constants: true, false or null -- Returns the appropriate Lua type, and the position of the next character to read. -- @param s The string being scanned. -- @param startPos The position in the string at which to start scanning. -- @return object, int The object (true, false or nil) and the position at which the next character should be -- scanned. function decode_scanConstant(s, startPos) local consts = { ["true"] = true, ["false"] = false, ["null"] = nil } local constNames = {"true","false","null"} for i,k in base.pairs(constNames) do --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k) if string.sub(s,startPos, startPos + string.len(k) -1 )==k then return consts[k], startPos + string.len(k) end end base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos) end --- Scans a number from the JSON encoded string. -- (in fact, also is able to scan numeric +- eqns, which is not -- in the JSON spec.) -- Returns the number, and the position of the next character -- after the number. -- @param s The string being scanned. -- @param startPos The position at which to start scanning. -- @return number, int The extracted number and the position of the next character to scan. function decode_scanNumber(s,startPos) local endPos = startPos+1 local stringLen = string.len(s) local acceptableChars = "+-0123456789.e" while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true) and endPos<=stringLen ) do endPos = endPos + 1 end local stringValue = 'return ' .. string.sub(s,startPos, endPos-1) local stringEval = base.loadstring(stringValue) base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos) return stringEval(), endPos end --- Scans a JSON object into a Lua object. -- startPos begins at the start of the object. -- Returns the object and the next starting position. -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return table, int The scanned object as a table and the position of the next character to scan. function decode_scanObject(s,startPos) local object = {} local stringLen = string.len(s) local key, value base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s) startPos = startPos + 1 repeat startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.') local curChar = string.sub(s,startPos,startPos) if (curChar=='}') then return object,startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.') -- Scan the key key, startPos = decode(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos) startPos = decode_scanWhitespace(s,startPos+1) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) value, startPos = decode(s,startPos) object[key]=value until false -- infinite loop while key-value pairs are found end --- Scans a JSON string from the opening inverted comma or single quote to the -- end of the string. -- Returns the string extracted as a Lua string, -- and the position of the next non-string character -- (after the closing inverted comma or single quote). -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return string, int The extracted string as a Lua string, and the next character to parse. function decode_scanString(s,startPos) base.assert(startPos, 'decode_scanString(..) called without start position') local startChar = string.sub(s,startPos,startPos) base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string') local escaped = false local endPos = startPos + 1 local bEnded = false local stringLen = string.len(s) repeat local curChar = string.sub(s,endPos,endPos) -- Character escaping is only used to escape the string delimiters if not escaped then if curChar==[[\]] then escaped = true else bEnded = curChar==startChar end else -- If we're escaped, we accept the current character come what may escaped = false end endPos = endPos + 1 base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos) until bEnded local stringValue = 'return ' .. string.sub(s, startPos, endPos-1) local stringEval = base.loadstring(stringValue) base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos) return stringEval(), endPos end --- Scans a JSON string skipping all whitespace from the current start position. -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached. -- @param s The string being scanned -- @param startPos The starting position where we should begin removing whitespace. -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string -- was reached. function decode_scanWhitespace(s,startPos) local whitespace=" \n\r\t" local stringLen = string.len(s) while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do startPos = startPos + 1 end return startPos end
apache-2.0
xing634325131/Luci-0.11.1
modules/niu/luasrc/model/cbi/niu/wireless/ap.lua
51
1406
local cursor = require "luci.model.uci".cursor() if not cursor:get("wireless", "ap") then cursor:section("wireless", "wifi-iface", "ap", {device = "_", doth = "1", _niu = "1", mode = "ap"}) cursor:save("wireless") end local function deviceroute(self) cursor:unload("wireless") local d = cursor:get("wireless", "ap", "device") local t = cursor:get("wireless", "ap", "_cfgtpl") if d ~= "none" then cursor:delete_all("wireless", "wifi-iface", function(s) return s.device == d and s._niu ~= "1" end) cursor:set("wireless", d, "disabled", 0) cursor:set("wireless", "ap", "network", "lan") if t and #t > 0 then cursor:delete("wireless", "ap", "_cfgtpl") cursor:set("wireless", "ap", "ssid", cursor:get("wireless", "bridge", "ssid")) cursor:set("wireless", "ap", "encryption", cursor:get("wireless", "bridge", "encryption")) cursor:set("wireless", "ap", "key", cursor:get("wireless", "bridge", "key")) cursor:set("wireless", "ap", "wds", "1") end self:set_route("ap1") else cursor:delete("wireless", "ap", "network") end cursor:save("wireless") end local d = Delegator() d.allow_finish = true d.allow_back = true d.allow_cancel = true d:add("device", "niu/wireless/apdevice") d:add("deviceroute", deviceroute) d:set("ap1", "niu/wireless/ap1") function d.on_cancel() cursor:revert("wireless") end function d.on_done() cursor:commit("wireless") end return d
apache-2.0
salorium/awesome
lib/wibox/layout/stack.lua
3
4327
--------------------------------------------------------------------------- -- A stacked layout. -- -- This layout display widgets on top of each other. It can be used to overlay -- a `wibox.widget.textbox` on top of a `awful.widget.progressbar` or manage -- "pages" where only one is visible at any given moment. -- -- The indices are going from 1 (the bottom of the stack) up to the top of -- the stack. The order can be changed either using `:swap` or `:raise`. -- --@DOC_wibox_layout_defaults_stack_EXAMPLE@ -- @author Emmanuel Lepage Vallee -- @copyright 2016 Emmanuel Lepage Vallee -- @release @AWESOME_VERSION@ -- @classmod wibox.layout.stack --------------------------------------------------------------------------- local base = require("wibox.widget.base" ) local fixed = require("wibox.layout.fixed") local table = table local pairs = pairs local util = require("awful.util") local stack = {mt={}} --@DOC_fixed_COMMON@ --- Add some widgets to the given stack layout -- @param layout The layout you are modifying. -- @tparam widget ... Widgets that should be added (must at least be one) -- @name add -- @class function --- Remove a widget from the layout -- @tparam index The widget index to remove -- @treturn boolean index If the operation is successful -- @name remove -- @class function --- Insert a new widget in the layout at position `index` -- @tparam number index The position -- @param widget The widget -- @treturn boolean If the operation is successful -- @name insert -- @class function --- Remove one or more widgets from the layout -- The last parameter can be a boolean, forcing a recursive seach of the -- widget(s) to remove. -- @param widget ... Widgets that should be removed (must at least be one) -- @treturn boolean If the operation is successful -- @name remove_widgets -- @class function --- Add spacing between each layout widgets -- @property spacing -- @tparam number spacing Spacing between widgets. function stack:layout(_, width, height) local result = {} local spacing = self._private.spacing for _, v in pairs(self._private.widgets) do table.insert(result, base.place_widget_at(v, spacing, spacing, width - 2*spacing, height - 2*spacing)) if self._private.top_only then break end end return result end function stack:fit(context, orig_width, orig_height) local max_w, max_h = 0,0 local spacing = self._private.spacing for _, v in pairs(self._private.widgets) do local w, h = base.fit_widget(self, context, v, orig_width, orig_height) max_w, max_h = math.max(max_w, w+2*spacing), math.max(max_h, h+2*spacing) end return math.min(max_w, orig_width), math.min(max_h, orig_height) end --- If only the first stack widget is drawn -- @property top_only function stack:get_top_only() return self._private.top_only end function stack:set_top_only(top_only) self._private.top_only = top_only end --- Raise a widget at `index` to the top of the stack -- @tparam number index the widget index to raise function stack:raise(index) if (not index) or self._private.widgets[index] then return end local w = self._private.widgets[index] table.remove(self._private.widgets, index) table.insert(self._private.widgets, w) self:emit_signal("widget::layout_changed") end --- Raise the first instance of `widget` -- @param widget The widget to raise -- @tparam[opt=false] boolean recursive Also look deeper in the hierarchy to -- find the widget function stack:raise_widget(widget, recursive) local idx, layout = self:index(widget, recursive) if not idx or not layout then return end -- Bubble up in the stack until the right index is found while layout and layout ~= self do idx, layout = self:index(layout, recursive) end if layout == self and idx ~= 1 then self:raise(idx) end end --- Create a new stack layout. -- @function wibox.layout.stack -- @treturn widget A new stack layout local function new(...) local ret = fixed.horizontal(...) util.table.crush(ret, stack, true) return ret end function stack.mt:__call(_, ...) return new(...) end --@DOC_widget_COMMON@ --@DOC_object_COMMON@ return setmetatable(stack, stack.mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
wcjscm/JackGame
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/TransitionSlideInR.lua
11
1045
-------------------------------- -- @module TransitionSlideInR -- @extend TransitionSlideInL -- @parent_module cc -------------------------------- -- Creates a transition with duration and incoming scene.<br> -- param t Duration time, in seconds.<br> -- param scene A given scene.<br> -- return A autoreleased TransitionSlideInR object. -- @function [parent=#TransitionSlideInR] create -- @param self -- @param #float t -- @param #cc.Scene scene -- @return TransitionSlideInR#TransitionSlideInR ret (return value: cc.TransitionSlideInR) -------------------------------- -- Returns the action that will be performed by the incoming and outgoing scene. -- @function [parent=#TransitionSlideInR] action -- @param self -- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval) -------------------------------- -- -- @function [parent=#TransitionSlideInR] TransitionSlideInR -- @param self -- @return TransitionSlideInR#TransitionSlideInR self (return value: cc.TransitionSlideInR) return nil
gpl-3.0
McGlaspie/mvm
lua/mvm/bots/TestBots.lua
1
1103
//============================================================================= // // lua/bots/TestBot.lua // // Created by Max McGuire (max@unknownworlds.com) // Copyright (c) 2011, Unknown Worlds Entertainment, Inc. // // This class is a simple bot that runs back and forth along a line for testing. // //============================================================================= Script.Load("lua/mvm/bots/Bot.lua") local gFreezeBots = false class 'TestBot' (Bot) function TestBot:GenerateMove() local move = Move() if self.switchTime == nil then self.switchTime = Shared.GetTime() + 2 self.direction = Vector(1, 0, 0) end if Shared.GetTime() >= self.switchTime then self.switchTime = Shared.GetTime() + 2 self.direction = -self.direction end move:Clear() move.yaw = 0 move.pitch = 0 if gFreezeBots then move.move = Vector(0,0,0) else move.move = self.direction end return move end Event.Hook("Console_freezebots", function() gFreezeBots = not gFreezeBots end)
gpl-3.0
wcjscm/JackGame
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/SkeletonRenderer.lua
2
5983
-------------------------------- -- @module SkeletonRenderer -- @extend Node,BlendProtocol -- @parent_module sp -------------------------------- -- -- @function [parent=#SkeletonRenderer] setTimeScale -- @param self -- @param #float scale -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] getDebugSlotsEnabled -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#SkeletonRenderer] setBonesToSetupPose -- @param self -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] initWithData -- @param self -- @param #spSkeletonData skeletonData -- @param #bool ownsSkeletonData -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] setDebugSlotsEnabled -- @param self -- @param #bool enabled -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- @overload self, string, string, float -- @overload self, string, spAtlas, float -- @function [parent=#SkeletonRenderer] initWithJsonFile -- @param self -- @param #string skeletonDataFile -- @param #spAtlas atlas -- @param #float scale -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] setSlotsToSetupPose -- @param self -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- @overload self, string, string, float -- @overload self, string, spAtlas, float -- @function [parent=#SkeletonRenderer] initWithBinaryFile -- @param self -- @param #string skeletonDataFile -- @param #spAtlas atlas -- @param #float scale -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] setToSetupPose -- @param self -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] getBlendFunc -- @param self -- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc) -------------------------------- -- -- @function [parent=#SkeletonRenderer] initialize -- @param self -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] setDebugBonesEnabled -- @param self -- @param #bool enabled -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] getDebugBonesEnabled -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#SkeletonRenderer] getTimeScale -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#SkeletonRenderer] setBlendFunc -- @param self -- @param #cc.BlendFunc blendFunc -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- @overload self, char -- @overload self, string -- @function [parent=#SkeletonRenderer] setSkin -- @param self -- @param #string skinName -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#SkeletonRenderer] getSkeleton -- @param self -- @return spSkeleton#spSkeleton ret (return value: spSkeleton) -------------------------------- -- @overload self, string, string, float -- @overload self, string, spAtlas, float -- @function [parent=#SkeletonRenderer] createWithFile -- @param self -- @param #string skeletonDataFile -- @param #spAtlas atlas -- @param #float scale -- @return SkeletonRenderer#SkeletonRenderer ret (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] create -- @param self -- @return SkeletonRenderer#SkeletonRenderer ret (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] onEnter -- @param self -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] onExit -- @param self -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] setOpacityModifyRGB -- @param self -- @param #bool value -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- -- @function [parent=#SkeletonRenderer] getBoundingBox -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- -- @function [parent=#SkeletonRenderer] isOpacityModifyRGB -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @overload self, spSkeletonData, bool -- @overload self -- @overload self, string, spAtlas, float -- @overload self, string, string, float -- @function [parent=#SkeletonRenderer] SkeletonRenderer -- @param self -- @param #string skeletonDataFile -- @param #string atlasFile -- @param #float scale -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) return nil
gpl-3.0
pydsigner/naev
dat/ai/include/atk_drone.lua
6
5707
--[[This file contains the attack profiles by ship type. --commonly used range and condition-based attack patterns are found in another file --Think functions for determining who to attack are found in another file --]] -- Initializes the drone function atk_drone_init () mem.atk_think = atk_drone_think mem.atk = atk_drone end --[[ -- Mainly targets small drones. --]] function atk_drone_think () local target = ai.target() -- Stop attacking if it doesn't exist if not ai.exists(target) then ai.poptask() return end local enemy = ai.getenemy_size(0, 200) -- find a small ship to attack local nearest_enemy = ai.getenemy() local dist = 0 local sizedist = 0 if enemy ~= nil then sizedist = ai.dist(enemy) end if nearest_enemy ~= nil then dist = ai.dist(nearest_enemy) end local range = ai.getweaprange(3, 0) -- Get new target if it's closer --prioritize targets within the size limit if enemy ~= target and enemy ~= nil then -- Shouldn't switch targets if close if sizedist > range * mem.atk_changetarget then ai.pushtask("attack", enemy ) end elseif nearest_enemy ~= target and nearest_enemy ~= nil then -- Shouldn't switch targets if close if dist > range * mem.atk_changetarget then ai.pushtask("attack", nearest_enemy ) end end end --[[ -- Enters ranged combat with the target - modified version for drones --]] function _atk_drone_ranged( target, dist ) --local dir = ai.face(target) -- Normal face the target local dir = ai.aim(target) -- Aim for the target -- TODO: should modify this line -- Check if in range if dist < ai.getweaprange( 4 ) and dir < 30 then ai.weapset( 4 ) end -- Always launch fighters ai.weapset( 5 ) -- Approach for melee if dir < 10 then ai.accel() end end --[[ -- Main control function for drone behavior. --]] function atk_drone () local target = _atk_com_think() if target == nil then return end -- Targeting stuff ai.hostile(target) -- Mark as hostile ai.settarget(target) -- Get stats about enemy local dist = ai.dist( target ) -- get distance local range = ai.getweaprange(3, 0) -- get my weapon range (?) -- We first bias towards range if dist > range * mem.atk_approach then _atk_drone_ranged( target, dist ) -- Use generic ranged function -- Otherwise melee else if ai.shipmass(target) < 200 then _atk_d_space_sup( target, dist ) else _atk_d_flyby( target, dist ) end end end --[[ -- Execute a sequence of close-in flyby attacks -- Uses a combination of facing and distance to determine what action to take -- This version is slightly less aggressive and cruises by the target --]] function _atk_d_flyby( target, dist ) local range = ai.getweaprange(3) local dir = 0 ai.weapset( 3 ) -- Forward/turrets -- Far away, must approach if dist > (3 * range) then dir = ai.idir(target) if dir < 10 and dir > -10 then --_atk_keep_distance() atk_spiral_approach(target, dist) -- mod ai.accel() else dir = ai.iface(target) end -- Midrange elseif dist > (0.75 * range) then --dir = ai.idir(target) dir = ai.aim(target) -- drones need to aim more to avoid circling --test if we're facing the target. If we are, keep approaching if dir <= 30 and dir > -30 then ai.iface(target) if dir < 10 and dir > -10 then ai.accel() end elseif dir > 30 and dir < 180 then ai.turn(1) ai.accel() else ai.turn(-1) ai.accel() end --otherwise we're close to the target and should attack until we start to zip away else dir = ai.aim(target) --not accellerating here is the only difference between the aggression levels. This can probably be an aggression AI parameter if mem.aggressive == true then ai.accel() end -- Shoot if should be shooting. if dir < 10 then ai.shoot() end ai.shoot(true) end end --[[ -- Attack Profile for a maneuverable ship engaging a maneuverable target -- --This is designed for drones engaging other drones --]] function _atk_d_space_sup( target, dist ) local range = ai.getweaprange(3) local dir = 0 ai.weapset( 3 ) -- Forward/turrets --if we're far away from the target, then turn and approach if dist > (1.1*range) then dir = ai.idir(target) if dir < 10 and dir > -10 then _atk_keep_distance() ai.accel() else dir = ai.iface(target) ai.accel() end elseif dist > 0.8* range then --drifting away from target, so emphasize intercept --course facing and accelerate to close --dir = ai.iface(target) dir = ai.aim(target) if dir < 15 and dir > -15 then ai.accel() end --within close range; aim and blast away with everything elseif dist > 0.4*range then dir = ai.aim(target) local dir2 = ai.idir(target) --accelerate and try to close --but only accel if it will be productive if dir2 < 15 and dir2 > -15 and ai.relvel(target) > -10 then ai.accel() end -- Shoot if should be shooting. if dir < 10 then ai.shoot() end ai.shoot(true) --within really close range (?); aim and blast away with everything else dir = ai.aim(target) -- Shoot if should be shooting. if dir < 15 then -- mod: was 10 ai.shoot() end ai.shoot(true) end end
gpl-3.0
SnarkyClark/luapgsql
test.lua
1
4103
package.cpath = "./?.so" require("pgsql") db = { dbname = "postgres", user = "pgsql", connect_timeout = 5 } print("\nRunning tests...") passed = true if passed then print("--connect") local info = '' -- we shall move this next line to C soon... for k, v in pairs(db) do info = string.format("%s%s=%s ", info, tostring(k), tostring(v)) end con, errmsg = pg.connect(string.format(info)) if not con then print(errmsg) passed = false else print(string.format("con = %s", tostring(con))) end end if passed then print("--string escape") s = "The quick brown fox's hide" print(string.format("%s = %s", s, con:escape(s))) if con:escape(s) ~= "The quick brown fox''s hide" then passed = false end end if passed then print("--sql error") local rs, errmsg = con:exec("select * from test where val1 = 1") if not rs then print(errmsg) else passed = false print(string.format("rs = %s, %d rows affected", tostring(rs), rs:count())) end end if passed then print("--sql type conversion") local rs, errmsg = con:exec("select null::varchar as \"null\", 't'::bool, 2::int2, 4::int4, 8::int8, 4.4::float4, 8.8::float8, '1970-01-01'::date") if not rs then print(errmsg) passed = false else data = rs:fetch() if data then print(string.format("[null](%s) = %s", type(data.null), tostring(data.null))) for k, v in pairs(data) do if type(k) == 'string' then print(string.format("[%s](%s) = %s", k, type(v), tostring(v))) end end else print("no data!") passed = false end end rs:clear() end q = [[ create temp table test ( val1 int primary key, val2 varchar ) ]] if passed then print("--sql create") local rs, errmsg = con:exec(q) if not rs then print(errmsg) passed = false else print(string.format("rs = %s", tostring(rs))) end rs:clear() end if passed then print("--sql insert") for i = 1, 3 do local rs, errmsg = con:exec("insert into test (val1, val2) values ($1, $2)", {i, string.char(64 + i)}) if not rs then print(errmsg) passed = false else print(string.format("rs = %s, %d rows affected", tostring(rs), rs:count())) end rs:clear() end end if passed then print("--sql update") for i = 1, 3 do local rs, errmsg = con:exec(string.format("update test set val2 = val2 || '*' where val1 = %d", i)) if not rs then print(errmsg) passed = false else print(string.format("rs = %s, %d rows affected", tostring(rs), rs:count())) end rs:clear() end end if passed then print("--sql select") rs, errmsg = con:exec("select * from test") if not rs then print(errmsg) passed = false else print(string.format("rs = %s, %d rows found", tostring(rs), rs:count())) end end if passed then print("--result fetch") local data = rs:fetch() while data do print(string.format("%s, %s", data.val1, data.val2)) data = rs:fetch() end end if passed then print("--sql select (using params)") rs, errmsg = con:exec("select * from test where val1 >= $1 and val2 >= $2", {0, 'A'}) if not rs then print(errmsg) passed = false else print(string.format("rs = %s, %d rows found", tostring(rs), rs:count())) end end if passed then print("--sql insert & select (using params with nulls)") local rs, errmsg = con:exec("insert into test (val1, val2) values ($1, $2)", {4, nil}, 2) if not rs then print(errmsg) passed = false else local rs, errmsg = con:exec("select * from test where val1 >= $1 and val2 is null", {0}) if not rs then print(errmsg) passed = false else print(string.format("rs = %s, %d rows found", tostring(rs), rs:count())) end end end if passed then print("--column iterator") local h = '' for index, name in rs:cols() do h = h .. string.format("[%d]%s, ", index, name) end print(h) print("--row iterator by index") for data in rs:rows() do -- column access by index local s = '' for i, v in ipairs(data) do s = s .. string.format("[%d]%s, ", i, v) end print(s) -- column access by name print(string.format("%d, %s", data.val1, data.val2)) end end if passed then print('All tests passed!') end
bsd-2-clause
stepjam/PyRep
pyrep/backend/simAddOnScript_PyRep.lua
1
13066
-- Additional PyRep functionality. To be placed in the CoppeliaSim root directory. function sysCall_init() end function sysCall_cleanup() end function sysCall_addOnScriptSuspend() end function sysCall_addOnScriptResume() end function sysCall_nonSimulation() end function sysCall_beforeMainScript() end function sysCall_beforeInstanceSwitch() end function sysCall_afterInstanceSwitch() end function sysCall_beforeSimulation() end function sysCall_afterSimulation() end _getConfig=function(jh) -- Returns the current robot configuration local config={} for i=1,#jh,1 do config[i]=sim.getJointPosition(jh[i]) end return config end _setConfig=function(jh, config) -- Applies the specified configuration to the robot if config then for i=1,#jh,1 do sim.setJointPosition(jh[i],config[i]) end end end _getConfigDistance=function(jointHandles,config1,config2) -- Returns the distance (in configuration space) between two configurations local d=0 for i=1,#jointHandles,1 do -- TODO *metric[i] should be here to give a weight to each joint. local dx=(config1[i]-config2[i])*1.0 d=d+dx*dx end return math.sqrt(d) end _sliceFromOffset=function(array, offset) sliced = {} for i=1,#array-offset,1 do sliced[i] = array[i+offset] end return sliced end _findPath=function(goalConfigs,cnt,jointHandles,algorithm,collisionPairs) -- Here we do path planning between the specified start and goal configurations. We run the search cnt times, -- and return the shortest path, and its length local startConfig = _getConfig(jointHandles) local task=simOMPL.createTask('task') simOMPL.setVerboseLevel(task, 0) alg = _getAlgorithm(algorithm) simOMPL.setAlgorithm(task,alg) local jSpaces={} for i=1,#jointHandles,1 do jh = jointHandles[i] cyclic, interval = sim.getJointInterval(jh) -- If there are huge intervals, then limit them if interval[1] < -6.28 and interval[2] > 6.28 then pos=sim.getJointPosition(jh) interval[1] = -6.28 interval[2] = 6.28 end local proj=i if i>3 then proj=0 end jSpaces[i]=simOMPL.createStateSpace('j_space'..i,simOMPL.StateSpaceType.joint_position,jh,{interval[1]},{interval[2]},proj) end simOMPL.setStateSpace(task, jSpaces) if collisionPairs ~= nil then simOMPL.setCollisionPairs(task, collisionPairs) end simOMPL.setStartState(task, startConfig) simOMPL.setGoalState(task, goalConfigs[1]) for i=2,#goalConfigs,1 do simOMPL.addGoalState(task,goalConfigs[i]) end local path=nil local l=999999999999 for i=1,cnt,1 do search_time = 4 local res,_path=simOMPL.compute(task,search_time,-1,300) -- Path can sometimes touch on invalid state during simplifying if res and _path then local is_valid=true local jhl=#jointHandles local pc=#_path/jhl for i=1,pc-1,1 do local config={} for j=1,jhl,1 do config[j]=_path[(i-1)*jhl+j] end is_valid=simOMPL.isStateValid(task, config) if not is_valid then break end end if is_valid then local _l=_getPathLength(_path, jointHandles) if _l<l then l=_l path=_path end end end end simOMPL.destroyTask(task) return path,l end _getAlgorithm=function(algorithm) -- Returns correct algorithm functions from user string alg = nil if algorithm == 'BiTRRT' then alg = simOMPL.Algorithm.BiTRRT elseif algorithm == 'BITstar' then alg = simOMPL.Algorithm.BITstar elseif algorithm == 'BKPIECE1' then alg = simOMPL.Algorithm.BKPIECE1 elseif algorithm == 'CForest' then alg = simOMPL.Algorithm.CForest elseif algorithm == 'EST' then alg = simOMPL.Algorithm.EST elseif algorithm == 'FMT' then alg = simOMPL.Algorithm.FMT elseif algorithm == 'KPIECE1' then alg = simOMPL.Algorithm.KPIECE1 elseif algorithm == 'LazyPRM' then alg = simOMPL.Algorithm.LazyPRM elseif algorithm == 'LazyPRMstar' then alg = simOMPL.Algorithm.LazyPRMstar elseif algorithm == 'LazyRRT' then alg = simOMPL.Algorithm.LazyRRT elseif algorithm == 'LBKPIECE1' then alg = simOMPL.Algorithm.LBKPIECE1 elseif algorithm == 'LBTRRT' then alg = simOMPL.Algorithm.LBTRRT elseif algorithm == 'PDST' then alg = simOMPL.Algorithm.PDST elseif algorithm == 'PRM' then alg = simOMPL.Algorithm.PRM elseif algorithm == 'PRMstar' then alg = simOMPL.Algorithm.PRMstar elseif algorithm == 'pRRT' then alg = simOMPL.Algorithm.pRRT elseif algorithm == 'pSBL' then alg = simOMPL.Algorithm.pSBL elseif algorithm == 'RRT' then alg = simOMPL.Algorithm.RRT elseif algorithm == 'RRTConnect' then alg = simOMPL.Algorithm.RRTConnect elseif algorithm == 'RRTstar' then alg = simOMPL.Algorithm.RRTstar elseif algorithm == 'SBL' then alg = simOMPL.Algorithm.SBL elseif algorithm == 'SPARS' then alg = simOMPL.Algorithm.SPARS elseif algorithm == 'SPARStwo' then alg = simOMPL.Algorithm.SPARStwo elseif algorithm == 'STRIDE' then alg = simOMPL.Algorithm.STRIDE elseif algorithm == 'TRRT' then alg = simOMPL.Algorithm.TRRT end return alg end _getPathLength=function(path, jointHandles) -- Returns the length of the path in configuration space local d=0 local l=#jointHandles local pc=#path/l for i=1,pc-1,1 do local config1, config2 = _beforeAfterConfigFromPath(path, i, l) d=d+_getConfigDistance(jointHandles,config1,config2) end return d end _beforeAfterConfigFromPath=function(path, path_index, num_handles) local config1 = {} local config2 = {} for i=1,num_handles,1 do config1[i] = path[(path_index-1)*num_handles+i] config2[i] = path[path_index*num_handles+i] end return config1, config2 end _getPoseOnPath=function(pathHandle, relativeDistance) local pos = sim.getPositionOnPath(pathHandle, relativeDistance) local ori = sim.getOrientationOnPath(pathHandle, relativeDistance) return pos, ori end getNonlinearPath=function(inInts,inFloats,inStrings,inBuffer) algorithm = inStrings[1] collisionHandle = inInts[1] ignoreCollisions = inInts[2] searchCntPerGoalConfig = inInts[3] jointHandles = _sliceFromOffset(inInts, 3) collisionPairs={collisionHandle, sim.handle_all} if ignoreCollisions==1 then collisionPairs=nil end local configCnt = #inFloats/#jointHandles goalConfigs = {} for i=1,configCnt,1 do local config={} for j=1,#jointHandles,1 do table.insert(config, inFloats[((i-1) * #jointHandles)+j]) end table.insert(goalConfigs, config) end -- Search a path from current config to a goal config. path = _findPath(goalConfigs, searchCntPerGoalConfig, jointHandles, algorithm, collisionPairs) if path == nil then path = {} end return {},path,{},'' end getPathFromCartesianPath=function(inInts,inFloats,inStrings,inBuffer) pathHandle = inInts[1] ikGroup = inInts[2] ikTarget = inInts[3] jointHandles = _sliceFromOffset(inInts, 3) collisionPairs = nil--{collisionHandle, sim.handle_all} orientationCorrection = inFloats local initIkPos = sim.getObjectPosition(ikTarget, -1) local initIkOri = sim.getObjectOrientation(ikTarget, -1) local originalConfig = _getConfig(jointHandles) local i = 0.05 local fullPath = {} local failed = false while i <= 1.0 do pos, ori = _getPoseOnPath(pathHandle, i) sim.setObjectPosition(ikTarget, -1, pos) sim.setObjectOrientation(ikTarget, -1, ori) intermediatePath = sim.generateIkPath(ikGroup,jointHandles,20,collisionPairs) if intermediatePath == nil then failed = true break end for j=1,#intermediatePath,1 do table.insert(fullPath, intermediatePath[j]) end newConfig = {} for j=#intermediatePath-#jointHandles+1,#intermediatePath,1 do table.insert(newConfig, intermediatePath[j]) end _setConfig(jointHandles, newConfig) i = i + 0.05 end _setConfig(jointHandles, originalConfig) sim.setObjectPosition(ikTarget, -1, initIkPos) sim.setObjectOrientation(ikTarget, -1, initIkOri) if failed then fullPath = {} end return {},fullPath,{},'' end insertPathControlPoint=function(inInts,inFloats,inStrings,inBuffer) local handle = inInts[1] local ptCnt = inInts[2] local floatSkip = 6 local ptData = {} for i=1,ptCnt,1 do local offset = (i-1)*floatSkip local ctrPos = {inFloats[offset+1], inFloats[offset+2], inFloats[offset+3]} local ctrOri = {inFloats[offset+4], inFloats[offset+5], inFloats[offset+6]} local vel = 0 local virDist = 0 local bezierPointsAtControl = 20 local bazierInterpolFactor1 = 0.990 local bazierInterpolFactor2 = 0.990 local auxFlags = 0 table.insert(ptData, ctrPos[1]) table.insert(ptData, ctrPos[2]) table.insert(ptData, ctrPos[3]) table.insert(ptData, ctrOri[1]) table.insert(ptData, ctrOri[2]) table.insert(ptData, ctrOri[3]) table.insert(ptData, vel) table.insert(ptData, virDist) table.insert(ptData, bezierPointsAtControl) table.insert(ptData, bazierInterpolFactor1) table.insert(ptData, bazierInterpolFactor2) end res = sim.insertPathCtrlPoints(handle, 0, 0, ptCnt, ptData) return {},{},{},'' end getBoxAdjustedMatrixAndFacingAngle=function(inInts,inFloats,inStrings,inBuffer) local baseHandle = inInts[1] local targetHandle = inInts[2] local p2=sim.getObjectPosition(targetHandle,-1) local p1=sim.getObjectPosition(baseHandle,-1) local p={p2[1]-p1[1],p2[2]-p1[2],p2[3]-p1[3]} local pl=math.sqrt(p[1]*p[1]+p[2]*p[2]+p[3]*p[3]) p[1]=p[1]/pl p[2]=p[2]/pl p[3]=p[3]/pl local m=sim.getObjectMatrix(targetHandle,-1) local matchingScore=0 for i=1,3,1 do v={m[0+i],m[4+i],m[8+i]} score=v[1]*p[1]+v[2]*p[2]+v[3]*p[3] if (math.abs(score)>matchingScore) then s=1 if (score<0) then s=-1 end matchingScore=math.abs(score) bestMatch={v[1]*s,v[2]*s,v[3]*s} end end angle=math.atan2(bestMatch[2],bestMatch[1]) m=sim.buildMatrix(p2,{0,0,angle}) table.insert(m,angle-math.pi/2) return {},m,{},'' end getNonlinearPathMobile=function(inInts,inFloats,inStrings,inBuffer) algorithm = inStrings[1] robotHandle = inInts[1] targetHandle = inInts[2] collisionHandle=inInts[3] ignoreCollisions=inInts[4] bd=inFloats[1] path_pts=inInts[5] collisionPairs={collisionHandle,sim.handle_all} if ignoreCollisions==1 then collisionPairs=nil end t=simOMPL.createTask('t') simOMPL.setVerboseLevel(t, 0) ss=simOMPL.createStateSpace('2d',simOMPL.StateSpaceType.dubins,robotHandle,{-bd,-bd},{bd,bd},1) state_h = simOMPL.setStateSpace(t,{ss}) simOMPL.setDubinsParams(ss,0.1,true) simOMPL.setAlgorithm(t,_getAlgorithm(algorithm)) if collisionPairs ~= nil then simOMPL.setCollisionPairs(t, collisionPairs) end startpos=sim.getObjectPosition(robotHandle,-1) startorient=sim.getObjectOrientation(robotHandle,-1) startpose={startpos[1],startpos[2],startorient[3]} simOMPL.setStartState(t,startpose) goalpos=sim.getObjectPosition(targetHandle,-1) goalorient=sim.getObjectOrientation(targetHandle,-1) goalpose={goalpos[1],goalpos[2],goalorient[3]} simOMPL.setGoalState(t,goalpose) r,path=simOMPL.compute(t,4,-1,path_pts) simOMPL.destroyTask(t) return {},path,{},'' end handleSpherical=function(inInts,inFloats,inStrings,inBuffer) local depth_handle=inInts[1] local rgb_handle=inInts[2] local six_sensor_handles = {inInts[3], inInts[4], inInts[5], inInts[6], inInts[7], inInts[8]} simVision.handleSpherical(rgb_handle, six_sensor_handles, 360, 180, depth_handle) return {},{},{},'' end
mit
salorium/awesome
tests/examples/shims/screen.lua
2
2646
local gears_obj = require("gears.object") local screen, meta = awesome._shim_fake_class() screen.count = 1 local function create_screen(args) local s = gears_obj() -- Copy the geo in case the args are mutated local geo = { x = args.x , y = args.y , width = args.width , height = args.height, } function s._resize(args2) geo.x = args2.x or geo.x geo.y = args2.y or geo.y geo.width = args2.width or geo.width geo.height = args2.height or geo.height end local wa = args.workarea_sides or 10 return setmetatable(s,{ __index = function(_, key) if key == "geometry" then return { x = geo.x or 0, y = geo.y or 0, width = geo.width , height = geo.height, } elseif key == "workarea" then return { x = (geo.x or 0) + wa , y = (geo.y or 0) + wa , width = geo.width - 2*wa, height = geo.height - 2*wa, } else return meta.__index(_, key) end end, __newindex = function(...) return meta.__newindex(...) end }) end local screens = {} function screen._add_screen(args) local s = create_screen(args) table.insert(screens, s) s.index = #screens screen[#screen+1] = s screen[s] = s end function screen._get_extents() local xmax, ymax for _, v in ipairs(screen) do if not xmax or v.geometry.x+v.geometry.width > xmax.geometry.x+xmax.geometry.width then xmax = v end if not ymax or v.geometry.y+v.geometry.height > ymax.geometry.y+ymax.geometry.height then ymax = v end end return xmax.geometry.x+xmax.geometry.width, ymax.geometry.y+ymax.geometry.height end function screen._clear() for i=1, #screen do screen[screen[i]] = nil screen[i] = nil end screens = {} end function screen._setup_grid(w, h, rows, args) args = args or {} screen._clear() for i, row in ipairs(rows) do for j=1, row do args.x = (j-1)*w + (j-1)*10 args.y = (i-1)*h + (i-1)*10 args.width = w args.height = h screen._add_screen(args) end end end screen._add_screen {width=320, height=240} return screen -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
T3hArco/skeyler-gamemodes
deathrun/gamemode/player_class/player_deathrun.lua
1
1541
---------------------------- -- Deathrun -- -- Created by Skeyler.com -- ---------------------------- AddCSLuaFile() DEFINE_BASECLASS("player_default") local PLAYER = {} PLAYER.DisplayName = "Deathrun Player" PLAYER.WalkSpeed = 250 -- How fast to move when not running PLAYER.RunSpeed = 250 -- How fast to move when running PLAYER.CrouchedWalkSpeed = 0.6 PLAYER.DuckSpeed = 0.4 -- How fast to go from not ducking, to ducking PLAYER.UnDuckSpeed = 0.01 -- How fast to go from ducking, to not ducking PLAYER.JumpPower = 268.4 -- How powerful our jump should be PLAYER.AvoidPlayers = false PLAYER.DropWeaponOnDie = true -- -- Called serverside only when the player spawns -- function PLAYER:Spawn() if self.Player:Team() == TEAM_DEATH then self.Player:SetModel("models/player/death.mdl") else hook.Call("PlayerSetModel", GAMEMODE, self.Player) end self.Player:SetHull(Vector(-16, -16, 0), Vector(16, 16, 62)) self.Player:SetHullDuck(Vector(-16, -16, 0), Vector(16, 16, 45)) self.Player:SetViewOffset(Vector(0, 0, 64)) self.Player:SetViewOffsetDucked(Vector(0, 0, 47)) end -- -- Called on spawn to give the player their default loadout -- function PLAYER:Loadout() self.Player:StripWeapons() self.Player:StripAmmo() if self.Player:Team() == TEAM_RUNNER then self.Player:Give("weapon_crowbar") elseif self.Player:Team() == TEAM_DEATH then self.Player:Give("weapon_scythe") end end player_manager.RegisterClass( "player_deathrun", PLAYER, "player_default" )
bsd-3-clause
wcjscm/JackGame
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ControlButton.lua
6
14222
-------------------------------- -- @module ControlButton -- @extend Control -- @parent_module cc -------------------------------- -- -- @function [parent=#ControlButton] isPushed -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Sets the title label to use for the specified state.<br> -- If a property is not specified for a state, the default is to use<br> -- the ButtonStateNormal value.<br> -- param label The title label to use for the specified state.<br> -- param state The state that uses the specified title. The values are described<br> -- in "CCControlState". -- @function [parent=#ControlButton] setTitleLabelForState -- @param self -- @param #cc.Node label -- @param #int state -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setAdjustBackgroundImage -- @param self -- @param #bool adjustBackgroundImage -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- Sets the title string to use for the specified state.<br> -- If a property is not specified for a state, the default is to use<br> -- the ButtonStateNormal value.<br> -- param title The title string to use for the specified state.<br> -- param state The state that uses the specified title. The values are described<br> -- in "CCControlState". -- @function [parent=#ControlButton] setTitleForState -- @param self -- @param #string title -- @param #int state -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setLabelAnchorPoint -- @param self -- @param #vec2_table var -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] getLabelAnchorPoint -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- -- @function [parent=#ControlButton] initWithBackgroundSprite -- @param self -- @param #ccui.Scale9Sprite sprite -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ControlButton] getTitleTTFSizeForState -- @param self -- @param #int state -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#ControlButton] setTitleTTFForState -- @param self -- @param #string fntFile -- @param #int state -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setTitleTTFSizeForState -- @param self -- @param #float size -- @param #int state -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setTitleLabel -- @param self -- @param #cc.Node var -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setPreferredSize -- @param self -- @param #size_table var -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] getCurrentTitleColor -- @param self -- @return color3b_table#color3b_table ret (return value: color3b_table) -------------------------------- -- -- @function [parent=#ControlButton] setZoomOnTouchDown -- @param self -- @param #bool var -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setBackgroundSprite -- @param self -- @param #ccui.Scale9Sprite var -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- Returns the background sprite used for a state.<br> -- param state The state that uses the background sprite. Possible values are<br> -- described in "CCControlState". -- @function [parent=#ControlButton] getBackgroundSpriteForState -- @param self -- @param #int state -- @return Scale9Sprite#Scale9Sprite ret (return value: ccui.Scale9Sprite) -------------------------------- -- -- @function [parent=#ControlButton] getHorizontalOrigin -- @param self -- @return int#int ret (return value: int) -------------------------------- -- -- @function [parent=#ControlButton] initWithTitleAndFontNameAndFontSize -- @param self -- @param #string title -- @param #string fontName -- @param #float fontSize -- @return bool#bool ret (return value: bool) -------------------------------- -- Sets the font of the label, changes the label to a BMFont if necessary.<br> -- param fntFile The name of the font to change to<br> -- param state The state that uses the specified fntFile. The values are described<br> -- in "CCControlState". -- @function [parent=#ControlButton] setTitleBMFontForState -- @param self -- @param #string fntFile -- @param #int state -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] getScaleRatio -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#ControlButton] getTitleTTFForState -- @param self -- @param #int state -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ControlButton] getBackgroundSprite -- @param self -- @return Scale9Sprite#Scale9Sprite ret (return value: ccui.Scale9Sprite) -------------------------------- -- Returns the title color used for a state.<br> -- param state The state that uses the specified color. The values are described<br> -- in "CCControlState".<br> -- return The color of the title for the specified state. -- @function [parent=#ControlButton] getTitleColorForState -- @param self -- @param #int state -- @return color3b_table#color3b_table ret (return value: color3b_table) -------------------------------- -- Sets the color of the title to use for the specified state.<br> -- param color The color of the title to use for the specified state.<br> -- param state The state that uses the specified color. The values are described<br> -- in "CCControlState". -- @function [parent=#ControlButton] setTitleColorForState -- @param self -- @param #color3b_table color -- @param #int state -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- Adjust the background image. YES by default. If the property is set to NO, the<br> -- background will use the preferred size of the background image. -- @function [parent=#ControlButton] doesAdjustBackgroundImage -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Sets the background spriteFrame to use for the specified button state.<br> -- param spriteFrame The background spriteFrame to use for the specified state.<br> -- param state The state that uses the specified image. The values are described<br> -- in "CCControlState". -- @function [parent=#ControlButton] setBackgroundSpriteFrameForState -- @param self -- @param #cc.SpriteFrame spriteFrame -- @param #int state -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- Sets the background sprite to use for the specified button state.<br> -- param sprite The background sprite to use for the specified state.<br> -- param state The state that uses the specified image. The values are described<br> -- in "CCControlState". -- @function [parent=#ControlButton] setBackgroundSpriteForState -- @param self -- @param #ccui.Scale9Sprite sprite -- @param #int state -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setScaleRatio -- @param self -- @param #float var -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] getTitleBMFontForState -- @param self -- @param #int state -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ControlButton] getTitleLabel -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- -- @function [parent=#ControlButton] getPreferredSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- -- @function [parent=#ControlButton] getVerticalMargin -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Returns the title label used for a state.<br> -- param state The state that uses the title label. Possible values are described<br> -- in "CCControlState". -- @function [parent=#ControlButton] getTitleLabelForState -- @param self -- @param #int state -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- -- @function [parent=#ControlButton] setMargins -- @param self -- @param #int marginH -- @param #int marginV -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- @overload self -- @overload self -- @function [parent=#ControlButton] getCurrentTitle -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ControlButton] initWithLabelAndBackgroundSprite -- @param self -- @param #cc.Node label -- @param #ccui.Scale9Sprite backgroundSprite -- @param #bool adjustBackGroundSize -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ControlButton] getZoomOnTouchDown -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Returns the title used for a state.<br> -- param state The state that uses the title. Possible values are described in<br> -- "CCControlState".<br> -- return The title for the specified state. -- @function [parent=#ControlButton] getTitleForState -- @param self -- @param #int state -- @return string#string ret (return value: string) -------------------------------- -- @overload self, ccui.Scale9Sprite -- @overload self -- @overload self, cc.Node, ccui.Scale9Sprite -- @overload self, string, string, float -- @overload self, cc.Node, ccui.Scale9Sprite, bool -- @function [parent=#ControlButton] create -- @param self -- @param #cc.Node label -- @param #ccui.Scale9Sprite backgroundSprite -- @param #bool adjustBackGroundSize -- @return ControlButton#ControlButton ret (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setEnabled -- @param self -- @param #bool enabled -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] onTouchEnded -- @param self -- @param #cc.Touch touch -- @param #cc.Event event -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setColor -- @param self -- @param #color3b_table -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] onTouchMoved -- @param self -- @param #cc.Touch touch -- @param #cc.Event event -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setSelected -- @param self -- @param #bool enabled -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] onTouchCancelled -- @param self -- @param #cc.Touch touch -- @param #cc.Event event -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] needsLayout -- @param self -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] onTouchBegan -- @param self -- @param #cc.Touch touch -- @param #cc.Event event -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ControlButton] updateDisplayedOpacity -- @param self -- @param #unsigned char parentOpacity -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ControlButton] setHighlighted -- @param self -- @param #bool enabled -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] updateDisplayedColor -- @param self -- @param #color3b_table parentColor -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- -- @function [parent=#ControlButton] setOpacity -- @param self -- @param #unsigned char var -- @return ControlButton#ControlButton self (return value: cc.ControlButton) -------------------------------- -- js ctor -- @function [parent=#ControlButton] ControlButton -- @param self -- @return ControlButton#ControlButton self (return value: cc.ControlButton) return nil
gpl-3.0
githubtelebot/Telebot
plugins/invite2.lua
8
1206
do local function callbackres(extra, success, result) -- Callback for res_user in line 27 local user = 'user#id'..result.id local chat = 'chat#id'..extra.chatid if is_banned(result.id, extra.chatid) then -- Ignore bans send_large_msg(chat, 'کاربر بن است') elseif is_gbanned(result.id) then -- Ignore globall bans send_large_msg(chat, 'کاربر بن جهانی است') else chat_add_user(chat, user, ok_cb, false) -- Add user on chat end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_realm(msg) then if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then return 'قفل اعضا فعال است' end end if msg.to.type ~= 'chat' then return end if not is_momod(msg) then return end if not is_admin(msg) then -- For admins only ! return 'Only admins can invite.' end local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") res_user(username, callbackres, cbres_extra) end return { patterns = { "^دعوت (.*)$" }, run = run } end
gpl-2.0
hadirahimi1380/speedbot
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end 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 --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
T3hArco/skeyler-gamemodes
Sassilization/entities/entities/building_gate/init.lua
1
3862
-------------------- -- Sassilization -- By Sassafrass / Spacetech / LuaPineapple -------------------- AddCSLuaFile("shared.lua") include("shared.lua") ENT.OpenSound = Sound("buttons/lever4.wav") ENT.CloseSound = Sound("buttons/lever6.wav") ENT.AutomaticFrameAdvance = true util.AddNetworkString( "PlayGateAnim" ) util.AddNetworkString( "SendConnectedPieces" ) function ENT:Initialize() self.Open = false self.Opened = false self.Closed = false self.TouchTable = {} self:Setup("gate", false, true) self.Connected = {} timer.Create(tostring(self), 0.5, 0, function() if self.type then timer.Destroy(tostring(self)) end self.Allies = nil --If a unit collides with the gate while it's still open, they won't be able to move through it until they move back/forward first. for i, v in ipairs(ents.FindInSphere(self:GetPos(), 30)) do if(v:IsUnit() and (v:GetEmpire() == self:GetEmpire() or Allied(self:GetEmpire(), v:GetEmpire()))) then self.Allies = true end end if self.Allies then self:OpenGate() else self:CloseGate() end end) end function ENT:AddConnected(givenEnt) table.insert(self.Connected, givenEnt) timer.Simple(0.1, function() for k,v in pairs(player.GetAll()) do net.Start("SendConnectedPieces") net.WriteEntity(self) net.WriteTable(self.Connected) net.Send(v) end end) end function ENT:SellConnected() for k,v in pairs(self.Connected) do v:Destroy(building.BUILDING_SELL) end self:Destroy(building.BUILDING_SELL) end function ENT:ChangeSettings(type, model, bool) self.type = type if model then self:SetModel(model) end self:SetSolid(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_NONE) self:PhysicsInit( SOLID_VPHYSICS ) self:SetCollisionGroup(COLLISION_GROUP_WEAPON) local Phys = self:GetPhysicsObject() if(Phys:IsValid()) then Phys:EnableMotion(false) Phys:EnableCollisions(true) end end -- local vec1, vec2 = Vector( -6, -20, 0 ), Vector( 6, 20, 30 ) -- self:PhysicsInitBox( vec1, vec2 ) -- self:SetCollisionBounds( vec1, vec2 ) -- self:SetSolid( SOLID_BBOX ) -- self:SetMoveCollide( MOVECOLLIDE_FLY_SLIDE ) -- self:SetCollisionGroup( COLLISION_GROUP_WEAPON ) function ENT:OnThink() self:WallUpdateControl() return 2 end function ENT:OpenGate() if self.type then return end if(self.Opened) then return end self.Opened = true self.Closed = false self:SetNotSolid(true) self:SetTrigger(true) self:EmitSound(self.OpenSound) if( IsValid( self ) ) then for k,v in pairs(player.GetAll()) do net.Start("PlayGateAnim") net.WriteEntity(self) net.WriteString("raise") net.Send(v) end end end function ENT:CloseGate() if self.type then return end if(self.Closed) then return end self.Opened = false self.Closed = true self:SetNotSolid(false) self:SetTrigger(false) self:EmitSound(self.CloseSound) if( IsValid( self ) ) then for k,v in pairs(player.GetAll()) do net.Start("PlayGateAnim") net.WriteEntity(self) net.WriteString("lower") net.Send(v) end end end /* function ENT:StartTouch(Ent) if self.type then return end if(Ent:IsUnit() and (Ent:GetEmpire() == self:GetEmpire() or Allied(self:GetEmpire(), Ent:GetEmpire()))) then self.TouchTable[Ent] = true self:OpenGate() end end function ENT:EndTouch(Ent) if self.type then return end if(Ent:IsUnit() and Ent:GetEmpire() == self:GetEmpire()) then self.TouchTable[Ent] = nil if(table.Count(self.TouchTable) == 0) then self:CloseGate() end end end */ function ENT:UpdateControl() self:WallUpdateControl() end function ENT:OnControl() self:WallUpdateControl() end
bsd-3-clause
xing634325131/Luci-0.11.1
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
CodeLiners/Silcom-Kernel
mod/prog.lua
1
1087
function prog_execute(file, mode, uid, term, parent, args, env, name) name = name or file data = vfs.readAll(file) if data:sub(1,2) == "#!" then -- script local ip = "" while true do local c = data:sub(1, 1) if c == LF then break end ip = ip..c data = data:sub(2) end prog_execute(ip, mode, uid, term, parent, args.." "..file, env, name) elseif data:sub(1,1) == string.char(27) then local headerlen = data:sub(2, 2):byte() * 256 + data:sub(3, 3):byte() local header = "" for i = 1, headerlen do header = header..data:sub(3 + i, 3 + i) end local code = data:sub(4 + headerlen) local func = vfs.loadstring(ascii.ESC + code) process_create(func, uid, mode, nil, parent, args, term, env, name) elseif DEBUG then local func = vfs.loadfile(file) process_create(func, uid, mode, nil, parent, args, term, env, name) else error("Invalid file") end end on("load", function () -- end)
bsd-3-clause
ominux/nn
test.lua
5
159454
-- you can easily test specific units like this: -- th -lnn -e "nn.test{'LookupTable'}" -- th -lnn -e "nn.test{'LookupTable', 'Add'}" nn.hessian.enable() local mytester = torch.Tester() local jac local sjac local precision = 1e-5 local expprecision = 1e-4 local nntest = {} local function equal(t1, t2, msg) if (torch.type(t1) == "table") then for k, v in pairs(t2) do equal(t1[k], t2[k], msg) end else mytester:assertTensorEq(t1, t2, 0.00001, msg) end end --[[ Generate tests to exercise the tostring component of modules. ]] local tostringTestModules = { nnLinear = nn.Linear(1, 2), nnReshape = nn.Reshape(10), nnSpatialZeroPadding = nn.SpatialZeroPadding(1, 1, 1, 1)} for test_name, component in pairs(tostringTestModules) do nntest['tostring' .. test_name] = function () mytester:assert(tostring(component):find(torch.type(component) .. '(', 1, true), 'nn components should have a descriptive tostring' .. ' beginning with the classname') end end function nntest.Add() local inj_vals = {math.random(3,5), 1} -- Also test the inj = 1 spatial case local ini = math.random(3,5) local ink = math.random(3,5) for ind, inj in pairs(inj_vals) do local input = torch.Tensor(ini,inj,ink):zero() local module = nn.Add(ini,inj,ink) -- 1D local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err,precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err,precision, 'error on bias [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format('error on bias [%s]', t)) end -- 2D local nframe = math.random(50,70) local input = torch.Tensor(nframe, ini,inj,ink):zero() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err,precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err,precision, 'error on bias [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format('error on bias [%s]', t)) end -- IO local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end end function nntest.CMul() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj,ink):zero() local module = nn.CMul(ini, inj, ink) -- 1D local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end -- 2D local nframe = math.random(50,70) local nframe = 5 local input = torch.randn(nframe, ini,inj,ink) local output = module:forward(input) local output2 = torch.cmul(input, module.weight:view(1,ini,inj,ink):expandAs(input)) mytester:assertTensorEq(output2, output, 0.000001, 'CMul forward 2D err') module:zeroGradParameters() local gradWeight = module.gradWeight:clone() local gradInput = module:backward(input, output) local gradInput2 = gradInput:clone():zero() local outputView = output:view(input:size(1), -1) gradInput2:view(input:size(1), -1):addcmul(1, module.weight:view(1,-1):expandAs(outputView), outputView) mytester:assertTensorEq(gradInput2, gradInput, 0.000001, 'CMul updateGradInput 2D err') mytester:assert(gradInput:isSameSizeAs(input), 'CMul gradInput 2D size err') local inputView = input:view(nframe, -1) local gradWeightView = gradWeight:view(1, -1) for i=1,nframe do gradWeightView:addcmul(1, inputView[i], outputView[i]) end mytester:assertTensorEq(gradWeight, module.gradWeight, 0.000001, 'CMul accGradParameters 2D err') mytester:assert(module.weight:isSameSizeAs(module.gradWeight), 'CMul gradWeight size err') input:zero() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format('error on weight [%s]', t)) end -- IO local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Dropout() local p = 0.2 --prob of droping out a neuron local input = torch.Tensor(1000):fill((1-p)) local module = nn.Dropout(p) -- version 2 local output = module:forward(input) mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output') local gradInput = module:backward(input, input) mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput') -- version 1 (old nnx version) local input = input:fill(1) local module = nn.Dropout(p,true) local output = module:forward(input) mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output') local gradInput = module:backward(input, input) mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput') end function nntest.SpatialDropout() local p = 0.2 --prob of dropiing out a neuron local w = math.random(1,5) local h = math.random(1,5) local nfeats = 1000 local input = torch.Tensor(nfeats, w, h):fill(1) local module = nn.SpatialDropout(p) module.train = true local output = module:forward(input) mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output') local gradInput = module:backward(input, input) mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput') end function nntest.SpatialDropoutBatch() local p = 0.2 --prob of dropiing out a neuron local bsz = math.random(1,5) local w = math.random(1,5) local h = math.random(1,5) local nfeats = 1000 local input = torch.Tensor(bsz, nfeats, w, h):fill(1) local module = nn.SpatialDropout(p) module.train = true local output = module:forward(input) mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output') local gradInput = module:backward(input, input) mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput') end function nntest.ReLU() local input = torch.randn(3,4) local gradOutput = torch.randn(3,4) local module = nn.ReLU() local output = module:forward(input) local output2 = input:clone():gt(input, 0):cmul(input) mytester:assertTensorEq(output, output2, 0.000001, 'ReLU output') local gradInput = module:backward(input, gradOutput) local gradInput2 = input:clone():gt(input, 0):cmul(gradOutput) mytester:assertTensorEq(gradInput, gradInput2, 0.000001, 'ReLU gradInput') end function nntest.Exp() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj,ink):zero() local module = nn.Exp() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Log() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj,ink):zero() local module = nn.Log() local err = jac.testJacobian(module,input, 0.1, 10) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input, 0.1, 10) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.HardTanh() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, inj, ini):zero() local module = nn.HardTanh() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision , 'error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Abs() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, inj, ini):zero() local module = nn.Abs() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision , 'error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Threshold() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, inj, ini):zero() local module = nn.Threshold(torch.uniform(-2,2),torch.uniform(-2,2)) local err = nn.Jacobian.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = nn.Jacobian.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.PReLU() local ini = math.random(3,5) local input = torch.Tensor(ini):zero() local module = nn.PReLU(ini) -- 1D local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end -- 2D local nframe = math.random(1,7) local input = torch.Tensor(nframe, ini):zero() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end -- 4D local nframe = math.random(1,7) local kW, kH = math.random(1,8), math.random(1,8) local input = torch.Tensor(nframe, ini, kW, kH):zero() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end -- IO local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.HardShrink() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, inj, ini):zero() local module = nn.HardShrink(math.random()/2) local err = nn.Jacobian.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = nn.Jacobian.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.SoftShrink() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, inj, ini):zero() local module = nn.SoftShrink(math.random()/2) local err = nn.Jacobian.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = nn.Jacobian.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Power() local in1 = torch.rand(5,7) local module = nn.Power(2) local out = module:forward(in1) local err = out:dist(in1:cmul(in1)) mytester:assertlt(err, 1e-15, torch.typename(module) .. ' - forward err ') local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local pw = torch.uniform()*math.random(1,10) local input = torch.Tensor(ink, inj, ini):zero() local module = nn.Power(pw) local err = nn.Jacobian.testJacobian(module, input, 0.1, 2) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = nn.Jacobian.testIO(module,input, 0.1, 2) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Square() local in1 = torch.rand(5,7) local module = nn.Square() local out = module:forward(in1) local err = out:dist(in1:cmul(in1)) mytester:assertlt(err, 1e-15, torch.typename(module) .. ' - forward err ') local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, inj, ini):zero() local module = nn.Square() local err = nn.Jacobian.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = nn.Jacobian.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Sqrt() local in1 = torch.rand(5,7) local module = nn.Sqrt() local out = module:forward(in1) local err = out:dist(in1:sqrt()) mytester:assertlt(err, 1e-15, torch.typename(module) .. ' - forward err ') -- Test zero inputs; we will avoid a div-by-zero by setting to zero local zin = torch.DoubleTensor(5, 7):zero() module:forward(zin) local zgradout = torch.rand(5, 7) local zgradin = module:backward(zin, zgradout) mytester:assertTensorEq(zgradin, torch.DoubleTensor(5, 7):zero(), 0.000001, "error in sqrt backward singularity") local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, inj, ini):zero() local module = nn.Sqrt() local err = nn.Jacobian.testJacobian(module, input, 0.1, 2) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = nn.Jacobian.testIO(module, input, 0, 2) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Linear() local ini = math.random(3,5) local inj_vals = {math.random(3,5), 1} -- Also test the inj = 1 spatial case local input = torch.Tensor(ini):zero() for ind, inj in pairs(inj_vals) do local module = nn.Linear(ini,inj) -- 1D local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err,precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err,precision, 'error on bias [direct update] ') local err = jac.testDiagHessianInput(module, input) mytester:assertlt(err , precision, 'error on diagHessianInput') local err = jac.testDiagHessianWeight(module, input) mytester:assertlt(err , precision, 'error on diagHessianWeight') local err = jac.testDiagHessianBias(module, input) mytester:assertlt(err , precision, 'error on diagHessianBias') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end -- 2D local nframe = math.random(50,70) local input = torch.Tensor(nframe, ini):zero() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err,precision, 'error on bias [direct update] ') local err = jac.testDiagHessianInput(module, input) mytester:assertlt(err , precision, 'error on diagHessianInput') local err = jac.testDiagHessianWeight(module, input) mytester:assertlt(err , precision, 'error on diagHessianWeight') local err = jac.testDiagHessianBias(module, input) mytester:assertlt(err , precision, 'error on diag HessianBias') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end -- IO local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end -- for ind, inj in pairs(inj_vals) do end function nntest.SparseLinear() local ini = math.random(50,100) local inj = math.random(5,10) local numNonzero = math.random(3,5) local module = nn.SparseLinear(ini,inj) -- Create a random sparse vector local N = {} for i = 1, ini do N[i] = i end for i = 1, numNonzero do local j = math.random(i,ini) N[i], N[j] = N[j], N[i] end local input = torch.Tensor(numNonzero, 2):zero() for i = 1, numNonzero do input[{i,1}] = N[i] end local values = input:select(2,2) values:copy(torch.rand(values:nElement())):mul(2):add(-1) -- Check output local actual = module:forward(input) local expected = torch.Tensor(inj) for j = 1, inj do expected[j] = 0 for i = 1,numNonzero do expected[j] = expected[j] + values[i] * module.weight[{j, N[i]}] end end local err = (expected - actual):abs():max() mytester:assertle(err, precision, 'error on result') -- Jacobian 1D local err = sjac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = sjac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = sjac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err,precision, 'error on bias ') local err = sjac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') local err = sjac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err,precision, 'error on bias [direct update] ') for t,err in pairs(sjac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(sjac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end local ferr, berr = sjac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') end function nntest.Euclidean() local ini = math.random(5,7) local inj = math.random(5,7) local input = torch.randn(ini) local gradOutput = torch.randn(inj) local module = nn.Euclidean(ini,inj) local output = module:forward(input):clone() local output2 = torch.Tensor(inj):zero() for o = 1,module.weight:size(2) do output2[o] = input:dist(module.weight:select(2,o)) end mytester:assertTensorEq(output, output2, 0.000001, 'Euclidean forward 1D err') local input2 = torch.randn(8, ini) input2[2]:copy(input) local output2 = module:forward(input2) mytester:assertTensorEq(output2[2], output, 0.000001, 'Euclidean forward 2D err') local output = module:forward(input):clone() module:zeroGradParameters() local gradInput = module:backward(input, gradOutput, 1):clone() local gradInput2 = torch.zeros(ini) local temp = input:clone() for o = 1,module.weight:size(2) do temp:copy(input) temp:add(-1,module.weight:select(2,o)) temp:mul(gradOutput[o]/output[o]) gradInput2:add(temp) end mytester:assertTensorEq(gradInput, gradInput2, 0.000001, 'Euclidean updateGradInput 1D err') local gradWeight = module.gradWeight:clone():zero() for o = 1,module.weight:size(2) do temp:copy(module.weight:select(2,o)):add(-1,input) temp:mul(gradOutput[o]/output[o]) gradWeight:select(2,o):add(1, temp) end mytester:assertTensorEq(gradWeight, module.gradWeight, 0.000001, 'Euclidean accGradParameters 1D err') local input2 = input:view(1, -1):repeatTensor(8, 1) local gradOutput2 = gradOutput:view(1, -1):repeatTensor(8, 1) local output2 = module:forward(input2) module:zeroGradParameters() local gradInput2 = module:backward(input2, gradOutput2, 1/8) mytester:assertTensorEq(gradInput2[2], gradInput, 0.000001, 'Euclidean updateGradInput 2D err') mytester:assertTensorEq(gradWeight, module.gradWeight, 0.000001, 'Euclidean accGradParameters 2D err') input:zero() module.fastBackward = false local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.WeightedEuclidean() local ini = math.random(5,7) local inj = math.random(5,7) local input = torch.randn(ini) local gradOutput = torch.randn(inj) local module = nn.WeightedEuclidean(ini,inj) local output = module:forward(input):clone() local output2 = torch.Tensor(inj):zero() local temp = input:clone() for o = 1,module.weight:size(2) do temp:copy(input):add(-1,module.weight:select(2,o)) temp:cmul(temp) temp:cmul(module.diagCov:select(2,o)):cmul(module.diagCov:select(2,o)) output2[o] = math.sqrt(temp:sum()) end mytester:assertTensorEq(output, output2, 0.000001, 'WeightedEuclidean forward 1D err') local input2 = torch.randn(8, ini) input2[2]:copy(input) local output2 = module:forward(input2) mytester:assertTensorEq(output2[2], output, 0.000001, 'WeightedEuclidean forward 2D err') local output = module:forward(input):clone() module:zeroGradParameters() local gradInput = module:backward(input, gradOutput, 1):clone() local gradInput2 = torch.zeros(ini) for o = 1,module.weight:size(2) do temp:copy(input) temp:add(-1,module.weight:select(2,o)) temp:cmul(module.diagCov:select(2,o)):cmul(module.diagCov:select(2,o)) temp:mul(gradOutput[o]/output[o]) gradInput2:add(temp) end mytester:assertTensorEq(gradInput, gradInput2, 0.000001, 'WeightedEuclidean updateGradInput 1D err') local gradWeight = module.gradWeight:clone():zero() local gradDiagCov = module.gradDiagCov:clone():zero() for o = 1,module.weight:size(2) do if output[o] ~= 0 then temp:copy(module.weight:select(2,o)):add(-1,input) temp:cmul(module.diagCov:select(2,o)):cmul(module.diagCov:select(2,o)) temp:mul(gradOutput[o]/output[o]) gradWeight:select(2,o):add(temp) temp:copy(module.weight:select(2,o)):add(-1,input) temp:cmul(temp) temp:cmul(module.diagCov:select(2,o)) temp:mul(gradOutput[o]/output[o]) gradDiagCov:select(2,o):add(temp) end end mytester:assertTensorEq(gradWeight, module.gradWeight, 0.000001, 'WeightedEuclidean accGradParameters gradWeight 1D err') mytester:assertTensorEq(gradDiagCov, module.gradDiagCov, 0.000001, 'WeightedEuclidean accGradParameters gradDiagCov 1D err') local input2 = input:view(1, -1):repeatTensor(8, 1) local gradOutput2 = gradOutput:view(1, -1):repeatTensor(8, 1) local output2 = module:forward(input2) module:zeroGradParameters() local gradInput2 = module:backward(input2, gradOutput2, 1/8) mytester:assertTensorEq(gradInput2[2], gradInput, 0.000001, 'WeightedEuclidean updateGradInput 2D err') mytester:assertTensorEq(gradWeight, module.gradWeight, 0.000001, 'WeightedEuclidean accGradParameters gradWeight 2D err') mytester:assertTensorEq(gradDiagCov, module.gradDiagCov, 0.000001, 'WeightedEuclidean accGradParameters gradDiagCov 2D err') input:zero() module.fastBackward = false local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.diagCov, module.gradDiagCov) mytester:assertlt(err,precision, 'error on bias ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') input:zero() module:zeroGradParameters() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.diagCov, module.gradDiagCov) mytester:assertlt(err,precision, 'error on bias ') local ferr,berr = jac.testIO(module,input2) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end local function criterionJacobianTest1D(cri, input, target) local eps = 1e-6 local _ = cri:forward(input, target) local dfdx = cri:backward(input, target) -- for each input perturbation, do central difference local centraldiff_dfdx = torch.Tensor():resizeAs(dfdx) local input_s = input:storage() local centraldiff_dfdx_s = centraldiff_dfdx:storage() for i=1,input:nElement() do -- f(xi + h) input_s[i] = input_s[i] + eps local fx1 = cri:forward(input, target) -- f(xi - h) input_s[i] = input_s[i] - 2*eps local fx2 = cri:forward(input, target) -- f'(xi) = (f(xi + h) - f(xi - h)) / 2h local cdfx = (fx1 - fx2) / (2*eps) -- store f' in appropriate place centraldiff_dfdx_s[i] = cdfx -- reset input[i] input_s[i] = input_s[i] + eps end -- compare centraldiff_dfdx with :backward() local err = (centraldiff_dfdx - dfdx):abs():max() mytester:assertlt(err, precision, 'error in difference between central difference and :backward') end function nntest.MSECriterion() local input = torch.rand(10) local target = input:clone():add(torch.rand(10)) local cri = nn.MSECriterion() criterionJacobianTest1D(cri, input, target) end function nntest.MarginCriterion() local input = torch.rand(100) local target = input:clone():add(torch.rand(100)) local cri = nn.MarginCriterion() criterionJacobianTest1D(cri, input, target) end function nntest.MultiMarginCriterion() local input = torch.rand(100) local target = math.random(1,100) local cri = nn.MultiMarginCriterion(math.random(1,2)) criterionJacobianTest1D(cri, input, target) end function nntest.MarginRankingCriterion() local input = {torch.rand(1), torch.rand(1)} local mrc = nn.MarginRankingCriterion() local output = mrc:forward(input, 1) local gradInput = mrc:backward(input, 1) -- cast to float local input2 = {input[1]:float(), input[2]:float()} local mrc2 = mrc:clone():float() local output2 = mrc2:forward(input2, 1) local gradInput2 = mrc2:backward(input2, 1) mytester:assert(math.abs(output2 - output) < 0.00001, "MRC:type() forward error") mytester:assertTensorEq(gradInput[1]:float(), gradInput2[1], 0.00001, "MRC:type() backward error 1") mytester:assert(torch.type(gradInput2[1]) == 'torch.FloatTensor', "MRC:type() error 1") mytester:assertTensorEq(gradInput[2]:float(), gradInput2[2], 0.00001, "MRC:type() backward error 2") mytester:assert(torch.type(gradInput2[2]) == 'torch.FloatTensor', "MRC:type() error 2") end function nntest.ParallelCriterion() local input = {torch.rand(2,10), torch.randn(2,10)} local target = {torch.IntTensor{1,8}, torch.randn(2,10)} local nll = nn.ClassNLLCriterion() local mse = nn.MSECriterion() local pc = nn.ParallelCriterion():add(nll, 0.5):add(mse) local output = pc:forward(input, target) local output2 = nll:forward(input[1], target[1])/2 + mse:forward(input[2], target[2]) mytester:assert(math.abs(output2 - output) < 0.00001, "ParallelCriterion forward error") local gradInput2 = {nll:backward(input[1], target[1]):clone():div(2), mse:backward(input[2], target[2])} local gradInput = pc:backward(input, target) mytester:assertTensorEq(gradInput[1], gradInput2[1], 0.000001, "ParallelCriterion backward error 1") mytester:assertTensorEq(gradInput[2], gradInput2[2], 0.000001, "ParallelCriterion backward error 2") -- test type pc:float() gradInput[1], gradInput[2] = gradInput[1]:clone(), gradInput[2]:clone() local input3 = {input[1]:float(), input[2]:float()} local target3 = {target[1]:float(), target[2]:float()} local output3 = pc:forward(input3, target3) local gradInput3 = pc:backward(input3, target3) mytester:assert(math.abs(output3 - output) < 0.00001, "ParallelCriterion forward error type") mytester:assertTensorEq(gradInput[1]:float(), gradInput3[1], 0.000001, "ParallelCriterion backward error 1 type") mytester:assertTensorEq(gradInput[2]:float(), gradInput3[2], 0.000001, "ParallelCriterion backward error 2 type") -- test repeatTarget local input = {torch.rand(2,10), torch.randn(2,10)} local target = torch.randn(2,10) local mse = nn.MSECriterion() local pc = nn.ParallelCriterion(true):add(mse, 0.5):add(mse:clone()) local output = pc:forward(input, target) local output2 = mse:forward(input[1], target)/2 + mse:forward(input[2], target) mytester:assert(math.abs(output2 - output) < 0.00001, "ParallelCriterion repeatTarget forward error") local gradInput = pc:backward(input, target) local gradInput2 = {mse:backward(input[1], target):clone():div(2), mse:backward(input[2], target)} mytester:assertTensorEq(gradInput[1], gradInput2[1], 0.000001, "ParallelCriterion repeatTarget backward error 1") mytester:assertTensorEq(gradInput[2], gradInput2[2], 0.000001, "ParallelCriterion repeatTarget backward error 2") -- table input local input = {torch.randn(2,10), {torch.rand(2,10), torch.randn(2,10)}} local target = {torch.IntTensor{2,5}, {torch.IntTensor{1,8}, torch.randn(2,10)}} local nll2 = nn.ClassNLLCriterion() local nll = nn.ClassNLLCriterion() local mse = nn.MSECriterion() local pc = nn.ParallelCriterion():add(nll, 0.5):add(mse) local pc2 = nn.ParallelCriterion():add(nll2, 0.4):add(pc) local output = pc2:forward(input, target) local output2 = nll2:forward(input[1], target[1])*0.4 + nll:forward(input[2][1], target[2][1])/2 + mse:forward(input[2][2], target[2][2]) mytester:assert(math.abs(output2 - output) < 0.00001, "ParallelCriterion table forward error") local gradInput2 = { nll2:backward(input[1], target[1]):clone():mul(0.4), {nll:backward(input[2][2], target[2][1]):clone():div(2), mse:backward(input[2][2], target[2][2])} } local gradInput = pc2:backward(input, target) mytester:assertTensorEq(gradInput[1], gradInput2[1], 0.000001, "ParallelCriterion table backward error 1") mytester:assertTensorEq(gradInput[2][1], gradInput2[2][1], 0.000001, "ParallelCriterion table backward error 2") mytester:assertTensorEq(gradInput[2][2], gradInput2[2][2], 0.000001, "ParallelCriterion table backward error 3") end function nntest.MultiCriterion() local input = torch.rand(2,10) local target = torch.IntTensor{1,8} local nll = nn.ClassNLLCriterion() local nll2 = nn.CrossEntropyCriterion() local mc = nn.MultiCriterion():add(nll, 0.5):add(nll2) local output = mc:forward(input, target) local output2 = nll:forward(input, target)/2 + nll2:forward(input, target) mytester:assert(math.abs(output2 - output) < 0.00001, "MultiCriterion forward error") local gradInput = mc:backward(input, target) local gradInput2 = nll:backward(input, target):clone():div(2):add(nll2:backward(input, target)) mytester:assertTensorEq(gradInput, gradInput2, 0.000001, "MultiCriterion backward error ") -- test type mc:float() gradInput = gradInput:clone() local input3 = input:float() local target3 = target:float() local output3 = mc:forward(input3, target3) local gradInput3 = mc:backward(input3, target3) mytester:assert(math.abs(output3 - output) < 0.00001, "MultiCriterion forward error type") mytester:assertTensorEq(gradInput:float(), gradInput3, 0.000001, "MultiCriterion backward error type") -- test table input mc:double() local input = {torch.randn(2,10), {torch.randn(2,10), torch.randn(2,10)}} local target = {torch.IntTensor{1,8}, {torch.IntTensor{5,6}, torch.IntTensor{4,3}}} local pnllc = nn.ParallelCriterion():add(nll):add(nn.ParallelCriterion():add(nll:clone()):add(nll:clone())) local pnllc2 = nn.ParallelCriterion():add(nll2):add(nn.ParallelCriterion():add(nll2:clone()):add(nll2:clone())) local mc = nn.MultiCriterion():add(pnllc, 0.5):add(pnllc2) local output = mc:forward(input, target) local output2 = pnllc:forward(input, target)/2 + pnllc2:forward(input, target) mytester:assert(math.abs(output2 - output) < 0.00001, "MultiCriterion forward table error") local gradInput = mc:backward(input, target) local gradInput2 = pnllc:clone():backward(input, target) local gradInput2b = pnllc2:backward(input, target) gradInput2[1]:div(2):add(gradInput2b[1]) gradInput2[2][1]:div(2):add(gradInput2b[2][1]) gradInput2[2][2]:div(2):add(gradInput2b[2][2]) mytester:assertTensorEq(gradInput[1], gradInput2[1], 0.000001, "MultiCriterion backward table 1 error ") mytester:assertTensorEq(gradInput[2][1], gradInput2[2][1], 0.000001, "MultiCriterion backward table 2 error ") mytester:assertTensorEq(gradInput[2][2], gradInput2[2][2], 0.000001, "MultiCriterion backward table 3 error ") end function nntest.WeightedMSECriterion() local input = torch.rand(10) local target = input:clone():add(torch.rand(10)) local cri = nn.WeightedMSECriterion(torch.rand(10)) criterionJacobianTest1D(cri, input, target) end function nntest.BCECriterion() local eps = 1e-2 local input = torch.rand(10)*(1-eps) + eps/2 local target = torch.rand(10)*(1-eps) + eps/2 local cri = nn.BCECriterion() criterionJacobianTest1D(cri, input, target) end function nntest.DistKLDivCriterion() local input = torch.rand(10) local target = input:clone():add(torch.rand(10)) local cri = nn.DistKLDivCriterion(true) -- sizeAverage = true criterionJacobianTest1D(cri, input, target) cri = nn.DistKLDivCriterion(false) -- sizeAverage = false criterionJacobianTest1D(cri, input, target) end function nntest.ClassNLLCriterion() local numLabels = math.random(5,10) local input = torch.rand(numLabels) local target = math.random(1,numLabels) -- default ClassNLLCriterion local cri = nn.ClassNLLCriterion() criterionJacobianTest1D(cri, input, target) -- ClassNLLCriterion with weights local weights = torch.rand(numLabels) weights = weights / weights:sum() cri = nn.ClassNLLCriterion(weights) criterionJacobianTest1D(cri, input, target) end function nntest.CrossEntropyCriterion() -- stochastic local numLabels = math.random(5, 10) local input = torch.zeros(numLabels) local target = torch.random(1, numLabels) local cri = nn.CrossEntropyCriterion() criterionJacobianTest1D(cri, input, target) -- batch local numLabels = math.random(5,10) local bsz = math.random(3, 7) local input = torch.zeros(bsz, numLabels) local target = torch.Tensor(bsz):random(1, numLabels) local cri = nn.CrossEntropyCriterion() criterionJacobianTest1D(cri, input, target) -- with weights local weights = torch.rand(numLabels) weights = weights / weights:sum() cri = nn.CrossEntropyCriterion(weights) criterionJacobianTest1D(cri, input, target) end function nntest.LogSigmoid() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj,ink):zero() local module = nn.LogSigmoid() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.LogSoftmax() local ini = math.random(3,5) local inj = math.random(3,5) local input = torch.Tensor(ini,inj):zero() local module = nn.LogSoftMax() local err = jac.testJacobian(module,input) mytester:assertlt(err,1e-3, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end -- function nntest.TemporalLogSoftmax() -- local ini = math.random(10,20) -- local inj = math.random(10,20) -- local input = torch.Tensor(ini,inj):zero() -- local module = nn.TemporalLogSoftMax() -- local err = jac.testJacobian(module,input) -- mytester:assertlt(err,precision, 'error on state ') -- local ferr,berr = jac.testIO(module,input) -- mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') -- mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- end function nntest.Max() -- 1D local ini = math.random(3,7) local input = torch.Tensor(ini):zero() local module = nn.Max(1) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') -- 3D local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj*ink):zero() local module = nn.Max(1) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Min() -- 1D local ini = math.random(3,7) local input = torch.Tensor(ini):zero() local module = nn.Min(1) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') -- 3D local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj*ink):zero() local module = nn.Min(1) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Mean() -- 1D local ini = math.random(3,7) local input = torch.Tensor(ini):zero() local module = nn.Mean(1) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') -- 3D local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj,ink):zero() local module = nn.Mean(torch.random(1,3)) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Mul() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj,ink):zero() local module = nn.Mul() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Sigmoid() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj,ink):zero() local module = nn.Sigmoid() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Softmax() local ini = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, ini):zero() local module = nn.SoftMax() local err = jac.testJacobian(module,input) mytester:assertlt(err,expprecision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Softmin() local ini = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, ini):zero() local module = nn.SoftMin() local err = jac.testJacobian(module,input) mytester:assertlt(err,expprecision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Softsign() local ini = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, ini):zero() local module = nn.SoftSign() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.SoftPlus() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj,ink):zero() local module = nn.SoftPlus() local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialSubtractiveNormalization_2dkernel() local inputSize = math.random(6,9) local kersize = 3 local nbfeatures = math.random(3,5) local kernel = torch.Tensor(kersize,kersize):fill(1) local module = nn.SpatialSubtractiveNormalization(nbfeatures,kernel) local input = torch.rand(nbfeatures,inputSize,inputSize/2) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- test batch mode local output = module:forward(input):clone() local gradOutput = output:clone():uniform(0,1) local gradInput = module:backward(input, gradOutput):clone() local batchSize = 4 local input2 = torch.rand(batchSize,nbfeatures,inputSize,inputSize/2) input2[2]:copy(input) local output2 = module:forward(input2) local gradOutput2 = output2:clone():uniform(0,1) gradOutput2[2]:copy(gradOutput) local gradInput2 = module:backward(input2, gradOutput2) mytester:assertTensorEq(output2[2], output, 0.000001, "SpatialSubstractiveNormalization 2d forward batch err") mytester:assertTensorEq(gradOutput2[2], gradOutput, 0.000001, "SpatialSubstractiveNormalization 2d backward batch err") local err = jac.testJacobian(module,input2) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input2) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialSubtractiveNormalization_1dkernel() local inputSize = math.random(6,9) local kersize = 3 local nbfeatures = math.random(3,5) local kernel = torch.Tensor(kersize):fill(1) local module = nn.SpatialSubtractiveNormalization(nbfeatures,kernel) local input = torch.rand(nbfeatures,inputSize,inputSize/2) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- test batch mode local output = module:forward(input):clone() local gradOutput = output:clone():uniform(0,1) local gradInput = module:backward(input, gradOutput):clone() local batchSize = 4 local input2 = torch.rand(batchSize,nbfeatures,inputSize,inputSize/2) input2[2]:copy(input) local output2 = module:forward(input2) local gradOutput2 = output2:clone():uniform(0,1) gradOutput2[2]:copy(gradOutput) local gradInput2 = module:backward(input2, gradOutput2) mytester:assertTensorEq(output2[2], output, 0.000001, "SpatialSubstractiveNormalization 1d forward batch err") mytester:assertTensorEq(gradOutput2[2], gradOutput, 0.000001, "SpatialSubstractiveNormalization 1d backward batch err") local err = jac.testJacobian(module,input2) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input2) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialDivisiveNormalization_2dkernel() local inputSize = math.random(6,9) local kersize = 3 local nbfeatures = math.random(3,5) local kernel = torch.Tensor(kersize,kersize):fill(1) local module = nn.SpatialDivisiveNormalization(nbfeatures,kernel) local input = torch.rand(nbfeatures,inputSize,inputSize/2) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- test batch mode local output = module:forward(input):clone() local gradOutput = output:clone():uniform(0,1) local gradInput = module:backward(input, gradOutput):clone() local batchSize = 4 local input2 = torch.rand(batchSize,nbfeatures,inputSize,inputSize/2) input2[2]:copy(input) local output2 = module:forward(input2) local gradOutput2 = output2:clone():uniform(0,1) gradOutput2[2]:copy(gradOutput) local gradInput2 = module:backward(input2, gradOutput2) mytester:assertTensorEq(output2[2], output, 0.000001, "SpatialDivisiveNormalization 2d forward batch err") mytester:assertTensorEq(gradOutput2[2], gradOutput, 0.000001, "SpatialDivisiveNormalization 2d backward batch err") local err = jac.testJacobian(module,input2) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input2) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialDivisiveNormalization_1dkernel() local inputSize = math.random(6,9) local kersize = 3 local nbfeatures = math.random(3,5) local kernel = torch.Tensor(kersize):fill(1) local module = nn.SpatialDivisiveNormalization(nbfeatures,kernel) local input = torch.rand(nbfeatures,inputSize,inputSize/2) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- test batch mode local output = module:forward(input):clone() local gradOutput = output:clone():uniform(0,1) local gradInput = module:backward(input, gradOutput):clone() local batchSize = 4 local input2 = torch.rand(batchSize,nbfeatures,inputSize,inputSize/2) input2[2]:copy(input) local output2 = module:forward(input2) local gradOutput2 = output2:clone():uniform(0,1) gradOutput2[2]:copy(gradOutput) local gradInput2 = module:backward(input2, gradOutput2) mytester:assertTensorEq(output2[2], output, 0.000001, "SpatialDivisiveNormalization 1d forward batch err") mytester:assertTensorEq(gradOutput2[2], gradOutput, 0.000001, "SpatialDivisiveNormalization 1d backward batch err") local err = jac.testJacobian(module,input2) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input2) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialContrastiveNormalization() local inputSize = math.random(6,9) local kersize = 3 local nbfeatures = math.random(3,5) local kernel = torch.Tensor(kersize,kersize):fill(1) local module = nn.SpatialContrastiveNormalization(nbfeatures,kernel) local input = torch.rand(nbfeatures,inputSize,inputSize/2) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- test batch mode and type local output = module:forward(input):clone() local gradOutput = output:clone():uniform(0,1) local gradInput = module:backward(input, gradOutput):clone() local batchSize = 4 local input2 = torch.rand(batchSize,nbfeatures,inputSize,inputSize/2):float() input2[2]:copy(input) module:float() -- type-cast local output2 = module:forward(input2) local gradOutput2 = output2:clone():uniform(0,1) gradOutput2[2]:copy(gradOutput) local gradInput2 = module:backward(input2, gradOutput2) mytester:assertTensorEq(output2[2], output:float(), 0.000001, "SpatialContrastiveNormalization 2d forward batch err") mytester:assertTensorEq(gradOutput2[2], gradOutput:float(), 0.000001, "SpatialContrastiveNormalization 2d backward batch err") module:double() input2 = input2:double() local err = jac.testJacobian(module,input2) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input2) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialConvolution() local from = math.random(1,5) local to = math.random(1,5) local ki = math.random(1,5) local kj = math.random(1,5) local si = math.random(1,4) local sj = math.random(1,4) local outi = math.random(5,7) local outj = math.random(5,7) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local module = nn.SpatialConvolution(from, to, ki, kj, si, sj) local input = torch.Tensor(from, inj, ini):zero() -- stochastic local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'error on bias [direct update] ') local err = jac.testDiagHessianInput(module, input) mytester:assertlt(err , precision, 'error on diagHessianInput') local err = jac.testDiagHessianWeight(module, input) mytester:assertlt(err , precision, 'error on diagHessianWeight') local err = jac.testDiagHessianBias(module, input) mytester:assertlt(err , precision, 'error on diag HessianBias') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end -- batch --verbose = true local batch = math.random(2,5) outi = math.random(4,8) outj = math.random(4,8) ini = (outi-1)*si+ki inj = (outj-1)*sj+kj module = nn.SpatialConvolution(from, to, ki, kj, si, sj) input = torch.Tensor(batch,from,inj,ini):zero() -- print(from, to, ki, kj, si, sj, batch, ini, inj) -- print(module.weight:size()) -- print(module.gradWeight:size()) local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'batch error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'batch error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'batch error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'batch error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'batch error on bias [direct update] ') local err = jac.testDiagHessianInput(module, input) mytester:assertlt(err , precision, 'error on diagHessianInput') local err = jac.testDiagHessianWeight(module, input) mytester:assertlt(err , precision, 'error on diagHessianWeight') local err = jac.testDiagHessianBias(module, input) mytester:assertlt(err , precision, 'error on diag HessianBias') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'batch error on bias [%s]', t)) end local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialConvolutionMM() local from = math.random(2,5) local to = math.random(1,5) local ki = math.random(1,5) local kj = math.random(1,5) local di = math.random(1,4) local dj = math.random(1,4) local padW = math.random(0,2) local padH = math.random(0,2) local outi = math.random(5,9) local outj = math.random(5,9) local ini = (outi-1)*di+ki-padW*2 local inj = (outj-1)*dj+kj-padH*2 local module = nn.SpatialConvolutionMM(from, to, ki, kj, di, dj, padW, padH) local input = torch.Tensor(from, inj, ini):zero() -- stochastic local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'error on bias [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end -- batch --verbose = true local batch = math.random(2,5) module = nn.SpatialConvolutionMM(from, to, ki, kj, di, dj, padW, padH) input = torch.Tensor(batch,from,inj,ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'batch error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'batch error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'batch error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'batch error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'batch error on bias [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'batch error on bias [%s]', t)) end local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') -- non-contiguous local input = torch.randn(batch,from,ini,inj):transpose(3,4) -- non-contiguous local inputc = input:contiguous() -- contiguous local output = module:forward(input) local outputc = module:forward(inputc) mytester:asserteq(0, (output-outputc):abs():max(), torch.typename(module) .. ' - contiguous err ') local gradInput = module:backward(input, output) local gradInputc = module:backward(inputc, outputc) mytester:asserteq(0, (gradInput-gradInputc):abs():max(), torch.typename(module) .. ' - contiguous err ') end function nntest.SpatialConvolutionMap() local from = math.random(1,5) local fanin = math.random(1, from) local to = math.random(1,5) local ki = math.random(1,5) local kj = math.random(1,5) local si = math.random(1,3) local sj = math.random(1,3) local outi = math.random(5,9) local outj = math.random(5,9) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local module = nn.SpatialConvolutionMap(nn.tables.random(from, to, fanin), ki, kj, si, sj) local input = torch.Tensor(from, inj, ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'error on bias ') local err = jac.testDiagHessianInput(module, input) mytester:assertlt(err , precision, 'error on diagHessianInput') local err = jac.testDiagHessianWeight(module, input) mytester:assertlt(err , precision, 'error on diagHessianWeight') local err = jac.testDiagHessianBias(module, input) mytester:assertlt(err , precision, 'error on diag HessianBias') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') -- batch --verbose = true local batch = math.random(2,6) module = nn.SpatialConvolutionMap(nn.tables.random(from, to, fanin), ki, kj, si, sj) input = torch.Tensor(batch,from,inj,ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'batch error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'batch error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'batch error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'batch error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'batch error on bias [direct update] ') local err = jac.testDiagHessianInput(module, input) mytester:assertlt(err , precision, 'error on diagHessianInput') local err = jac.testDiagHessianWeight(module, input) mytester:assertlt(err , precision, 'error on diagHessianWeight') local err = jac.testDiagHessianBias(module, input) mytester:assertlt(err , precision, 'error on diag HessianBias') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'batch error on bias [%s]', t)) end local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialFullConvolution() local from = math.random(1,5) local to = math.random(1,5) local ki = math.random(1,5) local kj = math.random(1,5) local si = math.random(1,4) local sj = math.random(1,4) local ini = math.random(5,8) local inj = math.random(5,8) local module = nn.SpatialFullConvolution(from, to, ki, kj, si, sj) local input = torch.Tensor(from, inj, ini):zero() -- stochastic local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'error on bias [direct update] ') local err = jac.testDiagHessianInput(module, input) mytester:assertlt(err , precision, 'error on diagHessianInput') local err = jac.testDiagHessianWeight(module, input) mytester:assertlt(err , precision, 'error on diagHessianWeight') local err = jac.testDiagHessianBias(module, input) mytester:assertlt(err , precision, 'error on diag HessianBias') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end -- batch local batch = math.random(2,5) ini = math.random(4,8) inj = math.random(4,8) module = nn.SpatialFullConvolution(from, to, ki, kj, si, sj) input = torch.Tensor(batch,from,inj,ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'batch error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'batch error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'batch error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'batch error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'batch error on bias [direct update] ') local err = jac.testDiagHessianInput(module, input) mytester:assertlt(err , precision, 'error on diagHessianInput') local err = jac.testDiagHessianWeight(module, input) mytester:assertlt(err , precision, 'error on diagHessianWeight') local err = jac.testDiagHessianBias(module, input) mytester:assertlt(err , precision, 'error on diag HessianBias') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'batch error on bias [%s]', t)) end local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialFullConvolutionMap() local from = math.random(2,4) local to = math.random(2,5) local fanin = math.random(1, from) local tt = nn.tables.random(from, to, fanin) local ki = math.random(2,5) local kj = math.random(2,5) local si = math.random(1,3) local sj = math.random(1,3) local ini = math.random(5,7) local inj = math.random(5,7) local module = nn.SpatialFullConvolutionMap(tt, ki, kj, si, sj) local input = torch.Tensor(from, inj, ini):zero() -- stochastic local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'error on bias [direct update] ') local err = jac.testDiagHessianInput(module, input) mytester:assertlt(err , precision, 'error on diagHessianInput') local err = jac.testDiagHessianWeight(module, input) mytester:assertlt(err , precision, 'error on diagHessianWeight') local err = jac.testDiagHessianBias(module, input) mytester:assertlt(err , precision, 'error on diag HessianBias') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialFullConvolutionCompare() local from = math.random(2,4) local to = math.random(2,5) local tt = nn.tables.full(from, to) local ki = math.random(2,5) local kj = math.random(2,5) local si = math.random(1,3) local sj = math.random(1,3) local ini = math.random(7,8) local inj = math.random(7,8) local module1 = nn.SpatialFullConvolutionMap(tt, ki, kj, si, sj) local module2 = nn.SpatialFullConvolution(from, to, ki, kj, si, sj) local input = torch.rand(from, inj, ini) for k=1,tt:size(1) do module1.weight[k]:copy(module2.weight[tt[k][1]][tt[k][2]]) module1.bias:copy(module2.bias) end local o1 = module1:updateOutput(input) local o2 = module2:updateOutput(input) mytester:assertlt(o1:dist(o2), precision, 'error on output') local go1 = torch.rand(o1:size()) local go2 = go1:clone() local gi1= module1:updateGradInput(input,go1) local gi2 = module2:updateGradInput(input,go2) mytester:assertlt(gi1:dist(gi2), precision, 'error on gradInput') module1:zeroGradParameters() module2:zeroGradParameters() module1:accGradParameters(input,go1) module2:accGradParameters(input,go2) for k=1,tt:size(1) do mytester:assertlt(module1.gradWeight[k]:dist(module2.gradWeight[tt[k][1]][tt[k][2]]),precision,'error on gradWeight ' .. k) end mytester:assertlt(module1.gradBias:dist(module2.gradBias),precision,'error on gradBias ') end local function batchcompare(smod, sin, plist) local bs = torch.LongStorage(sin:dim()+1) bs[1] = 1 for i=1,sin:dim() do bs[i+1] = sin:size()[i] end local bin = torch.Tensor(bs):copy(sin) local bmod = smod:clone() local sout = smod:forward(sin):clone() local bout = bmod:forward(bin):clone() local sgout = torch.randn(sout:size()) local bgout = torch.Tensor(bout:size()) bgout:copy(sgout) local sgin = smod:backward(sin, sgout) local bgin = bmod:backward(bin, bgout) smod:accGradParameters(sin, sgout, 1) bmod:accGradParameters(bin, bgout, 1) mytester:assertTensorEq(sout,bout:select(1,1), 1e-8, 'batchcompare error on output') mytester:assertTensorEq(sgin,bgin:select(1,1), 1e-8, 'batchcompare error on gradInput') for i,v in pairs(plist) do mytester:assertTensorEq(smod[v],bmod[v], 1e-8, 'batchcompare error on ' .. v) end end function nntest.SpatialConvolutionBatchCompare() local from = math.random(1,5) local to = math.random(1,5) local ki = math.random(1,5) local kj = math.random(1,5) local si = math.random(1,4) local sj = math.random(1,4) local outi = math.random(5,9) local outj = math.random(5,9) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local module = nn.SpatialConvolution(from, to, ki, kj, si, sj) module:zeroGradParameters() local input = torch.randn(from,inj,ini) batchcompare(module,input, {'weight','bias','gradWeight','gradBias'}) end function nntest.SpatialFullConvolutionBatchCompare() local from = math.random(1,5) local to = math.random(1,5) local ki = math.random(1,5) local kj = math.random(1,5) local si = math.random(1,4) local sj = math.random(1,4) local ini = math.random(5,9) local inj = math.random(5,9) local module = nn.SpatialFullConvolution(from, to, ki, kj, si, sj) module:zeroGradParameters() local input = torch.randn(from, inj, ini) batchcompare(module,input, {'weight','bias','gradWeight','gradBias'}) end function nntest.SpatialSubSamplingBatchCompare() local from = math.random(1,6) local ki = math.random(1,5) local kj = math.random(1,5) local si = math.random(1,4) local sj = math.random(1,4) local outi = math.random(6,10) local outj = math.random(6,10) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local module = nn.SpatialSubSampling(from, ki, kj, si, sj) module:zeroGradParameters() local input = torch.randn(from,inj,ini)--torch.Tensor(from, inj, ini):zero() batchcompare(module,input, {'weight','bias','gradWeight','gradBias'}) end function nntest.SpatialSubSampling() local from = math.random(1,6) local ki = math.random(1,5) local kj = math.random(1,5) local si = math.random(1,4) local sj = math.random(1,4) local outi = math.random(6,10) local outj = math.random(6,10) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local module = nn.SpatialSubSampling(from, ki, kj, si, sj) local input = torch.Tensor(from, inj, ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'error on bias [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end local batch = math.random(2,5) outi = math.random(4,8) outj = math.random(4,8) ini = (outi-1)*si+ki inj = (outj-1)*sj+kj module = nn.SpatialSubSampling(from, ki, kj, si, sj) input = torch.Tensor(batch,from,inj,ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'batch error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'batch error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'batch error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'batch error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'batch error on bias [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'batch error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'batch error on bias [%s]', t)) end local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialMaxPooling() for _,ceil_mode in pairs({true,false}) do local from = math.random(1,5) local ki = math.random(1,4) local kj = math.random(1,4) local si = math.random(1,3) local sj = math.random(1,3) local outi = math.random(4,5) local outj = math.random(4,5) local padW = math.min(math.random(0,1),math.floor(ki/2)) local padH = math.min(math.random(0,1),math.floor(kj/2)) local ini = (outi-1)*si+ki-2*padW local inj = (outj-1)*sj+kj-2*padH local ceil_string = ceil_mode and 'ceil' or 'floor' local module = nn.SpatialMaxPooling(ki,kj,si,sj,padW,padH) if ceil_mode then module:ceil() else module:floor() end local input = torch.rand(from,inj,ini) local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error '..ceil_string..' mode on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- batch local nbatch = math.random(2,5) input = torch.rand(nbatch,from,inj,ini) module = nn.SpatialMaxPooling(ki,kj,si,sj,padW,padH) if ceil_mode then module:ceil() else module:floor() end local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error '..ceil_string..' mode on state (Batch)') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err (Batch) ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err (Batch) ') end end function nntest.SpatialAveragePooling() local from = math.random(1,6) local ki = math.random(1,5) local kj = math.random(1,5) local si = math.random(1,4) local sj = math.random(1,4) local outi = math.random(6,10) local outj = math.random(6,10) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local module = nn.SpatialAveragePooling(ki, kj, si, sj) local input = torch.Tensor(from, inj, ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') local sap = nn.SpatialSubSampling(from, ki, kj, si, sj) sap.weight:fill(1.0/(ki*kj)) sap.bias:fill(0.0) local output = module:forward(input) local gradInput = module:backward(input, output) local output2 = sap:forward(input) local gradInput2 = sap:updateGradInput(input, output) mytester:assertTensorEq(output, output2, 0.000001, torch.typename(module) .. ' forward err ') mytester:assertTensorEq(gradInput, gradInput2, 0.000001, torch.typename(module) .. ' backward err ') local batch = math.random(2,5) outi = math.random(4,8) outj = math.random(4,8) ini = (outi-1)*si+ki inj = (outj-1)*sj+kj module = nn.SpatialAveragePooling(ki, kj, si, sj) input = torch.Tensor(batch,from,inj,ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'batch error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err (Batch) ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err (Batch) ') local sap = nn.SpatialSubSampling(from, ki, kj, si, sj) sap.weight:fill(1.0/(ki*kj)) sap.bias:fill(0.0) local output = module:forward(input) local gradInput = module:backward(input, output) local output2 = sap:forward(input) local gradInput2 = sap:updateGradInput(input, output) mytester:assertTensorEq(output, output2, 0.000001, torch.typename(module) .. ' forward err (Batch) ') mytester:assertTensorEq(gradInput, gradInput2, 0.000001, torch.typename(module) .. ' backward err (Batch) ') end function nntest.SpatialAdaptiveMaxPooling() local from = math.random(1,5) local ki = math.random(1,5) local kj = math.random(1,5) local ini = math.random(1,16) local inj = math.random(1,16) local module = nn.SpatialAdaptiveMaxPooling(ki,kj) local input = torch.rand(from,ini,inj) local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- batch local nbatch = math.random(1,3) input = torch.rand(nbatch,from,ini,inj) module = nn.SpatialAdaptiveMaxPooling(ki,kj) local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state (Batch) ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err (Batch) ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err (Batch) ') -- non-contiguous input = torch.rand(from,ini,inj):transpose(2,3) module = nn.SpatialAdaptiveMaxPooling(ki,kj) local inputc = input:contiguous() -- contiguous local output = module:forward(input):clone() local outputc = module:forward(inputc):clone() mytester:asserteq(0, (output-outputc):abs():max(), torch.typename(module) .. ' - non-contiguous err ') local gradInput = module:backward(input, output):clone() local gradInputc = module:backward(inputc, outputc):clone() mytester:asserteq(0, (gradInput-gradInputc):abs():max(), torch.typename(module) .. ' - non-contiguous err ') -- non-contiguous batch local nbatch = math.random(1,3) input = torch.rand(nbatch,from,ini,inj):transpose(1,3):transpose(2,4) local inputc = input:contiguous() -- contiguous module = nn.SpatialAdaptiveMaxPooling(ki,kj) local output = module:forward(input):clone() local outputc = module:forward(inputc):clone() mytester:asserteq(0, (output-outputc):abs():max(), torch.typename(module) .. ' - batch non-contiguous err ') local gradInput = module:backward(input, output):clone() local gradInputc = module:backward(inputc, outputc):clone() mytester:asserteq(0, (gradInput-gradInputc):abs():max(), torch.typename(module) .. ' - batch non-contiguous err ') end function nntest.SpatialLPPooling() local fanin = math.random(1,4) local osizex = math.random(1,4) local osizey = math.random(1,4) local p = 2 local mx = math.random(2,6) local my = math.random(2,6) local dx = math.random(2,mx) local dy = math.random(2,my) local sizex = osizex*mx local sizey = osizey*my local module = nn.SpatialLPPooling(fanin,p,mx,my,dx,dy) local input = torch.rand(fanin,sizey,sizex) local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Sum() -- 1D local ini = math.random(3,7) local input = torch.Tensor(ini):zero() local module = nn.Sum(1) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') -- 3D local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ini,inj,ink):zero() local module = nn.Sum(torch.random(1,3)) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Tanh() local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local input = torch.Tensor(ink, inj, ini):zero() local module = nn.Tanh() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision , 'error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.TemporalConvolution() -- 1D local from = math.random(1,5) local to = math.random(1,5) local ki = math.random(1,5) local si = math.random(1,4) local outi = math.random(5,7) local ini = (outi-1)*si+ki local module = nn.TemporalConvolution(from, to, ki,si) local input = torch.Tensor(ini, from):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'error on weight [direct update]') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'error on bias [direct update]') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end -- 2D local nBatchFrame = 4 local input = torch.Tensor(nBatchFrame, ini, from):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'error on weight [direct update]') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'error on bias [direct update]') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') -- 2D matches 1D local output = module:forward(input):clone() local outputGrad = torch.randn(output:size()) local inputGrad = module:backward(input, outputGrad):clone() local input1D = input:select(1, 2) local output1D = module:forward(input1D) local outputGrad1D = outputGrad:select(1, 2) local inputGrad1D = module:backward(input1D, outputGrad1D) mytester:assertTensorEq(output:select(1,2), output1D, 0.000001, 'error on 2D vs 1D forward)') mytester:assertTensorEq(inputGrad:select(1,2), inputGrad1D, 0.000001, 'error on 2D vs 1D backward)') end function nntest.TemporalSubSampling() local from = math.random(1,5) local ki = math.random(1,6) local si = math.random(1,4) local outi = math.random(6,9) local ini = (outi-1)*si+ki local module = nn.TemporalSubSampling(from, ki, si) local input = torch.Tensor(ini, from):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'error on bias [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') end function nntest.TemporalMaxPooling() local from = math.random(2,4) local ki = math.random(5,7) local si = math.random(1,2) local outi = math.random(30,40) local ini = (outi-1)*si+ki local module = nn.TemporalMaxPooling(ki, si) local input = torch.Tensor(ini, from):zero() -- 1D local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') -- 2D local nBatchFrame = 2 local input = torch.Tensor(nBatchFrame, ini, from):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') -- 2D matches 1D local output = module:forward(input):clone() local outputGrad = torch.randn(output:size()) local inputGrad = module:backward(input, outputGrad):clone() local input1D = input:select(1, 2) local output1D = module:forward(input1D) local outputGrad1D = outputGrad:select(1, 2) local inputGrad1D = module:backward(input1D, outputGrad1D) mytester:assertTensorEq(output:select(1,2), output1D, 0.000001, 'error on 2D vs 1D forward)') mytester:assertTensorEq(inputGrad:select(1,2), inputGrad1D, 0.000001, 'error on 2D vs 1D backward)') end function nntest.VolumetricConvolution() local from = math.random(2,3) local to = math.random(2,3) local kt = math.random(3,4) local ki = math.random(3,4) local kj = math.random(3,4) local st = math.random(2,3) local si = math.random(2,3) local sj = math.random(2,3) local outt = math.random(3,4) local outi = math.random(3,4) local outj = math.random(3,4) local int = (outt-1)*st+kt local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local module = nn.VolumetricConvolution(from, to, kt, ki, kj, st, si, sj) local input = torch.Tensor(from, int, inj, ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err , precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err , precision, 'error on bias ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err , precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err , precision, 'error on bias [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') end function nntest.VolumetricConvolutionBatchCompare() local from = math.random(2,3) local to = math.random(2,3) local kt = math.random(3,4) local ki = math.random(3,4) local kj = math.random(3,4) local st = math.random(2,3) local si = math.random(2,3) local sj = math.random(2,3) local outt = math.random(3,4) local outi = math.random(3,4) local outj = math.random(3,4) local int = (outt-1)*st+kt local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local module = nn.VolumetricConvolution(from, to, kt, ki, kj, st, si, sj) module:zeroGradParameters() local input = torch.randn(from, int, inj, ini) batchcompare(module,input, {'weight','bias','gradWeight','gradBias'}) end function nntest.VolumetricAveragePooling() local from = math.random(2,3) local kt = math.random(3,4) local ki = math.random(3,4) local kj = math.random(3,4) local st = math.random(2,3) local si = math.random(2,3) local sj = math.random(2,3) local outt = math.random(3,4) local outi = math.random(3,4) local outj = math.random(3,4) local int = (outt-1)*st+kt local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local module = nn.VolumetricAveragePooling(kt, ki, kj, st, si, sj) local input = torch.Tensor(from, int, inj, ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') -- batch local nbatch = math.random(2,3) module = nn.VolumetricAveragePooling(kt, ki, kj, st, si, sj) input = torch.Tensor(nbatch, from, int, inj, ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state (Batch) ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err (Batch) ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err (Batch) ') end function nntest.VolumetricMaxPooling() local from = math.random(2,3) local kt = math.random(3,4) local ki = math.random(3,4) local kj = math.random(3,4) local st = math.random(2,3) local si = math.random(2,3) local sj = math.random(2,3) local outt = math.random(3,4) local outi = math.random(3,4) local outj = math.random(3,4) local int = (outt-1)*st+kt local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local module = nn.VolumetricMaxPooling(kt, ki, kj, st, si, sj) local input = torch.Tensor(from, int, inj, ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(0, ferr, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(0, berr, torch.typename(module) .. ' - i/o backward err ') -- batch local nbatch = math.random(2,3) module = nn.VolumetricMaxPooling(kt, ki, kj, st, si, sj) input = torch.Tensor(nbatch, from, int, inj, ini):zero() local err = jac.testJacobian(module, input) mytester:assertlt(err, precision, 'error on state (Batch) ') local ferr, berr = jac.testIO(module, input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err (Batch) ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err (Batch) ') end function nntest.Module_getParameters_1() local n = nn.Sequential() n:add( nn.Linear(10,10) ) local p = n:getParameters() mytester:asserteq((p[{ {1,100} }] - n.modules[1].weight):norm(), 0, 'getParameters(): weights wrong') mytester:asserteq((p[{ {101,110} }] - n.modules[1].bias):norm(), 0, 'getParameters(): bias wrong') end function nntest.Module_getParameters_2() local n = nn.Sequential() n:add( nn.Linear(10,10) ) local _ = n:getParameters() n:add( nn.Linear(10,10) ) local p = n:getParameters() mytester:asserteq((p[{ {111,210} }] - n.modules[2].weight):norm(), 0, 'error when appending new module') mytester:asserteq((p[{ {211,220} }] - n.modules[2].bias):norm(), 0, 'error when appending new module') end function nntest.Module_getParameters_3() local n = nn.Sequential() n:add( nn.Linear(10,10) ) n:add( n.modules[1]:clone() ) local p = n:getParameters() mytester:asserteq((p[{ {1,100} }] - n.modules[1].weight):norm(), 0, 'error when using cloning') mytester:asserteq((p[{ {101,110} }] - n.modules[1].bias):norm(), 0, 'error when using cloning') mytester:asserteq((p[{ {111,210} }] - n.modules[2].weight):norm(), 0, 'error when using cloning') mytester:asserteq((p[{ {211,220} }] - n.modules[2].bias):norm(), 0, 'error when using cloning') mytester:asserteq((p[{ {111,210} }] - n.modules[1].weight):norm(), 0, 'error when using cloning') mytester:asserteq((p[{ {211,220} }] - n.modules[1].bias):norm(), 0, 'error when using cloning') n:reset() mytester:assertgt((p[{ {111,210} }] - n.modules[1].weight):norm(), 0, 'error when using cloning') mytester:assertgt((p[{ {211,220} }] - n.modules[1].bias):norm(), 0, 'error when using cloning') end function nntest.Module_getParameters_4() local n = nn.Sequential() n:add( nn.Linear(10,10) ) n:add( n.modules[1]:clone() ) local _ = n:getParameters() n:add(nn.Linear(10,10)) local p = n:getParameters() mytester:asserteq((p[{ {1,100} }] - n.modules[1].weight):norm(), 0, 'error when using cloning') mytester:asserteq((p[{ {101,110} }] - n.modules[1].bias):norm(), 0, 'error when using cloning') mytester:asserteq((p[{ {111,210} }] - n.modules[2].weight):norm(), 0, 'error when using cloning') mytester:asserteq((p[{ {211,220} }] - n.modules[2].bias):norm(), 0, 'error when using cloning') mytester:asserteq((p[{ {221,320} }] - n.modules[3].weight):norm(), 0, 'error when using cloning') mytester:asserteq((p[{ {321,330} }] - n.modules[3].bias):norm(), 0, 'error when using cloning') mytester:asserteq(p:nElement(), 3*(10*10+10), 'error: incorrect number of elements in flat vector') end function nntest.Module_getParameters_5() local n = nn.Sequential() n:add( nn.Linear(10,10) ) n:add( n.modules[1]:clone('weight','bias') ) local p = n:getParameters() mytester:asserteq((p[{ {1,100} }] - n.modules[1].weight):norm(), 0, 'error when using cloning+sharing') mytester:asserteq((p[{ {101,110} }] - n.modules[1].bias):norm(), 0, 'error when using cloning+sharing') mytester:asserteq((p[{ {1,100} }] - n.modules[2].weight):norm(), 0, 'error when using cloning+sharing') mytester:asserteq((p[{ {101,110} }] - n.modules[2].bias):norm(), 0, 'error when using cloning+sharing') n:reset() mytester:asserteq((p[{ {1,100} }] - n.modules[2].weight):norm(), 0, 'error when using cloning+sharing') mytester:asserteq((p[{ {101,110} }] - n.modules[2].bias):norm(), 0, 'error when using cloning+sharing') mytester:asserteq(p:nElement(), (10*10+10), 'error: incorrect number of elements in flat vector') end function nntest.Module_getParameters_6() local n = nn.Sequential() n:add( nn.Linear(10,10) ) n:add( n.modules[1]:clone('weight','bias') ) local _ = n:getParameters() n:add(nn.Linear(10,10)) local p = n:getParameters() mytester:asserteq((p[{ {1,100} }] - n.modules[1].weight):norm(), 0, 'error when using cloning+sharing') mytester:asserteq((p[{ {101,110} }] - n.modules[1].bias):norm(), 0, 'error when using cloning+sharing') mytester:asserteq((p[{ {1,100} }] - n.modules[2].weight):norm(), 0, 'error when using cloning+sharing') mytester:asserteq((p[{ {101,110} }] - n.modules[2].bias):norm(), 0, 'error when using cloning+sharing') mytester:asserteq((p[{ {111,210} }] - n.modules[3].weight):norm(), 0, 'error when using cloning+sharing') mytester:asserteq((p[{ {211,220} }] - n.modules[3].bias):norm(), 0, 'error when using cloning+sharing') mytester:asserteq(p:nElement(), 2*(10*10+10), 'error: incorrect number of elements in flat vector') end function nntest.Module_getParameters_7() local n = nn.Sequential() n:add( nn.Linear(10,10) ) n:add( n.modules[1]:clone('weight','bias') ) local _ = n:getParameters() n:add(nn.Linear(10,10)) local _ = n:getParameters() local n1 = nn.Sequential() n1:add( nn.Linear(10,10) ) local n2 = nn.Sequential() n2:add( nn.Linear(10,10) ) local n = nn.Sequential() n:add( n1 ) n:add( n2 ) local _ = n:getParameters() local nf = nn.Sequential() nf:add( n1 ) nf:add( nn.Linear(10,1) ) local p = nf:getParameters() mytester:asserteq((p[{ {1,100} }] - n1.modules[1].weight):norm(), 0, 'error when using cloning+partial realloc') mytester:asserteq((p[{ {101,110} }] - n1.modules[1].bias):norm(), 0, 'error when using cloning+partial realloc') mytester:asserteq((p[{ {111,120} }] - nf.modules[2].weight):norm(), 0, 'error when using cloning+partial realloc') mytester:asserteq((p[{ {121,121} }] - nf.modules[2].bias):norm(), 0, 'error when using cloning+partial realloc') mytester:asserteq(p:nElement(), 121, 'error: incorrect number of elements in flat vector') end function nntest.Module_getParameters_8() local function makeMLP(nin, ns) local net = nn.Sequential() for k,v in ipairs(ns) do net:add(nn.Linear(nin, v)) nin = v end local _,_ = net:getParameters() return net end local mlp1 = makeMLP(10, {10,10}) local mlp2 = makeMLP(10, {10,10}) local net = nn.Sequential():add(mlp1:get(1)) :add(mlp2:get(1)) -- clone the second MLP to ensure that the weights before calling getParameters are preserved mlp2 = mlp2:clone() local p, _ = net:getParameters() mytester:asserteq((p[{ {1,100} }] - net.modules[1].weight):norm(), 0, 'error when using partial realloc') mytester:asserteq((p[{ {111,210} }] - net.modules[2].weight):norm(), 0, 'error when using partial realloc') -- check that the weights have the same values as before get Parameters was called mytester:asserteq((net.modules[1].weight - mlp1.modules[1].weight):norm(), 0, ' error when using partial realloc') mytester:asserteq((net.modules[2].weight - mlp2.modules[1].weight):norm(), 0, ' error when using partial realloc') end function nntest.Module_listModules() local batchSize = 4 local inputSize, outputSize = 7, 6 local linear = nn.Linear(inputSize, outputSize) local tanh = nn.Tanh() local reshape = nn.Reshape(outputSize/2, 2) local mlp3 = nn.Sequential() mlp3:add(linear) mlp3:add(tanh) mlp3:add(reshape) local mlp2 = nn.Sequential() local view = nn.View(outputSize) local linear2 = nn.Linear(outputSize, inputSize) local tanh2 = nn.Tanh() mlp2:add(mlp3) mlp2:add(view) mlp2:add(linear2) mlp2:add(tanh2) local concat = nn.ConcatTable() local id = nn.Identity() concat:add(mlp2) concat:add(id) local mlp = nn.Sequential() local add = nn.CAddTable() mlp:add(concat) mlp:add(add) local modules2 = {mlp, concat, mlp2, mlp3, linear, tanh, reshape, view, linear2, tanh2, id, add} local modules = mlp:listModules() mytester:assert(#modules2 == #modules, 'missing modules error') for i,module in ipairs(modules) do mytester:assert(torch.type(module) == torch.type(modules2[i]), 'module error') end end function nntest.PairwiseDistance() -- Note: testJacobian doesn't support table inputs, and rather than re-write -- it so that it does, I'll just use a split table module on the input. -- I assume both SplitTable and Sequential do not have bugs, otherwise this -- test will break. for p = 1,4 do -- test a few Lp norms -- TEST CASE 1: non-batch input, same code path but includes a resize local ini = math.random(3,5) local input = torch.Tensor(2, ini):zero() local module = nn.Sequential() module:add(nn.SplitTable(1)) module:add(nn.PairwiseDistance(p)) local err = jac.testJacobian(module,input) mytester:assertlt(err, 1e-4, ' error on state ') local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module)..' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module)..' - i/o backward err ') -- Also check that the forward prop result is correct. input = torch.rand(2, ini) err = torch.dist(input:select(1,1), input:select(1,2), p) - module:forward(input)[1] mytester:assertlt(err,precision, ' error on non-batch fprop ') -- TEST CASE 2: batch input local inj = math.random(3,5) input = torch.Tensor(2, inj, ini):zero() -- (Rebuild the module to avoid correlated tests) module = nn.Sequential() module:add(nn.SplitTable(1)) module:add(nn.PairwiseDistance(p)) err = jac.testJacobian(module,input) mytester:assertlt(err, 1e-4, ' error on state ') -- Also check that the forward prop result is correct. -- manually calculate each distance separately local inputa = torch.rand(inj,ini) local inputb = torch.rand(inj,ini) local dist_manual = torch.Tensor(inj) for i=1, inputa:size(1) do dist_manual[i] = torch.dist(inputa:select(1,i), inputb:select(1,i),p) end -- compare the distances to the module's fprop local dist = module:forward(torch.cat(inputa,inputb,1):resize(2,inj,ini)) err = dist - dist_manual mytester:assertlt(err:norm(), precision, torch.typename(module) .. ' error on batch fprop ') end end function nntest.LookupTable() local totalIndex = math.random(6,9) local nIndex = math.random(3,5) local entry_size = math.random(2,5) local input = torch.randperm(totalIndex):narrow(1,1,nIndex):int() local module = nn.LookupTable(totalIndex, entry_size) local minval = 1 local maxval = totalIndex local output = module:forward(input) module:backwardUpdate(input, output, 0.1) input:zero() -- 1D local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight, minval, maxval) mytester:assertlt(err,precision, '1D error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight, minval, maxval) mytester:assertlt(err,precision, '1D error on weight [direct update] ') module.gradWeight:zero() for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( '1D error on weight [%s]', t)) end -- 2D local nframe = math.random(2,5) local input = torch.IntTensor(nframe, nIndex):zero() local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight, minval, maxval) mytester:assertlt(err,precision, '2D error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight, minval, maxval) mytester:assertlt(err,precision, '2D error on weight [direct update] ') module.gradWeight:zero() for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( '2D error on weight [%s]', t)) end -- IO module.gradInput = torch.Tensor(3,4):zero() --fixes an error local ferr,berr = jac.testIO(module,input,minval,maxval) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- accUpdate module:accUpdateOnly() mytester:assert(not module.gradWeight, 'gradWeight is nil') module:float() local output = module:forward(input) module:backwardUpdate(input, output, 0.1) end function nntest.AddConstant() local nbatch = torch.random(3, 5) local f = torch.random(3, 5) local h = torch.random(7,9) local w = torch.random(7,9) local input = torch.rand(nbatch, f, h, w):mul(20):add(-10) -- [-10, 10] local constant = torch.randn(1):squeeze() local mod = nn.AddConstant(constant) -- Test FPROP local output = mod:forward(input) local delta = output - input mytester:assertlt(delta:add(-constant):abs():max(), precision, 'fprop error') -- Test BPROP local err = jac.testJacobian(mod, input) mytester:assertlt(err, precision, 'bprop error ') -- inplace comparisons local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local constant = torch.uniform()*math.random(1,10) local input1 = torch.rand(ink, inj, ini) local input2 = input1:clone() local module1 = nn.AddConstant(constant,true) local module2 = nn.AddConstant(constant) local gradOutput1 = torch.rand(ink, inj, ini) local gradOutput2 = gradOutput1:clone() local out1 = module1:forward(input1) local out2 = module2:forward(input2) mytester:asserteq(0, (out1-out2):abs():max(), torch.typename(module1) .. ' - in-place forward err ') local gradInput1 = module1:backward(input1, gradOutput1) local gradInput2 = module2:backward(input2, gradOutput2) mytester:asserteq(0, (gradInput1-gradInput2):abs():max(), torch.typename(module1) .. ' - in-place backward err ') local input1 = torch.rand(ink, inj, ini) local input2 = input1:clone() module1:forward(input1) module1:backward(module1.output,torch.rand(input1:size())) local err = (input1-input2):abs():max() mytester:asserteq(err, 0, torch.typename(module1) .. ' - inplace input change err ') end function nntest.MulConstant() local nbatch = torch.random(3, 5) local f = torch.random(3, 5) local h = torch.random(7,9) local w = torch.random(7,9) local input = torch.rand(nbatch, f, h, w):mul(20):add(-10) -- [-10, 10] local constant = torch.randn(1):squeeze() local mod = nn.MulConstant(constant) -- Test FPROP local output = mod:forward(input) local scale = output:clone():cdiv(input) mytester:assertlt(scale:add(-constant):abs():max(), precision, 'fprop error') -- Test BPROP local err = jac.testJacobian(mod, input) mytester:assertlt(err, precision, 'bprop error ') -- inplace comparisons local ini = math.random(3,5) local inj = math.random(3,5) local ink = math.random(3,5) local constant = torch.uniform()*math.random(1,10) local input1 = torch.rand(ink, inj, ini) local input2 = input1:clone() local module1 = nn.MulConstant(constant,true) local module2 = nn.MulConstant(constant) local gradOutput1 = torch.rand(ink, inj, ini) local gradOutput2 = gradOutput1:clone() local out1 = module1:forward(input1) local out2 = module2:forward(input2) mytester:asserteq(0, (out1-out2):abs():max(), torch.typename(module1) .. ' - in-place forward err ') local gradInput1 = module1:backward(input1, gradOutput1) local gradInput2 = module2:backward(input2, gradOutput2) mytester:asserteq(0, (gradInput1-gradInput2):abs():max(), torch.typename(module1) .. ' - in-place backward err ') local input1 = torch.rand(ink, inj, ini) local input2 = input1:clone() module1:forward(input1) module1:backward(module1.output,torch.rand(input1:size())) local err = (input1-input2):abs():max() mytester:assertalmosteq(err, 0, 1e-15, torch.typename(module1) .. ' - inplace input change err ') end function nntest.Copy() local input = torch.randn(3,4):double() local c = nn.Copy('torch.DoubleTensor', 'torch.FloatTensor') local output = c:forward(input) mytester:assert(torch.type(output) == 'torch.FloatTensor', 'copy forward type err') mytester:assertTensorEq(output, input:float(), 0.000001, 'copy forward value err') local gradInput = c:backward(input, output) mytester:assert(torch.type(gradInput) == 'torch.DoubleTensor', 'copy backward type err') mytester:assertTensorEq(gradInput, input, 0.000001, 'copy backward value err') c.dontCast = true c:double() mytester:assert(torch.type(output) == 'torch.FloatTensor', 'copy forward type err') end function nntest.JoinTable() local tensor = torch.rand(3,4,5) local input = {tensor, tensor} local module for d = 1,tensor:dim() do module = nn.JoinTable(d) mytester:asserteq(module:forward(input):size(d), tensor:size(d)*2, "dimension " .. d) end -- Minibatch local tensor = torch.rand(3,4,5) local input = {tensor, tensor} local module for d = 1,tensor:dim()-1 do module = nn.JoinTable(d, 2) mytester:asserteq(module:forward(input):size(d+1), tensor:size(d+1)*2, "dimension " .. d) end end function nntest.SplitTable() local input = torch.randn(3,4,5) local module for d = 1,input:dim() do module = nn.SplitTable(d) mytester:asserteq(#module:forward(input), input:size(d), "dimension " .. d) end -- Minibatch local input = torch.randn(3,4,5) local module for d = 1,input:dim()-1 do module = nn.SplitTable(d, 2) mytester:asserteq(#module:forward(input), input:size(d+1), "dimension " .. d) end -- Negative indices local module = nn.SplitTable(-3) local input = torch.randn(3,4,5) mytester:asserteq(#module:forward(input), 3, "negative index") local input = torch.randn(2,3,4,5) mytester:asserteq(#module:forward(input), 3, "negative index (minibatch)") end function nntest.SelectTable() local input = { torch.rand(3,4,5), torch.rand(3,4,5), {torch.rand(3,4,5)}, {torch.rand(3,4,5), {torch.rand(3,4,5)}} } local gradOutputs = { torch.rand(3,4,5), torch.rand(3,4,5), {torch.rand(3,4,5)}, {torch.rand(3,4,5), {torch.rand(3,4,5)}} } local zeros = { torch.Tensor(3,4,5):zero(), torch.Tensor(3,4,5):zero(), {torch.Tensor(3,4,5):zero()}, {torch.Tensor(3,4,5):zero(), {torch.Tensor(3,4,5):zero()}} } local nonIdx = {2,3,4,1} local module for idx = 1,#input do module = nn.SelectTable(idx) local output = module:forward(input) equal(output, input[idx], "output dimension " .. idx) local gradInput = module:backward(input, gradOutputs[idx]) equal(gradInput[idx], gradOutputs[idx], "gradInput[idx] dimension " .. idx) equal(gradInput[nonIdx[idx]], zeros[nonIdx[idx]], "gradInput[nonIdx] dimension " .. idx) end -- test negative index local idx = -2 module = nn.SelectTable(idx) local output = module:forward(input) equal(output, input[#input+idx+1], "output dimension " .. idx) local gradInput = module:backward(input, gradOutputs[#input+idx+1]) equal(gradInput[#input+idx+1], gradOutputs[#input+idx+1], "gradInput[idx] dimension " .. idx) equal(gradInput[nonIdx[#input+idx+1]], zeros[nonIdx[#input+idx+1]], "gradInput[nonIdx] dimension " .. idx) -- test typecast local idx = #input module = nn.SelectTable(idx) module:float() local output = module:forward(input) equal(output, input[idx], "type output") local gradInput = module:backward(input, gradOutputs[idx]) equal(gradInput[idx], gradOutputs[idx], "gradInput[idx] dimension " .. idx) equal(gradInput[nonIdx[idx]], zeros[nonIdx[idx]], "gradInput[nonIdx] dimension " .. idx) end function nntest.MixtureTable() --[[ 2D ]]-- -- expertInput is a Table: local expertInput = torch.randn(5,3,6) local gradOutput = torch.randn(5,6) local input = { torch.rand(5,3), {expertInput:select(2,1), expertInput:select(2,2), expertInput:select(2,3)} } local module = nn.MixtureTable() local output = module:forward(input) local output2 = torch.cmul(input[1]:view(5,3,1):expand(5,3,6), expertInput):sum(2) mytester:assertTensorEq(output, output2, 0.000001, "mixture output") local gradInput = module:backward(input, gradOutput) local gradOutput2 = torch.view(gradOutput, 5, 1, 6):expandAs(expertInput) local gaterGradInput2 = torch.cmul(gradOutput2, expertInput):sum(3):select(3,1) mytester:assertTensorEq(gradInput[1], gaterGradInput2, 0.000001, "mixture gater gradInput") local expertGradInput2 = torch.cmul(input[1]:view(5,3,1):expand(5,3,6), gradOutput:view(5,1,6):expand(5,3,6)) for i, expertGradInput in ipairs(gradInput[2]) do mytester:assertTensorEq(expertGradInput, expertGradInput2:select(2,i), 0.000001, "mixture expert "..i.." gradInput") end -- expertInput is a Tensor: local input = {input[1], expertInput} local module = nn.MixtureTable(2) local output = module:forward(input) mytester:assertTensorEq(output, output2, 0.000001, "mixture2 output") local gradInput = module:backward(input, gradOutput) mytester:assertTensorEq(gradInput[1], gaterGradInput2, 0.000001, "mixture2 gater gradInput") mytester:assertTensorEq(gradInput[2], expertGradInput2, 0.000001, "mixture2 expert gradInput") --[[ 3D ]]-- local expertInput = torch.randn(5,6,3,2) local gradOutput = torch.randn(5,6,2) -- expertInput is a Table: local input = { torch.rand(5,3), {expertInput:select(3,1), expertInput:select(3,2), expertInput:select(3,3)} } local module = nn.MixtureTable() local output = module:forward(input) local output2 = torch.cmul(input[1]:view(5,1,3,1):expand(5,6,3,2), expertInput):sum(3) mytester:assertTensorEq(output, output2, 0.000001, "mixture3 output") local gradInput = module:backward(input, gradOutput) local gradOutput2 = torch.view(gradOutput,5,6,1,2):expandAs(expertInput) local gaterGradInput2 = torch.cmul(gradOutput2, expertInput):sum(4):select(4,1):sum(2):select(2,1) mytester:assertTensorEq(gradInput[1], gaterGradInput2, 0.000001, "mixture3 gater gradInput") local expertGradInput2 = torch.cmul(input[1]:view(5,1,3,1):expand(5,6,3,2), gradOutput2) for i, expertGradInput in ipairs(gradInput[2]) do mytester:assertTensorEq(expertGradInput, expertGradInput2:select(3,i), 0.000001, "mixture3 expert "..i.." gradInput") end -- expertInput is a Tensor local input = {input[1], expertInput} local module = nn.MixtureTable(3) local output = module:forward(input) mytester:assertTensorEq(output, output2, 0.000001, "mixture4 output") local gradInput = module:backward(input, gradOutput) mytester:assertTensorEq(gradInput[1], gaterGradInput2, 0.000001, "mixture4 gater gradInput") mytester:assertTensorEq(gradInput[2], expertGradInput2, 0.000001, "mixture4 expert gradInput") --[[ 1D ]]-- -- expertInput is a Table: local expertInput = torch.randn(3,6) local gradOutput = torch.randn(6) local input = { torch.rand(3), {expertInput:select(1,1), expertInput:select(1,2), expertInput:select(1,3)} } local module = nn.MixtureTable() local output = module:forward(input) local output2 = torch.cmul(input[1]:view(3,1):expand(3,6), expertInput):sum(1) mytester:assertTensorEq(output, output2, 0.000001, "mixture5 output") local gradInput = module:backward(input, gradOutput) local gradOutput2 = torch.view(gradOutput, 1, 6):expandAs(expertInput) local gaterGradInput2 = torch.cmul(gradOutput2, expertInput):sum(2):select(2,1) mytester:assertTensorEq(gradInput[1], gaterGradInput2, 0.000001, "mixture5 gater gradInput") local expertGradInput2 = torch.cmul(input[1]:view(3,1):expand(3,6), gradOutput:view(1,6):expand(3,6)) for i, expertGradInput in ipairs(gradInput[2]) do mytester:assertTensorEq(expertGradInput, expertGradInput2:select(1,i), 0.000001, "mixture5 expert "..i.." gradInput") end -- test type-cast module:float() local input2 = { input[1]:float(), {input[2][1]:float(), input[2][2]:float(), input[2][3]:float()} } local output = module:forward(input2) mytester:assertTensorEq(output, output2:float(), 0.000001, "mixture5B output") local gradInput = module:backward(input2, gradOutput:float()) mytester:assertTensorEq(gradInput[1], gaterGradInput2:float(), 0.000001, "mixture5B gater gradInput") for i, expertGradInput in ipairs(gradInput[2]) do mytester:assertTensorEq(expertGradInput, expertGradInput2:select(1,i):float(), 0.000001, "mixture5B expert "..i.." gradInput") end -- expertInput is a Tensor: local input = {input[1], expertInput} local module = nn.MixtureTable(1) local output = module:forward(input) mytester:assertTensorEq(output, output2, 0.000001, "mixture6 output") local gradInput = module:backward(input, gradOutput) mytester:assertTensorEq(gradInput[1], gaterGradInput2, 0.000001, "mixture6 gater gradInput") mytester:assertTensorEq(gradInput[2], expertGradInput2, 0.000001, "mixture6 expert gradInput") -- test type-cast: module:float() local input2 = {input[1]:float(), expertInput:float()} local output = module:forward(input2) mytester:assertTensorEq(output, output2:float(), 0.000001, "mixture6B output") local gradInput = module:backward(input2, gradOutput:float()) mytester:assertTensorEq(gradInput[1], gaterGradInput2:float(), 0.000001, "mixture6B gater gradInput") mytester:assertTensorEq(gradInput[2], expertGradInput2:float(), 0.000001, "mixture6B expert gradInput") --[[ 2D gater, 1D expert]]-- -- expertInput is a Table: local expertInput = torch.randn(5,3) local gradOutput = torch.randn(5) local input = { torch.rand(5,3), {expertInput:select(2,1), expertInput:select(2,2), expertInput:select(2,3)} } local module = nn.MixtureTable() local output = module:forward(input) local output2 = torch.cmul(input[1], expertInput):sum(2) mytester:assertTensorEq(output, output2, 0.000001, "mixture7 output") local gradInput = module:backward(input, gradOutput) local gradOutput2 = torch.view(gradOutput, 5, 1):expandAs(expertInput) local gaterGradInput2 = torch.cmul(gradOutput2, expertInput) mytester:assertTensorEq(gradInput[1], gaterGradInput2, 0.000001, "mixture7 gater gradInput") local expertGradInput2 = torch.cmul(input[1], gradOutput:view(5,1):expand(5,3)) for i, expertGradInput in ipairs(gradInput[2]) do mytester:assertTensorEq(expertGradInput, expertGradInput2:select(2,i), 0.000001, "mixture7 expert "..i.." gradInput") end end function nntest.NarrowTable() local input = torch.randn(3,10,4) local gradOutput = torch.randn(3,3,4) local nt = nn.NarrowTable(5,3) local seq = nn.Sequential() seq:add(nn.SplitTable(1,2)) seq:add(nt) seq:add(nn.JoinTable(1,1)) seq:add(nn.Reshape(3,3,4)) local seq2 = nn.Narrow(2,5,3) local output = seq:forward(input) local gradInput = seq:backward(input, gradOutput) local output2 = seq2:forward(input) local gradInput2 = seq2:backward(input, gradOutput) mytester:assertTensorEq(output, output2, 0.0000001, "NarrowTable output err") mytester:assertTensorEq(gradInput, gradInput2, 0.00001, "NarrowTable gradInput err") -- now try it with a smaller input local input = input:narrow(2, 1, 8) local output = seq:forward(input) local gradInput = seq:backward(input, gradOutput) local output2 = seq2:forward(input) local gradInput2 = seq2:backward(input, gradOutput) mytester:assertTensorEq(output, output2, 0.0000001, "NarrowTable small output err") mytester:assertTensorEq(gradInput, gradInput2, 0.00001, "NarrowTable small gradInput err") -- test type-cast local input = input:float() local gradOutput = gradOutput:float() seq:float() seq2:float() local output = seq:forward(input) local gradInput = seq:backward(input, gradOutput) local output2 = seq2:forward(input) local gradInput2 = seq2:backward(input, gradOutput) mytester:assertTensorEq(output, output2, 0.0000001, "NarrowTable output float err") mytester:assertTensorEq(gradInput, gradInput2, 0.00001, "NarrowTable gradInput float err") end function nntest.View() local input = torch.rand(10) local template = torch.rand(5,2) local target = template:size():totable() local module = nn.View(template:size()) mytester:assertTableEq(module:forward(input):size():totable(), target, "Error in forward (1)") local module = nn.View(table.unpack(target)) mytester:assertTableEq(module:forward(input):size():totable(), target, "Error in forward (2)") -- Minibatch local minibatch = torch.rand(5,10) mytester:assertTableEq(module:forward(minibatch):size(1), minibatch:size(1), "Error in minibatch dimension") mytester:assertTableEq(module:forward(minibatch):nElement(), minibatch:nElement(), "Error in minibatch nElement") local module = nn.View(-1):setNumInputDims(1) mytester:assertTableEq(module:forward(minibatch):size(1), minibatch:size(1), "Error in minibatch dimension with size -1") mytester:assertTableEq(module:forward(minibatch):nElement(), minibatch:nElement(), "Error in minibatch nElement with size -1") -- another setNumInputDims case local minibatch = torch.rand(5,4,10) local module = nn.View(-1):setNumInputDims(2) mytester:assertTableEq(module:forward(minibatch):size(1), minibatch:size(1), "Error in minibatch dimension with size -1") -- another setNumInputDims case local minibatch = torch.rand(2,5,4,10) local module = nn.View(4,-1):setNumInputDims(2) local out = module:forward(minibatch) mytester:assertTableEq(out:size(1), minibatch:size(1)*minibatch:size(2), "Error in minibatch dimension with size -1") mytester:assertTableEq(out:size(2), minibatch:size(3), "Error in minibatch dimension with size -1") mytester:assertTableEq(out:size(3), minibatch:size(4), "Error in minibatch dimension with size -1") -- Minibatch Generalization local minibatch = torch.rand(5,2,6) local module = nn.View(6) mytester:assertTableEq( module:forward(minibatch):size(1), minibatch:size(1)*minibatch:size(2), "Error in minibatch generalization dimension") mytester:assertTableEq( module:forward(minibatch):nElement(), minibatch:nElement(), "Error in minibatch generalization nElement") end function nntest.Reshape() local input = torch.rand(10) local template = torch.rand(5,2) local target = template:size():totable() local module = nn.Reshape(template:size()) mytester:assertTableEq(module:forward(input):size():totable(), target, "Error in forward (1)") local module = nn.View(table.unpack(target)) mytester:assertTableEq(module:forward(input):size():totable(), target, "Error in forward (2)") -- Minibatch local minibatch = torch.rand(5,10) mytester:assertTableEq(module:forward(minibatch):size(1), minibatch:size(1), "Error in minibatch dimension") mytester:assertTableEq(module:forward(minibatch):nElement(), minibatch:nElement(), "Error in minibatch nElement") end -- Define a test for SpatialUpSamplingCuda function nntest.SpatialUpSamplingNearest() local scale = torch.random(2,4) for dim = 3,4 do local m = nn.SpatialUpSamplingNearest(scale) -- Create a randomly sized dimD vector local shape = {} for i = 1, dim do table.insert(shape, torch.random(2, 2+dim-1)) end -- Check that the gradient is correct by using finite elements local input = torch.Tensor(table.unpack(shape)):zero() local err = jac.testJacobian(m, input) mytester:assertlt(err, precision, ' error on state ') local ferr, berr = jac.testIO(m, input) mytester:asserteq(ferr, 0, torch.typename(m)..' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(m)..' - i/o backward err ') end end function nntest.Parallel() local input = torch.randn(3, 4, 5) local m = nn.Parallel(1,3) m:add(nn.View(4,5,1)) m:add(nn.View(4,5,1)) m:add(nn.View(4,5,1)) local output = m:forward(input) local output2 = input:transpose(1,3):transpose(1,2) mytester:assertTensorEq(output2, output, 0.000001, 'Parallel forward err') local gradInput = m:backward(input, output2) mytester:assertTensorEq(gradInput, input, 0.000001, 'Parallel backward err') end function nntest.ParallelTable() local input = torch.randn(3, 4, 5) local p = nn.ParallelTable() p:add(nn.View(4,5,1)) p:add(nn.View(4,5,1)) p:add(nn.View(4,5,1)) local m = nn.Sequential() m:add(nn.SplitTable(1)) m:add(p) m:add(nn.JoinTable(3)) local output = m:forward(input) local output2 = input:transpose(1,3):transpose(1,2) mytester:assertTensorEq(output2, output, 0.000001, 'ParallelTable forward err') local gradInput = m:backward(input, output2) mytester:assertTensorEq(gradInput, input, 0.000001, 'ParallelTable backward err') end function nntest.ConcatTable() -- Test tensor input local input = torch.rand(5, 5, 5) local m = nn.Sequential() local concat = nn.ConcatTable() concat:add(nn.Identity()) m:add(concat) -- Output of concat is a table of length 1 m:add(nn.JoinTable(1)) -- jac needs a tensor tensor output local err = jac.testJacobian(m, input) mytester:assertlt(err, precision, ' error on state ') local ferr, berr = jac.testIO(m, input) mytester:asserteq(ferr, 0, torch.typename(m)..' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(m)..' - i/o backward err ') -- Now test a table input local input = { torch.randn(3,4):float(), torch.randn(3,4):float(), {torch.randn(3,4):float()} } local _gradOutput = { torch.randn(3,3,4):float(), torch.randn(3,3,4):float(), torch.randn(3,3,4):float() } local gradOutput = { {_gradOutput[1][1], _gradOutput[2][1], {_gradOutput[3][1]}}, {_gradOutput[1][2], _gradOutput[2][2], {_gradOutput[3][2]}}, {_gradOutput[1][3], _gradOutput[2][3], {_gradOutput[3][3]}} } local module = nn.ConcatTable() module:add(nn.Identity()) module:add(nn.Identity()) module:add(nn.Identity()) module:float() local output = module:forward(input) local output2 = {input, input, input} equal(output2, output, "ConcatTable table output") local gradInput = module:backward(input, gradOutput) local gradInput2 = {_gradOutput[1]:sum(1), _gradOutput[2]:sum(1), {_gradOutput[3]:sum(1)}} equal(gradInput, gradInput2, "ConcatTable table gradInput") end function nntest.FlattenTable() -- Create a nested table. Obviously we can't even stochastically test -- the space of all possible nested tables (it's infinite), but here is a -- hand-coded one that covers all the cases we need: local input = { torch.rand(1), { torch.rand(2), { torch.rand(3) }, }, torch.rand(4) } local gradOutput = { torch.rand(1), torch.rand(2), torch.rand(3), torch.rand(4) } -- Check the FPROP local m = nn.FlattenTable() local output = m:forward(input) mytester:assert(#output == 4, torch.typename(m)..' - fprop err ') -- This is ugly, but check that the mapping from input to output is correct mytester:assert(output[1] == input[1]) mytester:assert(output[2] == input[2][1]) mytester:assert(output[3] == input[2][2][1]) mytester:assert(output[4] == input[3]) -- Check the BPROP local gradInput = m:backward(input, gradOutput) -- Again, check that the mapping is correct mytester:assert(gradOutput[1] == gradInput[1]) mytester:assert(gradOutput[2] == gradInput[2][1]) mytester:assert(gradOutput[3] == gradInput[2][2][1]) mytester:assert(gradOutput[4] == gradInput[3]) -- More uglyness: FlattenTable doesn't rebuild the table every updateOutput -- call, so we need to make sure that modifications to the input are -- detected correctly (and that the table is correctly rebuilt. -- CASE 1: Nothing changes so the output table shouldn't be redefined local old_input_map = m.input_map local old_output = m.output local _ = m:forward(input) mytester:assert(old_input_map == m.input_map and old_output == m.output) -- CASE 2: An element is added to the input table old_input_map = m.input_map old_output = m.output input[2][#(input[2])+1] = torch.rand(5) m:forward(input) mytester:assert(old_input_map ~= m.input_map and old_output ~= m.output) -- CASE 3: An element is removed from the input table old_input_map = m.input_map old_output = m.output input[#input] = nil m:forward(input) mytester:assert(old_input_map ~= m.input_map and old_output ~= m.output) -- At this point further testing is not necessary I think, but just to be -- consistent: perform a jacobian test by using SplitTable and JointTable -- elements m = nn.Sequential() local par = nn.ParallelTable() par:add(nn.SplitTable(1)) par:add(nn.SplitTable(1)) m:add(nn.SplitTable(1)) m:add(par) -- this will create a nested table m:add(nn.FlattenTable()) -- This will flatten the nested table m:add(nn.JoinTable(1)) -- Finally, this will create a 1D tensor input = torch.Tensor(2,2,2) local err = jac.testJacobian(m, input) mytester:assertlt(err, precision, 'error on bprop ') end function nntest.L1Penalty() local weight = 1 local sizeAverage = false local m = nn.L1Penalty(weight, sizeAverage, false) local input = torch.rand(2,10):add(-0.5) input[1][1] = 0 local _ = m:forward(input) local grad = m:backward(input, torch.ones(input:size())) local err = input:clone():abs():sum()*weight - m.loss mytester:assertlt(math.abs(err), precision, 'error on fprop ') local true_grad = (input:gt(0):typeAs(grad) + input:lt(0):typeAs(grad):mul(-1)):mul(weight) mytester:assertlt((true_grad - grad):abs():max(), precision, 'error on bprop ') -- Note: We cannot use the Jacobian test for this Module since the backward -- gradient cannot be estimated using finite differences (ie, the loss -- during BPROP is not included in the FPROP output) end function nntest.DepthConcat() local outputSize = torch.IntTensor{5,6,7,8} local input = torch.randn(2,3,12,12) local gradOutput = torch.randn(2, outputSize:sum(), 12, 12) local concat = nn.DepthConcat(2) concat:add(nn.SpatialConvolutionMM(3, outputSize[1], 1, 1, 1, 1)) --> 2, 5, 12, 12 concat:add(nn.SpatialConvolutionMM(3, outputSize[2], 3, 3, 1, 1)) --> 2, 6, 10, 10 concat:add(nn.SpatialConvolutionMM(3, outputSize[3], 4, 4, 1, 1)) --> 2, 7, 9, 9 concat:add(nn.SpatialConvolutionMM(3, outputSize[4], 5, 5, 1, 1)) --> 2, 8, 8, 8 concat:zeroGradParameters() -- forward/backward local outputConcat = concat:forward(input) local gradInputConcat = concat:backward(input, gradOutput) -- the spatial dims are the largest, the nFilters is the sum local output = torch.Tensor(2, outputSize:sum(), 12, 12):zero() -- zero for padding local narrows = { {{},{1,5},{},{}}, {{},{6,11},{2,11},{2,11}}, {{},{12,18},{2,10},{2,10}}, {{},{19,26},{3,10},{3,10}} } local gradInput = input:clone():zero() for i=1,4 do local conv = concat:get(i) local gradWeight = conv.gradWeight:clone() conv:zeroGradParameters() output[narrows[i]]:copy(conv:forward(input)) gradInput:add(conv:backward(input, gradOutput[narrows[i]])) mytester:assertTensorEq(gradWeight, conv.gradWeight, 0.000001, "Error in SpatialConcat:accGradParameters for conv "..i) end mytester:assertTensorEq(output, outputConcat, 0.000001, "Error in SpatialConcat:updateOutput") mytester:assertTensorEq(gradInput, gradInputConcat, 0.000001, "Error in SpatialConcat:updateGradInput") end local function createMatrixInputSizes() local M = torch.random(10, 20) local N = torch.random(10, 20) local P = torch.random(10, 20) return M, N, P end function nntest.MM() local mm = nn.MM(false, true) local M, N, P = createMatrixInputSizes() local A = torch.randn(M, N) local B = torch.randn(P, N) -- Test forward pass. local output = mm:forward({A, B}) mytester:assertTableEq(output:size():totable(), {M, P}, 'Output has wrong dimensionality') mytester:assertTensorEq(output, A * B:t(), 1e-10, 'Wrong output') -- Test backward pass. local gradOutput = torch.randn(M, P) local gradInput = mm:backward({A, B}, gradOutput) mytester:assert(#gradInput == 2, 'gradInput must be table of size 2') local gradA, gradB = table.unpack(gradInput) mytester:assertTableEq(gradA:size():totable(), A:size():totable(), 'Gradient for input A has wrong size') mytester:assertTableEq(gradB:size():totable(), B:size():totable(), 'Gradient for input B has wrong size') mytester:assertTensorEq(gradA, gradOutput * B, 1e-10, 'Wrong gradient for input A') mytester:assertTensorEq(gradB, gradOutput:t() * A, 1e-10, 'Wrong gradient for input B') end function nntest.BatchMMNoTranspose() local mm = nn.MM() local M, N, P = createMatrixInputSizes() for bSize = 1, 11, 5 do local A = torch.randn(bSize, M, N) local B = torch.randn(bSize, N, P) -- Test forward pass. local output = mm:forward({A, B}) mytester:assertTableEq(output:size():totable(), {bSize, M, P}, 'Output has wrong dimensionality') for i = 1, bSize do mytester:assertTensorEq(output[i], A[i] * B[i], 1e-10, 'Output wrong for bSize = ' .. bSize .. ' and i = ' .. i) end -- Test backward pass. local gradOutput = torch.randn(bSize, M, P) local gradInput = mm:backward({A, B}, gradOutput) mytester:assert(#gradInput == 2, 'gradInput must be table of size 2') local gradA, gradB = table.unpack(gradInput) mytester:assertTableEq(gradA:size():totable(), A:size():totable(), 'Gradient for input A has wrong size') mytester:assertTableEq(gradB:size():totable(), B:size():totable(), 'Gradient for input B has wrong size') for i = 1, bSize do mytester:assertTensorEq(gradA[i], gradOutput[i] * B[i]:t(), 1e-10, 'Gradient for input A wrong for bSize = ' .. bSize .. ' and i = ' .. i) mytester:assertTensorEq(gradB[i], A[i]:t() * gradOutput[i], 1e-10, 'Gradient for input B wrong for bSize = ' .. bSize .. ' and i = ' .. i) end end end function nntest.BatchMMTransposeA() local mm = nn.MM(true, false) local M, N, P = createMatrixInputSizes() for bSize = 1, 11, 5 do local A = torch.randn(bSize, N, M) local B = torch.randn(bSize, N, P) -- Test forward pass. local output = mm:forward({A, B}) mytester:assertTableEq(output:size():totable(), {bSize, M, P}, 'Output has wrong dimensionality') for i = 1, bSize do mytester:assertTensorEq(output[i], A[i]:t() * B[i], 1e-10, 'Output wrong for bSize = ' .. bSize .. ' and i = ' .. i) end -- Test backward pass. local gradOutput = torch.randn(bSize, M, P) local gradInput = mm:backward({A, B}, gradOutput) mytester:assert(#gradInput == 2, 'gradInput must be table of size 2') local gradA, gradB = table.unpack(gradInput) mytester:assertTableEq(gradA:size():totable(), A:size():totable(), 'Gradient for input A has wrong size') mytester:assertTableEq(gradB:size():totable(), B:size():totable(), 'Gradient for input B has wrong size') for i = 1, bSize do mytester:assertTensorEq(gradA[i], B[i] * gradOutput[i]:t(), 1e-10, 'Gradient for input A wrong for bSize = ' .. bSize .. ' and i = ' .. i) mytester:assertTensorEq(gradB[i], A[i] * gradOutput[i], 1e-10, 'Gradient for input B wrong for bSize = ' .. bSize .. ' and i = ' .. i) end end end function nntest.BatchMMTransposeB() local mm = nn.MM(false, true) local M, N, P = createMatrixInputSizes() for bSize = 1, 11, 5 do local A = torch.randn(bSize, M, N) local B = torch.randn(bSize, P, N) -- Test forward pass. local output = mm:forward({A, B}) mytester:assertTableEq(output:size():totable(), {bSize, M, P}, 'Output has wrong dimensionality') for i = 1, bSize do mytester:assertTensorEq(output[i], A[i] * B[i]:t(), 1e-10, 'Output wrong for bSize = ' .. bSize .. ' and i = ' .. i) end -- Test backward pass. local gradOutput = torch.randn(bSize, M, P) local gradInput = mm:backward({A, B}, gradOutput) mytester:assert(#gradInput == 2, 'gradInput must be table of size 2') local gradA, gradB = table.unpack(gradInput) mytester:assertTableEq(gradA:size():totable(), A:size():totable(), 'Gradient for input A has wrong size') mytester:assertTableEq(gradB:size():totable(), B:size():totable(), 'Gradient for input B has wrong size') for i = 1, bSize do mytester:assertTensorEq(gradA[i], gradOutput[i] * B[i], 1e-10, 'Gradient for input A wrong for bSize = ' .. bSize .. ' and i = ' .. i) mytester:assertTensorEq(gradB[i], gradOutput[i]:t() * A[i], 1e-10, 'Gradient for input B wrong for bSize = ' .. bSize .. ' and i = ' .. i) end end end function nntest.BatchMMTransposeBoth() local mm = nn.MM(true, true) local M, N, P = createMatrixInputSizes() for bSize = 1, 11, 5 do local A = torch.randn(bSize, N, M) local B = torch.randn(bSize, P, N) -- Test forward pass. local output = mm:forward({A, B}) mytester:assertTableEq(output:size():totable(), {bSize, M, P}, 'Output has wrong dimensionality') for i = 1, bSize do mytester:assertTensorEq(output[i], A[i]:t() * B[i]:t(), 1e-10, 'Output wrong for bSize = ' .. bSize .. ' and i = ' .. i) end -- Test backward pass. local gradOutput = torch.randn(bSize, M, P) local gradInput = mm:backward({A, B}, gradOutput) mytester:assert(#gradInput == 2, 'gradInput must be table of size 2') local gradA, gradB = table.unpack(gradInput) mytester:assertTableEq(gradA:size():totable(), A:size():totable(), 'Gradient for input A has wrong size') mytester:assertTableEq(gradB:size():totable(), B:size():totable(), 'Gradient for input B has wrong size') for i = 1, bSize do mytester:assertTensorEq(gradA[i], B[i]:t() * gradOutput[i]:t(), 1e-10, 'Gradient for input A wrong for bSize = ' .. bSize .. ' and i = ' .. i) mytester:assertTensorEq(gradB[i], gradOutput[i]:t() * A[i]:t(), 1e-10, 'Gradient for input B wrong for bSize = ' .. bSize .. ' and i = ' .. i) end end end function nntest.CosineDistance() local indim = math.random(1,10) local input = {torch.rand(indim),torch.rand(indim)} -- check forward against previous implementation local module = nn.CosineDistance() local w1 = input[1]:dot(input[2]) local w2 = math.sqrt(input[1]:dot(input[1])) local w3 = math.sqrt(input[2]:dot(input[2])) local output_old = w1/w2/w3 local output = module:forward(input) mytester:assertlt(math.abs(output_old-output[1]),precision,'error on forward ') -- check gradients -- Note: testJacobian doesn't support table inputs, and rather than re-write -- it so that it does, I'll just use a split table module on the input. -- I assume both SplitTable and Sequential do not have bugs, otherwise this -- test will break. local input = torch.rand(2,indim) local module = nn.Sequential() module:add(nn.SplitTable(1)) module:add(nn.CosineDistance()) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') -- IO local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- batch -- rebuild module to avoid correlated tests local module = nn.Sequential() module:add(nn.SplitTable(1)) module:add(nn.CosineDistance()) local nframes = math.random(1,10) local indim = math.random(1,10) local input = torch.rand(2,nframes,indim) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'batch error on state ') end function nntest.CosineEmbeddingCriterion() local v1 = torch.Tensor{1, 0} local v2 = torch.Tensor{0.5, math.sqrt(3)*0.5} local crit = nn.CosineEmbeddingCriterion(0.6) local output = crit:forward({v1, v2}, -1) -- must be called before backward local grads = crit:backward({v1, v2}, -1) local zero = torch.Tensor(2):zero() equal(grads[1], zero, 'gradient should be zero') equal(grads[2], zero, 'gradient should be zero') end function nntest.HingeEmbeddingCriterion() local x = torch.Tensor{0.3,2.1,1.8,0} local y = torch.Tensor{1,-1,-1,1} local expgrads = torch.Tensor{1,0,-1,1} / 4 local crit = nn.HingeEmbeddingCriterion(2) local output = crit:forward(x, y) -- must be called before backward local grads = crit:backward(x, y) mytester:assert(math.abs(output - (0.3 + 0.2) / 4) < 1e-10) equal(grads, expgrads) end function nntest.Replicate() local vector = torch.rand(3) local r1 = nn.Replicate(2, 1) local r2 = nn.Replicate(2, 2) local vOutput1 = r1:forward(vector):clone() local vOutput2 = r2:forward(vector):clone() local expected1 = torch.zeros(2, 3) local expected2 = torch.zeros(3, 2) expected1:select(1, 1):copy(vector) expected1:select(1, 2):copy(vector) expected2:select(2, 1):copy(vector) expected2:select(2, 2):copy(vector) mytester:assertTensorEq(vOutput1, expected1, precision, 'Wrong tiling of data when replicating vector.') mytester:assertTensorEq(vOutput2, expected2, precision, 'Wrong tiling of data when replicating vector.') -- batch mode local vector = torch.rand(4,3) local r1 = nn.Replicate(2, 1, 1) local r2 = nn.Replicate(2, 2, 1) local vOutput1 = r1:forward(vector):clone() local vOutput2 = r2:forward(vector):clone() local expected1 = torch.zeros(4, 2, 3) local expected2 = torch.zeros(4, 3, 2) expected1:select(2, 1):copy(vector) expected1:select(2, 2):copy(vector) expected2:select(3, 1):copy(vector) expected2:select(3, 2):copy(vector) mytester:assertTensorEq(vOutput1, expected1, precision, 'Wrong tiling of data when replicating batch vector.') mytester:assertTensorEq(vOutput2, expected2, precision, 'Wrong tiling of data when replicating batch vector.') end function nntest.BatchNormalization() local nframes = torch.random(50,70) local indim = torch.random(1,10) local input = torch.zeros(nframes, indim):uniform() local module = nn.BatchNormalization(indim) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err,precision, 'error on bias [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end -- IO local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- batch norm without affine transform module = nn.BatchNormalization(indim, 1e-5, 0.1, false) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') -- IO local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.SpatialBatchNormalization() local nframes = torch.random(1,10) local indim = torch.random(1,4) local ini = torch.random(1,5) local inj = torch.random(1,5) local input = torch.zeros(nframes, indim, ini, inj):uniform() local module = nn.SpatialBatchNormalization(indim) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias) mytester:assertlt(err,precision, 'error on weight ') local err = jac.testJacobianUpdateParameters(module, input, module.weight) mytester:assertlt(err,precision, 'error on weight [direct update] ') local err = jac.testJacobianUpdateParameters(module, input, module.bias) mytester:assertlt(err,precision, 'error on bias [direct update] ') for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do mytester:assertlt(err, precision, string.format( 'error on weight [%s]', t)) end for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do mytester:assertlt(err, precision, string.format( 'error on bias [%s]', t)) end -- IO local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') -- batch norm without affine transform module = nn.SpatialBatchNormalization(indim, 1e-5, 0.1, false) local err = jac.testJacobian(module,input) mytester:assertlt(err,precision, 'error on state ') -- IO local ferr,berr = jac.testIO(module,input) mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ') mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ') end function nntest.Padding() local fanin = math.random(1,3) local sizex = math.random(4,16) local sizey = math.random(4,16) local pad = math.random(-3,3) local val = torch.randn(1):squeeze() local module = nn.Padding(1, pad, 3, val) local input = torch.rand(fanin,sizey,sizex) local size = input:size():totable() size[1] = size[1] + math.abs(pad) local output = module:forward(input) mytester:assertTableEq(size, output:size():totable(), 0.00001, "Padding size error") local gradInput = module:backward(input, output) mytester:assertTensorEq(gradInput, input, 0.00001, "Padding backward error") end function nntest.addSingletonDimension() local dims = torch.random(5) local size = torch.LongTensor(dims):random(10) local perm = torch.randperm(dims):totable() local tensor = torch.Tensor(unpack(size:totable())):uniform():permute(unpack(perm)) size = torch.gather(size, 1, torch.LongTensor(perm)) local firstDim = nn.utils.addSingletonDimension(tensor) mytester:assertTableEq(firstDim:size():totable(), {1, unpack(size:totable())}, "wrong size for singleton dimension 1") mytester:assertTensorEq(firstDim[1], tensor, 0, "wrong content for singleton dimension 1") local dim = torch.random(dims + 1) local result = nn.utils.addSingletonDimension(tensor, dim) local resultSize = size:totable() table.insert(resultSize, dim, 1) mytester:assertTableEq(result:size():totable(), resultSize, "wrong size for random singleton dimension") mytester:assertTensorEq(result:select(dim, 1), tensor, 0, "wrong content for random singleton dimension") mytester:assertError(function() nn.utils.addSingletonDimension(tensor, dims + 2) end, "invalid dimension not detected") end mytester:add(nntest) if not nn then require 'nn' jac = nn.Jacobian sjac = nn.SparseJacobian mytester:run() else jac = nn.Jacobian sjac = nn.SparseJacobian function nn.test(tests) -- randomize stuff math.randomseed(os.time()) mytester:run(tests) return mytester end end
bsd-3-clause
nuintun/payday2
extras/mods/npc-weapons-customization/Weapons/scar_npc.lua
1
9445
log("scar_npc loaded") Hooks:Add("LocalizationManagerPostInit", "NPCWeap_scar_Localization", function(loc) LocalizationManager:add_localized_strings({ ["random"] = "Random", ["scar_none"] = "None", --Barrels ["scar_g_barrel_short"] = "Short", ["scar_g_barrel_medium"] = "Medium", ["scar_g_barrel_long"] = "Long", --Barrel Extensions ["scar_g_ns_firepig"] = "Firepig", ["scar_g_ns_jprifles"] = "JP Rifles", ["scar_g_ns_linear"] = "Linear", ["scar_g_ns_medium"] = "Medium", ["scar_g_ns_silencer_large"] = "Silencer", ["scar_g_ns_small"] = "Small", ["scar_g_ns_stubby"] = "Stubby Bastard", ["scar_g_ns_surefire"] = "Sure, fire!", ["scar_g_ns_tank"] = "Tank", ["scar_g_ns_pbs1"] = "PBS1", ["scar_g_ns_flashhider"] = "Flashhider", --Body -- No modifications availiable. --Foregrips ["scar_g_fg_ext"] = "Extended", --Grips ["scar_g_grip_m4"] = "M4 Grip", ["scar_g_grip_ergo"] = "Ergo", ["scar_g_grip_hgrip"] = "H-Grip", ["scar_g_grip_mgrip"] = "M-Grip", --Vertical Grips ["scar_g_vg_afg"] = "AFG", --Magazines -- No modifications availiable --Optics ["scar_g_optics_aimpoint"] = "Aimpoint", ["scar_g_optics_docter"] = "Docter", ["scar_g_optics_eotech"] = "EOtech", ["scar_g_optics_flipup"] = "Flipup", ["scar_g_optics_specter"] = "Specter", ["scar_g_optics_t1micro"] = "t1micro", ["scar_g_optics_cmore"] = "cmore", ["scar_g_optics_aimpoint_preorder"] = "Aimpoint preorder", ["scar_g_optics_eotech_xps"] = "EOtech Gage Courier", ["scar_g_optics_reflex"] = "Reflex", ["scar_g_optics_rx01"] = "RX01", ["scar_g_optics_rx30"] = "RX30", ["scar_optics_cs"] = "Aimpoint CS", ["scar_g_optics_acog"] = "Acog Sight", ["scar_g_optics_acog"] = "Acog Sight", --Stocks ["scar_g_stock_std"] = "Standard", ["scar_g_stock_sniper"] = "Sniper", --Attachments ["scar_g_attachment_peqbox"] = "Laser Module", ["scar_g_attachment_surefire"] = "Flashlight", ["scar_g_attachment_laser"] = "Laser Module 2", ["scar_g_attachment_peq"] = "PEQ15", }) end) NPCWeap.weapons.scar_npc = NPCWeap.weapons.scar_npc or {} NPCWeap.weapons.scar_npc.required_reset = NPCWeap.weapons.scar_npc.required_reset or {} NPCWeap.weapons.scar_npc.name_id = "scar_npc" NPCWeap.weapons.scar_npc.display_name = "Murkywater Scar" NPCWeap.weapons.scar_npc.unit = "units/payday2/weapons/wpn_npc_scar_murkywater/wpn_npc_scar_murkywater" NPCWeap.weapons.scar_npc.object_sub = 6 NPCWeap.loaded_options.scar_npc = NPCWeap.loaded_options.scar_npc or {} NPCWeap.weapons.scar_npc.objects_init = { "g_barrel_medium", "g_ns_flashhider", "g_body_upper", "g_body_lower", "g_body_cover", "g_body_bolt", "g_fg_ext", "g_grip_m4", "g_mag", "g_optics_flipup", "g_optics_flipup_up", "g_stock_sniper", "g_attachment_surefire" } NPCWeap.weapons.scar_npc.categories = { "barrel", "barrel_ext", "sight", "stock", "foregrip", "grip", "attachment", "vertical_grip", } NPCWeap.weapons.scar_npc.barrel = { [1] = "scar_g_barrel_short", [2] = "scar_g_barrel_medium", [3] = "scar_g_barrel_long", [4] = "random", } NPCWeap.loaded_options.scar_npc.barrel = NPCWeap.loaded_options.scar_npc.barrel or 1 NPCWeap.weapons.scar_npc.required_reset.barrel = {} NPCWeap.weapons.scar_npc.barrel_fire_offset = Vector3(0, -10.04417, 0) NPCWeap.weapons.scar_npc.g_barrel_short = {} NPCWeap.weapons.scar_npc.g_barrel_short.barrel_ext = Vector3(0, -3.8448, 0) --[0 12.91083 -0.007203754] NPCWeap.weapons.scar_npc.g_barrel_medium = {} NPCWeap.weapons.scar_npc.g_barrel_medium.barrel_ext = Vector3(0, 0, 0) --[0 16.75563 -0.007203754] NPCWeap.weapons.scar_npc.g_barrel_long = {} NPCWeap.weapons.scar_npc.g_barrel_long.barrel_ext = Vector3(0, 8.21512, 0) --[0 24.97075 -0.007203754] NPCWeap.weapons.scar_npc.barrel_ext = { [1] = "scar_none", [2] = "scar_g_ns_firepig", [3] = "scar_g_ns_jprifles", [4] = "scar_g_ns_linear", [5] = "scar_g_ns_medium", [6] = "scar_g_ns_silencer_large", [7] = "scar_g_ns_small", [8] = "scar_g_ns_stubby", [9] = "scar_g_ns_surefire", [10] = "scar_g_ns_tank", [11] = "scar_g_ns_pbs1", [12] = "scar_g_ns_flashhider", [13] = "random", } NPCWeap.loaded_options.scar_npc.barrel_ext = NPCWeap.loaded_options.scar_npc.barrel_ext or 1 NPCWeap.weapons.scar_npc.required_reset.barrel_ext = {} NPCWeap.weapons.scar_npc.g_ns_firepig = {} NPCWeap.weapons.scar_npc.g_ns_firepig.length = Vector3(0, 8.11474, 0) NPCWeap.weapons.scar_npc.g_ns_jprifles = {} NPCWeap.weapons.scar_npc.g_ns_jprifles.length = Vector3(0, 8.0442, 0) NPCWeap.weapons.scar_npc.g_ns_linear = {} NPCWeap.weapons.scar_npc.g_ns_linear.length = Vector3(0, 8.0442, 0) NPCWeap.weapons.scar_npc.g_ns_medium = {} NPCWeap.weapons.scar_npc.g_ns_medium.length = Vector3(0, 19.41887, 0) NPCWeap.weapons.scar_npc.g_ns_silencer_large = {} NPCWeap.weapons.scar_npc.g_ns_silencer_large.length = Vector3(0, 24.89792, 0) NPCWeap.weapons.scar_npc.g_ns_small = {} NPCWeap.weapons.scar_npc.g_ns_small.length = Vector3(0, 15.31046, 0) NPCWeap.weapons.scar_npc.g_ns_stubby = {} NPCWeap.weapons.scar_npc.g_ns_stubby.length = Vector3(0, 7.90433, 0) NPCWeap.weapons.scar_npc.g_ns_surefire = {} NPCWeap.weapons.scar_npc.g_ns_surefire.length = Vector3(0, 7.95938, 0) NPCWeap.weapons.scar_npc.g_ns_tank = {} NPCWeap.weapons.scar_npc.g_ns_tank.length = Vector3(0, 7.11834, 0) NPCWeap.weapons.scar_npc.g_ns_pbs1 = {} NPCWeap.weapons.scar_npc.g_ns_pbs1.length = Vector3(0, 23.5928, 0) NPCWeap.weapons.scar_npc.g_ns_flashhider = {} NPCWeap.weapons.scar_npc.g_ns_flashhider.length = Vector3(0, 10.04417, 0) NPCWeap.weapons.scar_npc.sight = { [1] = "scar_none", [2] = "scar_g_optics_flipup", [3] = "scar_g_optics_aimpoint", [4] = "scar_g_optics_docter", [5] = "scar_g_optics_eotech", [6] = "scar_g_optics_specter", [7] = "scar_g_optics_t1micro", [8] = "scar_g_optics_cmore", [9] = "scar_g_optics_aimpoint_preorder", [10] = "scar_g_optics_eotech_xps", [11] = "scar_g_optics_reflex", [12] = "scar_g_optics_rx01", [13] = "scar_g_optics_rx30", [14] = "scar_g_optics_cs", [15] = "scar_g_optics_acog", [16] = "random" } NPCWeap.loaded_options.scar_npc.sight = NPCWeap.loaded_options.scar_npc.sight or 1 NPCWeap.weapons.scar_npc.required_reset.sight = { "g_optics_eotech_gfx_lens", "g_optics_acog_lens", "g_optics_aimpoint_glass", "g_optics_docter_lens", "g_optics_specter_glass", "g_optics_t1micro_glass", "g_optics_cmore_lens", "g_optics_aimpoint_preorder_glass", "g_optics_eotech_xps_lens", "g_optics_reflex_lens", "g_optics_rx01_lens", "g_optics_rx30_lens", "g_optics_cs_lens", "g_optics_flipup_up", "g_optics_flipup_down", } NPCWeap.weapons.scar_npc.stock = { [1] = "scar_g_stock_std", [2] = "scar_g_stock_sniper", [3] = "random", } NPCWeap.loaded_options.scar_npc.stock = NPCWeap.loaded_options.scar_npc.stock or 1 NPCWeap.weapons.scar_npc.required_reset.stock = {} NPCWeap.weapons.scar_npc.foregrip = { [1] = "scar_none", [2] = "scar_g_fg_ext", [3] = "random", } NPCWeap.loaded_options.scar_npc.foregrip = NPCWeap.loaded_options.scar_npc.foregrip or 1 NPCWeap.weapons.scar_npc.required_reset.foregrip = {} NPCWeap.weapons.scar_npc.grip = { [1] = "scar_g_grip_m4", [2] = "scar_g_grip_ergo", [3] = "scar_g_grip_hgrip", [4] = "scar_g_grip_mgrip", [5] = "random", } NPCWeap.loaded_options.scar_npc.grip = NPCWeap.loaded_options.scar_npc.grip or 1 NPCWeap.weapons.scar_npc.required_reset.grip = {} NPCWeap.weapons.scar_npc.attachment = { [1] = "scar_none", [2] = "scar_g_attachment_peqbox", [3] = "scar_g_attachment_surefire", [4] = "scar_g_attachment_laser", [5] = "scar_g_attachment_peq", [6] = "random", } NPCWeap.loaded_options.scar_npc.attachment = NPCWeap.loaded_options.scar_npc.attachment or 1 NPCWeap.weapons.scar_npc.required_reset.attachment = {} NPCWeap.weapons.scar_npc.vertical_grip = { [1] = "scar_none", [2] = "scar_g_vg_afg", [3] = "random", } NPCWeap.loaded_options.scar_npc.vertical_grip = NPCWeap.loaded_options.scar_npc.vertical_grip or 1 NPCWeap.weapons.scar_npc.required_reset.vertical_grip = {} NPCWeap.weapons.scar_npc.required = { ["g_optics_eotech"] = { "g_optics_eotech_gfx_lens", "g_optics_flipup_down" }, ["g_optics_acog"] = { "g_optics_acog_lens", "g_optics_flipup_down" }, ["g_optics_aimpoint"] = { "g_optics_aimpoint_glass", "g_optics_flipup_down" }, ["g_optics_docter"] = { "g_optics_docter_lens", "g_optics_flipup_down" }, ["g_optics_specter"] = { "g_optics_specter_glass", "g_optics_flipup_down" }, ["g_optics_t1micro"] = { "g_optics_t1micro_glass", "g_optics_flipup_down" }, ["g_optics_cmore"] = { "g_optics_cmore_lens", "g_optics_flipup_down" }, ["g_optics_aimpoint_preorder"] = { "g_optics_aimpoint_preorder_glass", "g_optics_flipup_down" }, ["g_optics_eotech_xps"] = { "g_optics_eotech_xps_lens", "g_optics_flipup_down" }, ["g_optics_reflex"] = { "g_optics_reflex_lens", "g_optics_flipup_down" }, ["g_optics_rx01"] = { "g_optics_rx01_lens", "g_optics_flipup_down" }, ["g_optics_rx30"] = { "g_optics_rx30_lens", "g_optics_flipup_down" }, ["g_optics_cs"] = { "g_optics_cs_lens", "g_optics_flipup_down" }, ["g_optics_flipup"] = { "g_optics_flipup_up" }, } NPCWeap.weapons.scar_npc.absolute_reset_on_update = {} NPCWeap.weapons.scar_npc.incompatible = {} NPCWeap.weapons.scar_npc.pos_check = { ["barrel_ext"] = { "barrel" } }
mit
wcjscm/JackGame
src/cocos/cocos2d/DrawPrimitives.lua
98
12024
local dp_initialized = false local dp_shader = nil local dp_colorLocation = -1 local dp_color = { 1.0, 1.0, 1.0, 1.0 } local dp_pointSizeLocation = -1 local dp_pointSize = 1.0 local SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor" local targetPlatform = cc.Application:getInstance():getTargetPlatform() local function lazy_init() if not dp_initialized then dp_shader = cc.ShaderCache:getInstance():getProgram(SHADER_NAME_POSITION_U_COLOR) --dp_shader:retain() if nil ~= dp_shader then dp_colorLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_color") dp_pointSizeLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_pointSize") dp_Initialized = true end end if nil == dp_shader then print("Error:dp_shader is nil!") return false end return true end local function setDrawProperty() gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION ) dp_shader:use() dp_shader:setUniformsForBuiltins() dp_shader:setUniformLocationWith4fv(dp_colorLocation, dp_color, 1) end function ccDrawInit() lazy_init() end function ccDrawFree() dp_initialized = false end function ccDrawColor4f(r,g,b,a) dp_color[1] = r dp_color[2] = g dp_color[3] = b dp_color[4] = a end function ccPointSize(pointSize) dp_pointSize = pointSize * cc.Director:getInstance():getContentScaleFactor() end function ccDrawColor4B(r,g,b,a) dp_color[1] = r / 255.0 dp_color[2] = g / 255.0 dp_color[3] = b / 255.0 dp_color[4] = a / 255.0 end function ccDrawPoint(point) if not lazy_init() then return end local vertexBuffer = { } local function initBuffer() vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) local vertices = { point.x,point.y} gl.bufferData(gl.ARRAY_BUFFER,2,vertices,gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize) gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.POINTS,0,1) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawPoints(points,numOfPoint) if not lazy_init() then return end local vertexBuffer = {} local i = 1 local function initBuffer() vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) local vertices = {} for i = 1, numOfPoint do vertices[2 * i - 1] = points[i].x vertices[2 * i] = points[i].y end gl.bufferData(gl.ARRAY_BUFFER, numOfPoint * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize) gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.POINTS,0,numOfPoint) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawLine(origin,destination) if not lazy_init() then return end local vertexBuffer = {} local function initBuffer() vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) local vertices = { origin.x, origin.y, destination.x, destination.y} gl.bufferData(gl.ARRAY_BUFFER,4,vertices,gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.LINES ,0,2) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawPoly(points,numOfPoints,closePolygon) if not lazy_init() then return end local vertexBuffer = {} local i = 1 local function initBuffer() vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) local vertices = {} for i = 1, numOfPoints do vertices[2 * i - 1] = points[i].x vertices[2 * i] = points[i].y end gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) if closePolygon then gl.drawArrays(gl.LINE_LOOP , 0, numOfPoints) else gl.drawArrays(gl.LINE_STRIP, 0, numOfPoints) end gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawSolidPoly(points,numOfPoints,color) if not lazy_init() then return end local vertexBuffer = {} local i = 1 local function initBuffer() vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) local vertices = {} for i = 1, numOfPoints do vertices[2 * i - 1] = points[i].x vertices[2 * i] = points[i].y end gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION ) dp_shader:use() dp_shader:setUniformsForBuiltins() dp_shader:setUniformLocationWith4fv(dp_colorLocation, color, 1) gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.TRIANGLE_FAN , 0, numOfPoints) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawRect(origin,destination) ccDrawLine(CCPoint:__call(origin.x, origin.y), CCPoint:__call(destination.x, origin.y)) ccDrawLine(CCPoint:__call(destination.x, origin.y), CCPoint:__call(destination.x, destination.y)) ccDrawLine(CCPoint:__call(destination.x, destination.y), CCPoint:__call(origin.x, destination.y)) ccDrawLine(CCPoint:__call(origin.x, destination.y), CCPoint:__call(origin.x, origin.y)) end function ccDrawSolidRect( origin,destination,color ) local vertices = { origin, CCPoint:__call(destination.x, origin.y) , destination, CCPoint:__call(origin.x, destination.y) } ccDrawSolidPoly(vertices,4,color) end function ccDrawCircleScale( center, radius, angle, segments,drawLineToCenter,scaleX,scaleY) if not lazy_init() then return end local additionalSegment = 1 if drawLineToCenter then additionalSegment = additionalSegment + 1 end local vertexBuffer = { } local function initBuffer() local coef = 2.0 * math.pi / segments local i = 1 local vertices = {} vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) for i = 1, segments + 1 do local rads = (i - 1) * coef local j = radius * math.cos(rads + angle) * scaleX + center.x local k = radius * math.sin(rads + angle) * scaleY + center.y vertices[i * 2 - 1] = j vertices[i * 2] = k end vertices[(segments + 2) * 2 - 1] = center.x vertices[(segments + 2) * 2] = center.y gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.LINE_STRIP , 0, segments + additionalSegment) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawCircle(center, radius, angle, segments, drawLineToCenter) ccDrawCircleScale(center, radius, angle, segments, drawLineToCenter, 1.0, 1.0) end function ccDrawSolidCircle(center, radius, angle, segments,scaleX,scaleY) if not lazy_init() then return end local vertexBuffer = { } local function initBuffer() local coef = 2.0 * math.pi / segments local i = 1 local vertices = {} vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) for i = 1, segments + 1 do local rads = (i - 1) * coef local j = radius * math.cos(rads + angle) * scaleX + center.x local k = radius * math.sin(rads + angle) * scaleY + center.y vertices[i * 2 - 1] = j vertices[i * 2] = k end vertices[(segments + 2) * 2 - 1] = center.x vertices[(segments + 2) * 2] = center.y gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.TRIANGLE_FAN , 0, segments + 1) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawQuadBezier(origin, control, destination, segments) if not lazy_init() then return end local vertexBuffer = { } local function initBuffer() local vertices = { } local i = 1 local t = 0.0 for i = 1, segments do vertices[2 * i - 1] = math.pow(1 - t,2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x vertices[2 * i] = math.pow(1 - t,2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y t = t + 1.0 / segments end vertices[2 * (segments + 1) - 1] = destination.x vertices[2 * (segments + 1)] = destination.y vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.LINE_STRIP , 0, segments + 1) gl.bindBuffer(gl.ARRAY_BUFFER,0) end function ccDrawCubicBezier(origin, control1, control2, destination, segments) if not lazy_init then return end local vertexBuffer = { } local function initBuffer() local vertices = { } local t = 0 local i = 1 for i = 1, segments do vertices[2 * i - 1] = math.pow(1 - t,3) * origin.x + 3.0 * math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x vertices[2 * i] = math.pow(1 - t,3) * origin.y + 3.0 * math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y t = t + 1.0 / segments end vertices[2 * (segments + 1) - 1] = destination.x vertices[2 * (segments + 1)] = destination.y vertexBuffer.buffer_id = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id) gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW) gl.bindBuffer(gl.ARRAY_BUFFER, 0) end initBuffer() setDrawProperty() gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id) gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.LINE_STRIP , 0, segments + 1) gl.bindBuffer(gl.ARRAY_BUFFER,0) end
gpl-3.0
OpenRA/OpenRA
mods/d2k/maps/harkonnen-01b/harkonnen01b.lua
14
5015
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] AtreidesReinforcements = { easy = { { "light_inf", "light_inf" } }, normal = { { "light_inf", "light_inf" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" } }, hard = { { "light_inf", "light_inf" }, { "trike", "trike" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" }, { "trike", "trike" } } } AtreidesEntryWaypoints = { AtreidesWaypoint1.Location, AtreidesWaypoint2.Location, AtreidesWaypoint3.Location, AtreidesWaypoint4.Location } AtreidesAttackDelay = DateTime.Seconds(30) AtreidesAttackWaves = { easy = 1, normal = 5, hard = 12 } ToHarvest = { easy = 2500, normal = 3000, hard = 3500 } HarkonnenReinforcements = { "light_inf", "light_inf", "light_inf", "trike" } HarkonnenEntryPath = { HarkonnenWaypoint.Location, HarkonnenRally.Location } Messages = { "Build a concrete foundation before placing your buildings.", "Build a Wind Trap for power.", "Build a Refinery to collect Spice.", "Build a Silo to store additional Spice." } Tick = function() if AtreidesArrived and atreides.HasNoRequiredUnits() then player.MarkCompletedObjective(KillAtreides) end if player.Resources > SpiceToHarvest - 1 then player.MarkCompletedObjective(GatherSpice) end -- player has no Wind Trap if (player.PowerProvided <= 20 or player.PowerState ~= "Normal") and DateTime.GameTime % DateTime.Seconds(32) == 0 then HasPower = false Media.DisplayMessage(Messages[2], "Mentat") else HasPower = true end -- player has no Refinery and no Silos if HasPower and player.ResourceCapacity == 0 and DateTime.GameTime % DateTime.Seconds(32) == 0 then Media.DisplayMessage(Messages[3], "Mentat") end if HasPower and player.Resources > player.ResourceCapacity * 0.8 and DateTime.GameTime % DateTime.Seconds(32) == 0 then Media.DisplayMessage(Messages[4], "Mentat") end UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. SpiceToHarvest, player.Color) end WorldLoaded = function() player = Player.GetPlayer("Harkonnen") atreides = Player.GetPlayer("Atreides") SpiceToHarvest = ToHarvest[Difficulty] InitObjectives(player) KillHarkonnen = atreides.AddPrimaryObjective("Kill all Harkonnen units.") GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(SpiceToHarvest) .. " Solaris worth of Spice.") KillAtreides = player.AddSecondaryObjective("Eliminate all Atreides units and reinforcements\nin the area.") local checkResourceCapacity = function() Trigger.AfterDelay(0, function() if player.ResourceCapacity < SpiceToHarvest then Media.DisplayMessage("We don't have enough silo space to store the required amount of Spice!", "Mentat") Trigger.AfterDelay(DateTime.Seconds(3), function() harkonnen.MarkCompletedObjective(KillAtreides) end) return true end end) end Trigger.OnRemovedFromWorld(HarkonnenConyard, function() -- Mission already failed, no need to check the other conditions as well if checkResourceCapacity() then return end local refs = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "refinery" and actor.Owner == player end) if #refs == 0 then atreides.MarkCompletedObjective(KillHarkonnen) else Trigger.OnAllRemovedFromWorld(refs, function() atreides.MarkCompletedObjective(KillHarkonnen) end) local silos = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "silo" and actor.Owner == player end) Utils.Do(refs, function(actor) Trigger.OnRemovedFromWorld(actor, checkResourceCapacity) end) Utils.Do(silos, function(actor) Trigger.OnRemovedFromWorld(actor, checkResourceCapacity) end) end end) Media.DisplayMessage(Messages[1], "Mentat") Trigger.AfterDelay(DateTime.Seconds(25), function() Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.Reinforce(player, HarkonnenReinforcements, HarkonnenEntryPath) end) WavesLeft = AtreidesAttackWaves[Difficulty] SendReinforcements() end SendReinforcements = function() local units = AtreidesReinforcements[Difficulty] local delay = Utils.RandomInteger(AtreidesAttackDelay - DateTime.Seconds(2), AtreidesAttackDelay) AtreidesAttackDelay = AtreidesAttackDelay - (#units * 3 - 3 - WavesLeft) * DateTime.Seconds(1) if AtreidesAttackDelay < 0 then AtreidesAttackDelay = 0 end Trigger.AfterDelay(delay, function() Reinforcements.Reinforce(atreides, Utils.Random(units), { Utils.Random(AtreidesEntryWaypoints) }, 10, IdleHunt) WavesLeft = WavesLeft - 1 if WavesLeft == 0 then Trigger.AfterDelay(DateTime.Seconds(1), function() AtreidesArrived = true end) else SendReinforcements() end end) end
gpl-3.0
dmccuskey/dmc-gestures
examples/gesture-pinch-basic/dmc_corona/dmc_gestures/core/gesture.lua
10
14803
--====================================================================-- -- dmc_corona/dmc_gesture/core/gesture.lua -- -- Documentation: --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2015 David McCuskey 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. --]] --====================================================================-- --== DMC Corona Library : Gesture Base --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== DMC Gesture --====================================================================-- --====================================================================-- --== Imports local Objects = require 'dmc_objects' local Patch = require 'dmc_patch' local StatesMixModule = require 'dmc_states_mix' local Constants = require 'dmc_gestures.gesture_constants' --====================================================================-- --== Setup, Constants Patch.addPatch( 'print-output' ) local newClass = Objects.newClass local ObjectBase = Objects.ObjectBase local StatesMix = StatesMixModule.StatesMix local sfmt = string.format local tcancel = timer.cancel local tdelay = timer.performWithDelay local tstr = tostring --====================================================================-- --== Gesture Base Class --====================================================================-- --- Gesture Recognizer Base Class. -- Base class for all Gesture Recognizers. -- -- **Inherits from:** -- -- * DMC.ObjectBase -- * DMC.StatesMix -- -- @classmod Gesture.Gesture local Gesture = newClass( { ObjectBase, StatesMix }, { name="Gesture Base Class" } ) --== Class Constants Gesture.TYPE = nil -- override this --== State Constants Gesture.STATE_CREATE = 'state_create' Gesture.STATE_POSSIBLE = 'state_possible' Gesture.STATE_FAILED = 'state_failed' Gesture.STATE_RECOGNIZED = 'state_recognized' --== Event Constants --- EVENT Name Gesture.EVENT = 'gesture-event' --- GESTURE Event Gesture.GESTURE = 'recognized-gesture-event' --- STATE Event Gesture.STATE = 'state-changed-event' --======================================================-- -- Start: Setup DMC Objects function Gesture:__init__( params ) -- print( "Gesture:__init__", params ) params = params or {} self:superCall( StatesMix, '__init__', params ) self:superCall( ObjectBase, '__init__', params ) --==-- --== Sanity Check ==-- if self.is_class then return end assert( params.view ) -- save params for later self._gr_params = params --== Create Properties ==-- self._delegate = nil self._id = nil self._view = params.view -- internal properties self._fail_timer=nil self._gesture_attempt=false self._gesture_timer=nil self._multitouch_evt = nil self._multitouch_queue = {} self._touch_count = 0 self._total_touch_count = 0 self._touches = {} -- keyed on ID --== Objects ==-- self._gesture_mgr = nil self:setState( Gesture.STATE_CREATE ) end function Gesture:__undoInit__() -- print( "Gesture:__undoInit__" ) --==-- self:superCall( ObjectBase, '__undoInit__' ) self:superCall( StatesMix, '__undoInit__' ) end function Gesture:__initComplete__() -- print( "Gesture:__initComplete__" ) self:superCall( ObjectBase, '__initComplete__' ) --==-- local tmp = self._gr_params --== Use Setters self.id = tmp.id self.delegate = tmp.delegate self.gesture_mgr = tmp.gesture_mgr self._gr_params = nil self:gotoState( Gesture.STATE_POSSIBLE ) end function Gesture:__undoInitComplete__() -- print( "Gesture:__undoInitComplete__" ) self:_stopAllTimers() self._gesture_mgr:removeGesture( self ) --==-- self:superCall( ObjectBase, '__undoInitComplete__' ) end -- END: Setup DMC Objects --======================================================-- --====================================================================-- --== Public Methods --======================================================-- -- Getters/Setters --- Getters and Setters -- @section getters-setters --== .id --- the id (string). -- this is useful to differentiate between -- different gestures attached to the same view object -- -- @function .id -- @usage print( gesture.id ) -- @usage gesture.id = "myid" function Gesture.__getters:id() return self._id end function Gesture.__setters:id( value ) assert( value==nil or type(value)=='string' ) self._id = value end --== .delegate --- a gesture delegate (object/table) -- -- @function .delegate -- @usage print( gesture.delegate ) -- @usage gesture.delegate = { shouldRecognizeWith=<func> } function Gesture.__getters:delegate() return self._delegate end function Gesture.__setters:delegate( value ) assert( value==nil or type(value)=='table' ) self._delegate = value end function Gesture.__getters:gesture_mgr() return self._gesture_mgr end function Gesture.__setters:gesture_mgr( value ) self._gesture_mgr = value end --== .view --- the target view (Display Object). -- -- @function .view -- @usage print( gesture.view ) -- @usage gesture.view = DisplayObject function Gesture.__getters:view() return self._view end -- function Gesture.__setters:view( value ) -- self._view = value -- end -- @TODO function Gesture:cancelsTouchesInView() -- print( "Gesture:cancelsTouchesInView" ) end -- @TODO function Gesture:delaysTouchesBegan() -- print( "Gesture:delaysTouchesBegan" ) end -- @TODO function Gesture:delaysTouchesEnded() -- print( "Gesture:delaysTouchesEnded" ) end -- @TODO function Gesture:requiresGestureRecognizerToFail() -- print( "Gesture:requiresGestureRecognizerToFail" ) end function Gesture:ignoreTouch() -- print( "Gesture:ignoreTouch" ) end function Gesture:_do_reset() -- print( "Gesture:_do_reset" ) self._total_touch_count = 0 self._touch_count = 0 self._touches = {} -- keyed on ID self._multitouch_evt = nil self._multitouch_queue = {} self._gesture_attempt=false self:_stopAllTimers() end function Gesture:reset() -- print( "Gesture:reset" ) self:_do_reset() self:gotoState( Gesture.STATE_POSSIBLE ) end function Gesture:shouldReceiveTouch() -- print( "Gesture:reset" ) local del = self._delegate local f = del and del.shouldReceiveTouch local shouldReceiveTouch = true if f then shouldReceiveTouch = f( self ) end assert( type(shouldReceiveTouch)=='boolean', "ERROR: Delegate shouldReceiveTouch, expected return type boolean") return shouldReceiveTouch end -- gesture is one which is Recognizing -- function Gesture:forceToFail( gesture ) -- print( "Gesture:forceToFail", gesture ) local del = self._delegate local f = del and del.shouldRecognizeWith local shouldResume = false if f then shouldResume = f( del, gesture, self ) end assert( type(shouldResume)=='boolean', "ERROR: Delegate shouldRecognizeWith, expected return type boolean") if not shouldResume then self:gotoState( Gesture.STATE_FAILED, {notify=false} ) end return (not shouldResume) end --====================================================================-- --== Private Methods --======================================================-- -- Event Dispatch -- this one goes to the Gesture Manager function Gesture:_dispatchGestureNotification( params ) -- print("Gesture:_dispatchGestureNotification", notify ) local g_mgr = self._gesture_mgr if g_mgr and params.notify then g_mgr:gesture{ target=self, id=self._id, type=Gesture.GESTURE, gesture=self.TYPE } end end -- this one goes to the Gesture Manager function Gesture:_dispatchStateNotification( params ) -- print("Gesture:_dispatchStateNotification" ) params = params or {} local state = params.state or self:getState() --==-- local g_mgr = self._gesture_mgr if g_mgr and params.notify then g_mgr:gesture{ target=self, id=self._id, type=Gesture.STATE, state=state } end end -- this one goes to the Gesture consumer (who created gesture) function Gesture:_dispatchRecognizedEvent( data ) -- print("Gesture:_dispatchRecognizedEvent" ) data = data or {} if data.id==nil then data.id=self._id end if data.gesture==nil then data.gesture=self.TYPE end --==-- self:dispatchEvent( self.GESTURE, data, {merge=true} ) end --======================================================-- -- Gesture Timers function Gesture:_stopFailTimer() -- print( "Gesture:_stopFailTimer" ) if not self._fail_timer then return end tcancel( self._fail_timer ) self._fail_timer=nil end function Gesture:_startFailTimer( time ) if time==nil then time=Constants.FAIL_TIMEOUT end --==-- -- print( "Gesture:_startFailTimer", self ) self:_stopFailTimer() local func = function() tdelay( 1, function() self:gotoState( Gesture.STATE_FAILED ) self._fail_timer = nil end) end self._fail_timer = tdelay( time, func ) end function Gesture:_stopGestureTimer() -- print( "Gesture:_stopGestureTimer" ) if not self._gesture_timer then return end tcancel( self._gesture_timer ) self._gesture_timer=nil end function Gesture:_startGestureTimer( time ) -- print( "Gesture:_startGestureTimer", self ) if time==nil then time=Constants.GESTURE_TIMEOUT end --==-- self:_stopFailTimer() self:_stopGestureTimer() local func = function() tdelay( 1, function() self:gotoState( Gesture.STATE_FAILED ) self._gesture_timer = nil end) end self._gesture_timer = tdelay( time, func ) end function Gesture:_stopAllTimers() self:_stopFailTimer() self:_stopGestureTimer() end --======================================================-- -- Touch Event function Gesture:_createTouchEvent( event ) -- print( "Gesture:_createTouchEvent", self.id ) self._total_touch_count = self._total_touch_count + 1 self._touch_count = self._touch_count + 1 self._touches[ tstr(event.id) ] = { id=event.id, name=event.name, target=event.target, isFocused=event.isFocused, phase=event.phase, xStart=event.xStart, yStart=event.yStart, x=event.x, y=event.y, } end function Gesture:_updateTouchEvent( event ) -- print( "Gesture:_updateTouchEvent", self.id ) for id, evt in pairs( self._touches ) do if id==tstr(event.id) then evt.x, evt.y = event.x, event.y evt.phase = event.phase else evt.phase='stationary' end end end function Gesture:_endTouchEvent( event ) -- print( "Gesture:_endTouchEvent", self.id ) self:_updateTouchEvent( event ) self._touch_count = self._touch_count - 1 end function Gesture:_removeTouchEvent( event ) -- print( "Gesture:_removeTouchEvent" ) self._touches[ tstr(event.id) ] = nil end --====================================================================-- --== Event Handlers function Gesture:touch( event ) -- print("Gesture:touch", event.phase, self.id ) local phase = event.phase if phase=='began' then self:_createTouchEvent( event ) elseif phase=='moved' then self:_updateTouchEvent( event ) elseif phase=='cancelled' or phase=='ended' then self:_endTouchEvent( event ) end end --====================================================================-- --== State Machine --== State Create ==-- function Gesture:state_create( next_state, params ) -- print( "Gesture:state_create: >> ", next_state ) if next_state == Gesture.STATE_POSSIBLE then self:do_state_possible( params ) elseif next_state == Gesture.STATE_FAILED then self:do_state_failed( params ) else pwarn( sfmt( "Gesture:state_create unknown transition '%s'", tstr( next_state ))) end end --== State Possible ==-- function Gesture:do_state_possible( params ) -- print( "Gesture:do_state_possible" ) self:setState( Gesture.STATE_POSSIBLE ) end function Gesture:state_possible( next_state, params ) -- print( "Gesture:state_possible: >> ", next_state, self.id ) --== Check Delegate to see if this transition is OK local del = self._delegate local f = del and del.gestureShouldBegin local shouldBegin = true if f then shouldBegin = f( self ) end if not shouldBegin then next_state=Gesture.STATE_FAILED end --== Go to next State if next_state == Gesture.STATE_FAILED then self:do_state_failed( params ) elseif next_state == Gesture.STATE_RECOGNIZED then self:do_state_recognized( params ) elseif next_state == Gesture.STATE_POSSIBLE then self:do_state_possible( params ) else pwarn( sfmt( "Gesture:state_possible unknown transition '%s'", tstr( next_state ))) end end --== State Recognized ==-- function Gesture:do_state_recognized( params ) -- print( "Gesture:do_state_recognized", self._id ) params = params or {} if params.notify==nil then params.notify=true end --==-- self:setState( Gesture.STATE_RECOGNIZED ) self:_dispatchGestureNotification( params ) self:_dispatchStateNotification( params ) self:_dispatchRecognizedEvent() end function Gesture:state_recognized( next_state, params ) -- print( "Gesture:state_recognized: >> ", next_state, self.id ) if next_state == Gesture.STATE_POSSIBLE then self:do_state_possible( params ) else pwarn( sfmt( "Gesture:state_recognized unknown transition '%s'", tstr( next_state ))) end end --== State Failed ==-- function Gesture:do_state_failed( params ) -- print( "Gesture:do_state_failed", self._id ) params = params or {} if params.notify==nil then params.notify=true end --==-- self:_stopAllTimers() self:setState( Gesture.STATE_FAILED ) self:_dispatchStateNotification( params ) end function Gesture:state_failed( next_state, params ) -- print( "Gesture:state_failed: >> ", next_state, self.id ) if next_state == Gesture.STATE_POSSIBLE then self:do_state_possible( params ) elseif next_state == Gesture.STATE_FAILED then -- pass else pwarn( sfmt( "Gesture:state_failed unknown transition '%s'", tstr( next_state ))) end end return Gesture
mit
dmccuskey/dmc-gestures
examples/gesture-multigesture-simultaneous/dmc_corona/dmc_gestures/core/gesture.lua
10
14803
--====================================================================-- -- dmc_corona/dmc_gesture/core/gesture.lua -- -- Documentation: --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2015 David McCuskey 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. --]] --====================================================================-- --== DMC Corona Library : Gesture Base --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== DMC Gesture --====================================================================-- --====================================================================-- --== Imports local Objects = require 'dmc_objects' local Patch = require 'dmc_patch' local StatesMixModule = require 'dmc_states_mix' local Constants = require 'dmc_gestures.gesture_constants' --====================================================================-- --== Setup, Constants Patch.addPatch( 'print-output' ) local newClass = Objects.newClass local ObjectBase = Objects.ObjectBase local StatesMix = StatesMixModule.StatesMix local sfmt = string.format local tcancel = timer.cancel local tdelay = timer.performWithDelay local tstr = tostring --====================================================================-- --== Gesture Base Class --====================================================================-- --- Gesture Recognizer Base Class. -- Base class for all Gesture Recognizers. -- -- **Inherits from:** -- -- * DMC.ObjectBase -- * DMC.StatesMix -- -- @classmod Gesture.Gesture local Gesture = newClass( { ObjectBase, StatesMix }, { name="Gesture Base Class" } ) --== Class Constants Gesture.TYPE = nil -- override this --== State Constants Gesture.STATE_CREATE = 'state_create' Gesture.STATE_POSSIBLE = 'state_possible' Gesture.STATE_FAILED = 'state_failed' Gesture.STATE_RECOGNIZED = 'state_recognized' --== Event Constants --- EVENT Name Gesture.EVENT = 'gesture-event' --- GESTURE Event Gesture.GESTURE = 'recognized-gesture-event' --- STATE Event Gesture.STATE = 'state-changed-event' --======================================================-- -- Start: Setup DMC Objects function Gesture:__init__( params ) -- print( "Gesture:__init__", params ) params = params or {} self:superCall( StatesMix, '__init__', params ) self:superCall( ObjectBase, '__init__', params ) --==-- --== Sanity Check ==-- if self.is_class then return end assert( params.view ) -- save params for later self._gr_params = params --== Create Properties ==-- self._delegate = nil self._id = nil self._view = params.view -- internal properties self._fail_timer=nil self._gesture_attempt=false self._gesture_timer=nil self._multitouch_evt = nil self._multitouch_queue = {} self._touch_count = 0 self._total_touch_count = 0 self._touches = {} -- keyed on ID --== Objects ==-- self._gesture_mgr = nil self:setState( Gesture.STATE_CREATE ) end function Gesture:__undoInit__() -- print( "Gesture:__undoInit__" ) --==-- self:superCall( ObjectBase, '__undoInit__' ) self:superCall( StatesMix, '__undoInit__' ) end function Gesture:__initComplete__() -- print( "Gesture:__initComplete__" ) self:superCall( ObjectBase, '__initComplete__' ) --==-- local tmp = self._gr_params --== Use Setters self.id = tmp.id self.delegate = tmp.delegate self.gesture_mgr = tmp.gesture_mgr self._gr_params = nil self:gotoState( Gesture.STATE_POSSIBLE ) end function Gesture:__undoInitComplete__() -- print( "Gesture:__undoInitComplete__" ) self:_stopAllTimers() self._gesture_mgr:removeGesture( self ) --==-- self:superCall( ObjectBase, '__undoInitComplete__' ) end -- END: Setup DMC Objects --======================================================-- --====================================================================-- --== Public Methods --======================================================-- -- Getters/Setters --- Getters and Setters -- @section getters-setters --== .id --- the id (string). -- this is useful to differentiate between -- different gestures attached to the same view object -- -- @function .id -- @usage print( gesture.id ) -- @usage gesture.id = "myid" function Gesture.__getters:id() return self._id end function Gesture.__setters:id( value ) assert( value==nil or type(value)=='string' ) self._id = value end --== .delegate --- a gesture delegate (object/table) -- -- @function .delegate -- @usage print( gesture.delegate ) -- @usage gesture.delegate = { shouldRecognizeWith=<func> } function Gesture.__getters:delegate() return self._delegate end function Gesture.__setters:delegate( value ) assert( value==nil or type(value)=='table' ) self._delegate = value end function Gesture.__getters:gesture_mgr() return self._gesture_mgr end function Gesture.__setters:gesture_mgr( value ) self._gesture_mgr = value end --== .view --- the target view (Display Object). -- -- @function .view -- @usage print( gesture.view ) -- @usage gesture.view = DisplayObject function Gesture.__getters:view() return self._view end -- function Gesture.__setters:view( value ) -- self._view = value -- end -- @TODO function Gesture:cancelsTouchesInView() -- print( "Gesture:cancelsTouchesInView" ) end -- @TODO function Gesture:delaysTouchesBegan() -- print( "Gesture:delaysTouchesBegan" ) end -- @TODO function Gesture:delaysTouchesEnded() -- print( "Gesture:delaysTouchesEnded" ) end -- @TODO function Gesture:requiresGestureRecognizerToFail() -- print( "Gesture:requiresGestureRecognizerToFail" ) end function Gesture:ignoreTouch() -- print( "Gesture:ignoreTouch" ) end function Gesture:_do_reset() -- print( "Gesture:_do_reset" ) self._total_touch_count = 0 self._touch_count = 0 self._touches = {} -- keyed on ID self._multitouch_evt = nil self._multitouch_queue = {} self._gesture_attempt=false self:_stopAllTimers() end function Gesture:reset() -- print( "Gesture:reset" ) self:_do_reset() self:gotoState( Gesture.STATE_POSSIBLE ) end function Gesture:shouldReceiveTouch() -- print( "Gesture:reset" ) local del = self._delegate local f = del and del.shouldReceiveTouch local shouldReceiveTouch = true if f then shouldReceiveTouch = f( self ) end assert( type(shouldReceiveTouch)=='boolean', "ERROR: Delegate shouldReceiveTouch, expected return type boolean") return shouldReceiveTouch end -- gesture is one which is Recognizing -- function Gesture:forceToFail( gesture ) -- print( "Gesture:forceToFail", gesture ) local del = self._delegate local f = del and del.shouldRecognizeWith local shouldResume = false if f then shouldResume = f( del, gesture, self ) end assert( type(shouldResume)=='boolean', "ERROR: Delegate shouldRecognizeWith, expected return type boolean") if not shouldResume then self:gotoState( Gesture.STATE_FAILED, {notify=false} ) end return (not shouldResume) end --====================================================================-- --== Private Methods --======================================================-- -- Event Dispatch -- this one goes to the Gesture Manager function Gesture:_dispatchGestureNotification( params ) -- print("Gesture:_dispatchGestureNotification", notify ) local g_mgr = self._gesture_mgr if g_mgr and params.notify then g_mgr:gesture{ target=self, id=self._id, type=Gesture.GESTURE, gesture=self.TYPE } end end -- this one goes to the Gesture Manager function Gesture:_dispatchStateNotification( params ) -- print("Gesture:_dispatchStateNotification" ) params = params or {} local state = params.state or self:getState() --==-- local g_mgr = self._gesture_mgr if g_mgr and params.notify then g_mgr:gesture{ target=self, id=self._id, type=Gesture.STATE, state=state } end end -- this one goes to the Gesture consumer (who created gesture) function Gesture:_dispatchRecognizedEvent( data ) -- print("Gesture:_dispatchRecognizedEvent" ) data = data or {} if data.id==nil then data.id=self._id end if data.gesture==nil then data.gesture=self.TYPE end --==-- self:dispatchEvent( self.GESTURE, data, {merge=true} ) end --======================================================-- -- Gesture Timers function Gesture:_stopFailTimer() -- print( "Gesture:_stopFailTimer" ) if not self._fail_timer then return end tcancel( self._fail_timer ) self._fail_timer=nil end function Gesture:_startFailTimer( time ) if time==nil then time=Constants.FAIL_TIMEOUT end --==-- -- print( "Gesture:_startFailTimer", self ) self:_stopFailTimer() local func = function() tdelay( 1, function() self:gotoState( Gesture.STATE_FAILED ) self._fail_timer = nil end) end self._fail_timer = tdelay( time, func ) end function Gesture:_stopGestureTimer() -- print( "Gesture:_stopGestureTimer" ) if not self._gesture_timer then return end tcancel( self._gesture_timer ) self._gesture_timer=nil end function Gesture:_startGestureTimer( time ) -- print( "Gesture:_startGestureTimer", self ) if time==nil then time=Constants.GESTURE_TIMEOUT end --==-- self:_stopFailTimer() self:_stopGestureTimer() local func = function() tdelay( 1, function() self:gotoState( Gesture.STATE_FAILED ) self._gesture_timer = nil end) end self._gesture_timer = tdelay( time, func ) end function Gesture:_stopAllTimers() self:_stopFailTimer() self:_stopGestureTimer() end --======================================================-- -- Touch Event function Gesture:_createTouchEvent( event ) -- print( "Gesture:_createTouchEvent", self.id ) self._total_touch_count = self._total_touch_count + 1 self._touch_count = self._touch_count + 1 self._touches[ tstr(event.id) ] = { id=event.id, name=event.name, target=event.target, isFocused=event.isFocused, phase=event.phase, xStart=event.xStart, yStart=event.yStart, x=event.x, y=event.y, } end function Gesture:_updateTouchEvent( event ) -- print( "Gesture:_updateTouchEvent", self.id ) for id, evt in pairs( self._touches ) do if id==tstr(event.id) then evt.x, evt.y = event.x, event.y evt.phase = event.phase else evt.phase='stationary' end end end function Gesture:_endTouchEvent( event ) -- print( "Gesture:_endTouchEvent", self.id ) self:_updateTouchEvent( event ) self._touch_count = self._touch_count - 1 end function Gesture:_removeTouchEvent( event ) -- print( "Gesture:_removeTouchEvent" ) self._touches[ tstr(event.id) ] = nil end --====================================================================-- --== Event Handlers function Gesture:touch( event ) -- print("Gesture:touch", event.phase, self.id ) local phase = event.phase if phase=='began' then self:_createTouchEvent( event ) elseif phase=='moved' then self:_updateTouchEvent( event ) elseif phase=='cancelled' or phase=='ended' then self:_endTouchEvent( event ) end end --====================================================================-- --== State Machine --== State Create ==-- function Gesture:state_create( next_state, params ) -- print( "Gesture:state_create: >> ", next_state ) if next_state == Gesture.STATE_POSSIBLE then self:do_state_possible( params ) elseif next_state == Gesture.STATE_FAILED then self:do_state_failed( params ) else pwarn( sfmt( "Gesture:state_create unknown transition '%s'", tstr( next_state ))) end end --== State Possible ==-- function Gesture:do_state_possible( params ) -- print( "Gesture:do_state_possible" ) self:setState( Gesture.STATE_POSSIBLE ) end function Gesture:state_possible( next_state, params ) -- print( "Gesture:state_possible: >> ", next_state, self.id ) --== Check Delegate to see if this transition is OK local del = self._delegate local f = del and del.gestureShouldBegin local shouldBegin = true if f then shouldBegin = f( self ) end if not shouldBegin then next_state=Gesture.STATE_FAILED end --== Go to next State if next_state == Gesture.STATE_FAILED then self:do_state_failed( params ) elseif next_state == Gesture.STATE_RECOGNIZED then self:do_state_recognized( params ) elseif next_state == Gesture.STATE_POSSIBLE then self:do_state_possible( params ) else pwarn( sfmt( "Gesture:state_possible unknown transition '%s'", tstr( next_state ))) end end --== State Recognized ==-- function Gesture:do_state_recognized( params ) -- print( "Gesture:do_state_recognized", self._id ) params = params or {} if params.notify==nil then params.notify=true end --==-- self:setState( Gesture.STATE_RECOGNIZED ) self:_dispatchGestureNotification( params ) self:_dispatchStateNotification( params ) self:_dispatchRecognizedEvent() end function Gesture:state_recognized( next_state, params ) -- print( "Gesture:state_recognized: >> ", next_state, self.id ) if next_state == Gesture.STATE_POSSIBLE then self:do_state_possible( params ) else pwarn( sfmt( "Gesture:state_recognized unknown transition '%s'", tstr( next_state ))) end end --== State Failed ==-- function Gesture:do_state_failed( params ) -- print( "Gesture:do_state_failed", self._id ) params = params or {} if params.notify==nil then params.notify=true end --==-- self:_stopAllTimers() self:setState( Gesture.STATE_FAILED ) self:_dispatchStateNotification( params ) end function Gesture:state_failed( next_state, params ) -- print( "Gesture:state_failed: >> ", next_state, self.id ) if next_state == Gesture.STATE_POSSIBLE then self:do_state_possible( params ) elseif next_state == Gesture.STATE_FAILED then -- pass else pwarn( sfmt( "Gesture:state_failed unknown transition '%s'", tstr( next_state ))) end end return Gesture
mit
xing634325131/Luci-0.11.1
modules/admin-mini/luasrc/controller/mini/system.lua
5
6712
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.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: system.lua 9655 2013-01-27 18:43:41Z jow $ ]]-- module("luci.controller.mini.system", package.seeall) function index() entry({"mini", "system"}, alias("mini", "system", "index"), _("System"), 40).index = true entry({"mini", "system", "index"}, cbi("mini/system", {autoapply=true}), _("General"), 1) entry({"mini", "system", "passwd"}, form("mini/passwd"), _("Admin Password"), 10) entry({"mini", "system", "backup"}, call("action_backup"), _("Backup / Restore"), 80) entry({"mini", "system", "upgrade"}, call("action_upgrade"), _("Flash Firmware"), 90) entry({"mini", "system", "reboot"}, call("action_reboot"), _("Reboot"), 100) end function action_backup() local reset_avail = os.execute([[grep '"rootfs_data"' /proc/mtd >/dev/null 2>&1]]) == 0 local restore_cmd = "gunzip | tar -xC/ >/dev/null 2>&1" local backup_cmd = "tar -c %s | gzip 2>/dev/null" local restore_fpi luci.http.setfilehandler( function(meta, chunk, eof) if not restore_fpi then restore_fpi = io.popen(restore_cmd, "w") end if chunk then restore_fpi:write(chunk) end if eof then restore_fpi:close() end end ) local upload = luci.http.formvalue("archive") local backup = luci.http.formvalue("backup") local reset = reset_avail and luci.http.formvalue("reset") if upload and #upload > 0 then luci.template.render("mini/applyreboot") luci.sys.reboot() elseif backup then local reader = ltn12_popen(backup_cmd:format(_keep_pattern())) luci.http.header('Content-Disposition', 'attachment; filename="backup-%s-%s.tar.gz"' % { luci.sys.hostname(), os.date("%Y-%m-%d")}) luci.http.prepare_content("application/x-targz") luci.ltn12.pump.all(reader, luci.http.write) elseif reset then luci.template.render("mini/applyreboot") luci.util.exec("mtd -r erase rootfs_data") else luci.template.render("mini/backup", {reset_avail = reset_avail}) end end function action_reboot() local reboot = luci.http.formvalue("reboot") luci.template.render("mini/reboot", {reboot=reboot}) if reboot then luci.sys.reboot() end end function action_upgrade() require("luci.model.uci") local tmpfile = "/tmp/firmware.img" local function image_supported() -- XXX: yay... return ( 0 == os.execute( ". /lib/functions.sh; " .. "include /lib/upgrade; " .. "platform_check_image %q >/dev/null" % tmpfile ) ) end local function image_checksum() return (luci.sys.exec("md5sum %q" % tmpfile):match("^([^%s]+)")) end local function storage_size() local size = 0 if nixio.fs.access("/proc/mtd") then for l in io.lines("/proc/mtd") do local d, s, e, n = l:match('^([^%s]+)%s+([^%s]+)%s+([^%s]+)%s+"([^%s]+)"') if n == "linux" then size = tonumber(s, 16) break end end elseif nixio.fs.access("/proc/partitions") then for l in io.lines("/proc/partitions") do local x, y, b, n = l:match('^%s*(%d+)%s+(%d+)%s+([^%s]+)%s+([^%s]+)') if b and n and not n:match('[0-9]') then size = tonumber(b) * 1024 break end end end return size end -- Install upload handler local file luci.http.setfilehandler( function(meta, chunk, eof) if not nixio.fs.access(tmpfile) and not file and chunk and #chunk > 0 then file = io.open(tmpfile, "w") end if file and chunk then file:write(chunk) end if file and eof then file:close() end end ) -- Determine state local keep_avail = true local step = tonumber(luci.http.formvalue("step") or 1) local has_image = nixio.fs.access(tmpfile) local has_support = image_supported() local has_platform = nixio.fs.access("/lib/upgrade/platform.sh") local has_upload = luci.http.formvalue("image") -- This does the actual flashing which is invoked inside an iframe -- so don't produce meaningful errors here because the the -- previous pages should arrange the stuff as required. if step == 4 then if has_platform and has_image and has_support then -- Mimetype text/plain luci.http.prepare_content("text/plain") luci.http.write("Starting luci-flash...\n") -- Now invoke sysupgrade local keepcfg = keep_avail and luci.http.formvalue("keepcfg") == "1" local flash = ltn12_popen("/sbin/luci-flash %s %q" %{ keepcfg and "-k %q" % _keep_pattern() or "", tmpfile }) luci.ltn12.pump.all(flash, luci.http.write) -- Make sure the device is rebooted luci.sys.reboot() end -- -- This is step 1-3, which does the user interaction and -- image upload. -- -- Step 1: file upload, error on unsupported image format elseif not has_image or not has_support or step == 1 then -- If there is an image but user has requested step 1 -- or type is not supported, then remove it. if has_image then nixio.fs.unlink(tmpfile) end luci.template.render("mini/upgrade", { step=1, bad_image=(has_image and not has_support or false), keepavail=keep_avail, supported=has_platform } ) -- Step 2: present uploaded file, show checksum, confirmation elseif step == 2 then luci.template.render("mini/upgrade", { step=2, checksum=image_checksum(), filesize=nixio.fs.stat(tmpfile).size, flashsize=storage_size(), keepconfig=(keep_avail and luci.http.formvalue("keepcfg") == "1") } ) -- Step 3: load iframe which calls the actual flash procedure elseif step == 3 then luci.template.render("mini/upgrade", { step=3, keepconfig=(keep_avail and luci.http.formvalue("keepcfg") == "1") } ) end end function _keep_pattern() local kpattern = "" local files = luci.model.uci.cursor():get_all("luci", "flash_keep") if files then kpattern = "" for k, v in pairs(files) do if k:sub(1,1) ~= "." and nixio.fs.glob(v)() then kpattern = kpattern .. " " .. v end end end return kpattern end function ltn12_popen(command) local fdi, fdo = nixio.pipe() local pid = nixio.fork() if pid > 0 then fdo:close() local close return function() local buffer = fdi:read(2048) local wpid, stat = nixio.waitpid(pid, "nohang") if not close and wpid and stat == "exited" then close = true end if buffer and #buffer > 0 then return buffer elseif close then fdi:close() return nil end end elseif pid == 0 then nixio.dup(fdo, nixio.stdout) fdi:close() fdo:close() nixio.exec("/bin/sh", "-c", command) end end
apache-2.0
McGlaspie/mvm
lua/mvm/ReadyRoomPlayer.lua
1
2226
Script.Load("lua/mvm/ScoringMixin.lua") Script.Load("lua/MarineVariantMixin.lua") Script.Load("lua/Mixins/BaseMoveMixin.lua") Script.Load("lua/Mixins/GroundMoveMixin.lua") Script.Load("lua/Mixins/JumpMoveMixin.lua") Script.Load("lua/Mixins/CrouchMoveMixin.lua") Script.Load("lua/Mixins/LadderMoveMixin.lua") Script.Load("lua/Mixins/CameraHolderMixin.lua") Script.Load("lua/mvm/ScoringMixin.lua") //----------------------------------------------------------------------------- function ReadyRoomPlayer:OnCreate() //OVERRIDES InitMixin(self, BaseMoveMixin, { kGravity = Player.kGravity }) InitMixin(self, GroundMoveMixin) InitMixin(self, JumpMoveMixin) InitMixin(self, CrouchMoveMixin) InitMixin(self, LadderMoveMixin) InitMixin(self, CameraHolderMixin, { kFov = kDefaultFov }) InitMixin(self, ScoringMixin, { kMaxScore = kMaxScore }) InitMixin(self, MarineVariantMixin ) Player.OnCreate(self) end function ReadyRoomPlayer:OnInitialized() //OVERRIDES Player.OnInitialized(self) //Below (as in NS2) is always setting default model. If a player was copied //after the OnClientUpdate change kicked in (just before or during team join) //the variant data could be lost, and the server think one AnimationGraphState //was set but the client another. Resulting in T-pose players. self:SetModel( MarineVariantMixin.kDefaultModelName, MarineVariantMixin.kMarineAnimationGraph ) if Client then self:InitializeSkin() end end if Client then function ReadyRoomPlayer:InitializeSkin() self.skinBaseColor = kNeutral_BaseColor self.skinAccentColor = kNeutral_AccentColor self.skinTrimColor = kNeutral_TrimColor self.skinAtlasIndex = 0 self.skinColoringEnabled = true end function ReadyRoomPlayer:GetSkinAtlasIndex() return 0 end function ReadyRoomPlayer:GetBaseSkinColor() return kNeutral_BaseColor end function ReadyRoomPlayer:GetAccentSkinColor() return kNeutral_AccentColor end function ReadyRoomPlayer:GetTrimSkinColor() return kNeutral_TrimColor end end //End Client //----------------------------------------------------------------------------- Class_Reload( "ReadyRoomPlayer", {} )
gpl-3.0
pirate/snabbswitch
src/core/counter.lua
13
3265
-- counter.lua - Count discrete events for diagnostic purposes -- -- This module provides a thin layer for representing 64-bit counters -- as shared memory objects. -- -- Counters let you efficiently count discrete events (packet drops, -- etc) and are accessible as shared memory from other processes such -- as monitoring tools. Counters hold 64-bit unsigned integers. -- -- Use counters to make troubleshooting easier. For example, if there -- are several reasons that an app could drop a packet then you can -- use counters to keep track of why this is actually happening. -- -- You can access the counters using this module, or the raw core.shm -- module, or even directly on disk. Each counter is an 8-byte ramdisk -- file that contains the 64-bit value in native host endian. -- -- For example, you can read a counter on the command line with od(1): -- -- # od -A none -t u8 /var/run/snabb/15347/counter/a -- 43 module(..., package.seeall) local shm = require("core.shm") local ffi = require("ffi") require("core.counter_h") local counter_t = ffi.typeof("struct counter") -- Double buffering: -- For each counter we have a private copy to update directly and then -- a public copy in shared memory that we periodically commit to. -- -- This is important for a subtle performance reason: the shared -- memory counters all have page-aligned addresses (thanks to mmap) -- and accessing many of them can lead to expensive cache misses (due -- to set-associative CPU cache). See SnabbCo/snabbswitch#558. local public = {} local private = {} local numbers = {} -- name -> number function open (name, readonly) if numbers[name] then error("counter already opened: " .. name) end local n = #public+1 numbers[name] = n public[n] = shm.map(name, counter_t, readonly) if readonly then private[n] = public[#public] -- use counter directly else private[n] = ffi.new(counter_t) end return private[n] end function delete (name) local number = numbers[name] if not number then error("counter not found for deletion: " .. name) end -- Free shm object shm.unmap(public[number]) -- If we "own" the counter for writing then we unlink it too. if public[number] ~= private[number] then shm.unlink(name) end -- Free local state numbers[name] = false public[number] = false private[number] = false end -- Copy counter private counter values to public shared memory. function commit () for i = 1, #public do if public[i] ~= private[i] then public[i].c = private[i].c end end end function set (counter, value) counter.c = value end function add (counter, value) counter.c = counter.c + (value or 1) end function read (counter) return counter.c end function selftest () print("selftest: core.counter") local a = open("core.counter/counter/a") local b = open("core.counter/counter/b") local a2 = shm.map("core.counter/counter/a", counter_t, true) set(a, 42) set(b, 43) assert(read(a) == 42) assert(read(b) == 43) commit() assert(read(a) == a2.c) add(a, 1) assert(read(a) == 43) commit() assert(read(a) == a2.c) shm.unlink("core.counter") print("selftest ok") end
apache-2.0
MrCerealGuy/Stonecraft
games/stonecraft_game/mods/WorldEdit/worldedit/visualization.lua
1
3955
--- Functions for visibly hiding nodes -- @module worldedit.visualization minetest.register_node("worldedit:placeholder", { drawtype = "airlike", paramtype = "light", sunlight_propagates = true, diggable = false, pointable = false, walkable = false, groups = {not_in_creative_inventory=1}, }) --- Hides all nodes in a region defined by positions `pos1` and `pos2` by -- non-destructively replacing them with invisible nodes. -- @return The number of nodes hidden. function worldedit.hide(pos1, pos2) pos1, pos2 = worldedit.sort_pos(pos1, pos2) worldedit.keep_loaded(pos1, pos2) local pos = {x=pos1.x, y=0, z=0} local get_node, get_meta, swap_node = minetest.get_node, minetest.get_meta, minetest.swap_node while pos.x <= pos2.x do pos.y = pos1.y while pos.y <= pos2.y do pos.z = pos1.z while pos.z <= pos2.z do local node = get_node(pos) if node.name ~= "air" and node.name ~= "worldedit:placeholder" then -- Save the node's original name get_meta(pos):set_string("worldedit_placeholder", node.name) -- Swap in placeholder node node.name = "worldedit:placeholder" swap_node(pos, node) end pos.z = pos.z + 1 end pos.y = pos.y + 1 end pos.x = pos.x + 1 end return worldedit.volume(pos1, pos2) end --- Suppresses all instances of `node_name` in a region defined by positions -- `pos1` and `pos2` by non-destructively replacing them with invisible nodes. -- @return The number of nodes suppressed. function worldedit.suppress(pos1, pos2, node_name) -- Ignore placeholder supression if node_name == "worldedit:placeholder" then return 0 end pos1, pos2 = worldedit.sort_pos(pos1, pos2) worldedit.keep_loaded(pos1, pos2) local nodes = minetest.find_nodes_in_area(pos1, pos2, node_name) local get_node, get_meta, swap_node = minetest.get_node, minetest.get_meta, minetest.swap_node for _, pos in ipairs(nodes) do local node = get_node(pos) -- Save the node's original name get_meta(pos):set_string("worldedit_placeholder", node.name) -- Swap in placeholder node node.name = "worldedit:placeholder" swap_node(pos, node) end return #nodes end --- Highlights all instances of `node_name` in a region defined by positions -- `pos1` and `pos2` by non-destructively hiding all other nodes. -- @return The number of nodes found. function worldedit.highlight(pos1, pos2, node_name) pos1, pos2 = worldedit.sort_pos(pos1, pos2) worldedit.keep_loaded(pos1, pos2) local pos = {x=pos1.x, y=0, z=0} local get_node, get_meta, swap_node = minetest.get_node, minetest.get_meta, minetest.swap_node local count = 0 while pos.x <= pos2.x do pos.y = pos1.y while pos.y <= pos2.y do pos.z = pos1.z while pos.z <= pos2.z do local node = get_node(pos) if node.name == node_name then -- Node found count = count + 1 elseif node.name ~= "worldedit:placeholder" then -- Hide other nodes -- Save the node's original name get_meta(pos):set_string("worldedit_placeholder", node.name) -- Swap in placeholder node node.name = "worldedit:placeholder" swap_node(pos, node) end pos.z = pos.z + 1 end pos.y = pos.y + 1 end pos.x = pos.x + 1 end return count end -- Restores all nodes hidden with WorldEdit functions in a region defined -- by positions `pos1` and `pos2`. -- @return The number of nodes restored. function worldedit.restore(pos1, pos2) local pos1, pos2 = worldedit.sort_pos(pos1, pos2) worldedit.keep_loaded(pos1, pos2) local nodes = minetest.find_nodes_in_area(pos1, pos2, "worldedit:placeholder") local get_node, get_meta, swap_node = minetest.get_node, minetest.get_meta, minetest.swap_node for _, pos in ipairs(nodes) do local node = get_node(pos) local meta = get_meta(pos) local data = meta:to_table() node.name = data.fields.worldedit_placeholder data.fields.worldedit_placeholder = nil meta:from_table(data) swap_node(pos, node) end return #nodes end
gpl-3.0
xing634325131/Luci-0.11.1
libs/sgi-cgi/luasrc/sgi/cgi.lua
13
2301
--[[ LuCI - SGI-Module for CGI Description: Server Gateway Interface for CGI FileId: $Id: cgi.lua 6535 2010-11-23 01:02:21Z soma $ License: Copyright 2008 Steven Barth <steven@midlink.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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- exectime = os.clock() module("luci.sgi.cgi", package.seeall) local ltn12 = require("luci.ltn12") require("nixio.util") require("luci.http") require("luci.sys") require("luci.dispatcher") -- Limited source to avoid endless blocking local function limitsource(handle, limit) limit = limit or 0 local BLOCKSIZE = ltn12.BLOCKSIZE return function() if limit < 1 then handle:close() return nil else local read = (limit > BLOCKSIZE) and BLOCKSIZE or limit limit = limit - read local chunk = handle:read(read) if not chunk then handle:close() end return chunk end end end function run() local r = luci.http.Request( luci.sys.getenv(), limitsource(io.stdin, tonumber(luci.sys.getenv("CONTENT_LENGTH"))), ltn12.sink.file(io.stderr) ) local x = coroutine.create(luci.dispatcher.httpdispatch) local hcache = "" local active = true while coroutine.status(x) ~= "dead" do local res, id, data1, data2 = coroutine.resume(x, r) if not res then print("Status: 500 Internal Server Error") print("Content-Type: text/plain\n") print(id) break; end if active then if id == 1 then io.write("Status: " .. tostring(data1) .. " " .. data2 .. "\r\n") elseif id == 2 then hcache = hcache .. data1 .. ": " .. data2 .. "\r\n" elseif id == 3 then io.write(hcache) io.write("\r\n") elseif id == 4 then io.write(tostring(data1 or "")) elseif id == 5 then io.flush() io.close() active = false elseif id == 6 then data1:copyz(nixio.stdout, data2) data1:close() end end end end
apache-2.0
McGlaspie/mvm
lua/mvm/Hud/GUIMineDisplay.lua
1
3589
// ======= Copyright (c) 2003-2011, Unknown Worlds Entertainment, Inc. All rights reserved. ===== // // lua\GUIMineDisplay.lua // // Created by: Andreas Urwalek (andi@unknownworlds.com) // // Displays the current number of bullets and clips for the ammo counter on a bullet weapon // // ========= For more information, visit us at http://www.unknownworlds.com ===================== Script.Load("lua/GUIScript.lua") Script.Load("lua/Utility.lua") Script.Load("lua/mvm/GUIColorGlobals.lua") weaponClip = 0 teamNumber = 0 class 'GUIMineDisplay' (GUIScript) local kBackgroundColor = Color(0.302, 0.859, 1, 0.2) function GUIMineDisplay:Initialize() self.weaponClip = 0 self.teamNumber = 0 self.background = GUIManager:CreateGraphicItem() self.background:SetSize( Vector(256, 512, 0) ) self.background:SetPosition( Vector(0, 0, 0) ) self.background:SetColor( kGUI_NameTagFontColors[self.teamNumber] ) self.background:SetIsVisible(true) // Slightly larger copy of the text for a glow effect self.ammoTextBg = GUIManager:CreateTextItem() self.ammoTextBg:SetFontName("fonts/MicrogrammaDMedExt_large.fnt") self.ammoTextBg:SetScale(Vector( 1.8, 2.25, 1.8)) self.ammoTextBg:SetTextAlignmentX(GUIItem.Align_Center) self.ammoTextBg:SetTextAlignmentY(GUIItem.Align_Center) self.ammoTextBg:SetAnchor(GUIItem.Middle, GUIItem.Center) self.ammoTextBg:SetColor( kGUI_Grey ) // Text displaying the amount of ammo in the clip self.ammoText = GUIManager:CreateTextItem() self.ammoText:SetFontName("fonts/MicrogrammaDMedExt_large.fnt") self.ammoText:SetScale(Vector(1.75, 2.2, 1.75)) self.ammoText:SetTextAlignmentX(GUIItem.Align_Center) self.ammoText:SetTextAlignmentY(GUIItem.Align_Center) self.ammoText:SetAnchor(GUIItem.Middle, GUIItem.Center) self.ammoText:SetColor( kGUI_HealthBarColors[self.teamNumber] ) self.flashInOverlay = GUIManager:CreateGraphicItem() self.flashInOverlay:SetSize(Vector(256, 512, 0)) self.flashInOverlay:SetPosition(Vector(0, 0, 0)) self.flashInOverlay:SetColor(Color(1, 1, 1, 0.7)) // Force an update so our initial state is correct. self:Update(0) end function GUIMineDisplay:SetTeamNumber(team) self.teamNumber = team end function GUIMineDisplay:SetClip(clip) self.weaponClip = clip end function GUIMineDisplay:UpdateTeamColors() self.background:SetColor( kGUI_TeamThemes_BaseColor[self.teamNumber] ) //self.ammoText:SetColor( kGUI_HealthBarColors[self.teamNumber] ) end function GUIMineDisplay:Update(deltaTime) PROFILE("GUIMineDisplay:Update") self:UpdateTeamColors() local ammoFormat = string.format("%d", self.weaponClip) self.ammoText:SetText(ammoFormat) self.ammoTextBg:SetText(ammoFormat) local flashInAlpha = self.flashInOverlay:GetColor().a if flashInAlpha > 0 then local alphaPerSecond = 0.5 flashInAlpha = Clamp(flashInAlpha - alphaPerSecond * deltaTime, 0, 1) self.flashInOverlay:SetColor(Color(1, 1, 1, flashInAlpha)) end end mineDisplay = nil /** * Called by the player to update the components. */ function Update(deltaTime) PROFILE("GUIMineDisplay Update") mineDisplay:SetClip( weaponClip ) mineDisplay:SetTeamNumber( teamNumber ) mineDisplay:Update( deltaTime ) end /** * Initializes the player components. */ function Initialize() GUI.SetSize(256, 417) mineDisplay = GUIMineDisplay() mineDisplay:Initialize() end Initialize()
gpl-3.0
spixi/wesnoth
data/lua/helper.lua
2
8301
--! #textdomain wesnoth local helper = {} local wml_actions = wesnoth.wml_actions --! Returns an iterator over all the sides matching a given filter that can be used in a for-in loop. function helper.get_sides(cfg) local function f(s) local i = s.i while i < #wesnoth.sides do i = i + 1 if wesnoth.match_side(i, cfg) then s.i = i return wesnoth.sides[i], i end end end return f, { i = 0 } end --! Returns an iterator over teams that can be used in a for-in loop. function helper.all_teams() local function f(s) local i = s.i local team = wesnoth.sides[i] s.i = i + 1 return team end return f, { i = 1 } end -- Metatable that redirects access to wml.variables_proxy local proxy_var_mt = { __metatable = "WML variables", __index = function(t, k) return wml.variables_proxy[k] end, __newindex = function(t, k, v) wml.variables_proxy[k] = v end, } function helper.set_wml_var_metatable(t) return setmetatable(t, proxy_var_mt) end local fire_action_mt = { __metatable = "WML actions", __index = function(t, n) return function(cfg) wesnoth.fire(n, cfg) end end } --! Sets the metatable of @a t so that it can be used to fire WML actions. --! @return @a t. --! @code --! W = helper.set_wml_action_metatable {} --! W.message { speaker = "narrator", message = "?" } --! @endcode function helper.set_wml_action_metatable(t) return setmetatable(t, fire_action_mt) end -- Metatable that redirects to wml.tag local proxy_tag_mt = { __metatable = "WML tag builder", __index = function(t, n) return wml.tag[n] end } function helper.set_wml_tag_metatable(t) return setmetatable(t, proxy_tag_mt) end --! Returns an iterator over adjacent locations that can be used in a for-in loop. -- Not deprecated because, unlike wesnoth.map.get_adjacent_tiles, -- this verifies that the locations are on the map. function helper.adjacent_tiles(x, y, with_borders) local x1,y1,x2,y2,b = 1,1,wesnoth.get_map_size() if with_borders then x1 = x1 - b y1 = y1 - b x2 = x2 + b y2 = y2 + b end local adj = {wesnoth.map.get_adjacent_tiles(x, y)} local i = 0 return function() while i < #adj do i = i + 1 local u, v = adj[i][1], adj[i][2] if u >= x1 and u <= x2 and v >= y1 and v <= y2 then return u, v end end return nil end end function helper.rand (possible_values, random_func) random_func = random_func or wesnoth.random assert(type(possible_values) == "table" or type(possible_values) == "string", string.format("helper.rand expects a string or table as parameter, got %s instead", type(possible_values))) local items = {} local num_choices = 0 if type(possible_values) == "string" then -- split on commas for word in possible_values:gmatch("[^,]+") do -- does the word contain two dots? If yes, that's a range local dots_start, dots_end = word:find("%.%.") if dots_start then -- split on the dots if so and cast as numbers local low = tonumber(word:sub(1, dots_start-1)) local high = tonumber(word:sub(dots_end+1)) -- perhaps someone passed a string as part of the range, intercept the issue if not (low and high) then wesnoth.message("Malformed range: " .. possible_values) table.insert(items, word) num_choices = num_choices + 1 else if low > high then -- low is greater than high, swap them low, high = high, low end -- if both ends represent the same number, then just use that number if low == high then table.insert(items, low) num_choices = num_choices + 1 else -- insert a table representing the range table.insert(items, {low, high}) -- how many items does the range contain? Increase difference by 1 because we include both ends num_choices = num_choices + (high - low) + 1 end end else -- handle as a string table.insert(items, word) num_choices = num_choices + 1 end end else num_choices = #possible_values items = possible_values -- We need to parse ranges separately anyway for i, val in ipairs(possible_values) do if type(val) == "table" then assert(#val == 2 and type(val[1]) == "number" and type(val[2]) == "number", "Malformed range for helper.rand") if val[1] > val[2] then val = {val[2], val[1]} end num_choices = num_choices + (val[2] - val[1]) end end end local idx = random_func(1, num_choices) for i, item in ipairs(items) do if type(item) == "table" then -- that's a range local elems = item[2] - item[1] + 1 -- amount of elements in the range, both ends included if elems >= idx then return item[1] + elems - idx else idx = idx - elems end else -- that's a single element idx = idx - 1 if idx == 0 then return item end end end return nil end function helper.deprecate(msg, f) return function(...) if msg then wesnoth.log("warn", msg, wesnoth.game_config.debug) -- trigger the message only once msg = nil end return f(...) end end function helper.round( number ) -- code converted from util.hpp, round_portable function -- round half away from zero method if number >= 0 then number = math.floor( number + 0.5 ) else number = math.ceil ( number - 0.5 ) end return number end function helper.shuffle( t, random_func ) random_func = random_func or wesnoth.random -- since tables are passed by reference, this is an in-place shuffle -- it uses the Fisher-Yates algorithm, also known as Knuth shuffle assert( type( t ) == "table", string.format( "helper.shuffle expects a table as parameter, got %s instead", type( t ) ) ) local length = #t for index = length, 2, -1 do local random = random_func( 1, index ) t[index], t[random] = t[random], t[index] end end function helper.find_attack(unit, filter) for i, atk in ipairs(unit.attacks) do if atk:matches(filter) then return atk end end end -- Compatibility and deprecations helper.distance_between = wesnoth.deprecate_api('helper.distance_between', 'wesnoth.map.distance_between', 1, nil, wesnoth.map.distance_between) helper.get_child = wesnoth.deprecate_api('helper.get_child', 'wml.get_child', 1, nil, wml.get_child) helper.get_nth_child = wesnoth.deprecate_api('helper.get_nth_child', 'wml.get_nth_child', 1, nil, wml.get_nth_child) helper.child_count = wesnoth.deprecate_api('helper.child_count', 'wml.child_count', 1, nil, wml.child_count) helper.child_range = wesnoth.deprecate_api('helper.child_range', 'wml.child_range', 1, nil, wml.child_range) helper.child_array = wesnoth.deprecate_api('helper.child_array', 'wml.child_array', 1, nil, wml.child_array) if wesnoth.kernel_type() == "Game Lua Kernel" then helper.get_variable_array = wesnoth.deprecate_api('helper.get_variable_array', ' wml.array_access.get', 1, nil, wml.array_access.get) helper.set_variable_array = wesnoth.deprecate_api('helper.set_variable_array', 'wml.array_access.set', 1, nil, wml.array_access.set) helper.get_variable_proxy_array = wesnoth.deprecate_api('helper.get_variable_proxy_array', 'wml.array_access.get_proxy', 1, nil, wml.array_access.get_proxy) helper.wml_error = wesnoth.deprecate_api('helper.wml_error', 'wml.error', 1, nil, wml.error) helper.move_unit_fake = wesnoth.deprecate_api('helper.move_unit_fake', 'wesnoth.interface.move_unit_fake', 1, nil, wesnoth.interface.move_unit_fake) helper.modify_unit = wesnoth.deprecate_api('helper.modify_unit', 'wesnoth.units.modify', 1, nil, wesnoth.units.modify) end helper.literal = wesnoth.deprecate_api('helper.literal', 'wml.literal', 1, nil, wml.literal) helper.parsed = wesnoth.deprecate_api('helper.parsed', 'wml.parsed', 1, nil, wml.parsed) helper.shallow_literal = wesnoth.deprecate_api('helper.shallow_literal', 'wml.shallow_literal', 1, nil, wml.shallow_literal) helper.shallow_parsed = wesnoth.deprecate_api('helper.shallow_parsed', 'wml.shallow_parsed', 1, nil, wml.shallow_parsed) helper.set_wml_var_metatable = wesnoth.deprecate_api('helper.set_wml_var_metatable', 'wml.variable.proxy', 2, nil, helper.set_wml_var_metatable) helper.set_wml_tag_metatable = wesnoth.deprecate_api('helper.set_wml_tag_metatable', 'wml.tag', 2, nil, helper.set_wml_tag_metatable) helper.get_user_choice = wesnoth.deprecate_api('helper.get_user_choice', 'gui.get_user_choice', 1, nil, gui.get_user_choice) return helper
gpl-2.0
amirkingred/telejian
plugins/anti-flood.lua
281
2422
local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds local TIME_CHECK = 5 local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, function (data, success, result) if success ~= 1 then local text = 'I can\'t kick '..data.user..' but should be kicked' send_msg(data.chat, '', ok_cb, nil) end end, {chat=chat, user=user}) end local function run (msg, matches) if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' else local chat = msg.to.id local hash = 'anti-flood:enabled:'..chat if matches[1] == 'enable' then redis:set(hash, true) return 'Anti-flood enabled on chat' end if matches[1] == 'disable' then redis:del(hash) return 'Anti-flood disabled on chat' end end end local function pre_process (msg) -- Ignore service msg if msg.service then print('Service message') return msg end local hash_enable = 'anti-flood:enabled:'..msg.to.id local enabled = redis:get(hash_enable) if enabled then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then -- Increase the number of messages from the user on the chat local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then local receiver = get_receiver(msg) local user = msg.from.id local text = 'User '..user..' is flooding' local chat = msg.to.id send_msg(receiver, text, ok_cb, nil) if msg.to.type ~= 'chat' then print("Flood in not a chat group!") elseif user == tostring(our_id) then print('I won\'t kick myself') elseif is_sudo(msg) then print('I won\'t kick an admin!') else -- Ban user -- TODO: Check on this plugin bans local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) kick_user(user, chat) end msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end end return msg end return { description = 'Plugin to kick flooders from group.', usage = {}, patterns = { '^!antiflood (enable)$', '^!antiflood (disable)$' }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
OpenRA/OpenRA
mods/ra/maps/fall-of-greece-2-evacuation/evacuation-AI.lua
7
3468
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] AttackGroup = { } SovietInfantry = { "e1", "e2" } SovietVehicles = { "3tnk", "3tnk", "v2rl" } SovietAircraftType = { "yak" } Yaks = { } AttackPaths = { AttackRight, AttackLeft } AttackGroupSizes = { easy = 8, normal = 9, hard = 10 } ProductionInterval = { easy = DateTime.Seconds(20), normal = DateTime.Seconds(10), hard = DateTime.Seconds(5) } SendAttackGroup = function() if #AttackGroup < AttackGroupSize then return end local path = Utils.Random(AttackPaths) Utils.Do(AttackGroup, function(unit) if not unit.IsDead then unit.AttackMove(path.Location) Trigger.OnIdle(unit, unit.Hunt) end end) AttackGroup = { } end ProduceInfantry = function() if USSRRax.IsDead or USSRRax.Owner ~= USSR then return end USSR.Build({ Utils.Random(SovietInfantry) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceInfantry) end) end ProduceVehicles = function() if USSRWarFactory.IsDead or USSRWarFactory.Owner ~= USSR then return end USSR.Build({ Utils.Random(SovietVehicles) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceVehicles) end) end ProduceAircraft = function() if Airfield.IsDead or Airfield.Owner ~= USSR then return end USSR.Build(SovietAircraftType, function(units) local yak = units[1] Yaks[#Yaks + 1] = yak Trigger.OnKilled(yak, ProduceAircraft) local alive = Utils.Where(Yaks, function(y) return not y.IsDead end) if #alive < 2 then Trigger.AfterDelay(DateTime.Seconds(ProductionInterval[Difficulty] / 2), ProduceAircraft) end InitializeAttackAircraft(yak, Allies) end) end ParadropDelays = { easy = { DateTime.Minutes(1), DateTime.Minutes(2) }, normal = { DateTime.Seconds(45), DateTime.Seconds(105) }, hard = { DateTime.Seconds(30), DateTime.Seconds(90) } } ParadropLZs = { ParaLZ1.CenterPosition, ParaLZ2.CenterPosition, ParaLZ3.CenterPosition, ParaLZ4.CenterPosition } Paradrop = function() if Airfield.IsDead or Airfield.Owner ~= USSR then return end local aircraft = StandardDrop.TargetParatroopers(Utils.Random(ParadropLZs)) Utils.Do(aircraft, function(a) Trigger.OnPassengerExited(a, function(t, p) IdleHunt(p) end) end) Trigger.AfterDelay(Utils.RandomInteger(ParadropDelay[1], ParadropDelay[2]), Paradrop) end ActivateAI = function() local buildings = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == USSR and self.HasProperty("StartBuildingRepairs") end) Utils.Do(buildings, function(actor) Trigger.OnDamaged(actor, function(building) if building.Owner == USSR and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) end) ParadropDelay = ParadropDelays[Difficulty] AttackGroupSize = AttackGroupSizes[Difficulty] Trigger.AfterDelay(DateTime.Seconds(30), ProduceInfantry) Trigger.AfterDelay(DateTime.Minutes(3), ProduceVehicles) Trigger.AfterDelay(DateTime.Minutes(4), Paradrop) Trigger.AfterDelay(DateTime.Minutes(5), ProduceAircraft) end
gpl-3.0
payday-restoration/restoration-mod
lua/sc/units/player_team/logics/teamailogicdisabled.lua
1
2127
function TeamAILogicDisabled._upd_enemy_detection(data) data.t = TimerManager:game():time() local my_data = data.internal_data local delay = CopLogicBase._upd_attention_obj_detection(data, AIAttentionObject.REACT_SURPRISED, nil) local new_attention, new_prio_slot, new_reaction = TeamAILogicIdle._get_priority_attention(data, data.detected_attention_objects, nil, data.cool) TeamAILogicBase._set_attention_obj(data, new_attention, new_reaction) TeamAILogicDisabled._upd_aim(data, my_data) if data.unit:character_damage():bleed_out() and not data.unit:character_damage():fatal() or data.unit:character_damage():arrested() then TeamAILogicIdle._upd_sneak_spotting(data, my_data) elseif data.unit:movement():tased() then if not data.unit:brain()._tase_mark_t or data.unit:brain()._tase_mark_t + 3 < data.t then for key, attention_info in pairs(data.detected_attention_objects) do if attention_info.identified and attention_info.is_person and attention_info.unit:contour() then if attention_info.unit:character_damage().dead and not attention_info.unit:character_damage():dead() then if attention_info.unit:brain() and attention_info.unit:brain()._logic_data and attention_info.unit:brain()._logic_data.internal_data then local tasing = attention_info.unit:brain()._logic_data.internal_data.tasing if tasing and tasing.target_u_data.unit == data.unit then data.unit:brain()._tase_mark_t = data.t data.unit:sound():say("s07x_sin", true) attention_info.unit:contour():add("mark_enemy", true) local skip_alert = managers.groupai:state():whisper_mode() if not skip_alert then local alert_rad = 500 local alert = { "vo_cbt", data.unit:movement():m_head_pos(), alert_rad, data.SO_access, data.unit } managers.groupai:state():propagate_alert(alert) end break end end end end end end end CopLogicBase.queue_task(my_data, my_data.detection_task_key, TeamAILogicDisabled._upd_enemy_detection, data, data.t + delay) end
agpl-3.0
AlexanderMatveenko/omim
3party/osrm/osrm-backend/profiles/bicycle.lua
59
12992
require("lib/access") require("lib/maxspeed") -- Begin of globals barrier_whitelist = { [""] = true, ["cycle_barrier"] = true, ["bollard"] = true, ["entrance"] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true } access_tag_whitelist = { ["yes"] = true, ["permissive"] = true, ["designated"] = true } access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true } access_tag_restricted = { ["destination"] = true, ["delivery"] = true } access_tags_hierachy = { "bicycle", "vehicle", "access" } cycleway_tags = {["track"]=true,["lane"]=true,["opposite"]=true,["opposite_lane"]=true,["opposite_track"]=true,["share_busway"]=true,["sharrow"]=true,["shared"]=true } service_tag_restricted = { ["parking_aisle"] = true } restriction_exception_tags = { "bicycle", "vehicle", "access" } default_speed = 15 walking_speed = 6 bicycle_speeds = { ["cycleway"] = default_speed, ["primary"] = default_speed, ["primary_link"] = default_speed, ["secondary"] = default_speed, ["secondary_link"] = default_speed, ["tertiary"] = default_speed, ["tertiary_link"] = default_speed, ["residential"] = default_speed, ["unclassified"] = default_speed, ["living_street"] = default_speed, ["road"] = default_speed, ["service"] = default_speed, ["track"] = 12, ["path"] = 12 --["footway"] = 12, --["pedestrian"] = 12, } pedestrian_speeds = { ["footway"] = walking_speed, ["pedestrian"] = walking_speed, ["steps"] = 2 } railway_speeds = { ["train"] = 10, ["railway"] = 10, ["subway"] = 10, ["light_rail"] = 10, ["monorail"] = 10, ["tram"] = 10 } platform_speeds = { ["platform"] = walking_speed } amenity_speeds = { ["parking"] = 10, ["parking_entrance"] = 10 } man_made_speeds = { ["pier"] = walking_speed } route_speeds = { ["ferry"] = 5 } bridge_speeds = { ["movable"] = 5 } surface_speeds = { ["asphalt"] = default_speed, ["cobblestone:flattened"] = 10, ["paving_stones"] = 10, ["compacted"] = 10, ["cobblestone"] = 6, ["unpaved"] = 6, ["fine_gravel"] = 6, ["gravel"] = 6, ["fine_gravel"] = 6, ["pebbelstone"] = 6, ["ground"] = 6, ["dirt"] = 6, ["earth"] = 6, ["grass"] = 6, ["mud"] = 3, ["sand"] = 3 } take_minimum_of_speeds = true obey_oneway = true obey_bollards = false use_restrictions = true ignore_areas = true -- future feature traffic_signal_penalty = 5 u_turn_penalty = 20 use_turn_restrictions = false turn_penalty = 60 turn_bias = 1.4 --modes mode_normal = 1 mode_pushing = 2 mode_ferry = 3 mode_train = 4 mode_movable_bridge = 5 local function parse_maxspeed(source) if not source then return 0 end local n = tonumber(source:match("%d*")) if not n then n = 0 end if string.match(source, "mph") or string.match(source, "mp/h") then n = (n*1609)/1000; end return n end function get_exceptions(vector) for i,v in ipairs(restriction_exception_tags) do vector:Add(v) end end function node_function (node, result) local barrier = node:get_value_by_key("barrier") local access = Access.find_access_tag(node, access_tags_hierachy) local traffic_signal = node:get_value_by_key("highway") -- flag node if it carries a traffic light if traffic_signal and traffic_signal == "traffic_signals" then result.traffic_lights = true end -- parse access and barrier tags if access and access ~= "" then if access_tag_blacklist[access] then result.barrier = true else result.barrier = false end elseif barrier and barrier ~= "" then if barrier_whitelist[barrier] then result.barrier = false else result.barrier = true end end end function way_function (way, result) -- initial routability check, filters out buildings, boundaries, etc local highway = way:get_value_by_key("highway") local route = way:get_value_by_key("route") local man_made = way:get_value_by_key("man_made") local railway = way:get_value_by_key("railway") local amenity = way:get_value_by_key("amenity") local public_transport = way:get_value_by_key("public_transport") local bridge = way:get_value_by_key("bridge") if (not highway or highway == '') and (not route or route == '') and (not railway or railway=='') and (not amenity or amenity=='') and (not man_made or man_made=='') and (not public_transport or public_transport=='') and (not bridge or bridge=='') then return end -- don't route on ways or railways that are still under construction if highway=='construction' or railway=='construction' then return end -- access local access = Access.find_access_tag(way, access_tags_hierachy) if access and access_tag_blacklist[access] then return end -- other tags local name = way:get_value_by_key("name") local ref = way:get_value_by_key("ref") local junction = way:get_value_by_key("junction") local maxspeed = parse_maxspeed(way:get_value_by_key ( "maxspeed") ) local maxspeed_forward = parse_maxspeed(way:get_value_by_key( "maxspeed:forward")) local maxspeed_backward = parse_maxspeed(way:get_value_by_key( "maxspeed:backward")) local barrier = way:get_value_by_key("barrier") local oneway = way:get_value_by_key("oneway") local onewayClass = way:get_value_by_key("oneway:bicycle") local cycleway = way:get_value_by_key("cycleway") local cycleway_left = way:get_value_by_key("cycleway:left") local cycleway_right = way:get_value_by_key("cycleway:right") local duration = way:get_value_by_key("duration") local service = way:get_value_by_key("service") local area = way:get_value_by_key("area") local foot = way:get_value_by_key("foot") local surface = way:get_value_by_key("surface") local bicycle = way:get_value_by_key("bicycle") -- name if ref and "" ~= ref and name and "" ~= name then result.name = name .. ' / ' .. ref elseif ref and "" ~= ref then result.name = ref elseif name and "" ~= name then result.name = name elseif highway then -- if no name exists, use way type -- this encoding scheme is excepted to be a temporary solution result.name = "{highway:"..highway.."}" end -- roundabout handling if junction and "roundabout" == junction then result.roundabout = true; end -- speed local bridge_speed = bridge_speeds[bridge] if (bridge_speed and bridge_speed > 0) then highway = bridge; if duration and durationIsValid(duration) then result.duration = math.max( parseDuration(duration), 1 ); end result.forward_mode = mode_movable_bridge result.backward_mode = mode_movable_bridge result.forward_speed = bridge_speed result.backward_speed = bridge_speed elseif route_speeds[route] then -- ferries (doesn't cover routes tagged using relations) result.forward_mode = mode_ferry result.backward_mode = mode_ferry result.ignore_in_grid = true if duration and durationIsValid(duration) then result.duration = math.max( 1, parseDuration(duration) ) else result.forward_speed = route_speeds[route] result.backward_speed = route_speeds[route] end elseif railway and platform_speeds[railway] then -- railway platforms (old tagging scheme) result.forward_speed = platform_speeds[railway] result.backward_speed = platform_speeds[railway] elseif platform_speeds[public_transport] then -- public_transport platforms (new tagging platform) result.forward_speed = platform_speeds[public_transport] result.backward_speed = platform_speeds[public_transport] elseif railway and railway_speeds[railway] then result.forward_mode = mode_train result.backward_mode = mode_train -- railways if access and access_tag_whitelist[access] then result.forward_speed = railway_speeds[railway] result.backward_speed = railway_speeds[railway] end elseif amenity and amenity_speeds[amenity] then -- parking areas result.forward_speed = amenity_speeds[amenity] result.backward_speed = amenity_speeds[amenity] elseif bicycle_speeds[highway] then -- regular ways result.forward_speed = bicycle_speeds[highway] result.backward_speed = bicycle_speeds[highway] elseif access and access_tag_whitelist[access] then -- unknown way, but valid access tag result.forward_speed = default_speed result.backward_speed = default_speed else -- biking not allowed, maybe we can push our bike? -- essentially requires pedestrian profiling, for example foot=no mean we can't push a bike if foot ~= 'no' and junction ~= "roundabout" then if pedestrian_speeds[highway] then -- pedestrian-only ways and areas result.forward_speed = pedestrian_speeds[highway] result.backward_speed = pedestrian_speeds[highway] result.forward_mode = mode_pushing result.backward_mode = mode_pushing elseif man_made and man_made_speeds[man_made] then -- man made structures result.forward_speed = man_made_speeds[man_made] result.backward_speed = man_made_speeds[man_made] result.forward_mode = mode_pushing result.backward_mode = mode_pushing elseif foot == 'yes' then result.forward_speed = walking_speed result.backward_speed = walking_speed result.forward_mode = mode_pushing result.backward_mode = mode_pushing elseif foot_forward == 'yes' then result.forward_speed = walking_speed result.forward_mode = mode_pushing result.backward_mode = 0 elseif foot_backward == 'yes' then result.forward_speed = walking_speed result.forward_mode = 0 result.backward_mode = mode_pushing end end end -- direction local impliedOneway = false if junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then impliedOneway = true end if onewayClass == "yes" or onewayClass == "1" or onewayClass == "true" then result.backward_mode = 0 elseif onewayClass == "no" or onewayClass == "0" or onewayClass == "false" then -- prevent implied oneway elseif onewayClass == "-1" then result.forward_mode = 0 elseif oneway == "no" or oneway == "0" or oneway == "false" then -- prevent implied oneway elseif cycleway and string.find(cycleway, "opposite") == 1 then if impliedOneway then result.forward_mode = 0 result.backward_mode = mode_normal result.backward_speed = bicycle_speeds["cycleway"] end elseif cycleway_left and cycleway_tags[cycleway_left] and cycleway_right and cycleway_tags[cycleway_right] then -- prevent implied elseif cycleway_left and cycleway_tags[cycleway_left] then if impliedOneway then result.forward_mode = 0 result.backward_mode = mode_normal result.backward_speed = bicycle_speeds["cycleway"] end elseif cycleway_right and cycleway_tags[cycleway_right] then if impliedOneway then result.forward_mode = mode_normal result.backward_speed = bicycle_speeds["cycleway"] result.backward_mode = 0 end elseif oneway == "-1" then result.forward_mode = 0 elseif oneway == "yes" or oneway == "1" or oneway == "true" or impliedOneway then result.backward_mode = 0 end -- pushing bikes if bicycle_speeds[highway] or pedestrian_speeds[highway] then if foot ~= "no" and junction ~= "roundabout" then if result.backward_mode == 0 then result.backward_speed = walking_speed result.backward_mode = mode_pushing elseif result.forward_mode == 0 then result.forward_speed = walking_speed result.forward_mode = mode_pushing end end end -- cycleways if cycleway and cycleway_tags[cycleway] then result.forward_speed = bicycle_speeds["cycleway"] elseif cycleway_left and cycleway_tags[cycleway_left] then result.forward_speed = bicycle_speeds["cycleway"] elseif cycleway_right and cycleway_tags[cycleway_right] then result.forward_speed = bicycle_speeds["cycleway"] end -- dismount if bicycle == "dismount" then result.forward_mode = mode_pushing result.backward_mode = mode_pushing result.forward_speed = walking_speed result.backward_speed = walking_speed end -- surfaces if surface then surface_speed = surface_speeds[surface] if surface_speed then if result.forward_speed > 0 then result.forward_speed = surface_speed end if result.backward_speed > 0 then result.backward_speed = surface_speed end end end -- maxspeed MaxSpeed.limit( result, maxspeed, maxspeed_forward, maxspeed_backward ) end function turn_function (angle) -- compute turn penalty as angle^2, with a left/right bias k = turn_penalty/(90.0*90.0) if angle>=0 then return angle*angle*k/turn_bias else return angle*angle*k*turn_bias end end
apache-2.0
nuintun/payday2
extras/mods/npc-weapons-customization/Weapons/benelli_npc.lua
1
7284
log("benelli_npc loaded") Hooks:Add("LocalizationManagerPostInit", "NPCWeap_benelli_Localization", function(loc) LocalizationManager:add_localized_strings({ ["random"] = "Random", ["benelli_none"] = "None", --Barrels ["benelli_g_barrel_std"] = "Standard", ["benelli_g_barrel_short"] = "Short", ["benelli_g_barrel_long"] = "Long", --Barrel Extensions ["benelli_g_ns_shark"] = "Shark", ["benelli_g_ns_thick"] = "Thick", ["benelli_g_ns_king"] = "THE King", --Body -- None, body can't be modified --Foregrips -- None, foregrips can't be modified --Optics ["benelli_g_optics_aimpoint"] = "Aimpoint", ["benelli_g_optics_docter"] = "Docter", ["benelli_g_optics_eotech"] = "EOtech", ["benelli_g_optics_specter"] = "Specter", ["benelli_g_optics_t1micro"] = "t1micro", ["benelli_g_optics_cmore"] = "cmore", ["benelli_g_optics_aimpoint_preorder"] = "Aimpoint preorder", ["benelli_g_optics_eotech_xps"] = "EOtech Gage Courier", ["benelli_g_optics_reflex"] = "Reflex", ["benelli_g_optics_rx01"] = "RX01", ["benelli_g_optics_rx30"] = "RX30", ["benelli_g_optics_cs"] = "Aimpoint CS", ["benelli_g_optics_acog"] = "Acog Sight", --Stocks ["benelli_g_stock_solid"] = "Solid", ["benelli_g_stock_collapsable"] = "Collapsable", ["benelli_g_stock_collapsabled"] = "Collaps'd", --Attachments ["benelli_g_attachment_rail"] = "Attachment Rail", ["benelli_g_attachment_peqbox"] = "Laser Module", ["benelli_g_attachment_surefire"] = "Flashlight", ["benelli_g_attachment_laser"] = "Laser Module 2", ["benelli_g_attachment_peq"] = "PEQ15", }) end) NPCWeap.weapons.benelli_npc = NPCWeap.weapons.benelli_npc or {} NPCWeap.weapons.benelli_npc.required_reset = NPCWeap.weapons.benelli_npc.required_reset or {} NPCWeap.weapons.benelli_npc.name_id = "benelli_npc" NPCWeap.weapons.benelli_npc.display_name = "XM1014" NPCWeap.weapons.benelli_npc.unit = "units/payday2/weapons/wpn_npc_benelli/wpn_npc_benelli" NPCWeap.weapons.benelli_npc.object_sub = 9 NPCWeap.loaded_options.benelli_npc = NPCWeap.loaded_options.benelli_npc or {} NPCWeap.weapons.benelli_npc.objects_init = { "g_barrel_std", "g_body_std", "g_body_bolt", "g_fg_std", "g_stock_solid", "g_attachment_rail", "g_attachment_surefire", } NPCWeap.weapons.benelli_npc.categories = { "barrel", "barrel_ext", "sight", "stock", "attachment", } NPCWeap.weapons.benelli_npc.barrel = { [1] = "benelli_g_barrel_std", [2] = "benelli_g_barrel_short", [3] = "benelli_g_barrel_long", [4] = "random", } NPCWeap.loaded_options.benelli_npc.barrel = NPCWeap.loaded_options.benelli_npc.barrel or 1 NPCWeap.weapons.benelli_npc.required_reset.barrel = {} NPCWeap.weapons.benelli_npc.barrel_fire_offset = Vector3(0, -43.09261, -0.3042422) NPCWeap.weapons.benelli_npc.g_barrel_std = {} NPCWeap.weapons.benelli_npc.g_barrel_std.barrel_ext = Vector3(0, 43.09261, 0.3042422) -- [0 43.09261 0.30424] NPCWeap.weapons.benelli_npc.g_barrel_short = {} NPCWeap.weapons.benelli_npc.g_barrel_short.barrel_ext = Vector3(0, 32.37598, 0.3042422) --[0 32.37598 0.3042422] NPCWeap.weapons.benelli_npc.g_barrel_long = {} NPCWeap.weapons.benelli_npc.g_barrel_long.barrel_ext = Vector3(0, 49.22952, 0.3042422) -- [0 49.22952 0.3042422] NPCWeap.weapons.benelli_npc.barrel_ext = { [1] = "benelli_none", [2] = "benelli_g_ns_shark", [3] = "benelli_g_ns_thick", [4] = "benelli_g_ns_king", [5] = "random", } NPCWeap.loaded_options.benelli_npc.barrel_ext = NPCWeap.loaded_options.benelli_npc.barrel_ext or 1 NPCWeap.weapons.benelli_npc.required_reset.barrel_ext = {} NPCWeap.weapons.benelli_npc.g_ns_shark = {} NPCWeap.weapons.benelli_npc.g_ns_shark.length = Vector3(0, 6.7632, 0) NPCWeap.weapons.benelli_npc.g_ns_thick = {} NPCWeap.weapons.benelli_npc.g_ns_thick.length = Vector3(0, 17.40295, 0) NPCWeap.weapons.benelli_npc.g_ns_king = {} NPCWeap.weapons.benelli_npc.g_ns_king.length = Vector3(0, 7.6996, 0) NPCWeap.weapons.benelli_npc.sight = { [1] = "benelli_none", [2] = "benelli_g_optics_aimpoint", [3] = "benelli_g_optics_docter", [4] = "benelli_g_optics_eotech", [5] = "benelli_g_optics_specter", [6] = "benelli_g_optics_t1micro", [7] = "benelli_g_optics_cmore", [8] = "benelli_g_optics_aimpoint_preorder", [9] = "benelli_g_optics_eotech_xps", [10] = "benelli_g_optics_reflex", [11] = "benelli_g_optics_rx01", [12] = "benelli_g_optics_rx30", [13] = "benelli_g_optics_cs", [14] = "benelli_g_optics_acog", [15] = "random" } NPCWeap.loaded_options.benelli_npc.sight = NPCWeap.loaded_options.benelli_npc.sight or 1 NPCWeap.weapons.benelli_npc.required_reset.sight = { "g_optics_eotech_gfx_lens", "g_optics_acog_lens", "g_optics_aimpoint_glass", "g_optics_aimpoint_preorder_glass", "g_optics_cmore_lens", "g_optics_cs_lens", "g_optics_docter_lens", "g_optics_eotech_xps_lens", "g_optics_reflex_lens", "g_optics_rx01_lens", "g_optics_rx30_lens", "g_optics_specter_glass", "g_optics_t1micro_glass", "g_optics_adapter", } NPCWeap.weapons.benelli_npc.stock = { [1] = "benelli_g_stock_solid", [2] = "benelli_g_stock_collapsable", [3] = "benelli_g_stock_collapsabled", [4] = "random", } NPCWeap.loaded_options.benelli_npc.stock = NPCWeap.loaded_options.benelli_npc.stock or 1 NPCWeap.weapons.benelli_npc.required_reset.stock = {} NPCWeap.loaded_options.benelli_npc.foregrip = NPCWeap.loaded_options.benelli_npc.foregrip or 1 NPCWeap.weapons.benelli_npc.required_reset.foregrip = {} NPCWeap.weapons.benelli_npc.attachment = { [1] = "benelli_none", [2] = "benelli_g_attachment_surefire", [3] = "benelli_g_attachment_laser", [4] = "benelli_g_attachment_peq", [5] = "benelli_g_attachment_peqbox", [6] = "random", } NPCWeap.loaded_options.benelli_npc.attachment = NPCWeap.loaded_options.benelli_npc.attachment or 1 NPCWeap.weapons.benelli_npc.required_reset.attachment = { "g_attachment_rail" } NPCWeap.weapons.benelli_npc.required = { ["g_optics_eotech"] = { "g_optics_eotech_gfx_lens", "g_optics_adapter" }, ["g_optics_acog"] = { "g_optics_acog_lens", "g_optics_adapter" }, ["g_optics_aimpoint"] = { "g_optics_aimpoint_glass", "g_optics_adapter" }, ["g_optics_docter"] = { "g_optics_docter_lens", "g_optics_adapter" }, ["g_optics_specter"] = { "g_optics_specter_glass", "g_optics_adapter" }, ["g_optics_t1micro"] = { "g_optics_t1micro_glass", "g_optics_adapter" }, ["g_optics_cmore"] = { "g_optics_cmore_lens", "g_optics_adapter" }, ["g_optics_aimpoint_preorder"] = { "g_optics_aimpoint_preorder_glass", "g_optics_adapter" }, ["g_optics_eotech_xps"] = { "g_optics_eotech_xps_lens", "g_optics_adapter" }, ["g_optics_reflex"] = { "g_optics_reflex_lens", "g_optics_adapter" }, ["g_optics_rx01"] = { "g_optics_rx01_lens", "g_optics_adapter" }, ["g_optics_rx30"] = { "g_optics_rx30_lens", "g_optics_adapter" }, ["g_optics_cs"] = { "g_optics_cs_lens", "g_optics_adapter" }, ["g_attachment_surefire"] = { "g_attachment_rail" }, ["g_attachment_laser"] = { "g_attachment_rail" }, ["g_attachment_peq"] = { "g_attachment_rail" }, ["g_attachment_peqbox"] = { "g_attachment_rail" }, } NPCWeap.weapons.benelli_npc.incompatible = {} NPCWeap.weapons.benelli_npc.pos_check = { ["barrel_ext"] = { "barrel" } }
mit
phunculist/dotfiles
.config/vis/themes/phunculist.lua
1
1142
-- Monotone color scheme local lexers = vis.lexers lexers.STYLE_DEFAULT = 'default' lexers.STYLE_NOTHING = 'default' lexers.STYLE_CLASS = '' lexers.STYLE_COMMENT = 'fore:#6e6e6e,italics' lexers.STYLE_CONSTANT = '' lexers.STYLE_DEFINITION = '' lexers.STYLE_ERROR = 'fore:red' lexers.STYLE_FUNCTION = '' lexers.STYLE_KEYWORD = '' lexers.STYLE_LABEL = '' lexers.STYLE_NUMBER = '' lexers.STYLE_OPERATOR = '' lexers.STYLE_REGEX = '' lexers.STYLE_STRING = 'fore:#5f875f' lexers.STYLE_PREPROCESSOR = '' lexers.STYLE_TAG = '' lexers.STYLE_TYPE = '' lexers.STYLE_VARIABLE = '' lexers.STYLE_WHITESPACE = '' lexers.STYLE_EMBEDDED = '' lexers.STYLE_IDENTIFIER = '' lexers.STYLE_LINENUMBER = '' lexers.STYLE_LINENUMBER_CURSOR = lexers.STYLE_LINENUMBER lexers.STYLE_CURSOR = 'reverse' lexers.STYLE_CURSOR_PRIMARY = 'back:blue' lexers.STYLE_CURSOR_LINE = '' lexers.STYLE_COLOR_COLUMN = '' lexers.STYLE_SELECTION = 'back:#585858' lexers.STYLE_STATUS = 'fore:#6c6c6c,back:#444444' lexers.STYLE_STATUS_FOCUSED = 'fore:default,back:#585858' lexers.STYLE_SEPARATOR = '' lexers.STYLE_INFO = lexers.STYLE_DEFAULT..',bold' lexers.STYLE_EOF = lexers.STYLE_COMMENT
mit
McGlaspie/mvm
lua/mvm/TechData.lua
1
133838
// ======= Copyright (c) 2003-2012, Unknown Worlds Entertainment, Inc. All rights reserved. ======= // // lua\TechData.lua // // Created by: Charlie Cleveland (charlie@unknownworlds.com) // // A "database" of attributes for all units, abilities, structures, weapons, etc. in the game. // Shared between client and server. // // ========= For more information, visit us at http://www.unknownworlds.com ===================== // Set up structure data for easy use by Server.lua and model classes // Store whatever data is necessary here and use LookupTechData to access // Store any data that needs to used on both client and server here // Lookup by key with LookupTechData() kTechDataId = "id" // Localizable string describing tech node kTechDataDisplayName = "displayname" // For alien traits and marine upgrades, these distinct character codes will be stored in sponitor's database kTechDataSponitorCode = "sponitorchar" // Include and set to false if not meant to display on commander UI "enables: " kTechIDShowEnables = "showenables" kTechDataMapName = "mapname" kTechDataModel = "model" // TeamResources, resources or energy kTechDataCostKey = "costkey" kTechDataBuildTime = "buildtime" // If an entity has this field, it's treated as a research node instead of a build node kTechDataResearchTimeKey = "researchTime" kTechDataMaxHealth = "maxhealth" kTechDataMaxArmor = "maxarmor" kTechDataDamageType = "damagetype" // Class that structure must be placed on top of (resource towers on resource points) // If adding more attach classes, add them to GetIsAttachment(). When attaching entities // to this attach class, ignore class. kStructureAttachClass = "attachclass" // Structure must be placed within kStructureAttachRange of this class, but it isn't actually attached. // This can be a table of strings as well. Near class must have the same team number. kStructureBuildNearClass = "buildnearclass" // Structure attaches to wall/roof kStructureBuildOnWall = "buildonwall" // If specified along with attach class, this entity can only be built within this range of an attach class (infantry portal near Command Station) // If specified, you must also specify the tech id of the attach class. // This can be a table of ids as well. kStructureAttachRange = "attachrange" // If specified, this entity can only be built if there is a powered attach class within kStructureAttachRange. kStructureAttachRequiresPower = "attachrequirespower" // If specified, draw a range indicator for the commander when selected. kVisualRange = "visualrange" // set to true when attach structure is not required but optional kTechDataAttachOptional = "attachoptional" // The tech id of the attach class kStructureAttachId = "attachid" // If specified, this tech is an alien class that can be gestated into kTechDataGestateName = "gestateclass" // upgrade cost (life form specific) kTechDataUpgradeCost = "upgradecost" // If specified, how much time it takes to evolve into this class kTechDataGestateTime = "gestatetime" // If specified, object spawns this far off the ground kTechDataSpawnHeightOffset = "spawnheight" // All player tech ids should have this, nothing else uses it. Pre-computed by looking at the min and max extents of the model, // adding their absolute values together and dividing by 2. kTechDataMaxExtents = "maxextents" // Radius of a cylinder carved out of the navmesh when a structure with this tech id is placed kTechDataObstacleRadius = "obstacleradius" // If specified, is amount of energy structure starts with kTechDataInitialEnergy = "initialenergy" // If specified, is max energy structure can have kTechDataMaxEnergy = "maxenergy" // Menu priority. If more than one techId is specified for the same spot in a menu, use the one with the higher priority. // If a tech doesn't specify a priority, treat as 0. If all priorities are tied, show none of them. This is how Starcraft works (see siege behavior). kTechDataMenuPriority = "menupriority" // if an alert with higher priority is trigger the interval should be ignored kTechDataAlertPriority = "alertpriority" // Indicates that the tech node is an upgrade of another tech node, so that the previous tech is still active (ie, if you upgrade a hive // to an advanced hive, your team still has "hive" technology. kTechDataUpgradeTech = "upgradetech" // Set true if entity should be rotated before being placed kTechDataSpecifyOrientation = "specifyorientation" // manipulate build coords in a custom function kTechDataOverrideCoordsMethod = "overridecoordsmethod" // Point value for killing structure kTechDataPointValue = "pointvalue" // Set to false if not yet implemented, for displaying differently for not enabling kTechDataImplemented = "implemented" // Set to localizable string that will be added to end of description indicating date it went in. kTechDataNew = "new" // For setting grow parameter on alien structures kTechDataGrows = "grows" // Commander hotkey. Not currently used. kTechDataHotkey = "hotkey" // Alert sound name kTechDataAlertSound = "alertsound" // Alert text for commander HUD kTechDataAlertText = "alerttext" // Alert type. These are the types in CommanderUI_GetDynamicMapBlips. "Request" alert types count as player alert requests and show up on the commander HUD as such. kTechDataAlertType = "alerttype" // Alert scope kTechDataAlertTeam = "alertteam" // Alert should ignore distance for triggering kTechDataAlertIgnoreDistance = "alertignoredistance" // Alert should also trigger a team message. kTechDataAlertSendTeamMessage = "alertsendteammessage" // Sound that plays for Comm and ordered players when given this order kTechDataOrderSound = "ordersound" // Don't send alert to originator of this alert kTechDataAlertOthersOnly = "alertothers" // Usage notes, caveats, etc. for use in commander tooltip (localizable) kTechDataTooltipInfo = "tooltipinfo" // Quite the same as tooltip, but shorter kTechDataHint = "hintinfo" // Indicate tech id that we're replicating // Engagement distance - how close can unit get to it before it can repair or build it kTechDataEngagementDistance = "engagementdist" // Can only be built on infestation kTechDataRequiresInfestation = "requiresinfestation" // Cannot be built on infestation (cannot be specified with kTechDataRequiresInfestation) kTechDataNotOnInfestation = "notoninfestation" // Special ghost-guide method. Called with commander as argument, returns a map of entities with ranges to lit up. kTechDataGhostGuidesMethod = "ghostguidesmethod" // Special requirements for building. Called with techId, the origin and normal for building location and the commander. Returns true if the special requirement is met. kTechDataBuildRequiresMethod = "buildrequiresmethod" // Allows dropping onto other entities kTechDataAllowStacking = "allowstacking" // will ignore other entities when searching for spawn position kTechDataCollideWithWorldOnly = "collidewithworldonly" // ignore pathing mesh when placing entities kTechDataIgnorePathingMesh = "ignorepathing" // used for gorgess kTechDataMaxAmount = "maxstructureamount" // requires power kTechDataRequiresPower = "requirespower" // for drawing ghost model, client kTechDataGhostModelClass = "ghostmodelclass" // for gorge build, can consume when dropping kTechDataAllowConsumeDrop = "allowconsumedrop" // true when the host structure requires to be mature kTechDataRequiresMature = "requiresmature" // only useable once every X seconds kTechDataCooldown = "coldownduration" // ignore any alert interval kTechDataAlertIgnoreInterval = "ignorealertinterval" // used for alien upgrades kTechDataCategory = "techcategory" // custom message displayed for the commander when build method failed kTechDataBuildMethodFailedMessage = "commanderbuildmethodfailed" kTechDataAbilityType = "abilitytype" kTechDataSupply = "supply" kTechDataSpawnBlock = "spawnblock" kTechDataBioMass = "biomasslevel" kTechDataShowOrderLine = "showorderline" //Probably don't need all the above crap... function BuildTechData() //OVERRIDES local techData = { // Orders { [kTechDataId] = kTechId.Move, [kTechDataDisplayName] = "MOVE", [kTechDataHotkey] = Move.M, [kTechDataTooltipInfo] = "MOVE_TOOLTIP", [kTechDataOrderSound] = MarineCommander.kMoveToWaypointSoundName }, { [kTechDataId] = kTechId.Patrol, [kTechDataDisplayName] = "PATROL", [kTechDataShowOrderLine] = true, [kTechDataHotkey] = Move.M, [kTechDataTooltipInfo] = "PATROL_TOOLTIP", [kTechDataOrderSound] = MarineCommander.kMoveToWaypointSoundName }, { [kTechDataId] = kTechId.Attack, [kTechDataDisplayName] = "ATTACK", [kTechDataHotkey] = Move.A, [kTechDataTooltipInfo] = "ATTACK_TOOLTIP", [kTechDataOrderSound] = MarineCommander.kAttackOrderSoundName }, { [kTechDataId] = kTechId.Build, [kTechDataDisplayName] = "BUILD", [kTechDataTooltipInfo] = "BUILD_TOOLTIP" }, { [kTechDataId] = kTechId.Construct, [kTechDataDisplayName] = "CONSTRUCT", [kTechDataOrderSound] = MarineCommander.kBuildStructureSound }, { [kTechDataId] = kTechId.AutoConstruct, [kTechDataDisplayName] = "CONSTRUCT", [kTechDataOrderSound] = MarineCommander.kBuildStructureSound}, { [kTechDataId] = kTechId.Grow, [kTechDataDisplayName] = "GROW", [kTechDataTooltipInfo] = "GROW_TOOLTIP" }, { [kTechDataId] = kTechId.HoldPosition, [kTechDataDisplayName] = "HOLD_POSITION" }, { [kTechDataId] = kTechId.FollowAlien, [kTechDataDisplayName] = "FOLLOW_NEAREST_ALIEN", [kTechDataTooltipInfo] = "FOLLOW_NEAREST_ALIEN_TOOLTIP" }, { [kTechDataId] = kTechId.Follow, [kTechDataDisplayName] = "FOLLOW" }, { [kTechDataId] = kTechId.Cancel, [kTechDataDisplayName] = "CANCEL", [kTechDataHotkey] = Move.ESC}, { [kTechDataId] = kTechId.Weld, [kTechDataDisplayName] = "WELD", [kTechDataHotkey] = Move.W, [kTechDataTooltipInfo] = "WELD_TOOLTIP", [kTechDataOrderSound] = MarineCommander.kWeldOrderSound}, { [kTechDataId] = kTechId.FollowAndWeld, [kTechDataDisplayName] = "FOLLOWANDWELD", [kTechDataHotkey] = Move.W, [kTechDataTooltipInfo] = "FOLLOWANDWELD_TOOLTIP", [kTechDataOrderSound] = MarineCommander.kWeldOrderSound}, { [kTechDataId] = kTechId.Stop, [kTechDataDisplayName] = "STOP", [kTechDataHotkey] = Move.S, [kTechDataTooltipInfo] = "STOP_TOOLTIP"}, { [kTechDataId] = kTechId.SetRally, [kTechDataDisplayName] = "SET_RALLY_POINT", [kTechDataHotkey] = Move.L, [kTechDataTooltipInfo] = "RALLY_POINT_TOOLTIP", [kTechDataShowOrderLine] = true,}, { [kTechDataId] = kTechId.SetTarget, [kTechDataDisplayName] = "SET_TARGET", [kTechDataHotkey] = Move.T, [kTechDataTooltipInfo] = "SET_TARGET_TOOLTIP"}, { [kTechDataId] = kTechId.Welding, [kTechDataDisplayName] = "WELDING", [kTechDataTooltipInfo] = "WELDING_TOOLTIP", }, { [kTechDataId] = kTechId.AlienMove, [kTechDataDisplayName] = "MOVE", [kTechDataHotkey] = Move.M, [kTechDataTooltipInfo] = "MOVE_TOOLTIP", [kTechDataOrderSound] = AlienCommander.kMoveToWaypointSoundName}, { [kTechDataId] = kTechId.AlienAttack, [kTechDataDisplayName] = "ATTACK", [kTechDataHotkey] = Move.A, [kTechDataTooltipInfo] = "ATTACK_TOOLTIP", [kTechDataOrderSound] = AlienCommander.kAttackOrderSoundName}, { [kTechDataId] = kTechId.AlienConstruct, [kTechDataDisplayName] = "CONSTRUCT", [kTechDataOrderSound] = AlienCommander.kBuildStructureSound}, { [kTechDataId] = kTechId.Heal, [kTechDataDisplayName] = "HEAL", [kTechDataOrderSound] = AlienCommander.kHealTarget}, { [kTechDataId] = kTechId.AutoHeal, [kTechDataDisplayName] = "HEAL", [kTechDataOrderSound] = AlienCommander.kHealTarget}, { [kTechDataId] = kTechId.SpawnMarine, [kTechDataDisplayName] = "SPAWN_MARINE", [kTechDataTooltipInfo] = "SPAWN_MARINE_TOOLTIP", }, { [kTechDataId] = kTechId.SpawnAlien, [kTechDataDisplayName] = "SPAWN_ALIEN", [kTechDataTooltipInfo] = "SPAWN_ALIEN_TOOLTIP", }, { [kTechDataId] = kTechId.CollectResources, [kTechDataDisplayName] = "COLLECT_RESOURCES", [kTechDataTooltipInfo] = "COLLECT_RESOURCES_TOOLTIP", }, { [kTechDataId] = kTechId.Detector, [kTechDataDisplayName] = "DETECTOR", [kTechDataTooltipInfo] = "DETECTOR_TOOLTIP", }, { [kTechDataId] = kTechId.TransformResources, [kTechDataResearchTimeKey] = kTransformResourcesTime, [kTechDataDisplayName] = "TRANSFORM_RESOURCES", [kTechDataCostKey] = kTransformResourcesCost, [kTechDataTooltipInfo] = "TRANSFORM_RESOURCES_TOOLTIP",}, // Ready room player is the default player, hence the ReadyRoomPlayer.kMapName { [kTechDataId] = kTechId.ReadyRoomPlayer, [kTechDataDisplayName] = "READY_ROOM_PLAYER", [kTechDataMapName] = ReadyRoomPlayer.kMapName, [kTechDataModel] = MarineVariantMixin.kModelNames["male"]["green"], [kTechDataMaxExtents] = Vector(Player.kXZExtents, Player.kYExtents, Player.kXZExtents) }, // Spectators classes. { [kTechDataId] = kTechId.Spectator, [kTechDataModel] = "" }, { [kTechDataId] = kTechId.AlienSpectator, [kTechDataModel] = "" }, // Marine classes { [kTechDataId] = kTechId.Marine, [kTechDataDisplayName] = "MARINE", [kTechDataMapName] = Marine.kMapName, [kTechDataModel] = MarineVariantMixin.kModelNames["male"]["green"], [kTechDataMaxExtents] = Vector(Player.kXZExtents, Player.kYExtents, Player.kXZExtents), [kTechDataMaxHealth] = Marine.kHealth, [kTechDataEngagementDistance] = kPlayerEngagementDistance, [kTechDataPointValue] = kMarinePointValue }, { [kTechDataId] = kTechId.Exo, [kTechDataDisplayName] = "EXOSUIT", [kTechDataTooltipInfo] = "EXOSUIT_TOOLTIP", [kTechDataMapName] = Exo.kMapName, [kTechDataMaxExtents] = Vector(Exo.kXZExtents, Exo.kYExtents, Exo.kXZExtents), [kTechDataMaxHealth] = kExosuitHealth, [kTechDataEngagementDistance] = kExoEngagementDistance, [kTechDataPointValue] = kExosuitPointValue }, { [kTechDataId] = kTechId.MarineCommander, [kTechDataDisplayName] = "MARINE_COMMANDER", [kTechDataMapName] = MarineCommander.kMapName, [kTechDataModel] = ""}, { [kTechDataId] = kTechId.JetpackMarine, [kTechDataHint] = "JETPACK_HINT", [kTechDataDisplayName] = "JETPACK", [kTechDataMapName] = JetpackMarine.kMapName, [kTechDataModel] = JetpackMarine.kModelName, [kTechDataMaxExtents] = Vector(Player.kXZExtents, Player.kYExtents, Player.kXZExtents), [kTechDataMaxHealth] = JetpackMarine.kHealth, [kTechDataEngagementDistance] = kPlayerEngagementDistance, [kTechDataPointValue] = kMarinePointValue}, // Marine orders { [kTechDataId] = kTechId.Defend, [kTechDataDisplayName] = "DEFEND", [kTechDataOrderSound] = MarineCommander.kDefendTargetSound}, // Menus { [kTechDataId] = kTechId.RootMenu, [kTechDataDisplayName] = "SELECT", [kTechDataHotkey] = Move.B, [kTechDataTooltipInfo] = "SELECT_TOOLTIP"}, { [kTechDataId] = kTechId.BuildMenu, [kTechDataDisplayName] = "BUILD", [kTechDataHotkey] = Move.W, [kTechDataTooltipInfo] = "BUILD_TOOLTIP"}, { [kTechDataId] = kTechId.AdvancedMenu, [kTechDataDisplayName] = "ADVANCED", [kTechDataHotkey] = Move.E, [kTechDataTooltipInfo] = "ADVANCED_TOOLTIP"}, { [kTechDataId] = kTechId.AssistMenu, [kTechDataDisplayName] = "ASSIST", [kTechDataHotkey] = Move.R, [kTechDataTooltipInfo] = "ASSIST_TOOLTIP"}, { [kTechDataId] = kTechId.MarkersMenu, [kTechDataDisplayName] = "MARKERS", [kTechDataHotkey] = Move.M, [kTechDataTooltipInfo] = "PHEROMONE_TOOLTIP"}, { [kTechDataId] = kTechId.UpgradesMenu, [kTechDataDisplayName] = "UPGRADES", [kTechDataHotkey] = Move.U, [kTechDataTooltipInfo] = "TEAM_UPGRADES_TOOLTIP"}, { [kTechDataId] = kTechId.WeaponsMenu, [kTechDataDisplayName] = "WEAPONS_MENU", [kTechDataTooltipInfo] = "WEAPONS_MENU_TOOLTIP"}, // Marine menus { [kTechDataId] = kTechId.RoboticsFactoryARCUpgradesMenu, [kTechDataDisplayName] = "ARC_UPGRADES", [kTechDataHotkey] = Move.P}, { [kTechDataId] = kTechId.RoboticsFactoryMACUpgradesMenu, [kTechDataDisplayName] = "MAC_UPGRADES", [kTechDataHotkey] = Move.P}, { [kTechDataId] = kTechId.TwoCommandStations, [kTechDataDisplayName] = "TWO_COMMAND_STATIONS", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "TWO_COMMAND_STATIONS"}, { [kTechDataId] = kTechId.ThreeCommandStations, [kTechDataDisplayName] = "TWO_COMMAND_STATIONS", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "THREE_COMMAND_STATIONS"}, { [kTechDataId] = kTechId.TwoHives, [kTechDataDisplayName] = "TWO_HIVES", [kTechIDShowEnables] = false}, { [kTechDataId] = kTechId.ThreeHives, [kTechDataDisplayName] = "THREE_HIVES", [kTechIDShowEnables] = false}, { [kTechDataId] = kTechId.TwoWhips, [kTechDataDisplayName] = "TWO_WHIPS", [kTechIDShowEnables] = false}, { [kTechDataId] = kTechId.TwoCrags, [kTechDataDisplayName] = "TWO_CRAGS", [kTechIDShowEnables] = false}, { [kTechDataId] = kTechId.TwoShifts, [kTechDataDisplayName] = "TWO_SHIFTS", [kTechIDShowEnables] = false}, { [kTechDataId] = kTechId.TwoShades, [kTechDataDisplayName] = "TWO_SHADES", [kTechIDShowEnables] = false}, // Misc. { [kTechDataId] = kTechId.PowerPoint, [kTechDataHint] = "POWERPOINT_HINT", [kTechDataMapName] = PowerPoint.kMapName, [kTechDataDisplayName] = "POWER_NODE", [kTechDataCostKey] = 0, [kTechDataMaxHealth] = kPowerPointHealth, [kTechDataMaxArmor] = kPowerPointArmor, [kTechDataBuildTime] = kPowerPointBuildTime, [kTechDataPointValue] = kPowerPointPointValue, [kTechDataTooltipInfo] = "POWERPOINT_TOOLTIP" }, { [kTechDataId] = kTechId.SocketPowerNode, [kTechDataDisplayName] = "SOCKET_POWER_NODE", [kTechDataCostKey] = kPowerNodeCost, [kTechDataBuildTime] = 0.1, }, { [kTechDataId] = kTechId.ResourcePoint, [kTechDataHint] = "RESOURCE_NOZZLE_TOOLTIP", [kTechDataMapName] = ResourcePoint.kPointMapName, [kTechDataDisplayName] = "RESOURCE_NOZZLE", [kTechDataModel] = ResourcePoint.kModelName, [kTechDataObstacleRadius] = 1.0 }, { [kTechDataId] = kTechId.TechPoint, [kTechDataHint] = "TECH_POINT_HINT", [kTechDataTooltipInfo] = "TECH_POINT_TOOLTIP", [kTechDataMapName] = TechPoint.kMapName, [kTechDataDisplayName] = "TECH_POINT", [kTechDataModel] = TechPoint.kModelName }, { [kTechDataId] = kTechId.Door, [kTechDataDisplayName] = "DOOR", [kTechDataTooltipInfo] = "DOOR_TOOLTIP", [kTechDataMapName] = Door.kMapName, [kTechDataMaxHealth] = kDoorHealth, [kTechDataMaxArmor] = kDoorArmor, [kTechDataPointValue] = kDoorPointValue }, { [kTechDataId] = kTechId.DoorOpen, [kTechDataDisplayName] = "OPEN_DOOR", [kTechDataHotkey] = Move.O, [kTechDataTooltipInfo] = "OPEN_DOOR_TOOLTIP"}, { [kTechDataId] = kTechId.DoorClose, [kTechDataDisplayName] = "CLOSE_DOOR", [kTechDataHotkey] = Move.C, [kTechDataTooltipInfo] = "CLOSE_DOOR_TOOLTIP"}, { [kTechDataId] = kTechId.DoorLock, [kTechDataDisplayName] = "LOCK_DOOR", [kTechDataHotkey] = Move.L, [kTechDataTooltipInfo] = "LOCKED_DOOR_TOOLTIP"}, { [kTechDataId] = kTechId.DoorUnlock, [kTechDataDisplayName] = "UNLOCK_DOOR", [kTechDataHotkey] = Move.U, [kTechDataTooltipInfo] = "UNLOCK_DOOR_TOOLTIP"}, // Marine Commander abilities { [kTechDataId] = kTechId.NanoShieldTech, [kTechDataDisplayName] = "NANO_SHIELD_TECH", [kTechDataTooltipInfo] = "NANO_SHIELD_DEFENSE_TOOLTIP", [kTechDataCostKey] = kNanoShieldResearchCost, [kTechDataResearchTimeKey] = kNanoSnieldResearchTime }, { [kTechDataId] = kTechId.PowerSurge, [kTechDataCooldown] = kPowerSurgeCooldown, [kTechDataAllowStacking] = true, [kTechDataIgnorePathingMesh] = true, [kTechDataDisplayName] = "POWER_SURGE", [kTechDataCostKey] = kPowerSurgeCost, [kTechDataTooltipInfo] = "POWER_SURGE_TOOLTIP" }, { [kTechDataId] = kTechId.NanoShield, [kTechDataCooldown] = kNanoShieldCooldown, [kTechDataAllowStacking] = true, [kTechDataIgnorePathingMesh] = true, [kTechDataMapName] = NanoShield.kMapName, [kTechDataDisplayName] = "NANO_SHIELD_DEFENSE", [kTechDataCostKey] = kNanoShieldCost, [kTechDataTooltipInfo] = "NANO_SHIELD_DEFENSE_TOOLTIP" }, { [kTechDataId] = kTechId.AmmoPack, [kTechDataAllowStacking] = true, [kTechDataIgnorePathingMesh] = true, [kTechDataMapName] = AmmoPack.kMapName, [kTechDataDisplayName] = "AMMO_PACK", [kTechDataCostKey] = kAmmoPackCost, [kTechDataModel] = AmmoPack.kModelName, [kTechDataTooltipInfo] = "AMMO_PACK_TOOLTIP", [kTechDataSpawnHeightOffset] = kCommanderDropSpawnHeight }, { [kTechDataId] = kTechId.MedPack, [kTechDataCooldown] = kMedPackCooldown, [kTechDataAllowStacking] = true, [kTechDataIgnorePathingMesh] = true, [kTechDataMapName] = MedPack.kMapName, [kTechDataDisplayName] = "MED_PACK", [kTechDataCostKey] = kMedPackCost, [kTechDataModel] = MedPack.kModelName, [kTechDataTooltipInfo] = "MED_PACK_TOOLTIP", [kTechDataSpawnHeightOffset] = kCommanderDropSpawnHeight}, { [kTechDataId] = kTechId.CatPack, [kTechDataAllowStacking] = true, [kTechDataIgnorePathingMesh] = true, [kTechDataMapName] = CatPack.kMapName, [kTechDataDisplayName] = "CAT_PACK", [kTechDataCostKey] = kCatPackCost, [kTechDataModel] = CatPack.kModelName, [kTechDataTooltipInfo] = "CAT_PACK_TOOLTIP", [kTechDataSpawnHeightOffset] = kCommanderDropSpawnHeight}, { [kTechDataId] = kTechId.Scan, [kTechDataCooldown] = kScanCooldown, [kTechDataAllowStacking] = true, [kTechDataCollideWithWorldOnly] = true, [kTechDataIgnorePathingMesh] = true, [kTechDataMapName] = Scan.kMapName, [kTechDataDisplayName] = "SCAN", [kTechDataHotkey] = Move.S, [kTechDataCostKey] = kObservatoryScanCost, [kTechDataTooltipInfo] = "SCAN_TOOLTIP"}, // Command station and its buildables { [kTechDataId] = kTechId.CommandStation, [kTechDataIgnorePathingMesh] = true, [kTechDataSpawnBlock] = true, [kTechDataMaxExtents] = Vector(1.5, 1, 0.4), [kTechDataHint] = "COMMAND_STATION_HINT", [kTechDataAllowStacking] = true, [kStructureAttachClass] = "TechPoint", [kTechDataAttachOptional] = false, [kTechDataOverrideCoordsMethod] = OptionalAttachToFreeTechPoint, [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataMapName] = CommandStation.kMapName, [kTechDataDisplayName] = "COMMAND_STATION", [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataBuildTime] = kCommandStationBuildTime, [kTechDataCostKey] = kCommandStationCost, [kTechDataModel] = CommandStation.kModelName, [kTechDataMaxHealth] = kCommandStationHealth, [kTechDataMaxArmor] = kCommandStationArmor, [kTechDataSpawnHeightOffset] = 0, [kTechDataEngagementDistance] = kCommandStationEngagementDistance, [kTechDataInitialEnergy] = kCommandStationInitialEnergy, [kTechDataMaxEnergy] = kCommandStationMaxEnergy, [kTechDataPointValue] = kCommandStationPointValue, [kTechDataHotkey] = Move.C, [kTechDataTooltipInfo] = "COMMAND_STATION_TOOLTIP", [kTechDataObstacleRadius] = 2 }, { [kTechDataId] = kTechId.Recycle, [kTechDataDisplayName] = "RECYCLE", [kTechDataCostKey] = 0, [kTechIDShowEnables] = false, [kTechDataResearchTimeKey] = kRecycleTime, [kTechDataHotkey] = Move.R, [kTechDataTooltipInfo] = "RECYCLE_TOOLTIP" }, { [kTechDataId] = kTechId.MAC, [kTechDataSupply] = kMACSupply, [kTechDataHint] = "MAC_HINT", [kTechDataMapName] = MAC.kMapName, [kTechDataDisplayName] = "MAC", [kTechDataMaxHealth] = MAC.kHealth, [kTechDataMaxArmor] = MAC.kArmor, [kTechDataCostKey] = kMACCost, [kTechDataResearchTimeKey] = kMACBuildTime, [kTechDataModel] = MAC.kModelName, [kTechDataDamageType] = kMACAttackDamageType, [kTechDataInitialEnergy] = kMACInitialEnergy, [kTechDataMaxEnergy] = kMACMaxEnergy, [kTechDataMenuPriority] = 1, [kTechDataPointValue] = kMACPointValue, [kTechDataHotkey] = Move.M, [kTechDataTooltipInfo] = "MAC_TOOLTIP" }, { [kTechDataId] = kTechId.CatPackTech, [kTechDataCostKey] = kCatPackTechResearchCost, [kTechDataResearchTimeKey] = kCatPackTechResearchTime, [kTechDataDisplayName] = "CAT_PACKS", [kTechDataTooltipInfo] = "CAT_PACK_TECH_TOOLTIP" }, // Marine base structures { [kTechDataId] = kTechId.Extractor, [kTechDataIgnorePathingMesh] = true, [kTechDataSpawnBlock] = true, [kTechDataHint] = "EXTRACTOR_HINT", [kTechDataCollideWithWorldOnly] = true, [kTechDataAllowStacking] = true, [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataRequiresPower] = true, [kTechDataMapName] = Extractor.kMapName, [kTechDataDisplayName] = "EXTRACTOR", [kTechDataCostKey] = kExtractorCost, [kTechDataBuildTime] = kExtractorBuildTime, [kTechDataEngagementDistance] = kExtractorEngagementDistance, [kTechDataModel] = Extractor.kModelName, [kTechDataMaxHealth] = kExtractorHealth, [kTechDataMaxArmor] = kExtractorArmor, [kStructureAttachClass] = "ResourcePoint", [kTechDataPointValue] = kExtractorPointValue, [kTechDataHotkey] = Move.E, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataTooltipInfo] = "EXTRACTOR_TOOLTIP" }, { [kTechDataId] = kTechId.ExtractorArmor, [kTechDataCostKey] = kExtractorArmorCost, [kTechDataResearchTimeKey] = kExtractorArmorResearchTime, [kTechDataDisplayName] = "EXTRACTOR_ARMOR", [kTechDataTooltipInfo] = "EXTRACTOR_ARMOR_TOOLTIP", }, { [kTechDataId] = kTechId.InfantryPortal, [kTechDataHint] = "INFANTRY_PORTAL_HINT", [kTechDataSupply] = kInfantryPortalSupply, [kTechDataMaxExtents] = kStructureMediumExtents, [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataRequiresPower] = true, [kTechDataGhostGuidesMethod] = GetInfantryPortalGhostGuides, [kTechDataBuildRequiresMethod] = GetCommandStationIsBuilt, [kTechDataMapName] = InfantryPortal.kMapName, [kTechDataDisplayName] = "INFANTRY_PORTAL", [kTechDataCostKey] = kInfantryPortalCost, [kTechDataPointValue] = kInfantryPortalPointValue, [kTechDataBuildTime] = kInfantryPortalBuildTime, [kTechDataMaxHealth] = kInfantryPortalHealth, [kTechDataMaxArmor] = kInfantryPortalArmor, [kTechDataModel] = InfantryPortal.kModelName, [kStructureBuildNearClass] = "CommandStation", [kStructureAttachId] = kTechId.CommandStation, [kStructureAttachRange] = kInfantryPortalAttachRange, [kTechDataEngagementDistance] = kInfantryPortalEngagementDistance, [kTechDataHotkey] = Move.P, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataTooltipInfo] = "INFANTRY_PORTAL_TOOLTIP" }, { [kTechDataId] = kTechId.Armory, [kTechDataSupply] = kArmorySupply, [kTechDataHint] = "ARMORY_HINT", [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataMaxExtents] = kStructureMediumExtents, [kTechDataRequiresPower] = true, [kTechDataMapName] = Armory.kMapName, [kTechDataDisplayName] = "ARMORY", [kTechDataCostKey] = kArmoryCost, [kTechDataBuildTime] = kArmoryBuildTime, [kTechDataMaxHealth] = kArmoryHealth, [kTechDataMaxArmor] = kArmoryArmor, [kTechDataEngagementDistance] = kArmoryEngagementDistance, [kTechDataModel] = Armory.kModelName, [kTechDataPointValue] = kArmoryPointValue, [kTechDataInitialEnergy] = kArmoryInitialEnergy, [kTechDataMaxEnergy] = kArmoryMaxEnergy, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataTooltipInfo] = "ARMORY_TOOLTIP" }, { [kTechDataId] = kTechId.ArmsLab, [kTechDataSupply] = kArmsLabSupply, [kTechDataHint] = "ARMSLAB_HINT", [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataMaxExtents] = kStructureMediumExtents, [kTechDataRequiresPower] = true, [kTechDataMapName] = ArmsLab.kMapName, [kTechDataDisplayName] = "ARMS_LAB", [kTechDataCostKey] = kArmsLabCost, [kTechDataBuildTime] = kArmsLabBuildTime, [kTechDataMaxHealth] = kArmsLabHealth, [kTechDataMaxArmor] = kArmsLabArmor, [kTechDataEngagementDistance] = kArmsLabEngagementDistance, [kTechDataModel] = ArmsLab.kModelName, [kTechDataPointValue] = kArmsLabPointValue, [kTechDataHotkey] = Move.A, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataTooltipInfo] = "ARMS_LAB_TOOLTIP", [kTechDataObstacleRadius] = 0.25 }, { [kTechDataId] = kTechId.Sentry, [kTechDataSupply] = kSentrySupply, [kTechDataBuildMethodFailedMessage] = "COMMANDERERROR_TOO_MANY_SENTRIES", [kTechDataHint] = "SENTRY_HINT", [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataMaxExtents] = kStructureSmallExtents, [kTechDataMapName] = Sentry.kMapName, [kTechDataDisplayName] = "SENTRY_TURRET", [kTechDataCostKey] = kSentryCost, [kTechDataPointValue] = kSentryPointValue, [kTechDataModel] = Sentry.kModelName, [kTechDataBuildTime] = kSentryBuildTime, [kTechDataMaxHealth] = kSentryHealth, [kTechDataMaxArmor] = kSentryArmor, [kTechDataDamageType] = kSentryAttackDamageType, [kTechDataSpecifyOrientation] = true, [kTechDataHotkey] = Move.S, [kTechDataInitialEnergy] = kSentryInitialEnergy, [kTechDataMaxEnergy] = kSentryMaxEnergy, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataEngagementDistance] = kSentryEngagementDistance, [kTechDataTooltipInfo] = "SENTRY_TOOLTIP", [kStructureBuildNearClass] = "SentryBattery", [kStructureAttachRange] = SentryBattery.kRange, [kTechDataBuildRequiresMethod] = GetCheckSentryLimit, [kTechDataGhostGuidesMethod] = GetBatteryInRange, [kTechDataObstacleRadius] = 0.25 }, { [kTechDataId] = kTechId.SentryBattery, [kTechDataSupply] = kSentryBatterySupply, [kTechDataBuildRequiresMethod] = GetRoomHasNoSentryBattery, [kTechDataBuildMethodFailedMessage] = "COMMANDERERROR_ONLY_ONE_BATTERY_PER_ROOM", [kTechDataHint] = "SENTRY_BATTERY_HINT", [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataMaxExtents] = kStructureSmallExtents, [kTechDataMapName] = SentryBattery.kMapName, [kTechDataDisplayName] = "SENTRY_BATTERY", [kTechDataCostKey] = kSentryBatteryCost, [kTechDataPointValue] = kSentryBatteryPointValue, [kTechDataModel] = SentryBattery.kModelName, [kTechDataEngagementDistance] = 2, [kTechDataBuildTime] = kSentryBatteryBuildTime, [kTechDataMaxHealth] = kSentryBatteryHealth, [kTechDataMaxArmor] = kSentryBatteryArmor, [kTechDataTooltipInfo] = "SENTRY_BATTERY_TOOLTIP", [kTechDataHotkey] = Move.S, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kVisualRange] = SentryBattery.kRange, [kTechDataObstacleRadius] = 0.25 }, // MACs { [kTechDataId] = kTechId.MACEMP, [kTechDataDisplayName] = "MAC_EMP", [kTechDataTooltipInfo] = "MAC_EMP_TOOLTIP", [kTechDataCostKey] = kEMPCost, [kTechDataCooldown] = kMACEMPCooldown }, { [kTechDataId] = kTechId.MACEMPTech, [kTechDataDisplayName] = "MAC_EMP_RESEARCH", [kTechDataTooltipInfo] = "MAC_EMP_RESEARCH_TOOLTIP", [kTechDataCostKey] = kTechEMPResearchCost, [kTechDataResearchTimeKey] = kTechEMPResearchTime, }, { [kTechDataId] = kTechId.MACSpeedTech, [kTechDataDisplayName] = "MAC_SPEED", [kTechDataCostKey] = kTechMACSpeedResearchCost, [kTechDataResearchTimeKey] = kTechMACSpeedResearchTime, [kTechDataHotkey] = Move.S, [kTechDataTooltipInfo] = "MAC_SPEED_TOOLTIP" }, // Marine advanced structures { [kTechDataId] = kTechId.AdvancedArmory, [kTechDataSupply] = kAdvancedArmorySupply, [kTechDataHint] = "ADVANCED_ARMORY_HINT", [kTechDataTooltipInfo] = "ADVANCED_ARMORY_TOOLTIP", [kTechDataGhostModelClass] = "MarineGhostModel", [kTechIDShowEnables] = false, [kTechDataRequiresPower] = true, [kTechDataMapName] = AdvancedArmory.kMapName, [kTechDataDisplayName] = "ADVANCED_ARMORY", [kTechDataCostKey] = kAdvancedArmoryUpgradeCost, [kTechDataModel] = Armory.kModelName, [kTechDataMaxHealth] = kAdvancedArmoryHealth, [kTechDataMaxArmor] = kAdvancedArmoryArmor, [kTechDataEngagementDistance] = kArmoryEngagementDistance, [kTechDataUpgradeTech] = kTechId.Armory, [kTechDataPointValue] = kAdvancedArmoryPointValue }, { [kTechDataId] = kTechId.AdvancedArmoryUpgrade, [kTechDataSupply] = kAdvancedArmorySupply, [kTechDataCostKey] = kAdvancedArmoryUpgradeCost, [kTechIDShowEnables] = false, [kTechDataResearchTimeKey] = kAdvancedArmoryResearchTime, [kTechDataHotkey] = Move.U, [kTechDataDisplayName] = "ADVANCED_ARMORY_UPGRADE", [kTechDataTooltipInfo] = "ADVANCED_ARMORY_TOOLTIP" }, { [kTechDataId] = kTechId.Observatory, [kTechDataSupply] = kObservatorySupply, [kTechDataMaxExtents] = kStructureMediumExtents, [kTechDataHint] = "OBSERVATORY_HINT", [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataRequiresPower] = true, [kTechDataMapName] = Observatory.kMapName, [kTechDataDisplayName] = "OBSERVATORY", [kVisualRange] = Observatory.kDetectionRange, [kTechDataCostKey] = kObservatoryCost, [kTechDataModel] = Observatory.kModelName, [kTechDataBuildTime] = kObservatoryBuildTime, [kTechDataMaxHealth] = kObservatoryHealth, [kTechDataEngagementDistance] = kObservatoryEngagementDistance, [kTechDataMaxArmor] = kObservatoryArmor, [kTechDataInitialEnergy] = kObservatoryInitialEnergy, [kTechDataMaxEnergy] = kObservatoryMaxEnergy, [kTechDataPointValue] = kObservatoryPointValue, [kTechDataHotkey] = Move.O, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataTooltipInfo] = "OBSERVATORY_TOOLTIP", [kTechDataObstacleRadius] = 0.25 }, { [kTechDataId] = kTechId.DistressBeacon, [kTechDataBuildTime] = 0.1, [kTechDataDisplayName] = "DISTRESS_BEACON", [kTechDataHotkey] = Move.B, [kTechDataCostKey] = kObservatoryDistressBeaconCost, [kTechDataTooltipInfo] = "DISTRESS_BEACON_TOOLTIP" }, { [kTechDataId] = kTechId.RoboticsFactory, [kTechDataSupply] = kRoboticsFactorySupply, [kTechDataMaxExtents] = kStructureLargeExtents, [kTechDataHint] = "ROBOTICS_FACTORY_HINT", [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataRequiresPower] = true, [kTechDataDisplayName] = "ROBOTICS_FACTORY", [kTechDataMapName] = RoboticsFactory.kMapName, [kTechDataCostKey] = kRoboticsFactoryCost, [kTechDataModel] = RoboticsFactory.kModelName, [kTechDataEngagementDistance] = kRoboticsFactorEngagementDistance, [kTechDataSpecifyOrientation] = true, [kTechDataBuildTime] = kRoboticsFactoryBuildTime, [kTechDataMaxHealth] = kRoboticsFactoryHealth, [kTechDataMaxArmor] = kRoboticsFactoryArmor, [kTechDataPointValue] = kRoboticsFactoryPointValue, [kTechDataHotkey] = Move.R, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataTooltipInfo] = "ROBOTICS_FACTORY_TOOLTIP", [kTechDataObstacleRadius] = 2 }, { [kTechDataId] = kTechId.UpgradeRoboticsFactory, [kTechDataSupply] = kARCRoboticsFactorySupply, [kTechDataDisplayName] = "UPGRADE_ROBOTICS_FACTORY", [kTechIDShowEnables] = false, [kTechDataCostKey] = kUpgradeRoboticsFactoryCost, [kTechDataResearchTimeKey] = kUpgradeRoboticsFactoryTime, [kTechDataTooltipInfo] = "UPGRADE_ROBOTICS_FACTORY_TOOLTIP" }, { [kTechDataId] = kTechId.ARCRoboticsFactory, [kTechDataSupply] = kARCRoboticsFactorySupply, [kTechDataCostKey] = kRoboticsFactoryCost + kUpgradeRoboticsFactoryCost, [kTechDataHint] = "ARC_ROBOTICS_FACTORY_HINT", [kTechDataRequiresPower] = true, [kTechIDShowEnables] = false, [kTechDataDisplayName] = "ARC_ROBOTICS_FACTORY", [kTechDataMapName] = ARCRoboticsFactory.kMapName, [kTechDataModel] = RoboticsFactory.kModelName, [kTechDataEngagementDistance] = kRoboticsFactorEngagementDistance, [kTechDataSpecifyOrientation] = true, [kTechDataBuildTime] = kRoboticsFactoryBuildTime, [kTechDataMaxHealth] = kARCRoboticsFactoryHealth, [kTechDataMaxArmor] = kARCRoboticsFactoryArmor, [kTechDataPointValue] = kARCRoboticsFactoryPointValue, [kTechDataHotkey] = Move.R, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataTooltipInfo] = "ARC_ROBOTICS_FACTORY_TOOLTIP" }, { [kTechDataId] = kTechId.ARC, [kTechDataSupply] = kARCSupply, [kTechDataHint] = "ARC_HINT", [kTechDataDisplayName] = "ARC", [kTechDataTooltipInfo] = "ARC_TOOLTIP", [kTechDataMapName] = ARC.kMapName, [kTechDataCostKey] = kARCCost, [kTechDataDamageType] = kARCDamageType, [kTechDataResearchTimeKey] = kARCBuildTime, [kTechDataMaxHealth] = kARCHealth, [kTechDataEngagementDistance] = kARCEngagementDistance, [kVisualRange] = ARC.kFireRange, [kTechDataMaxArmor] = kARCArmor, [kTechDataModel] = ARC.kModelName, [kTechDataMaxHealth] = kARCHealth, [kTechDataPointValue] = kARCPointValue, [kTechDataHotkey] = Move.T }, { [kTechDataId] = kTechId.ARCSplashTech, [kTechDataCostKey] = kARCSplashTechResearchCost, [kTechDataResearchTimeKey] = kARCSplashTechResearchTime, [kTechDataDisplayName] = "ARC_SPLASH", [kTechDataImplemented] = false }, { [kTechDataId] = kTechId.ARCArmorTech, [kTechDataCostKey] = kARCArmorTechResearchCost, [kTechDataResearchTimeKey] = kARCArmorTechResearchTime, [kTechDataDisplayName] = "ARC_ARMOR", [kTechDataImplemented] = false }, // Upgrades { [kTechDataId] = kTechId.PhaseTech, [kTechDataCostKey] = kPhaseTechResearchCost, [kTechDataDisplayName] = "PHASE_TECH", [kTechDataResearchTimeKey] = kPhaseTechResearchTime, [kTechDataTooltipInfo] = "PHASE_TECH_TOOLTIP" }, { [kTechDataId] = kTechId.PhaseGate, [kTechDataHint] = "PHASE_GATE_HINT", [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataSupply] = kPhaseGateSupply, [kTechDataMaxExtents] = kStructureMediumExtents, [kTechDataRequiresPower] = true, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataMapName] = PhaseGate.kMapName, [kTechDataDisplayName] = "PHASE_GATE", [kTechDataCostKey] = kPhaseGateCost, [kTechDataModel] = PhaseGate.kModelName, [kTechDataBuildTime] = kPhaseGateBuildTime, [kTechDataMaxHealth] = kPhaseGateHealth, [kTechDataEngagementDistance] = kPhaseGateEngagementDistance, [kTechDataMaxArmor] = kPhaseGateArmor, [kTechDataPointValue] = kPhaseGatePointValue, [kTechDataHotkey] = Move.P, [kTechDataSpecifyOrientation] = true, [kTechDataBuildRequiresMethod] = CheckSpaceForPhaseGate, [kTechDataTooltipInfo] = "PHASE_GATE_TOOLTIP", [kTechDataObstacleRadius] = 0.5 }, { [kTechDataId] = kTechId.PrototypeLab, [kTechDataSupply] = kPrototypeLabSupply, [kTechDataMaxExtents] = kStructureMediumExtents, [kTechDataHint] = "PROTOTYPE_LAB_HINT", [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataRequiresPower] = true, [kTechDataMapName] = PrototypeLab.kMapName, [kTechDataNotOnInfestation] = kPreventMarineStructuresOnInfestation, [kTechDataCostKey] = kPrototypeLabCost, [kTechDataResearchTimeKey] = kPrototypeLabBuildTime, [kTechDataDisplayName] = "PROTOTYPE_LAB", [kTechDataModel] = PrototypeLab.kModelName, [kTechDataMaxHealth] = kPrototypeLabHealth, [kTechDataPointValue] = kPrototypeLabPointValue, [kTechDataTooltipInfo] = "PROTOTYPE_LAB_TOOLTIP", [kTechDataObstacleRadius] = 0.5 }, // Weapons { [kTechDataId] = kTechId.MinesTech, [kTechDataCostKey] = kMineResearchCost, [kTechDataResearchTimeKey] = kMineResearchTime, [kTechDataDisplayName] = "MINES" }, { [kTechDataId] = kTechId.DemoMines, [kTechDataMapName] = DemoMines.kMapName, [kTechDataDisplayName] = "DEMOMINES", [kTechDataModel] = Mine.kModelName, [kTechDataCostKey] = kMineCost }, { [kTechDataId] = kTechId.Mine, [kTechDataMapName] = Mine.kMapName, [kTechDataHint] = "MINE_HINT", [kTechDataDisplayName] = "MINE", [kTechDataEngagementDistance] = kMineDetonateRange, [kTechDataMaxHealth] = kMineHealth, [kTechDataTooltipInfo] = "MINE_TOOLTIP", [kTechDataMaxArmor] = kMineArmor, [kTechDataModel] = Mine.kModelName, [kTechDataPointValue] = kMinePointValue, }, { [kTechDataId] = kTechId.WelderTech, [kTechDataCostKey] = kWelderTechResearchCost, [kTechDataResearchTimeKey] = kWelderTechResearchTime, [kTechDataDisplayName] = "RESEARCH_WELDER", [kTechDataHotkey] = Move.F, [kTechDataTooltipInfo] = "WELDER_TECH_TOOLTIP" }, { [kTechDataId] = kTechId.Welder, [kTechDataMaxHealth] = kMarineWeaponHealth, [kTechDataMapName] = Welder.kMapName, [kTechDataDisplayName] = "WELDER", [kTechDataModel] = Welder.kModelName, [kTechDataDamageType] = kWelderDamageType, [kTechDataCostKey] = kWelderCost }, { [kTechDataId] = kTechId.Claw, [kTechDataMapName] = Claw.kMapName, [kTechDataDisplayName] = "CLAW", [kTechDataDamageType] = kClawDamageType }, { [kTechDataId] = kTechId.Rifle, [kTechDataMaxHealth] = kMarineWeaponHealth, [kTechDataTooltipInfo] = "RIFLE_TOOLTIP", [kTechDataMapName] = Rifle.kMapName, [kTechDataDisplayName] = "RIFLE", [kTechDataModel] = Rifle.kModelName, [kTechDataDamageType] = kRifleDamageType, [kTechDataCostKey] = kRifleCost, }, { [kTechDataId] = kTechId.Pistol, [kTechDataMaxHealth] = kMarineWeaponHealth, [kTechDataMapName] = Pistol.kMapName, [kTechDataDisplayName] = "PISTOL", [kTechDataModel] = Pistol.kModelName, [kTechDataDamageType] = kPistolDamageType, [kTechDataCostKey] = kPistolCost, [kTechDataTooltipInfo] = "PISTOL_TOOLTIP"}, { [kTechDataId] = kTechId.Axe, [kTechDataMapName] = Axe.kMapName, [kTechDataDisplayName] = "SWITCH_AX", [kTechDataModel] = Axe.kModelName, [kTechDataDamageType] = kAxeDamageType, [kTechDataCostKey] = kAxeCost, [kTechDataTooltipInfo] = "AXE_TOOLTIP" }, { [kTechDataId] = kTechId.Shotgun, [kTechDataMaxHealth] = kMarineWeaponHealth, [kTechDataPointValue] = kShotgunPointValue, [kTechDataMapName] = Shotgun.kMapName, [kTechDataDisplayName] = "SHOTGUN", [kTechDataTooltipInfo] = "SHOTGUN_TOOLTIP", [kTechDataModel] = Shotgun.kModelName, [kTechDataDamageType] = kShotgunDamageType, [kTechDataCostKey] = kShotgunCost, [kStructureAttachId] = kTechId.Armory, [kStructureAttachRange] = kArmoryWeaponAttachRange, [kStructureAttachRequiresPower] = true }, { [kTechDataId] = kTechId.HeavyRifle, [kTechDataMaxHealth] = kMarineWeaponHealth, [kTechDataTooltipInfo] = "HEAVY_RIFLE_TOOLTIP", [kTechDataPointValue] = kWeaponPointValue, [kTechDataMapName] = HeavyRifle.kMapName, [kTechDataDisplayName] = "HEAVY_RIFLE", [kTechDataModel] = HeavyRifle.kModelName, [kTechDataDamageType] = kHeavyRifleDamageType, [kTechDataCostKey] = kHeavyRifleCost, }, // hand grenades { [kTechDataId] = kTechId.ClusterGrenade, [kTechDataMapName] = ClusterGrenadeThrower.kMapName, [kTechDataDisplayName] = "CLUSTER_GRENADE", [kTechDataTooltipInfo] = "CLUSTER_GRENADE_TOOLTIP", [kTechDataCostKey] = kClusterGrenadeCost }, { [kTechDataId] = kTechId.GasGrenade, [kTechDataMapName] = GasGrenadeThrower.kMapName, [kTechDataDisplayName] = "GAS_GRENADE", [kTechDataTooltipInfo] = "GAS_GRENADE_TOOLTIP", [kTechDataCostKey] = kGasGrenadeCost }, { [kTechDataId] = kTechId.PulseGrenade, [kTechDataMapName] = PulseGrenadeThrower.kMapName, [kTechDataDisplayName] = "PULSE_GRENADE", [kTechDataTooltipInfo] = "PULSE_GRENADE_TOOLTIP", [kTechDataCostKey] = kPulseGrenadeCost }, { [kTechDataId] = kTechId.ClusterGrenadeProjectile, [kTechDataDamageType] = kClusterGrenadeDamageType, [kTechDataMapName] = ClusterGrenade.kMapName, [kTechDataDisplayName] = "CLUSTER_GRENADE", [kTechDataTooltipInfo] = "CLUSTER_GRENADE_TOOLTIP", }, { [kTechDataId] = kTechId.GasGrenadeProjectile, [kTechDataDamageType] = kNerveGasDamageType, [kTechDataMapName] = GasGrenade.kMapName, [kTechDataDisplayName] = "GAS_GRENADE", [kTechDataTooltipInfo] = "GAS_GRENADE_TOOLTIP", }, { [kTechDataId] = kTechId.PulseGrenadeProjectile, [kTechDataDamageType] = kPulseGrenadeDamageType, [kTechDataMapName] = PulseGrenade.kMapName, [kTechDataDisplayName] = "PULSE_GRENADE", [kTechDataTooltipInfo] = "PULSE_GRENADE_TOOLTIP", }, /* { [kTechDataId] = kTechId.NerveGasCloud, [kTechDataDamageType] = kNerveGasDamageType, [kTechDataMapName] = NerveGasCloud.kMapName, [kTechDataDisplayName] = "NERVE_GAS", }, */ // dropped by commander: { [kTechDataId] = kTechId.FlamethrowerTech, [kTechDataCostKey] = kFlamethrowerTechResearchCost, [kTechDataResearchTimeKey] = kFlamethrowerTechResearchTime, [kTechDataDisplayName] = "RESEARCH_FLAMETHROWERS", [kTechDataTooltipInfo] = "FLAMETHROWER_TECH_TOOLTIP" }, { [kTechDataId] = kTechId.FlamethrowerRangeTech, [kTechDataCostKey] = kFlamethrowerRangeTechResearchCost, [kTechDataResearchTimeKey] = kFlamethrowerRangeTechResearchTime, [kTechDataDisplayName] = "FLAMETHROWER_RANGE", [kTechDataTooltipInfo] = "FLAMETHROWER_RANGE_TOOLTIP" }, { [kTechDataId] = kTechId.Flamethrower, [kTechDataMaxHealth] = kMarineWeaponHealth, [kTechDataPointValue] = kFlamethrowerPointValue, [kTechDataMapName] = Flamethrower.kMapName, [kTechDataDisplayName] = "FLAMETHROWER", [kTechDataTooltipInfo] = "FLAMETHROWER_TOOLTIP", [kTechDataModel] = Flamethrower.kModelName, [kTechDataDamageType] = kFlamethrowerDamageType, [kTechDataCostKey] = kFlamethrowerCost, [kStructureAttachId] = kTechId.Armory, [kStructureAttachRange] = kArmoryWeaponAttachRange, [kStructureAttachRequiresPower] = true }, { [kTechDataId] = kTechId.DualMinigunTech, [kTechDataCostKey] = kDualMinigunTechResearchCost, [kTechDataResearchTimeKey] = kDualRailgunTechResearchTime, [kTechDataDisplayName] = "RESEARCH_DUAL_MINIGUNS", [kTechDataHotkey] = Move.D, [kTechDataTooltipInfo] = "DUAL_MINIGUN_TECH_TOOLTIP" }, { [kTechDataId] = kTechId.ClawRailgunTech, [kTechIDShowEnables] = false, [kTechDataCostKey] = kClawRailgunTechResearchCost, [kTechDataResearchTimeKey] = kClawMinigunTechResearchTime, [kTechDataDisplayName] = "RESEARCH_CLAW_RAILGUN", [kTechDataHotkey] = Move.D, [kTechDataTooltipInfo] = "CLAW_RAILGUN_TECH_TOOLTIP" }, { [kTechDataId] = kTechId.DualRailgunTech, [kTechIDShowEnables] = false, [kTechDataCostKey] = kDualRailgunTechResearchCost, [kTechDataResearchTimeKey] = kDualMinigunTechResearchTime, [kTechDataDisplayName] = "RESEARCH_DUAL_RAILGUNS", [kTechDataHotkey] = Move.D, [kTechDataTooltipInfo] = "DUAL_RAILGUN_TECH_TOOLTIP"}, { [kTechDataId] = kTechId.Minigun, [kTechDataPointValue] = kMinigunPointValue, [kTechDataMapName] = Minigun.kMapName, [kTechDataDisplayName] = "MINIGUN", [kTechDataDamageType] = kMinigunDamageType, [kTechDataDisplayName] = "MINIGUN_CLAW_TOOLTIP", [kTechDataModel] = Minigun.kModelName }, { [kTechDataId] = kTechId.Railgun, [kTechDataPointValue] = kRailgunPointValue, [kTechDataMapName] = Railgun.kMapName, [kTechDataDisplayName] = "RAILGUN", [kTechDataDamageType] = kRailgunDamageType, [kTechDataDisplayName] = "RAILGUN_CLAW_TOOLTIP", [kTechDataModel] = Railgun.kModelName}, { [kTechDataId] = kTechId.GrenadeLauncher, [kTechDataMaxHealth] = kMarineWeaponHealth, [kTechDataPointValue] = kGrenadeLauncherPointValue, [kTechDataMapName] = GrenadeLauncher.kMapName, [kTechDataDisplayName] = "GRENADE_LAUNCHER", [kTechDataTooltipInfo] = "GRENADE_LAUNCHER_TOOLTIP", [kTechDataModel] = GrenadeLauncher.kModelName, [kTechDataDamageType] = kRifleDamageType, [kTechDataCostKey] = kGrenadeLauncherCost, [kStructureAttachId] = kTechId.Armory, [kStructureAttachRange] = kArmoryWeaponAttachRange, [kStructureAttachRequiresPower] = true}, { [kTechDataId] = kTechId.DropShotgun, [kTechDataMapName] = Shotgun.kMapName, [kTechDataDisplayName] = "SHOTGUN", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "SHOTGUN_TOOLTIP", [kTechDataModel] = Shotgun.kModelName, [kTechDataCostKey] = kShotgunDropCost, [kStructureAttachId] = { kTechId.Armory, kTechId.AdvancedArmory }, [kStructureAttachRange] = kArmoryWeaponAttachRange, [kStructureAttachRequiresPower] = true }, { [kTechDataId] = kTechId.DropWelder, [kTechDataMapName] = Welder.kMapName, [kTechDataDisplayName] = "WELDER", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "WELDER_TOOLTIP", [kTechDataModel] = Welder.kModelName, [kTechDataCostKey] = kWelderDropCost, [kStructureAttachId] = { kTechId.Armory, kTechId.AdvancedArmory }, [kStructureAttachRange] = kArmoryWeaponAttachRange, [kStructureAttachRequiresPower] = true }, { [kTechDataId] = kTechId.DropDemoMines, [kTechDataMapName] = DemoMines.kMapName, [kTechDataDisplayName] = "MINE", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "MINE_TOOLTIP", [kTechDataModel] = DemoMines.kModelName, [kTechDataCostKey] = kDropMineCost, [kStructureAttachId] = { kTechId.Armory, kTechId.AdvancedArmory }, [kStructureAttachRange] = kArmoryWeaponAttachRange, [kStructureAttachRequiresPower] = true }, { [kTechDataId] = kTechId.DropGrenadeLauncher, [kTechDataMapName] = GrenadeLauncher.kMapName, [kTechIDShowEnables] = false, [kTechDataDisplayName] = "GRENADE_LAUNCHER", [kTechDataTooltipInfo] = "GRENADE_LAUNCHER_TOOLTIP", [kTechDataModel] = GrenadeLauncher.kModelName, [kTechDataCostKey] = kGrenadeLauncherDropCost, [kStructureAttachId] = kTechId.AdvancedArmory, [kStructureAttachRange] = kArmoryWeaponAttachRange, [kStructureAttachRequiresPower] = true }, { [kTechDataId] = kTechId.DropFlamethrower, [kTechDataMapName] = Flamethrower.kMapName, [kTechDataDisplayName] = "FLAMETHROWER", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "FLAMETHROWER_TOOLTIP", [kTechDataModel] = Flamethrower.kModelName, [kTechDataCostKey] = kFlamethrowerDropCost, [kStructureAttachId] = kTechId.AdvancedArmory, [kStructureAttachRange] = kArmoryWeaponAttachRange, [kStructureAttachRequiresPower] = true }, { [kTechDataId] = kTechId.DropJetpack, [kTechDataMapName] = Jetpack.kMapName, [kTechDataDisplayName] = "JETPACK", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "JETPACK_TOOLTIP", [kTechDataModel] = Jetpack.kModelName, [kTechDataCostKey] = kJetpackDropCost, [kStructureAttachId] = kTechId.PrototypeLab, [kStructureAttachRange] = kArmoryWeaponAttachRange, [kStructureAttachRequiresPower] = true }, { [kTechDataId] = kTechId.DropExosuit, [kTechDataMapName] = Exosuit.kMapName, [kTechDataDisplayName] = "EXOSUIT", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "EXOSUIT_TOOLTIP", [kTechDataModel] = Exosuit.kModelName, [kTechDataCostKey] = kExosuitDropCost, [kStructureAttachId] = kTechId.PrototypeLab, [kStructureAttachRange] = kArmoryWeaponAttachRange, [kStructureAttachRequiresPower] = true }, // Armor and upgrades { [kTechDataId] = kTechId.Jetpack, [kTechDataMapName] = Jetpack.kMapName, [kTechDataDisplayName] = "JETPACK", [kTechDataModel] = Jetpack.kModelName, [kTechDataCostKey] = kJetpackCost, [kTechDataSpawnHeightOffset] = kCommanderEquipmentDropSpawnHeight }, { [kTechDataId] = kTechId.JetpackTech, [kTechDataCostKey] = kJetpackTechResearchCost, [kTechDataResearchTimeKey] = kJetpackTechResearchTime, [kTechDataDisplayName] = "JETPACK_TECH" }, { [kTechDataId] = kTechId.JetpackFuelTech, [kTechDataCostKey] = kJetpackFuelTechResearchCost, [kTechDataResearchTimeKey] = kJetpackFuelTechResearchTime, [kTechDataDisplayName] = "JETPACK_FUEL_TECH", [kTechDataHotkey] = Move.F, [kTechDataTooltipInfo] = "JETPACK_FUEL_TOOLTIP" }, { [kTechDataId] = kTechId.JetpackArmorTech, [kTechDataCostKey] = kJetpackArmorTechResearchCost, [kTechDataResearchTimeKey] = kJetpackArmorTechResearchTime, [kTechDataDisplayName] = "JETPACK_ARMOR_TECH", [kTechDataImplemented] = false, [kTechDataHotkey] = Move.S, [kTechDataTooltipInfo] = "JETPACK_ARMOR_TOOLTIP" }, { [kTechDataId] = kTechId.Exosuit, [kTechDataDisplayName] = "EXOSUIT", [kTechDataMapName] = "exo", [kTechDataCostKey] = kExosuitCost, [kTechDataHotkey] = Move.E, [kTechDataTooltipInfo] = "EXOSUIT_TECH_TOOLTIP", [kTechDataSpawnHeightOffset] = kCommanderEquipmentDropSpawnHeight }, { [kTechDataId] = kTechId.DualMinigunExosuit, [kTechIDShowEnables] = false, [kTechDataDisplayName] = "DUALMINIGUN_EXOSUIT", [kTechDataMapName] = "exo", [kTechDataCostKey] = kDualMinigunExosuitCost, [kTechDataHotkey] = Move.E, [kTechDataTooltipInfo] = "DUALMINIGUN_EXOSUIT_TECH_TOOLTIP", [kTechDataSpawnHeightOffset] = kCommanderEquipmentDropSpawnHeight }, { [kTechDataId] = kTechId.ClawRailgunExosuit, [kTechIDShowEnables] = false, [kTechDataDisplayName] = "CLAWRAILGUN_EXOSUIT", [kTechDataMapName] = "exo", [kTechDataCostKey] = kClawRailgunExosuitCost, [kTechDataHotkey] = Move.E, [kTechDataTooltipInfo] = "CLAWRAILGUN_EXOSUIT_TECH_TOOLTIP", [kTechDataSpawnHeightOffset] = kCommanderEquipmentDropSpawnHeight }, { [kTechDataId] = kTechId.DualRailgunExosuit, [kTechIDShowEnables] = false, [kTechDataDisplayName] = "DUALRAILGUN_EXOSUIT", [kTechDataMapName] = "exo", [kTechDataCostKey] = kDualRailgunExosuitCost, [kTechDataHotkey] = Move.E, [kTechDataTooltipInfo] = "DUALRAILGUN_EXOSUIT_TECH_TOOLTIP", [kTechDataSpawnHeightOffset] = kCommanderEquipmentDropSpawnHeight }, { [kTechDataId] = kTechId.ExosuitTech, [kTechDataDisplayName] = "RESEARCH_EXOSUITS", [kTechDataCostKey] = kExosuitTechResearchCost, [kTechDataResearchTimeKey] = kExosuitTechResearchTime }, { [kTechDataId] = kTechId.ExosuitLockdownTech, [kTechDataCostKey] = kExosuitLockdownTechResearchCost, [kTechDataResearchTimeKey] = kExosuitLockdownTechResearchTime, [kTechDataDisplayName] = "EXOSUIT_LOCKDOWN_TECH", [kTechDataImplemented] = false, [kTechDataHotkey] = Move.L, [kTechDataTooltipInfo] = "EXOSUIT_LOCKDOWN_TOOLTIP" }, { [kTechDataId] = kTechId.ExosuitUpgradeTech, [kTechDataCostKey] = kExosuitUpgradeTechResearchCost, [kTechDataResearchTimeKey] = kExosuitUpgradeTechResearchTime, [kTechDataDisplayName] = "EXOSUIT_UPGRADE_TECH", [kTechDataImplemented] = false }, { [kTechDataId] = kTechId.UpgradeToDualMinigun, [kTechIDShowEnables] = false, [kTechDataCostKey] = kUpgradeToDualMinigunCost, [kTechDataDisplayName] = "DUALMINIGUN_EXOSUIT" }, { [kTechDataId] = kTechId.UpgradeToDualRailgun, [kTechIDShowEnables] = false, [kTechDataCostKey] = kUpgradeToDualRailgunCost, [kTechDataDisplayName] = "DUALRAILGUN_EXOSUIT" }, // Armor research { [kTechDataId] = kTechId.Armor1, [kTechDataCostKey] = kArmor1ResearchCost, [kTechDataResearchTimeKey] = kArmor1ResearchTime, [kTechDataDisplayName] = "MARINE_ARMOR1", [kTechDataTooltipInfo] = "MARINE_ARMOR1_TOOLTIP" }, { [kTechDataId] = kTechId.Armor2, [kTechDataCostKey] = kArmor2ResearchCost, [kTechDataResearchTimeKey] = kArmor2ResearchTime, [kTechDataDisplayName] = "MARINE_ARMOR2", [kTechDataTooltipInfo] = "MARINE_ARMOR2_TOOLTIP" }, { [kTechDataId] = kTechId.Armor3, [kTechDataCostKey] = kArmor3ResearchCost, [kTechDataResearchTimeKey] = kArmor3ResearchTime, [kTechDataDisplayName] = "MARINE_ARMOR3", [kTechDataTooltipInfo] = "MARINE_ARMOR3_TOOLTIP" }, { [kTechDataId] = kTechId.Armor4, [kTechDataCostKey] = kArmor4ResearchCost, [kTechDataResearchTimeKey] = kArmor4ResearchTime, [kTechDataDisplayName] = "MARINE_ARMOR4", [kTechDataTooltipInfo] = "MARINE_ARMOR4_TOOLTIP" }, { [kTechDataId] = kTechId.NanoArmor, [kTechDataCostKey] = kNanoArmorResearchCost, [kTechDataResearchTimeKey] = kNanoArmorResearchTime, [kTechDataDisplayName] = "NANO_ARMOR", [kTechDataTooltipInfo] = "NANO_ARMOR_TOOLTIP" }, // Weapons research { [kTechDataId] = kTechId.Weapons1, [kTechDataCostKey] = kWeapons1ResearchCost, [kTechDataResearchTimeKey] = kWeapons1ResearchTime, [kTechDataDisplayName] = "MARINE_WEAPONS1", [kTechDataHotkey] = Move.Z, [kTechDataTooltipInfo] = "MARINE_WEAPONS1_TOOLTIP" }, { [kTechDataId] = kTechId.Weapons2, [kTechDataCostKey] = kWeapons2ResearchCost, [kTechDataResearchTimeKey] = kWeapons2ResearchTime, [kTechDataDisplayName] = "MARINE_WEAPONS2", [kTechDataHotkey] = Move.Z, [kTechDataTooltipInfo] = "MARINE_WEAPONS2_TOOLTIP" }, { [kTechDataId] = kTechId.Weapons3, [kTechDataCostKey] = kWeapons3ResearchCost, [kTechDataResearchTimeKey] = kWeapons3ResearchTime, [kTechDataDisplayName] = "MARINE_WEAPONS3", [kTechDataHotkey] = Move.Z, [kTechDataTooltipInfo] = "MARINE_WEAPONS3_TOOLTIP" }, { [kTechDataId] = kTechId.Weapons4, [kTechDataCostKey] = kWeapons4ResearchCost, [kTechDataResearchTimeKey] = kWeapons4ResearchTime, [kTechDataDisplayName] = "MARINE_WEAPONS4", [kTechDataHotkey] = Move.Z, [kTechDataTooltipInfo] = "MARINE_WEAPONS4_TOOLTIP" }, { [kTechDataId] = kTechId.ShotgunTech, [kTechDataCostKey] = kShotgunTechResearchCost, [kTechDataResearchTimeKey] = kShotgunTechResearchTime, [kTechDataDisplayName] = "RESEARCH_SHOTGUNS", [kTechDataTooltipInfo] = "SHOTGUN_TECH_TOOLTIP" }, { [kTechDataId] = kTechId.HeavyRifleTech, [kTechDataCostKey] = kHeavyRifleTechResearchCost, [kTechDataResearchTimeKey] = kHeavyRifleTechResearchTime, [kTechDataDisplayName] = "RESEARCH_HEAVY_RIFLES", [kTechDataTooltipInfo] = "HEAVY_RIFLE_TECH_TOOLTIP" }, { [kTechDataId] = kTechId.GrenadeLauncherTech, [kTechDataCostKey] = kGrenadeLauncherTechResearchCost, [kTechDataResearchTimeKey] = kGrenadeLauncherTechResearchTime, [kTechDataDisplayName] = "RESEARCH_GRENADE_LAUNCHERS", [kTechDataTooltipInfo] = "GRENADE_LAUNCHER_TECH_TOOLTIP" }, { [kTechDataId] = kTechId.GrenadeTech, [kTechDataCostKey] = kGrenadeTechResearchCost, [kTechDataResearchTimeKey] = kGrenadeTechResearchTime, [kTechDataDisplayName] = "RESEARCH_GRENADES", [kTechDataTooltipInfo] = "GRENADES_TOOLTIP" }, { [kTechDataId] = kTechId.AdvancedWeaponry, [kTechDataCostKey] = kAdvancedWeaponryResearchCost, [kTechDataResearchTimeKey] = kAdvancedWeaponryResearchTime, [kTechDataDisplayName] = "ADVANCED_WEAPONRY", [kTechDataHotkey] = Move.G, [kTechDataTooltipInfo] = "ADVANCED_WEAPONRY_TOOLTIP" }, // ARC abilities { [kTechDataId] = kTechId.ARCDeploy, [kTechIDShowEnables] = false, [kTechDataResearchTimeKey] = kARCDeployTime, [kTechDataDisplayName] = "ARC_DEPLOY", [kTechDataMenuPriority] = 1, [kTechDataHotkey] = Move.D, [kTechDataTooltipInfo] = "ARC_DEPLOY_TOOLTIP" }, { [kTechDataId] = kTechId.ARCUndeploy, [kTechIDShowEnables] = false, [kTechDataResearchTimeKey] = kARCUndeployTime, [kTechDataDisplayName] = "ARC_UNDEPLOY", [kTechDataMenuPriority] = 2, [kTechDataHotkey] = Move.D, [kTechDataTooltipInfo] = "ARC_UNDEPLOY_TOOLTIP" }, // upgradeable life forms { [kTechDataId] = kTechId.LifeFormMenu, [kTechDataDisplayName] = "BASIC_LIFE_FORMS", [kTechDataTooltipInfo] = "BASIC_LIFE_FORMS_TOOLTIP", }, { [kTechDataId] = kTechId.SkulkMenu, [kTechDataDisplayName] = "UPGRADE_SKULK", [kTechDataTooltipInfo] = "UPGRADE_SKULK_TOOLTIP", }, { [kTechDataId] = kTechId.GorgeMenu, [kTechDataDisplayName] = "UPGRADE_GORGE", [kTechDataTooltipInfo] = "UPGRADE_GORGE_TOOLTIP", }, { [kTechDataId] = kTechId.LerkMenu, [kTechDataDisplayName] = "UPGRADE_LERK", [kTechDataTooltipInfo] = "UPGRADE_LERK_TOOLTIP", }, { [kTechDataId] = kTechId.FadeMenu, [kTechDataDisplayName] = "UPGRADE_FADE", [kTechDataTooltipInfo] = "UPGRADE_FADE_TOOLTIP", }, { [kTechDataId] = kTechId.OnosMenu, [kTechDataDisplayName] = "UPGRADE_ONOS", [kTechDataTooltipInfo] = "UPGRADE_ONOS_TOOLTIP", }, { [kTechDataId] = kTechId.UpgradeSkulk, [kTechDataCostKey] = kUpgradeSkulkResearchCost, [kTechDataResearchTimeKey] = kUpgradeSkulkResearchTime, [kTechDataDisplayName] = "UPGRADE_SKULK", [kTechDataTooltipInfo] = "UPGRADE_SKULK_TOOLTIP", }, { [kTechDataId] = kTechId.UpgradeGorge, [kTechDataCostKey] = kUpgradeGorgeResearchCost, [kTechDataResearchTimeKey] = kUpgradeGorgeResearchTime, [kTechDataDisplayName] = "UPGRADE_GORGE", [kTechDataTooltipInfo] = "UPGRADE_GORGE_TOOLTIP", }, { [kTechDataId] = kTechId.UpgradeLerk, [kTechDataCostKey] = kUpgradeLerkResearchCost, [kTechDataResearchTimeKey] = kUpgradeLerkResearchTime, [kTechDataDisplayName] = "UPGRADE_LERK", [kTechDataTooltipInfo] = "UPGRADE_LERK_TOOLTIP", }, { [kTechDataId] = kTechId.UpgradeFade, [kTechDataCostKey] = kUpgradeFadeResearchCost, [kTechDataResearchTimeKey] = kUpgradeFadeResearchTime, [kTechDataDisplayName] = "UPGRADE_FADE", [kTechDataTooltipInfo] = "UPGRADE_FADE_TOOLTIP", }, { [kTechDataId] = kTechId.UpgradeOnos, [kTechDataCostKey] = kUpgradeOnosResearchCost, [kTechDataResearchTimeKey] = kUpgradeOnosResearchTime, [kTechDataDisplayName] = "UPGRADE_ONOS", [kTechDataTooltipInfo] = "UPGRADE_ONOS_TOOLTIP", }, // Alien abilities for damage types // tier 0 { [kTechDataId] = kTechId.Bite, [kTechDataMapName] = BiteLeap.kMapName, [kTechDataDamageType] = kBiteDamageType, [kTechDataDisplayName] = "BITE", [kTechDataTooltipInfo] = "BITE_TOOLTIP"}, { [kTechDataId] = kTechId.Parasite, [kTechDataMapName] = Parasite.kMapName, [kTechDataDamageType] = kParasiteDamageType, [kTechDataDisplayName] = "PARASITE", [kTechDataTooltipInfo] = "PARASITE_TOOLTIP"}, { [kTechDataId] = kTechId.Spit, [kTechDataMapName] = SpitSpray.kMapName, [kTechDataDamageType] = kSpitDamageType, [kTechDataDisplayName] = "SPIT", [kTechDataTooltipInfo] = "SPIT_TOOLTIP" }, { [kTechDataId] = kTechId.BuildAbility, [kTechDataMapName] = DropStructureAbility.kMapName, [kTechDataDisplayName] = "BUILD_ABILITY", [kTechDataTooltipInfo] = "BUILD_ABILITY_TOOLTIP"}, { [kTechDataId] = kTechId.Spray, [kTechDataMapName] = SpitSpray.kMapName, [kTechDataDamageType] = kHealsprayDamageType, [kTechDataDisplayName] = "SPRAY", [kTechDataTooltipInfo] = "SPRAY_TOOLTIP"}, { [kTechDataId] = kTechId.Swipe, [kTechDataMapName] = SwipeBlink.kMapName, [kTechDataDamageType] = kSwipeDamageType, [kTechDataDisplayName] = "SWIPE_BLINK", [kTechDataTooltipInfo] = "SWIPE_TOOLTIP"}, { [kTechDataId] = kTechId.Gore, [kTechDataMapName] = Gore.kMapName, [kTechDataDamageType] = kGoreDamageType, [kTechDataDisplayName] = "GORE", [kTechDataTooltipInfo] = "GORE_TOOLTIP"}, { [kTechDataId] = kTechId.LerkBite, [kTechDataMapName] = LerkBite.kMapName, [kTechDataDamageType] = kLerkBiteDamageType, [kTechDataDisplayName] = "LERK_BITE", [kTechDataTooltipInfo] = "LERK_BITE_TOOLTIP"}, { [kTechDataId] = kTechId.Spikes, [kTechDataDisplayName] = "SPIKES", [kTechDataDamageType] = kSpikeDamageType, [kTechDataTooltipInfo] = "SPIKES_TOOLTIP"}, { [kTechDataId] = kTechId.Blink, [kTechDataDisplayName] = "BLINK", [kTechDataTooltipInfo] = "BLINK_TOOLTIP"}, { [kTechDataId] = kTechId.BabblerAbility, [kTechDataMapName] = BabblerAbility.kMapName, [kTechDataDisplayName] = "BABBLER_ABILITY", [kTechDataTooltipInfo] = "BABBLER_ABILITY_TOOLTIP", }, // tier 1 { [kTechDataId] = kTechId.Umbra, [kTechDataCategory] = kTechId.Lerk, [kTechDataMapName] = LerkUmbra.kMapName, [kTechDataDisplayName] = "UMBRA", [kTechDataCostKey] = kUmbraResearchCost, [kTechDataResearchTimeKey] = kUmbraResearchTime, [kTechDataTooltipInfo] = "UMBRA_TOOLTIP"}, { [kTechDataId] = kTechId.BileBomb, [kTechDataCategory] = kTechId.Gorge, [kTechDataMapName] = BileBomb.kMapName, [kTechDataDamageType] = kBileBombDamageType, [kTechDataDisplayName] = "BILEBOMB", [kTechDataCostKey] = kBileBombResearchCost, [kTechDataResearchTimeKey] = kBileBombResearchTime, [kTechDataTooltipInfo] = "BILEBOMB_TOOLTIP" }, { [kTechDataId] = kTechId.ShadowStep, [kTechDataCategory] = kTechId.Fade, [kTechDataCostKey] = kShadowStepResearchCost, [kTechDataResearchTimeKey] = kShadowStepResearchTime, [kTechDataDisplayName] = "SHADOWSTEP", [kTechDataTooltipInfo] = "SHADOWSTEP_TOOLTIP"}, { [kTechDataId] = kTechId.Charge, [kTechDataCategory] = kTechId.Onos, [kTechDataCostKey] = kChargeResearchCost, [kTechDataResearchTimeKey] = kChargeResearchTime, [kTechDataDisplayName] = "CHARGE", [kTechDataTooltipInfo] = "CHARGE_TOOLTIP"}, // tier 2 { [kTechDataId] = kTechId.Leap, [kTechDataCategory] = kTechId.Skulk, [kTechDataDisplayName] = "LEAP", [kTechDataCostKey] = kLeapResearchCost, [kTechDataResearchTimeKey] = kLeapResearchTime, [kTechDataTooltipInfo] = "LEAP_TOOLTIP" }, { [kTechDataId] = kTechId.Stab, [kTechDataCategory] = kTechId.Fade, [kTechDataMapName] = StabBlink.kMapName, [kTechDataCostKey] = kStabResearchCost, [kTechDataResearchTimeKey] = kStabResearchTime, [kTechDataDamageType] = kStabDamageType, [kTechDataDisplayName] = "STAB_BLINK", [kTechDataTooltipInfo] = "STAB_TOOLTIP"}, { [kTechDataId] = kTechId.BoneShield, [kTechDataCategory] = kTechId.Onos, [kTechDataMapName] = BoneShield.kMapName, [kTechDataDisplayName] = "BONESHIELD", [kTechDataCostKey] = kBoneShieldResearchCost, [kTechDataResearchTimeKey] = kBoneShieldResearchTime, [kTechDataTooltipInfo] = "BONESHIELD_TOOLTIP" }, { [kTechDataId] = kTechId.Spores, [kTechDataCategory] = kTechId.Lerk, [kTechDataDisplayName] = "SPORES", [kTechDataMapName] = Spores.kMapName, [kTechDataCostKey] = kSporesResearchCost, [kTechDataResearchTimeKey] = kSporesResearchTime, [kTechDataTooltipInfo] = "SPORES_TOOLTIP"}, // tier 3 { [kTechDataId] = kTechId.Stomp, [kTechDataCategory] = kTechId.Onos, [kTechDataDisplayName] = "STOMP", [kTechDataCostKey] = kStompResearchCost, [kTechDataResearchTimeKey] = kStompResearchTime, [kTechDataTooltipInfo] = "STOMP_TOOLTIP" }, { [kTechDataId] = kTechId.Shockwave, [kTechDataDisplayName] = "SHOCKWAVE", [kTechDataDamageType] = kStompDamageType, [kTechDataMapName] = Shockwave.kMapName, [kTechDataTooltipInfo] = "SHOCKWAVE_TOOLTIP" }, { [kTechDataId] = kTechId.WebTech, [kTechDataDisplayName] = "WEBTECH", [kTechDataCostKey] = kWebResearchCost, [kTechDataResearchTimeKey] = kWebResearchTime, [kTechDataTooltipInfo] = "WEBTECH_TOOLTIP" }, { [kTechDataId] = kTechId.Xenocide, [kTechDataCategory] = kTechId.Skulk, [kTechDataMapName] = XenocideLeap.kMapName, [kTechDataDamageType] = kXenocideDamageType, [kTechDataDisplayName] = "XENOCIDE", [kTechDataCostKey] = kXenocideResearchCost, [kTechDataResearchTimeKey] = kXenocideResearchTime, [kTechDataTooltipInfo] = "XENOCIDE_TOOLTIP"}, { [kTechDataId] = kTechId.Vortex , [kTechDataCategory] = kTechId.Fade, [kTechDataMapName] = Vortex.kMapName, [kTechDataDisplayName] = "VORTEX", [kTechDataCostKey] = kVortexResearchCost, [kTechDataResearchTimeKey] = kVortexResearchTime, [kTechDataTooltipInfo] = "VORTEX_TOOLTIP"}, // Alien structures (spawn hive at 110 units off ground = 2.794 meters) { [kTechDataId] = kTechId.Hive, [kTechDataIgnorePathingMesh] = true, [kTechDataBioMass] = kHiveBiomass, [kTechDataSpawnBlock] = true, [kTechDataMaxExtents] = Vector(2, 1, 2), [kTechDataHint] = "HIVE_HINT", [kTechDataAllowStacking] = true, [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Hive.kMapName, [kTechDataDisplayName] = "HIVE", [kTechDataCostKey] = kHiveCost, [kTechDataBuildTime] = kHiveBuildTime, [kTechDataModel] = Hive.kModelName, [kTechDataHotkey] = Move.V, [kTechDataMaxHealth] = kHiveHealth, [kTechDataMaxArmor] = kHiveArmor, [kStructureAttachClass] = "TechPoint", [kTechDataSpawnHeightOffset] = 2.494, [kTechDataInitialEnergy] = kHiveInitialEnergy, [kTechDataMaxEnergy] = kHiveMaxEnergy, [kTechDataPointValue] = kHivePointValue, [kTechDataTooltipInfo] = "HIVE_TOOLTIP", [kTechDataObstacleRadius] = 2}, { [kTechDataId] = kTechId.HiveHeal, [kTechDataDisplayName] = "HEAL", [kTechDataTooltipInfo] = "HIVE_HEAL_TOOLTIP"}, { [kTechDataId] = kTechId.ResearchBioMassOne, [kTechDataBioMass] = kHiveBiomass, [kTechDataCostKey] = kResearchBioMassOneCost, [kTechDataResearchTimeKey] = kBioMassOneTime, [kTechDataDisplayName] = "BIOMASS", [kTechDataTooltipInfo] = "ADD_BIOMASS_TOOLTIP"}, { [kTechDataId] = kTechId.ResearchBioMassTwo, [kTechDataBioMass] = kHiveBiomass, [kTechDataCostKey] = kResearchBioMassTwoCost, [kTechDataResearchTimeKey] = kBioMassTwoTime, [kTechDataDisplayName] = "BIOMASS", [kTechDataTooltipInfo] = "ADD_BIOMASS_TOOLTIP"}, { [kTechDataId] = kTechId.ResearchBioMassThree, [kTechDataBioMass] = kHiveBiomass, [kTechDataCostKey] = kResearchBioMassThreeCost, [kTechDataResearchTimeKey] = kBioMassThreeTime, [kTechDataDisplayName] = "BIOMASS", [kTechDataTooltipInfo] = "ADD_BIOMASS_TOOLTIP"}, { [kTechDataId] = kTechId.ResearchBioMassFour, [kTechDataBioMass] = kHiveBiomass, [kTechDataCostKey] = kResearchBioMassFourCost, [kTechDataResearchTimeKey] = kBioMassFourTime, [kTechDataDisplayName] = "BIOMASS", [kTechDataTooltipInfo] = "ADD_BIOMASS_TOOLTIP"}, { [kTechDataId] = kTechId.BioMassOne, [kTechDataDisplayName] = "BIOMASS_ONE" }, { [kTechDataId] = kTechId.BioMassTwo, [kTechDataDisplayName] = "BIOMASS_TWO" }, { [kTechDataId] = kTechId.BioMassThree, [kTechDataDisplayName] = "BIOMASS_THREE" }, { [kTechDataId] = kTechId.BioMassFour, [kTechDataDisplayName] = "BIOMASS_FOUR" }, { [kTechDataId] = kTechId.BioMassFive, [kTechDataDisplayName] = "BIOMASS_FIVE" }, { [kTechDataId] = kTechId.BioMassSix, [kTechDataDisplayName] = "BIOMASS_SIX" }, { [kTechDataId] = kTechId.BioMassSeven, [kTechDataDisplayName] = "BIOMASS_SEVEN" }, { [kTechDataId] = kTechId.BioMassEight, [kTechDataDisplayName] = "BIOMASS_EIGHT" }, { [kTechDataId] = kTechId.BioMassNine, [kTechDataDisplayName] = "BIOMASS_NINE" }, { [kTechDataId] = kTechId.UpgradeToCragHive, [kTechDataMapName] = CragHive.kMapName, [kTechDataDisplayName] = "UPGRADE_CRAG_HIVE", [kTechDataCostKey] = kUpgradeHiveCost, [kTechDataResearchTimeKey] = kUpgradeHiveResearchTime, [kTechDataModel] = Hive.kModelName, [kTechDataTooltipInfo] = "UPGRADE_CRAG_HIVE_TOOLTIP", }, { [kTechDataId] = kTechId.UpgradeToShiftHive, [kTechDataMapName] = ShiftHive.kMapName, [kTechDataDisplayName] = "UPGRADE_SHIFT_HIVE", [kTechDataCostKey] = kUpgradeHiveCost, [kTechDataResearchTimeKey] = kUpgradeHiveResearchTime, [kTechDataModel] = Hive.kModelName, [kTechDataTooltipInfo] = "UPGRADE_SHIFT_HIVE_TOOLTIP", }, { [kTechDataId] = kTechId.UpgradeToShadeHive, [kTechDataMapName] = ShadeHive.kMapName, [kTechDataDisplayName] = "UPGRADE_SHADE_HIVE", [kTechDataCostKey] = kUpgradeHiveCost, [kTechDataResearchTimeKey] = kUpgradeHiveResearchTime, [kTechDataModel] = Hive.kModelName, [kTechDataTooltipInfo] = "UPGRADE_SHADE_HIVE_TOOLTIP", }, { [kTechDataId] = kTechId.CragHive, [kTechDataHint] = "CRAG_HIVE_HINT", [kTechDataMapName] = CragHive.kMapName, [kTechDataDisplayName] = "CRAG_HIVE", [kTechDataCostKey] = kUpgradeHiveCost, [kTechDataResearchTimeKey] = kUpgradeHiveResearchTime, [kTechDataBuildTime] = kUpgradeHiveResearchTime, [kTechDataModel] = Hive.kModelName, [kTechDataHotkey] = Move.V, [kTechDataMaxHealth] = kHiveHealth, [kTechDataMaxArmor] = kHiveArmor, [kStructureAttachClass] = "TechPoint", [kTechDataSpawnHeightOffset] = 2.494, [kTechDataInitialEnergy] = kHiveInitialEnergy, [kTechDataMaxEnergy] = kHiveMaxEnergy, [kTechDataPointValue] = kHivePointValue, [kTechDataTooltipInfo] = "CRAG_HIVE_TOOLTIP"}, { [kTechDataId] = kTechId.ShadeHive, [kTechDataHint] = "SHADE_HIVE_HINT", [kTechDataMapName] = ShadeHive.kMapName, [kTechDataDisplayName] = "SHADE_HIVE", [kTechDataCostKey] = kUpgradeHiveCost, [kTechDataResearchTimeKey] = kUpgradeHiveResearchTime, [kTechDataBuildTime] = kUpgradeHiveResearchTime, [kTechDataModel] = Hive.kModelName, [kTechDataHotkey] = Move.V, [kTechDataMaxHealth] = kHiveHealth, [kTechDataMaxArmor] = kHiveArmor, [kStructureAttachClass] = "TechPoint", [kTechDataSpawnHeightOffset] = 2.494, [kTechDataInitialEnergy] = kHiveInitialEnergy, [kTechDataMaxEnergy] = kHiveMaxEnergy, [kTechDataPointValue] = kHivePointValue, [kTechDataTooltipInfo] = "SHADE_HIVE_TOOLTIP"}, { [kTechDataId] = kTechId.ShiftHive, [kTechDataHint] = "SHIFT_HIVE_HINT", [kTechDataMapName] = ShiftHive.kMapName, [kTechDataDisplayName] = "SHIFT_HIVE", [kTechDataCostKey] = kUpgradeHiveCost, [kTechDataResearchTimeKey] = kUpgradeHiveResearchTime, [kTechDataBuildTime] = kUpgradeHiveResearchTime, [kTechDataModel] = Hive.kModelName, [kTechDataHotkey] = Move.V, [kTechDataMaxHealth] = kHiveHealth, [kTechDataMaxArmor] = kHiveArmor, [kStructureAttachClass] = "TechPoint", [kTechDataSpawnHeightOffset] = 2.494, [kTechDataInitialEnergy] = kHiveInitialEnergy, [kTechDataMaxEnergy] = kHiveMaxEnergy, [kTechDataPointValue] = kHivePointValue, [kTechDataTooltipInfo] = "SHIFT_HIVE_TOOLTIP"}, // Drifter and tech { [kTechDataId] = kTechId.DrifterCamouflage, [kTechDataDisplayName] = "CAMOUFLAGE", [kTechDataTooltipInfo] = "DRIFTER_CAMOUFLAGE_TOOLTIP"}, { [kTechDataId] = kTechId.DrifterCelerity, [kTechDataDisplayName] = "CELERITY", [kTechDataTooltipInfo] = "DRIFTER_CELERITY_TOOLTIP"}, { [kTechDataId] = kTechId.DrifterRegeneration, [kTechDataDisplayName] = "REGENERATION", [kTechDataTooltipInfo] = "DRIFTER_REGENERATION_TOOLTIP"}, { [kTechDataId] = kTechId.Drifter, [kTechDataBuildTime] = kDrifterHatchTime, [kTechDataSupply] = kDrifterSupply, [kTechDataHint] = "DRIFTER_HINT", [kTechDataMapName] = Drifter.kMapName, [kTechDataDisplayName] = "DRIFTER", [kTechDataCostKey] = kDrifterCost, [kTechDataCooldown] = kDrifterBuildTime, [kTechDataMaxHealth] = kDrifterHealth, [kTechDataMaxArmor] = kDrifterArmor, [kTechDataModel] = Drifter.kModelName, [kTechDataDamageType] = kDrifterAttackDamageType, [kTechDataPointValue] = kDrifterPointValue, [kTechDataTooltipInfo] = "DRIFTER_TOOLTIP", [kTechDataInitialEnergy] = kDrifterInitialEnergy, [kTechDataMaxEnergy] = kDrifterMaxEnergy,}, { [kTechDataId] = kTechId.DrifterEgg, [kTechDataRequiresInfestation] = true, [kTechDataSupply] = kDrifterSupply, [kTechDataBuildTime] = kDrifterHatchTime, [kTechDataSupply] = kDrifterSupply, [kTechDataHint] = "DRIFTER_HINT", [kTechDataMapName] = DrifterEgg.kMapName, [kTechDataDisplayName] = "DRIFTER", [kTechDataCostKey] = kDrifterCost, [kTechDataCooldown] = kDrifterCooldown, [kTechDataMaxHealth] = kDrifterHealth, [kTechDataMaxArmor] = kDrifterArmor, [kTechDataModel] = DrifterEgg.kModelName, [kTechDataPointValue] = kDrifterPointValue, [kTechDataTooltipInfo] = "DRIFTER_TOOLTIP", [kTechDataInitialEnergy] = kDrifterInitialEnergy, [kTechDataMaxEnergy] = kDrifterMaxEnergy,}, { [kTechDataId] = kTechId.SelectDrifter, [kTechIDShowEnables] = false, [kTechDataDisplayName] = "SELECT_DRIFTER", [kTechDataTooltipInfo] = "SELECT_NEAREST_DRIFTER" }, { [kTechDataId] = kTechId.SelectShift, [kTechIDShowEnables] = false, [kTechDataDisplayName] = "SELECT_SHIFT", [kTechDataTooltipInfo] = "SELECT_NEAREST_SHIFT" }, // Alien buildables { [kTechDataId] = kTechId.Egg, [kTechDataHint] = "EGG_HINT", [kTechDataMapName] = Egg.kMapName, [kTechDataDisplayName] = "EGG", [kTechDataTooltipInfo] = "EGG_DROP_TOOLTIP", [kTechDataMaxHealth] = Egg.kHealth, [kTechDataMaxArmor] = Egg.kArmor, [kTechDataModel] = Egg.kModelName, [kTechDataPointValue] = kEggPointValue, [kTechDataBuildTime] = 1, [kTechDataMaxExtents] = Vector(1.75/2, .664/2, 1.275/2), [kTechDataRequiresInfestation] = true }, { [kTechDataId] = kTechId.GorgeEgg, [kTechDataHint] = "EGG_HINT", [kTechDataMapName] = GorgeEgg.kMapName, [kTechDataDisplayName] = "GORGE_EGG", [kTechDataTooltipInfo] = "GORGE_EGG_DROP_TOOLTIP", [kTechDataMaxHealth] = Egg.kHealth, [kTechDataMaxArmor] = Egg.kArmor, [kTechDataModel] = Egg.kModelName, [kTechDataPointValue] = kEggPointValue, [kTechDataResearchTimeKey] = kEggGestateTime, [kTechDataCostKey] = kGorgeEggCost, [kTechDataMaxExtents] = Vector(1.75/2, .664/2, 1.275/2), [kTechDataRequiresInfestation] = true }, { [kTechDataId] = kTechId.LerkEgg, [kTechDataHint] = "EGG_HINT", [kTechDataMapName] = LerkEgg.kMapName, [kTechDataDisplayName] = "LERK_EGG", [kTechDataTooltipInfo] = "LERK_EGG_DROP_TOOLTIP", [kTechDataMaxHealth] = Egg.kHealth, [kTechDataMaxArmor] = Egg.kArmor, [kTechDataModel] = Egg.kModelName, [kTechDataPointValue] = kEggPointValue, [kTechDataResearchTimeKey] = kEggGestateTime, [kTechDataCostKey] = kLerkEggCost, [kTechDataMaxExtents] = Vector(1.75/2, .664/2, 1.275/2), [kTechDataRequiresInfestation] = true }, { [kTechDataId] = kTechId.FadeEgg, [kTechDataHint] = "EGG_HINT", [kTechDataMapName] = FadeEgg.kMapName, [kTechDataDisplayName] = "FADE_EGG", [kTechDataTooltipInfo] = "FADE_EGG_DROP_TOOLTIP", [kTechDataMaxHealth] = Egg.kHealth, [kTechDataMaxArmor] = Egg.kArmor, [kTechDataModel] = Egg.kModelName, [kTechDataPointValue] = kEggPointValue, [kTechDataResearchTimeKey] = kEggGestateTime, [kTechDataCostKey] = kFadeEggCost, [kTechDataMaxExtents] = Vector(1.75/2, .664/2, 1.275/2), [kTechDataRequiresInfestation] = true }, { [kTechDataId] = kTechId.OnosEgg, [kTechDataHint] = "EGG_HINT", [kTechDataMapName] = OnosEgg.kMapName, [kTechDataDisplayName] = "ONOS_EGG", [kTechDataTooltipInfo] = "ONOS_EGG_DROP_TOOLTIP", [kTechDataMaxHealth] = Egg.kHealth, [kTechDataMaxArmor] = Egg.kArmor, [kTechDataModel] = Egg.kModelName, [kTechDataPointValue] = kEggPointValue, [kTechDataResearchTimeKey] = kEggGestateTime, [kTechDataCostKey] = kOnosEggCost, [kTechDataMaxExtents] = Vector(1.75/2, .664/2, 1.275/2), [kTechDataRequiresInfestation] = true }, { [kTechDataId] = kTechId.Harvester, [kTechDataIgnorePathingMesh] = true, [kTechDataBioMass] = kHarvesterBiomass, [kTechDataSpawnBlock] = true, [kTechDataMaxExtents] = Vector(1, 1, 1), [kTechDataHint] = "HARVESTER_HINT", [kTechDataCollideWithWorldOnly] = true, [kTechDataAllowStacking] = true, [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Harvester.kMapName, [kTechDataDisplayName] = "HARVESTER", [kTechDataRequiresInfestation] = true, [kTechDataCostKey] = kHarvesterCost, [kTechDataBuildTime] = kHarvesterBuildTime, [kTechDataHotkey] = Move.H, [kTechDataMaxHealth] = kHarvesterHealth, [kTechDataMaxArmor] = kHarvesterArmor, [kTechDataModel] = Harvester.kModelName, [kStructureAttachClass] = "ResourcePoint", [kTechDataPointValue] = kHarvesterPointValue, [kTechDataTooltipInfo] = "HARVESTER_TOOLTIP"}, // Infestation { [kTechDataId] = kTechId.Infestation, [kTechDataDisplayName] = "INFESTATION", [kTechDataTooltipInfo] = "INFESTATION_TOOLTIP", }, { [kTechDataId] = kTechId.Slap, [kTechDataDisplayName] = "WHIP_SLAP", [kTechDataTooltipInfo] = "WHIP_SLAP_TOOLTIP", }, // Upgrade structures and research { [kTechDataId] = kTechId.Crag, [kTechDataBioMass] = kCragBiomass, [kTechDataSupply] = kCragSupply, [kTechDataHint] = "CRAG_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Crag.kMapName, [kTechDataDisplayName] = "CRAG", [kTechDataCostKey] = kCragCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.C, [kTechDataBuildTime] = kCragBuildTime, [kTechDataModel] = Crag.kModelName, [kTechDataMaxHealth] = kCragHealth, [kTechDataMaxArmor] = kCragArmor, [kTechDataInitialEnergy] = kCragInitialEnergy, [kTechDataMaxEnergy] = kCragMaxEnergy, [kTechDataPointValue] = kCragPointValue, [kVisualRange] = Crag.kHealRadius, [kTechDataTooltipInfo] = "CRAG_TOOLTIP", [kTechDataGrows] = true}, { [kTechDataId] = kTechId.Whip, [kTechDataBioMass] = kWhipBiomass, [kTechDataSupply] = kWhipSupply, [kTechDataHint] = "WHIP_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Whip.kMapName, [kTechDataDisplayName] = "WHIP", [kTechDataCostKey] = kWhipCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.W, [kTechDataBuildTime] = kWhipBuildTime, [kTechDataModel] = Whip.kModelName, [kTechDataMaxHealth] = kWhipHealth, [kTechDataMaxArmor] = kWhipArmor, [kTechDataDamageType] = kDamageType.Structural, [kTechDataInitialEnergy] = kWhipInitialEnergy, [kTechDataMaxEnergy] = kWhipMaxEnergy, [kVisualRange] = Whip.kRange, [kTechDataPointValue] = kWhipPointValue, [kTechDataTooltipInfo] = "WHIP_TOOLTIP", [kTechDataGrows] = true}, { [kTechDataId] = kTechId.EvolveBombard, [kTechDataRequiresMature] = true, [kTechDataDisplayName] = "EVOLVE_BOMBARD", [kTechDataCostKey] = kEvolveBombardCost, [kTechDataResearchTimeKey] = kEvolveBombardResearchTime, [kTechDataTooltipInfo] = "EVOLVE_BOMBARD_TOOLTIP" }, { [kTechDataId] = kTechId.Shift, [kTechDataBioMass] = kShiftBiomass, [kTechDataSupply] = kShiftSupply, [kTechDataHint] = "SHIFT_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Shift.kMapName, [kTechDataDisplayName] = "SHIFT", [kTechDataRequiresInfestation] = true, [kTechDataCostKey] = kShiftCost, [kTechDataHotkey] = Move.S, [kTechDataBuildTime] = kShiftBuildTime, [kTechDataModel] = Shift.kModelName, [kTechDataMaxHealth] = kShiftHealth, [kTechDataMaxArmor] = kShiftArmor, [kTechDataInitialEnergy] = kShiftInitialEnergy, [kTechDataMaxEnergy] = kShiftMaxEnergy, [kTechDataPointValue] = kShiftPointValue, [kVisualRange] = kEchoRange, [kTechDataTooltipInfo] = "SHIFT_TOOLTIP", [kTechDataGrows] = true }, { [kTechDataId] = kTechId.Veil, [kTechDataBioMass] = kVeilBiomass, [kTechDataHint] = "VEIL_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Veil.kMapName, [kTechDataDisplayName] = "VEIL", [kTechDataCostKey] = kVeilCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.C, [kTechDataBuildTime] = kVeilBuildTime, [kTechDataModel] = Veil.kModelName, [kTechDataMaxHealth] = kVeilHealth, [kTechDataMaxArmor] = kVeilArmor, [kTechDataPointValue] = kVeilPointValue, [kTechDataTooltipInfo] = "VEIL_TOOLTIP", [kTechDataGrows] = true, [kTechDataObstacleRadius] = 0.5 }, { [kTechDataId] = kTechId.TwoVeils, [kTechDataDisplayName] = "TWO_VEILS", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "TWO_VEILS_TOOLTIP"}, { [kTechDataId] = kTechId.ThreeVeils, [kTechDataDisplayName] = "THREE_VEILS", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "THREE_VEILS_TOOLTIP"}, { [kTechDataId] = kTechId.Spur, [kTechDataBioMass] = kSpurBiomass, [kTechDataHint] = "SPUR_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Spur.kMapName, [kTechDataDisplayName] = "SPUR", [kTechDataCostKey] = kSpurCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.C, [kTechDataBuildTime] = kSpurBuildTime, [kTechDataModel] = Spur.kModelName, [kTechDataMaxHealth] = kSpurHealth, [kTechDataMaxArmor] = kSpurArmor, [kTechDataPointValue] = kSpurPointValue, [kTechDataTooltipInfo] = "SPUR_TOOLTIP", [kTechDataGrows] = true, [kTechDataObstacleRadius] = 0.75 }, { [kTechDataId] = kTechId.TwoSpurs, [kTechDataDisplayName] = "TWO_SPURS", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "TWO_SPURS_TOOLTIP"}, { [kTechDataId] = kTechId.ThreeSpurs, [kTechDataDisplayName] = "THREE_SPURS", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "THREE_SPURS_TOOLTIP"}, { [kTechDataId] = kTechId.Shell, [kTechDataBioMass] = kShellBiomass, [kTechDataHint] = "SHELL_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Shell.kMapName, [kTechDataDisplayName] = "SHELL", [kTechDataCostKey] = kShellCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.C, [kTechDataBuildTime] = kShellBuildTime, [kTechDataModel] = Shell.kModelName, [kTechDataMaxHealth] = kShellHealth, [kTechDataMaxArmor] = kShellArmor, [kTechDataPointValue] = kShellPointValue, [kTechDataTooltipInfo] = "SHELL_TOOLTIP", [kTechDataGrows] = true, [kTechDataObstacleRadius] = 0.75 }, { [kTechDataId] = kTechId.TwoShells, [kTechDataDisplayName] = "TWO_SHELLS", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "TWO_SHELLS_TOOLTIP"}, { [kTechDataId] = kTechId.ThreeShells, [kTechDataDisplayName] = "THREE_SHELLS", [kTechIDShowEnables] = false, [kTechDataTooltipInfo] = "THREE_SHELLS_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportHydra, [kTechIDShowEnables] = false, [kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_HYDRA", [kTechDataCostKey] = kEchoHydraCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = Hydra.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportWhip, [kTechIDShowEnables] = false, [kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_WHIP", [kTechDataCostKey] = kEchoWhipCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = Whip.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportTunnel, [kTechIDShowEnables] = false,[kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_TUNNEL", [kTechDataCostKey] = kEchoTunnelCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = TunnelEntrance.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportCrag, [kTechIDShowEnables] = false,[kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_CRAG", [kTechDataCostKey] = kEchoCragCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = Crag.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportShade, [kTechIDShowEnables] = false,[kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_SHADE", [kTechDataCostKey] = kEchoShadeCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = Shade.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportShift, [kTechIDShowEnables] = false,[kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_SHIFT", [kTechDataCostKey] = kEchoShiftCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = Shift.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportVeil, [kTechIDShowEnables] = false, [kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_VEIL", [kTechDataCostKey] = kEchoVeilCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = Veil.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportSpur, [kTechIDShowEnables] = false,[kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_SPUR", [kTechDataCostKey] = kEchoSpurCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = Spur.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportShell, [kTechIDShowEnables] = false, [kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_SHELL", [kTechDataCostKey] = kEchoShellCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = Shell.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportHive, [kTechIDShowEnables] = false, [kTechDataImplemented] = false, [kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_HIVE", [kTechDataCostKey] = kEchoHiveCost, [kTechDataRequiresInfestation] = false, [kTechDataModel] = Hive.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP", [kTechDataSpawnHeightOffset] = 2.494, [kStructureAttachClass] = "TechPoint"}, { [kTechDataId] = kTechId.TeleportEgg, [kTechIDShowEnables] = false,[kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_EGG", [kTechDataCostKey] = kEchoEggCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = Egg.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.TeleportHarvester, [kTechIDShowEnables] = false,[kStructureAttachClass] = "ResourcePoint", [kTechDataMaxExtents] = Vector(1, 1, 1), [kTechDataRequiresMature] = false, [kTechDataCollideWithWorldOnly] = true, [kTechDataAllowStacking] = true, [kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_HARVESTER", [kTechDataCostKey] = kEchoHarvesterCost, [kTechDataRequiresInfestation] = true, [kTechDataModel] = Harvester.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.Shade, [kTechDataBioMass] = kShadeBiomass, [kTechDataSupply] = kShadeSupply, [kTechDataHint] = "SHADE_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Shade.kMapName, [kTechDataDisplayName] = "SHADE", [kTechDataCostKey] = kShadeCost, [kTechDataRequiresInfestation] = true, [kTechDataBuildTime] = kShadeBuildTime, [kTechDataHotkey] = Move.D, [kTechDataModel] = Shade.kModelName, [kTechDataMaxHealth] = kShadeHealth, [kTechDataMaxArmor] = kShadeArmor, [kTechDataInitialEnergy] = kShadeInitialEnergy, [kTechDataMaxEnergy] = kShadeMaxEnergy, [kTechDataPointValue] = kShadePointValue, [kVisualRange] = Shade.kCloakRadius, [kTechDataMaxExtents] = Vector(1, 1.3, .4), [kTechDataTooltipInfo] = "SHADE_TOOLTIP", [kTechDataGrows] = true }, { [kTechDataId] = kTechId.Web, [kTechDataCategory] = kTechId.Gorge, [kTechDataMaxHealth] = kWebHealth, [kTechDataModel] = Web.kRootModelName, [kTechDataSpecifyOrientation] = true, [kTechDataGhostModelClass] = "WebGhostModel", [kTechDataMaxAmount] = kNumWebsPerGorge, [kTechDataAllowConsumeDrop] = true, [kTechDataDisplayName] = "WEB", [kTechDataCostKey] = kWebBuildCost, [kTechDataTooltipInfo] = "WEB_TOOLTIP" }, { [kTechDataId] = kTechId.Hydra, [kTechDataHint] = "HYDRA_HINT", [kTechDataTooltipInfo] = "HYDRA_TOOLTIP", [kTechDataDamageType] = kHydraAttackDamageType, [kTechDataAllowConsumeDrop] = true, [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMaxAmount] = kHydrasPerHive, [kTechDataMapName] = Hydra.kMapName, [kTechDataDisplayName] = "HYDRA", [kTechDataCostKey] = kHydraCost, [kTechDataBuildTime] = kHydraBuildTime, [kTechDataMaxHealth] = kHydraHealth, [kTechDataMaxArmor] = kHydraArmor, [kTechDataModel] = Hydra.kModelName, [kVisualRange] = Hydra.kRange, [kTechDataRequiresInfestation] = false, [kTechDataPointValue] = kHydraPointValue, [kTechDataGrows] = true}, { [kTechDataId] = kTechId.Clog, [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataAllowConsumeDrop] = true, [kTechDataTooltipInfo] = "CLOG_TOOLTIP", [kTechDataAllowStacking] = true, [kTechDataMaxAmount] = kClogsPerHive, [kTechDataMapName] = Clog.kMapName, [kTechDataDisplayName] = "CLOG", [kTechDataCostKey] = kClogCost, [kTechDataMaxHealth] = kClogHealth, [kTechDataMaxArmor] = kClogArmor, [kTechDataModel] = Clog.kModelName, [kTechDataRequiresInfestation] = false, [kTechDataPointValue] = kClogPointValue }, { [kTechDataId] = kTechId.GorgeTunnel, [kTechDataCategory] = kTechId.Gorge, [kTechDataMaxExtents] = Vector(1.2, 1.2, 1.2), [kTechDataTooltipInfo] = "GORGE_TUNNEL_TOOLTIP", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataAllowConsumeDrop] = true, [kTechDataAllowStacking] = false, [kTechDataMaxAmount] = kNumGorgeTunnels, [kTechDataMapName] = TunnelEntrance.kMapName, [kTechDataDisplayName] = "TUNNEL_ENTRANCE", [kTechDataCostKey] = kGorgeTunnelCost, [kTechDataMaxHealth] = kTunnelEntranceHealth, [kTechDataMaxArmor] = kTunnelEntranceArmor, [kTechDataBuildTime] = kGorgeTunnelBuildTime, [kTechDataModel] = TunnelEntrance.kModelName, [kTechDataRequiresInfestation] = false, [kTechDataPointValue] = kTunnelEntrancePointValue }, { [kTechDataId] = kTechId.GorgeTunnelTech, [kTechDataDisplayName] = "GORGE_TUNNEL_TECH", [kTechDataTooltipInfo] = "GORGE_TUNNEL_TECH_TOOLTIP", [kTechDataCostKey] = kGorgeTunnelResearchCost, [kTechDataResearchTimeKey] = kGorgeTunnelResearchTime }, { [kTechDataId] = kTechId.Babbler, [kTechDataMapName] = Babbler.kMapName, [kTechDataDisplayName] = "BABBLER", [kTechDataModel] = Babbler.kModelName, [kTechDataMaxHealth] = kBabblerHealth, [kTechDataMaxArmor] = kBabblerArmor, [kTechDataPointValue] = kBabblerPointValue, [kTechDataTooltipInfo] = "BABBLER_TOOLTIP" }, { [kTechDataId] = kTechId.BabblerTech, [kTechDataDisplayName] = "BABBLER", [kTechDataTooltipInfo] = "BABBLER_TOOLTIP" }, { [kTechDataId] = kTechId.BellySlide, [kTechDataDisplayName] = "BELLY_SLIDE", [kTechDataTooltipInfo] = "BELLY_SLIDE_TOOLTIP" }, { [kTechDataId] = kTechId.BabblerEgg, [kTechDataCategory] = kTechId.Gorge, [kTechDataAllowConsumeDrop] = true, [kTechDataMaxAmount] = kNumBabblerEggsPerGorge, [kTechDataCostKey] = kBabblerCost, [kTechDataBuildTime] = kBabblerEggBuildTime, [kTechDataMapName] = BabblerEgg.kMapName, [kTechDataDisplayName] = "BABBLER_EGG", [kTechDataModel] = BabblerEgg.kModelName, [kTechDataMaxHealth] = kBabblerEggHealth, [kTechDataMaxArmor] = kBabblerEggArmor, [kTechDataPointValue] = kBabblerEggPointValue, [kTechDataTooltipInfo] = "BABBLER_EGG_TOOLTIP" }, { [kTechDataId] = kTechId.Cyst, [kTechDataSpawnBlock] = true, [kTechDataBuildMethodFailedMessage] = "COMMANDERERROR_NO_CYST_PARENT_FOUND", [kTechDataOverrideCoordsMethod] = AlignCyst, [kTechDataHint] = "CYST_HINT", [kTechDataCooldown] = kCystCooldown, [kTechDataGhostModelClass] = "CystGhostModel", [kTechDataMapName] = Cyst.kMapName, [kTechDataDisplayName] = "CYST", [kTechDataTooltipInfo] = "CYST_TOOLTIP", [kTechDataCostKey] = kCystCost, [kTechDataBuildTime] = kCystBuildTime, [kTechDataMaxHealth] = kCystHealth, [kTechDataMaxArmor] = kCystArmor, [kTechDataModel] = Cyst.kModelName, [kVisualRange] = kInfestationRadius, [kTechDataRequiresInfestation] = false, [kTechDataPointValue] = kCystPointValue, [kTechDataGrows] = false, [kTechDataBuildRequiresMethod] = GetCystParentAvailable }, { [kTechDataId] = kTechId.Hallucinate, [kTechDataCooldown] = kHallucinationCloudCooldown, [kTechDataMapName] = HallucinationCloud.kMapName, [kTechDataDisplayName] = "HALLUCINATION_CLOUD", [kTechDataCostKey] = kHallucinationCloudCost, [kTechDataTooltipInfo] = "HALLUCINATION_CLOUD_TOOLTIP"}, { [kTechDataId] = kTechId.EnzymeCloud, [kTechDataCooldown] = kDrifterAbilityCooldown, [kTechDataMapName] = EnzymeCloud.kMapName, [kTechDataDisplayName] = "ENZYME_CLOUD", [kTechDataCostKey] = kEnzymeCloudCost, [kTechDataTooltipInfo] = "ENZYME_CLOUD_TOOLTIP"}, { [kTechDataId] = kTechId.Storm, [kTechDataCooldown] = kDrifterAbilityCooldown, [kTechDataMapName] = StormCloud.kMapName, [kTechDataDisplayName] = "STORM", [kTechDataCostKey] = kStormCost, [kTechDataTooltipInfo] = "STORM_TOOLTIP"}, { [kTechDataId] = kTechId.MucousMembrane, [kTechDataCooldown] = kDrifterAbilityCooldown, [kTechDataDisplayName] = "MUCOUS_MEMBRANE", [kTechDataCostKey] = kMucousMembraneCost, [kTechDataMapName] = MucousMembrane.kMapName, [kTechDataTooltipInfo] = "MUCOUS_MEMBRANE_TOOLTIP"}, { [kTechDataId] = kTechId.DestroyHallucination, [kTechDataDisplayName] = "DESTROY_HALLUCINATION"}, // Alien structure abilities and their energy costs { [kTechDataId] = kTechId.CragHeal, [kTechDataDisplayName] = "HEAL", [kTechDataTooltipInfo] = "CRAG_HEAL_TOOLTIP"}, { [kTechDataId] = kTechId.CragUmbra, [kTechDataDisplayName] = "UMBRA", [kVisualRange] = Crag.kHealRadius, [kTechDataTooltipInfo] = "CRAG_UMBRA_TOOLTIP"}, { [kTechDataId] = kTechId.HealWave, [kTechDataCooldown] = kHealWaveCooldown, [kTechDataDisplayName] = "HEAL_WAVE", [kTechDataCostKey] = kCragHealWaveCost, [kTechDataTooltipInfo] = "HEAL_WAVE_TOOLTIP"}, { [kTechDataId] = kTechId.WhipBombard, [kTechDataHint] = "BOMBARD_WHIP_HINT", [kTechDataDisplayName] = "BOMBARD", [kTechDataTooltipInfo] = "WHIP_BOMBARD_TOOLTIP" }, { [kTechDataId] = kTechId.WhipBombardCancel, [kTechDataDisplayName] = "CANCEL", [kTechDataTooltipInfo] = "WHIP_BOMBARD_CANCEL"}, { [kTechDataId] = kTechId.WhipBomb, [kTechDataMapName] = WhipBomb.kMapName, [kTechDataDamageType] = kWhipBombDamageType, [kTechDataModel] = "", [kTechDataDisplayName] = "WHIPBOMB", }, { [kTechDataId] = kTechId.ShiftEcho, [kTechDataDisplayName] = "ECHO", [kTechDataTooltipInfo] = "SHIFT_ECHO_TOOLTIP"}, { [kTechDataId] = kTechId.ShiftHatch, [kTechDataCooldown] = kHatchCooldown, [kTechDataMaxExtents] = Vector(Onos.XExtents, Onos.YExtents, Onos.ZExtents), [kStructureAttachRange] = kShiftHatchRange, [kTechDataBuildRequiresMethod] = GetShiftIsBuilt, [kTechDataGhostGuidesMethod] = GetShiftHatchGhostGuides, [kTechDataMapName] = Egg.kMapName, [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataModel] = Egg.kModelName, [kTechDataRequiresInfestation] = true, [kTechDataDisplayName] = "HATCH", [kTechDataTooltipInfo] = "SHIFT_HATCH_TOOLTIP", [kTechDataCostKey] = kShiftHatchCost}, { [kTechDataId] = kTechId.ShiftEnergize, [kTechDataDisplayName] = "ENERGIZE", [kTechDataTooltipInfo] = "SHIFT_ENERGIZE_TOOLTIP"}, { [kTechDataId] = kTechId.ShadeDisorient, [kTechDataDisplayName] = "DISORIENT", [kTechDataHotkey] = Move.D, [kVisualRange] = Shade.kCloakRadius, [kTechDataTooltipInfo] = "SHADE_DISORIENT_TOOLTIP"}, { [kTechDataId] = kTechId.ShadeCloak, [kTechDataDisplayName] = "CLOAK", [kTechDataHotkey] = Move.C, [kTechDataTooltipInfo] = "SHADE_CLOAK_TOOLTIP"}, { [kTechDataId] = kTechId.ShadeInk, [kTechDataCooldown] = kShadeInkCooldown, [kTechDataDisplayName] = "INK", [kTechDataHotkey] = Move.C, [kTechDataCostKey] = kShadeInkCost, [kTechDataTooltipInfo] = "SHADE_INK_TOOLTIP"}, { [kTechDataId] = kTechId.ShadePhantomMenu, [kTechDataDisplayName] = "PHANTOM", [kTechDataHotkey] = Move.P, [kTechDataImplemented] = true }, { [kTechDataId] = kTechId.ShadePhantomStructuresMenu, [kTechDataDisplayName] = "PHANTOM", [kTechDataHotkey] = Move.P, [kTechDataImplemented] = true }, { [kTechDataId] = kTechId.HallucinateDrifter, [kTechDataRequiresMature] = true, [kTechDataDisplayName] = "HALLUCINATE_DRIFTER", [kTechDataTooltipInfo] = "HALLUCINATE_DRIFTER_TOOLTIP", [kTechDataCostKey] = kHallucinateDrifterEnergyCost }, { [kTechDataId] = kTechId.HallucinateSkulk, [kTechDataRequiresMature] = true, [kTechDataDisplayName] = "HALLUCINATE_SKULK", [kTechDataTooltipInfo] = "HALLUCINATE_SKULK_TOOLTIP", [kTechDataCostKey] = kHallucinateSkulkEnergyCost }, { [kTechDataId] = kTechId.HallucinateGorge, [kTechDataRequiresMature] = true, [kTechDataDisplayName] = "HALLUCINATE_GORGE", [kTechDataTooltipInfo] = "HALLUCINATE_GORGE_TOOLTIP", [kTechDataCostKey] = kHallucinateGorgeEnergyCost }, { [kTechDataId] = kTechId.HallucinateLerk, [kTechDataRequiresMature] = true, [kTechDataDisplayName] = "HALLUCINATE_LERK", [kTechDataTooltipInfo] = "HALLUCINATE_LERK_TOOLTIP", [kTechDataCostKey] = kHallucinateLerkEnergyCost }, { [kTechDataId] = kTechId.HallucinateFade, [kTechDataRequiresMature] = true, [kTechDataDisplayName] = "HALLUCINATE_FADE", [kTechDataTooltipInfo] = "HALLUCINATE_FADE_TOOLTIP", [kTechDataCostKey] = kHallucinateFadeEnergyCost }, { [kTechDataId] = kTechId.HallucinateOnos, [kTechDataRequiresMature] = true, [kTechDataDisplayName] = "HALLUCINATE_ONOS", [kTechDataTooltipInfo] = "HALLUCINATE_ONOS_TOOLTIP", [kTechDataCostKey] = kHallucinateOnosEnergyCost }, { [kTechDataId] = kTechId.HallucinateHive, [kTechDataRequiresMature] = true, [kTechDataSpawnHeightOffset] = 2.494, [kStructureAttachClass] = "TechPoint", [kTechDataDisplayName] = "HALLUCINATE_HIVE", [kTechDataModel] = Hive.kModelName, [kTechDataTooltipInfo] = "HALLUCINATE_HIVE_TOOLTIP", [kTechDataCostKey] = kHallucinateHiveEnergyCost }, { [kTechDataId] = kTechId.HallucinateWhip, [kTechDataRequiresMature] = true, [kTechDataRequiresInfestation] = true, [kTechDataDisplayName] = "HALLUCINATE_WHIP", [kTechDataModel] = Whip.kModelName, [kTechDataTooltipInfo] = "HALLUCINATE_WHIP_TOOLTIP", [kTechDataCostKey] = kHallucinateWhipEnergyCost }, { [kTechDataId] = kTechId.HallucinateShade, [kTechDataRequiresMature] = true, [kTechDataRequiresInfestation] = true, [kTechDataDisplayName] = "HALLUCINATE_SHADE", [kTechDataModel] = Shade.kModelName, [kTechDataTooltipInfo] = "HALLUCINATE_SHADE_TOOLTIP", [kTechDataCostKey] = kHallucinateShadeEnergyCost }, { [kTechDataId] = kTechId.HallucinateCrag, [kTechDataRequiresMature] = true, [kTechDataRequiresInfestation] = true, [kTechDataDisplayName] = "HALLUCINATE_CRAG", [kTechDataModel] = Crag.kModelName, [kTechDataTooltipInfo] = "HALLUCINATE_CRAG_TOOLTIP", [kTechDataCostKey] = kHallucinateCragEnergyCost }, { [kTechDataId] = kTechId.HallucinateShift, [kTechDataRequiresMature] = true, [kTechDataRequiresInfestation] = true, [kTechDataDisplayName] = "HALLUCINATE_SHIFT", [kTechDataModel] = Shift.kModelName, [kTechDataTooltipInfo] = "HALLUCINATE_SHIFT_TOOLTIP", [kTechDataCostKey] = kHallucinateShiftEnergyCost }, { [kTechDataId] = kTechId.HallucinateHarvester, [kTechDataRequiresMature] = true, [kStructureAttachClass] = "ResourcePoint", [kTechDataRequiresInfestation] = true, [kTechDataDisplayName] = "HALLUCINATE_HARVESTER", [kTechDataModel] = Harvester.kModelName, [kTechDataTooltipInfo] = "HALLUCINATE_HARVESTER_TOOLTIP", [kTechDataCostKey] = kHallucinateHarvesterEnergyCost }, { [kTechDataId] = kTechId.HallucinateHydra, [kTechDataRequiresMature] = true, [kTechDataEngagementDistance] = 3.5, [kTechDataRequiresInfestation] = true, [kTechDataDisplayName] = "HALLUCINATE_HYDRA", [kTechDataModel] = Hydra.kModelName, [kTechDataTooltipInfo] = "HALLUCINATE_HYDRA_TOOLTIP", [kTechDataCostKey] = kHallucinateHydraEnergyCost }, { [kTechDataId] = kTechId.WhipUnroot, [kTechDataDisplayName] = "UNROOT_WHIP", [kTechDataTooltipInfo] = "UNROOT_WHIP_TOOLTIP", [kTechDataMenuPriority] = 1}, { [kTechDataId] = kTechId.WhipRoot, [kTechDataDisplayName] = "ROOT_WHIP", [kTechDataTooltipInfo] = "ROOT_WHIP_TOOLTIP", [kTechDataMenuPriority] = 2}, // Alien lifeforms { [kTechDataId] = kTechId.Skulk, [kTechDataUpgradeCost] = kSkulkUpgradeCost, [kTechDataMapName] = Skulk.kMapName, [kTechDataGestateName] = Skulk.kMapName, [kTechDataGestateTime] = kSkulkGestateTime, [kTechDataDisplayName] = "SKULK", [kTechDataTooltipInfo] = "SKULK_TOOLTIP", [kTechDataModel] = Skulk.kModelName, [kTechDataCostKey] = kSkulkCost, [kTechDataMaxHealth] = Skulk.kHealth, [kTechDataMaxArmor] = Skulk.kArmor, [kTechDataEngagementDistance] = kPlayerEngagementDistance, [kTechDataMaxExtents] = Vector(Skulk.kXExtents, Skulk.kYExtents, Skulk.kZExtents), [kTechDataPointValue] = kSkulkPointValue}, { [kTechDataId] = kTechId.Gorge, [kTechDataUpgradeCost] = kGorgeUpgradeCost, [kTechDataMapName] = Gorge.kMapName, [kTechDataGestateName] = Gorge.kMapName, [kTechDataGestateTime] = kGorgeGestateTime, [kTechDataDisplayName] = "GORGE", [kTechDataTooltipInfo] = "GORGE_TOOLTIP", [kTechDataModel] = Gorge.kModelName,[kTechDataCostKey] = kGorgeCost, [kTechDataMaxHealth] = kGorgeHealth, [kTechDataMaxArmor] = kGorgeArmor, [kTechDataEngagementDistance] = kPlayerEngagementDistance, [kTechDataMaxExtents] = Vector(Gorge.kXZExtents, Gorge.kYExtents, Gorge.kXZExtents), [kTechDataPointValue] = kGorgePointValue}, { [kTechDataId] = kTechId.Lerk, [kTechDataUpgradeCost] = kLerkUpgradeCost, [kTechDataMapName] = Lerk.kMapName, [kTechDataGestateName] = Lerk.kMapName, [kTechDataGestateTime] = kLerkGestateTime, [kTechDataDisplayName] = "LERK", [kTechDataTooltipInfo] = "LERK_TOOLTIP", [kTechDataModel] = Lerk.kModelName,[kTechDataCostKey] = kLerkCost, [kTechDataMaxHealth] = kLerkHealth, [kTechDataMaxArmor] = kLerkArmor, [kTechDataEngagementDistance] = kPlayerEngagementDistance, [kTechDataMaxExtents] = Vector(Lerk.XZExtents, Lerk.YExtents, Lerk.XZExtents), [kTechDataPointValue] = kLerkPointValue}, { [kTechDataId] = kTechId.Fade, [kTechDataUpgradeCost] = kFadeUpgradeCost, [kTechDataMapName] = Fade.kMapName, [kTechDataGestateName] = Fade.kMapName, [kTechDataGestateTime] = kFadeGestateTime, [kTechDataDisplayName] = "FADE", [kTechDataTooltipInfo] = "FADE_TOOLTIP", [kTechDataModel] = Fade.kModelName,[kTechDataCostKey] = kFadeCost, [kTechDataMaxHealth] = Fade.kHealth, [kTechDataEngagementDistance] = kPlayerEngagementDistance, [kTechDataMaxArmor] = Fade.kArmor, [kTechDataMaxExtents] = Vector(Fade.XZExtents, Fade.YExtents, Fade.XZExtents), [kTechDataPointValue] = kFadePointValue}, { [kTechDataId] = kTechId.Onos, [kTechDataUpgradeCost] = kOnosUpgradeCost, [kTechDataMapName] = Onos.kMapName, [kTechDataGestateName] = Onos.kMapName, [kTechDataGestateTime] = kOnosGestateTime, [kTechDataDisplayName] = "ONOS", [kTechDataTooltipInfo] = "ONOS_TOOLTIP", [kTechDataModel] = Onos.kModelName,[kTechDataCostKey] = kOnosCost, [kTechDataMaxHealth] = Onos.kHealth, [kTechDataEngagementDistance] = kOnosEngagementDistance, [kTechDataMaxArmor] = Onos.kArmor, [kTechDataMaxExtents] = Vector(Onos.XExtents, Onos.YExtents, Onos.ZExtents), [kTechDataPointValue] = kOnosPointValue}, { [kTechDataId] = kTechId.Embryo, [kTechDataMapName] = Embryo.kMapName, [kTechDataGestateName] = Embryo.kMapName, [kTechDataDisplayName] = "EMBRYO", [kTechDataModel] = Embryo.kModelName, [kTechDataMaxExtents] = Vector(Embryo.kXExtents, Embryo.kYExtents, Embryo.kZExtents)}, { [kTechDataId] = kTechId.AlienCommander, [kTechDataMapName] = AlienCommander.kMapName, [kTechDataDisplayName] = "ALIEN COMMANDER", [kTechDataModel] = ""}, { [kTechDataId] = kTechId.Hallucination, [kTechDataMapName] = Hallucination.kMapName, [kTechDataDisplayName] = "HALLUCINATION", [kTechDataCostKey] = kHallucinationCost, [kTechDataEngagementDistance] = kPlayerEngagementDistance }, // Lifeform purchases { [kTechDataId] = kTechId.Carapace, [kTechDataCategory] = kTechId.CragHive, [kTechDataDisplayName] = "CARAPACE", [kTechDataSponitorCode] = "C", [kTechDataCostKey] = kCarapaceCost, [kTechDataTooltipInfo] = "CARAPACE_TOOLTIP", }, { [kTechDataId] = kTechId.Regeneration, [kTechDataCategory] = kTechId.CragHive, [kTechDataDisplayName] = "REGENERATION", [kTechDataSponitorCode] = "R", [kTechDataCostKey] = kRegenerationCost, [kTechDataTooltipInfo] = "REGENERATION_TOOLTIP", }, { [kTechDataId] = kTechId.Silence, [kTechDataCategory] = kTechId.ShadeHive, [kTechDataDisplayName] = "SILENCE", [kTechDataSponitorCode] = "S", [kTechDataTooltipInfo] = "SILENCE_TOOLTIP", [kTechDataCostKey] = kSilenceCost }, { [kTechDataId] = kTechId.Camouflage, [kTechDataCategory] = kTechId.ShadeHive, [kTechDataDisplayName] = "CAMOUFLAGE", [kTechDataSponitorCode] = "M", [kTechDataTooltipInfo] = "CAMOUFLAGE_TOOLTIP", [kTechDataCostKey] = kCamouflageCost }, { [kTechDataId] = kTechId.Phantom, [kTechDataCategory] = kTechId.ShadeHive, [kTechDataDisplayName] = "PHANTOM", [kTechDataSponitorCode] = "M", [kTechDataTooltipInfo] = "PHANTOM_TOOLTIP", [kTechDataCostKey] = kCamouflageCost }, { [kTechDataId] = kTechId.Aura, [kTechDataCategory] = kTechId.ShadeHive, [kTechDataDisplayName] = "AURA", [kTechDataSponitorCode] = "M", [kTechDataTooltipInfo] = "AURA_TOOLTIP", [kTechDataCostKey] = kAuraCost }, { [kTechDataId] = kTechId.Celerity, [kTechDataCategory] = kTechId.ShiftHive, [kTechDataDisplayName] = "CELERITY", [kTechDataSponitorCode] = "L", [kTechDataTooltipInfo] = "CELERITY_TOOLTIP", [kTechDataCostKey] = kCelerityCost }, { [kTechDataId] = kTechId.Adrenaline, [kTechDataCategory] = kTechId.ShiftHive, [kTechDataDisplayName] = "ADRENALINE", [kTechDataSponitorCode] = "A", [kTechDataTooltipInfo] = "ADRENALINE_TOOLTIP", [kTechDataCostKey] = kAdrenalineCost }, { [kTechDataId] = kTechId.HyperMutation, [kTechDataCategory] = kTechId.ShiftHive, [kTechDataDisplayName] = "HYPERMUTATION", [kTechDataSponitorCode] = "H", [kTechDataTooltipInfo] = "HYPERMUTATION_TOOLTIP", [kTechDataCostKey] = kHyperMutationCost }, // Alien markers { [kTechDataId] = kTechId.ThreatMarker, [kTechDataImplemented] = true, [kTechDataDisplayName] = "MARK_THREAT", [kTechDataTooltipInfo] = "PHEROMONE_THREAT_TOOLTIP",}, { [kTechDataId] = kTechId.NeedHealingMarker, [kTechDataImplemented] = true, [kTechDataDisplayName] = "NEED_HEALING_HERE", [kTechDataTooltipInfo] = "PHEROMONE_HEAL_TOOLTIP",}, { [kTechDataId] = kTechId.WeakMarker, [kTechDataImplemented] = true, [kTechDataDisplayName] = "WEAK_HERE", [kTechDataTooltipInfo] = "PHEROMONE_HEAL_TOOLTIP",}, { [kTechDataId] = kTechId.ExpandingMarker, [kTechDataImplemented] = true, [kTechDataDisplayName] = "EXPANDING_HERE", [kTechDataTooltipInfo] = "PHEROMONE_EXPANDING_TOOLTIP",}, { [kTechDataId] = kTechId.NutrientMist, [kTechDataMapName] = NutrientMist.kMapName, [kTechDataAllowStacking] = true, [kTechDataIgnorePathingMesh] = true, [kTechDataCollideWithWorldOnly] = true, [kTechDataRequiresInfestation] = true, [kTechDataDisplayName] = "NUTRIENT_MIST", [kTechDataCostKey] = kNutrientMistCost, [kTechDataCooldown] = kNutrientMistCooldown, [kTechDataTooltipInfo] = "NUTRIENT_MIST_TOOLTIP"}, { [kTechDataId] = kTechId.BoneWall, [kTechDataMaxExtents] = Vector(8, 1, 8), [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataModel] = BoneWall.kModelName, [kTechDataMapName] = BoneWall.kMapName, [kTechDataOverrideCoordsMethod] = AlignBoneWalls, [kTechDataMaxHealth] = kBoneWallHealth, [kTechDataMaxArmor] = kBoneWallArmor, [kTechDataPointValue] = 0, [kTechDataCooldown] = kBoneWallCooldown, [kTechDataAllowStacking] = true, [kTechDataIgnorePathingMesh] = true, [kTechDataCollideWithWorldOnly] = true, [kTechDataRequiresInfestation] = true, [kTechDataDisplayName] = "INFESTATION_SPIKE", [kTechDataCostKey] = kBoneWallCost, [kTechDataTooltipInfo] = "INFESTATION_SPIKE_TOOLTIP"}, { [kTechDataId] = kTechId.Contamination, [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataModel] = Contamination.kModelName, [kTechDataMapName] = Contamination.kMapName, [kTechDataMaxHealth] = kContaminationHealth, [kTechDataMaxArmor] = kContaminationArmor, [kTechDataPointValue] = 0, [kTechDataCooldown] = kContaminationCooldown, [kTechDataCollideWithWorldOnly] = true, [kTechDataDisplayName] = "CONTAMINATION", [kTechDataCostKey] = kContaminationCost, [kTechDataTooltipInfo] = "CONTAMINATION_TOOLTIP"}, { [kTechDataId] = kTechId.Rupture, [kTechDataCooldown] = kRuptureCooldown, [kTechDataMapName] = Rupture.kMapName, [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataDisplayName] = "RUPTURE", [kTechDataAllowStacking] = true, [kTechDataCollideWithWorldOnly] = true, [kTechDataRequiresInfestation] = true, [kTechDataIgnorePathingMesh] = true, [kTechDataCostKey] = kRuptureCost, [kTechDataTooltipInfo] = "RUPTURE_TOOLTIP"}, // Alerts { [kTechDataId] = kTechId.MarineAlertSentryUnderAttack, [kTechDataAlertSound] = Sentry.kUnderAttackSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 0, [kTechDataAlertText] = "MARINE_ALERT_SENTRY_UNDERATTACK", [kTechDataAlertTeam] = false}, { [kTechDataId] = kTechId.MarineAlertSoldierUnderAttack, [kTechDataAlertSound] = MarineCommander.kSoldierUnderAttackSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 0, [kTechDataAlertText] = "MARINE_ALERT_SOLDIER_UNDERATTACK", [kTechDataAlertTeam] = true}, { [kTechDataId] = kTechId.MarineAlertStructureUnderAttack, [kTechDataAlertSound] = MarineCommander.kStructureUnderAttackSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 1, [kTechDataAlertText] = "MARINE_ALERT_STRUCTURE_UNDERATTACK", [kTechDataAlertTeam] = true}, { [kTechDataId] = kTechId.MarineAlertExtractorUnderAttack, [kTechDataAlertSound] = MarineCommander.kStructureUnderAttackSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 1, [kTechDataAlertText] = "MARINE_ALERT_EXTRACTOR_UNDERATTACK", [kTechDataAlertTeam] = true, [kTechDataAlertIgnoreDistance] = true}, { [kTechDataId] = kTechId.MarineAlertCommandStationUnderAttack, [kTechDataAlertSound] = CommandStation.kUnderAttackSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 2, [kTechDataAlertText] = "MARINE_ALERT_COMMANDSTATION_UNDERAT", [kTechDataAlertTeam] = true, [kTechDataAlertIgnoreDistance] = true, [kTechDataAlertSendTeamMessage] = kTeamMessageTypes.CommandStationUnderAttack}, { [kTechDataId] = kTechId.MarineAlertInfantryPortalUnderAttack, [kTechDataAlertSound] = InfantryPortal.kUnderAttackSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 1, [kTechDataAlertText] = "MARINE_ALERT_INFANTRYPORTAL_UNDERAT", [kTechDataAlertTeam] = true, [kTechDataAlertSendTeamMessage] = kTeamMessageTypes.IPUnderAttack}, { [kTechDataId] = kTechId.MarineAlertCommandStationComplete, [kTechDataAlertSound] = MarineCommander.kCommandStationCompletedSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_COMMAND_STATION_COMPLETE", [kTechDataAlertTeam] = true, [kTechDataAlertIgnoreDistance] = true,}, { [kTechDataId] = kTechId.MarineAlertConstructionComplete, [kTechDataAlertSound] = MarineCommander.kObjectiveCompletedSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_CONSTRUCTION_COMPLETE", [kTechDataAlertTeam] = false}, { [kTechDataId] = kTechId.MarineCommanderEjected, [kTechDataAlertSound] = MarineCommander.kCommanderEjectedSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_COMMANDER_EJECTED", [kTechDataAlertTeam] = true}, { [kTechDataId] = kTechId.MarineAlertSentryFiring, [kTechDataAlertSound] = MarineCommander.kSentryFiringSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_SENTRY_FIRING"}, { [kTechDataId] = kTechId.MarineAlertSoldierLost, [kTechDataAlertSound] = MarineCommander.kSoldierLostSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_SOLDIER_LOST", [kTechDataAlertOthersOnly] = true}, { [kTechDataId] = kTechId.MarineAlertAcknowledge, [kTechDataAlertSound] = MarineCommander.kSoldierAcknowledgesSoundName, [kTechDataAlertType] = kAlertType.Request, [kTechDataAlertText] = "MARINE_ALERT_ACKNOWLEDGE"}, { [kTechDataId] = kTechId.MarineAlertNeedAmmo, [kTechDataAlertIgnoreInterval] = true, [kTechDataAlertSound] = MarineCommander.kSoldierNeedsAmmoSoundName, [kTechDataAlertType] = kAlertType.Request, [kTechDataAlertText] = "MARINE_ALERT_NEED_AMMO"}, { [kTechDataId] = kTechId.MarineAlertNeedMedpack, [kTechDataAlertIgnoreInterval] = true, [kTechDataAlertSound] = MarineCommander.kSoldierNeedsHealthSoundName, [kTechDataAlertType] = kAlertType.Request, [kTechDataAlertText] = "MARINE_ALERT_NEED_MEDPACK"}, { [kTechDataId] = kTechId.MarineAlertNeedOrder, [kTechDataAlertIgnoreInterval] = true, [kTechDataAlertSound] = MarineCommander.kSoldierNeedsOrderSoundName, [kTechDataAlertType] = kAlertType.Request, [kTechDataAlertText] = "MARINE_ALERT_NEED_ORDER"}, { [kTechDataId] = kTechId.MarineAlertUpgradeComplete, [kTechDataAlertSound] = MarineCommander.kUpgradeCompleteSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_UPGRADE_COMPLETE"}, { [kTechDataId] = kTechId.MarineAlertResearchComplete, [kTechDataAlertSound] = MarineCommander.kResearchCompleteSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_RESEARCH_COMPLETE"}, { [kTechDataId] = kTechId.MarineAlertManufactureComplete, [kTechDataAlertSound] = MarineCommander.kManufactureCompleteSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_MANUFACTURE_COMPLETE"}, { [kTechDataId] = kTechId.MarineAlertNotEnoughResources, [kTechDataAlertSound] = Player.kNotEnoughResourcesSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_NOT_ENOUGH_RESOURCES"}, { [kTechDataId] = kTechId.MarineAlertMACBlocked, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_MAC_BLOCKED"}, { [kTechDataId] = kTechId.MarineAlertOrderComplete, [kTechDataAlertSound] = MarineCommander.kObjectiveCompletedSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_ORDER_COMPLETE"}, { [kTechDataId] = kTechId.MACAlertConstructionComplete, [kTechDataAlertSound] = MarineCommander.kMACObjectiveCompletedSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "MARINE_ALERT_CONSTRUCTION_COMPLETE"}, { [kTechDataId] = kTechId.AlienAlertNeedMist, [kTechDataAlertIgnoreInterval] = true, [kTechDataAlertSound] = AlienCommander.kSoldierNeedsMistSoundName, [kTechDataAlertType] = kAlertType.Request, [kTechDataAlertText] = "ALIEN_ALERT_NEED_MIST"}, { [kTechDataId] = kTechId.AlienAlertNeedHarvester, [kTechDataAlertIgnoreInterval] = true, [kTechDataAlertSound] = AlienCommander.kSoldierNeedsHarvesterSoundName, [kTechDataAlertType] = kAlertType.Request, [kTechDataAlertText] = "ALIEN_ALERT_NEED_HARVESTER"}, // { [kTechDataId] = kTechId.AlienAlertNeedEnzyme, [kTechDataAlertIgnoreInterval] = true, [kTechDataAlertSound] = AlienCommander.kSoldierNeedsEnzymeSoundName, [kTechDataAlertType] = kAlertType.Request, [kTechDataAlertText] = "ALIEN_ALERT_NEED_ENZYME"}, { [kTechDataId] = kTechId.AlienAlertHiveUnderAttack, [kTechDataAlertSound] = Hive.kUnderAttackSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 2, [kTechDataAlertText] = "ALIEN_ALERT_HIVE_UNDERATTACK", [kTechDataAlertTeam] = true, [kTechDataAlertIgnoreDistance] = true, [kTechDataAlertSendTeamMessage] = kTeamMessageTypes.HiveUnderAttack}, { [kTechDataId] = kTechId.AlienAlertStructureUnderAttack, [kTechDataAlertSound] = AlienCommander.kStructureUnderAttackSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 0, [kTechDataAlertText] = "ALIEN_ALERT_STRUCTURE_UNDERATTACK", [kTechDataAlertTeam] = true}, { [kTechDataId] = kTechId.AlienAlertHarvesterUnderAttack, [kTechDataAlertSound] = AlienCommander.kHarvesterUnderAttackSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 1, [kTechDataAlertText] = "ALIEN_ALERT_HARVESTER_UNDERATTACK", [kTechDataAlertTeam] = true, [kTechDataAlertIgnoreDistance] = true}, { [kTechDataId] = kTechId.AlienAlertLifeformUnderAttack, [kTechDataAlertSound] = AlienCommander.kLifeformUnderAttackSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 0, [kTechDataAlertText] = "ALIEN_ALERT_LIFEFORM_UNDERATTACK", [kTechDataAlertTeam] = true}, { [kTechDataId] = kTechId.AlienAlertHiveDying, [kTechDataAlertSound] = Hive.kDyingSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertPriority] = 3, [kTechDataAlertText] = "ALIEN_ALERT_HIVE_DYING", [kTechDataAlertTeam] = true, [kTechDataAlertIgnoreDistance] = true}, { [kTechDataId] = kTechId.AlienAlertHiveComplete, [kTechDataAlertSound] = Hive.kCompleteSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "ALIEN_ALERT_HIVE_COMPLETE", [kTechDataAlertTeam] = true, [kTechDataAlertIgnoreDistance] = true}, { [kTechDataId] = kTechId.AlienAlertUpgradeComplete, [kTechDataAlertSound] = AlienCommander.kUpgradeCompleteSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "ALIEN_ALERT_UPGRADE_COMPLETE"}, { [kTechDataId] = kTechId.AlienAlertResearchComplete, [kTechDataAlertSound] = AlienCommander.kResearchCompleteSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "ALIEN_ALERT_RESEARCH_COMPLETE"}, { [kTechDataId] = kTechId.AlienAlertManufactureComplete, [kTechDataAlertSound] = AlienCommander.kManufactureCompleteSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "ALIEN_ALERT_MANUFACTURE_COMPLETE"}, { [kTechDataId] = kTechId.AlienAlertOrderComplete, [kTechDataAlertSound] = AlienCommander.kObjectiveCompletedSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "ALIEN_ALERT_ORDER_COMPLETE"}, { [kTechDataId] = kTechId.AlienAlertGorgeBuiltHarvester, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "ALIEN_ALERT_GORGEBUILT_HARVESTER"}, { [kTechDataId] = kTechId.AlienAlertNotEnoughResources, [kTechDataAlertSound] = Alien.kNotEnoughResourcesSound, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "ALIEN_ALERT_NOTENOUGH_RESOURCES"}, { [kTechDataId] = kTechId.AlienCommanderEjected, [kTechDataAlertSound] = AlienCommander.kCommanderEjectedSoundName, [kTechDataAlertType] = kAlertType.Info, [kTechDataAlertText] = "ALIEN_ALERT_COMMANDER_EJECTED", [kTechDataAlertTeam] = true}, { [kTechDataId] = kTechId.DeathTrigger, [kTechDataDisplayName] = "DEATH_TRIGGER", [kTechDataMapName] = DeathTrigger.kMapName, [kTechDataModel] = "" }, } return techData end kTechData = nil function LookupTechId(fieldData, fieldName) // Initialize table if necessary if(kTechData == nil) then kTechData = BuildTechData() end if fieldName == nil or fieldName == "" then Print("LookupTechId(%s, %s) called improperly.", tostring(fieldData), tostring(fieldName)) return kTechId.None end for index,record in ipairs(kTechData) do local currentField = record[fieldName] if(fieldData == currentField) then return record[kTechDataId] end end //Print("LookupTechId(%s, %s) returned kTechId.None", fieldData, fieldName) return kTechId.None end // Table of fieldName tables. Each fieldName table is indexed by techId and returns data. local cachedTechData = {} function ClearCachedTechData() cachedTechData = {} end // Returns true or false. If true, return output in "data" function GetCachedTechData(techId, fieldName) local entry = cachedTechData[fieldName] if entry ~= nil then return entry[techId] end return nil end function SetCachedTechData(techId, fieldName, data) local inserted = false local entry = cachedTechData[fieldName] if entry == nil then cachedTechData[fieldName] = {} entry = cachedTechData[fieldName] end if entry[techId] == nil then entry[techId] = data inserted = true end return inserted end // Call with techId and fieldname (returns nil if field not found). Pass optional // third parameter to use as default if not found. function LookupTechData(techId, fieldName, default) // Initialize table if necessary if(kTechData == nil) then kTechData = BuildTechData() end if techId == nil or techId == 0 or fieldName == nil or fieldName == "" then /* local techIdString = "" if type(tonumber(techId)) == "number" then techIdString = EnumToString(kTechId, techId) end Print("LookupTechData(%s, %s, %s) called improperly.", tostring(techIdString), tostring(fieldName), tostring(default)) */ return default end local data = GetCachedTechData(techId, fieldName) if data == nil then for index,record in ipairs(kTechData) do local currentid = record[kTechDataId] if(techId == currentid and record[fieldName] ~= nil) then data = record[fieldName] break end end if data == nil then data = default end if not SetCachedTechData(techId, fieldName, data) then //Print("Didn't insert anything when calling SetCachedTechData(%d, %s, %s)", techId, fieldName, tostring(data)) else //Print("Inserted new field with SetCachedTechData(%d, %s, %s)", techId, fieldName, tostring(data)) end end return data end // Returns true if specified class name is used to attach objects to function GetIsAttachment(className) return (className == "TechPoint") or (className == "ResourcePoint") end function GetRecycleAmount(techId, upgradeLevel) local amount = GetCachedTechData(techId, kTechDataCostKey) if techId == kTechId.AdvancedArmory then amount = GetCachedTechData(kTechId.Armory, kTechDataCostKey, 0) + GetCachedTechData(kTechId.AdvancedArmoryUpgrade, kTechDataCostKey, 0) end return amount end local gTechForCategory = nil function GetTechForCategory(techId) if gTechForCategory == nil then gTechForCategory = {} for upgradeId = 2, #kTechId do local category = LookupTechData(upgradeId, kTechDataCategory, nil) if category and category ~= kTechId.None then if not gTechForCategory[category] then gTechForCategory[category] = {} end table.insertunique(gTechForCategory[category], upgradeId) end end end return gTechForCategory[techId] or {} end
gpl-3.0
wcjscm/JackGame
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/AudioEngine.lua
2
9069
-------------------------------- -- @module AudioEngine -- @parent_module ccexp -------------------------------- -- -- @function [parent=#AudioEngine] lazyInit -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Sets the current playback position of an audio instance.<br> -- param audioID An audioID returned by the play2d function.<br> -- param sec The offset in seconds from the start to seek to.<br> -- return -- @function [parent=#AudioEngine] setCurrentTime -- @param self -- @param #int audioID -- @param #float sec -- @return bool#bool ret (return value: bool) -------------------------------- -- Gets the volume value of an audio instance.<br> -- param audioID An audioID returned by the play2d function.<br> -- return Volume value (range from 0.0 to 1.0). -- @function [parent=#AudioEngine] getVolume -- @param self -- @param #int audioID -- @return float#float ret (return value: float) -------------------------------- -- Uncache the audio data from internal buffer.<br> -- AudioEngine cache audio data on ios,mac, and win32 platform.<br> -- warning This can lead to stop related audio first.<br> -- param filePath Audio file path. -- @function [parent=#AudioEngine] uncache -- @param self -- @param #string filePath -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Resume all suspended audio instances. -- @function [parent=#AudioEngine] resumeAll -- @param self -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Stop all audio instances. -- @function [parent=#AudioEngine] stopAll -- @param self -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Pause an audio instance.<br> -- param audioID An audioID returned by the play2d function. -- @function [parent=#AudioEngine] pause -- @param self -- @param #int audioID -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Gets the maximum number of simultaneous audio instance of AudioEngine. -- @function [parent=#AudioEngine] getMaxAudioInstance -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Check whether AudioEngine is enabled. -- @function [parent=#AudioEngine] isEnabled -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Gets the current playback position of an audio instance.<br> -- param audioID An audioID returned by the play2d function.<br> -- return The current playback position of an audio instance. -- @function [parent=#AudioEngine] getCurrentTime -- @param self -- @param #int audioID -- @return float#float ret (return value: float) -------------------------------- -- Sets the maximum number of simultaneous audio instance for AudioEngine.<br> -- param maxInstances The maximum number of simultaneous audio instance. -- @function [parent=#AudioEngine] setMaxAudioInstance -- @param self -- @param #int maxInstances -- @return bool#bool ret (return value: bool) -------------------------------- -- Checks whether an audio instance is loop.<br> -- param audioID An audioID returned by the play2d function.<br> -- return Whether or not an audio instance is loop. -- @function [parent=#AudioEngine] isLoop -- @param self -- @param #int audioID -- @return bool#bool ret (return value: bool) -------------------------------- -- Pause all playing audio instances. -- @function [parent=#AudioEngine] pauseAll -- @param self -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Uncache all audio data from internal buffer.<br> -- warning All audio will be stopped first. -- @function [parent=#AudioEngine] uncacheAll -- @param self -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Sets volume for an audio instance.<br> -- param audioID An audioID returned by the play2d function.<br> -- param volume Volume value (range from 0.0 to 1.0). -- @function [parent=#AudioEngine] setVolume -- @param self -- @param #int audioID -- @param #float volume -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- @overload self, string, function -- @overload self, string -- @function [parent=#AudioEngine] preload -- @param self -- @param #string filePath -- @param #function callback -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Whether to enable playing audios<br> -- note If it's disabled, current playing audios will be stopped and the later 'preload', 'play2d' methods will take no effects. -- @function [parent=#AudioEngine] setEnabled -- @param self -- @param #bool isEnabled -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Play 2d sound.<br> -- param filePath The path of an audio file.<br> -- param loop Whether audio instance loop or not.<br> -- param volume Volume value (range from 0.0 to 1.0).<br> -- param profile A profile for audio instance. When profile is not specified, default profile will be used.<br> -- return An audio ID. It allows you to dynamically change the behavior of an audio instance on the fly.<br> -- see `AudioProfile` -- @function [parent=#AudioEngine] play2d -- @param self -- @param #string filePath -- @param #bool loop -- @param #float volume -- @param #cc.experimental::AudioProfile profile -- @return int#int ret (return value: int) -------------------------------- -- Returns the state of an audio instance.<br> -- param audioID An audioID returned by the play2d function.<br> -- return The status of an audio instance. -- @function [parent=#AudioEngine] getState -- @param self -- @param #int audioID -- @return int#int ret (return value: int) -------------------------------- -- Resume an audio instance.<br> -- param audioID An audioID returned by the play2d function. -- @function [parent=#AudioEngine] resume -- @param self -- @param #int audioID -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Stop an audio instance.<br> -- param audioID An audioID returned by the play2d function. -- @function [parent=#AudioEngine] stop -- @param self -- @param #int audioID -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Release objects relating to AudioEngine.<br> -- warning It must be called before the application exit.<br> -- lua endToLua -- @function [parent=#AudioEngine] end -- @param self -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Gets the duration of an audio instance.<br> -- param audioID An audioID returned by the play2d function.<br> -- return The duration of an audio instance. -- @function [parent=#AudioEngine] getDuration -- @param self -- @param #int audioID -- @return float#float ret (return value: float) -------------------------------- -- Sets whether an audio instance loop or not.<br> -- param audioID An audioID returned by the play2d function.<br> -- param loop Whether audio instance loop or not. -- @function [parent=#AudioEngine] setLoop -- @param self -- @param #int audioID -- @param #bool loop -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) -------------------------------- -- Gets the default profile of audio instances.<br> -- return The default profile of audio instances. -- @function [parent=#AudioEngine] getDefaultProfile -- @param self -- @return experimental::AudioProfile#experimental::AudioProfile ret (return value: cc.experimental::AudioProfile) -------------------------------- -- @overload self, string -- @overload self, int -- @function [parent=#AudioEngine] getProfile -- @param self -- @param #int audioID -- @return experimental::AudioProfile#experimental::AudioProfile ret (return value: cc.experimental::AudioProfile) -------------------------------- -- Gets playing audio count. -- @function [parent=#AudioEngine] getPlayingAudioCount -- @param self -- @return int#int ret (return value: int) return nil
gpl-3.0
khanasbot/Avatar_Bot
plugins/banhammer.lua
294
10470
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'superban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!') return superban_user(member_id, chat_id) elseif get_cmd == 'whitelist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'whitelist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end else return 'This isn\'t a chat group' end end if matches[1] == 'superban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' globally banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if matches[1] == 'whitelist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { user = "!kickme : Exit from group", moderator = { "!whitelist <enable>/<disable> : Enable or disable whitelist mode", "!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled", "!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled", "!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled", "!whitelist delete user <user_id> : Remove user from whitelist", "!whitelist delete chat : Remove chat from whitelist", "!ban user <user_id> : Kick user from chat and kicks it if joins chat again", "!ban user <username> : Kick user from chat and kicks it if joins chat again", "!ban delete <user_id> : Unban user", "!kick <user_id> : Kick user from chat group by id", "!kick <username> : Kick user from chat group by username", }, admin = { "!superban user <user_id> : Kick user from all chat and kicks it if joins again", "!superban user <username> : Kick user from all chat and kicks it if joins again", "!superban delete <user_id> : Unban user", }, }, patterns = { "^!(whitelist) (enable)$", "^!(whitelist) (disable)$", "^!(whitelist) (user) (.*)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (user) (.*)$", "^!(whitelist) (delete) (chat)$", "^!(ban) (user) (.*)$", "^!(ban) (delete) (.*)$", "^!(superban) (user) (.*)$", "^!(superban) (delete) (.*)$", "^!(kick) (.*)$", "^!(kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
oUF-wow/oUF
elements/raidtargetindicator.lua
10
2510
--[[ # Element: Raid Target Indicator Handles the visibility and updating of an indicator based on the unit's raid target assignment. ## Widget RaidTargetIndicator - A `Texture` used to display the raid target icon. ## Notes A default texture will be applied if the widget is a Texture and doesn't have a texture set. ## Examples -- Position and size local RaidTargetIndicator = self:CreateTexture(nil, 'OVERLAY') RaidTargetIndicator:SetSize(16, 16) RaidTargetIndicator:SetPoint('TOPRIGHT', self) -- Register it with oUF self.RaidTargetIndicator = RaidTargetIndicator --]] local _, ns = ... local oUF = ns.oUF local GetRaidTargetIndex = GetRaidTargetIndex local SetRaidTargetIconTexture = SetRaidTargetIconTexture local function Update(self, event) local element = self.RaidTargetIndicator --[[ Callback: RaidTargetIndicator:PreUpdate() Called before the element has been updated. * self - the RaidTargetIndicator element --]] if(element.PreUpdate) then element:PreUpdate() end local index = GetRaidTargetIndex(self.unit) if(index) then SetRaidTargetIconTexture(element, index) element:Show() else element:Hide() end --[[ Callback: RaidTargetIndicator:PostUpdate(index) Called after the element has been updated. * self - the RaidTargetIndicator element * index - the index of the raid target marker (number?)[1-8] --]] if(element.PostUpdate) then return element:PostUpdate(index) end end local function Path(self, ...) --[[ Override: RaidTargetIndicator.Override(self, event) Used to completely override the internal update function. * self - the parent object * event - the event triggering the update (string) --]] return (self.RaidTargetIndicator.Override or Update) (self, ...) end local function ForceUpdate(element) if(not element.__owner.unit) then return end return Path(element.__owner, 'ForceUpdate') end local function Enable(self) local element = self.RaidTargetIndicator if(element) then element.__owner = self element.ForceUpdate = ForceUpdate self:RegisterEvent('RAID_TARGET_UPDATE', Path, true) if(element:IsObjectType('Texture') and not element:GetTexture()) then element:SetTexture([[Interface\TargetingFrame\UI-RaidTargetingIcons]]) end return true end end local function Disable(self) local element = self.RaidTargetIndicator if(element) then element:Hide() self:UnregisterEvent('RAID_TARGET_UPDATE', Path) end end oUF:AddElement('RaidTargetIndicator', Path, Enable, Disable)
mit
CodeLiners/Silcom-Kernel
mod/io_old.lua
1
4333
local function getPID() return thread_get(thread_getRunning()).pid end on("load", function() registerHook("io_stdout", function(text) local pid = getPID() process_set(pid, "stdoutbuff", process_get(pid).stdoutbuff..text) end) registerHook("io_stdin", function(mode, block) local inp = process_get(getPID()).stdinbuff if mode == "line" then local ret = "" while true do if 1 == inp:len() and not block then ret = ret..inp inp = "" return ret elseif inp:len() == 0 and not block then return ret elseif inp:len() == 0 then coroutine.yield() end ret = ret.inp:sub(1,1) inp = inp:sub(2) if ret:sub(-1, -1) == "\n" then return ret:sub(1, -2) end end elseif mode == "char" then local ret while inp:len() == 0 do ret = inp:sub(1,1) inp = ret.inp:sub(1,1) if not block then break end coroutine.yield() end return ret end end) registerHook("io_stderr", function(text) local pid = getPID() process_set(pid, "stderrbuff", process_get(pid).stderrbuff..text) end) registerHook("io_readstderr", function(tarpid, mode) if not process_mayInteractWith(getPID(), tarpid) then error("Cannot read stderr from that process", 3) end local inp = process_get(tarpid).stderrbuff if mode == "line" then local ret = "" while true do if 1 == inp:len() then ret = ret..inp inp = "" return ret elseif inp:len() == 0 then return ret end ret = ret.inp:sub(1,1) inp = inp:sub(2) if ret:sub(-1, -1) == "\n" then return ret:sub(1, -2) end end elseif mode == "char" then local ret = inp:sub(1,1) inp = ret.inp:sub(1,1) return ret end end) registerHook("io_readstdout", function(tarpid, mode) if not process_mayInteractWith(getPID(), tarpid) then error("Cannot read stdout from that process", 3) end --print("1(read from):", tarpid or "nil") local inp = process_get(tarpid).stdoutbuff if mode == "line" then --print("2") local ret = "" while true do --print("3:", ret or "nil", ":", inp or "nil") if 1 == inp:len() then ret = ret..inp inp = "" process_set(tarpid, "stdoutbuff", inp) return ret elseif inp:len() == 0 then process_set(tarpid, "stdoutbuff", inp) return ret end ret = ret..inp:sub(1,1) inp = inp:sub(2) if ret:sub(-1, -1) == "\n" then process_set(tarpid, "stdoutbuff", inp) return ret:sub(1, -2) end end elseif mode == "char" then local ret = inp:sub(1,1) inp = ret.inp:sub(1,1) process_set(tarpid, "stdoutbuff", inp) return ret end end) registerHook("io_writestdin", function(tarpid, mode) if not process_mayInteractWith(getPID(), tarpid) then error("Cannot write stdin of that process", 3) end process_set(tarpid, "stdinbuff", process_get(tarpid).stdinbuff..text) end) end )
bsd-3-clause
wcjscm/JackGame
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Animation.lua
11
6377
-------------------------------- -- @module Animation -- @extend Ref -- @parent_module cc -------------------------------- -- Gets the times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ... <br> -- return The times the animation is going to loop. -- @function [parent=#Animation] getLoops -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- Adds a SpriteFrame to a Animation.<br> -- param frame The frame will be added with one "delay unit". -- @function [parent=#Animation] addSpriteFrame -- @param self -- @param #cc.SpriteFrame frame -- @return Animation#Animation self (return value: cc.Animation) -------------------------------- -- Sets whether to restore the original frame when animation finishes. <br> -- param restoreOriginalFrame Whether to restore the original frame when animation finishes. -- @function [parent=#Animation] setRestoreOriginalFrame -- @param self -- @param #bool restoreOriginalFrame -- @return Animation#Animation self (return value: cc.Animation) -------------------------------- -- -- @function [parent=#Animation] clone -- @param self -- @return Animation#Animation ret (return value: cc.Animation) -------------------------------- -- Gets the duration in seconds of the whole animation. It is the result of totalDelayUnits * delayPerUnit.<br> -- return Result of totalDelayUnits * delayPerUnit. -- @function [parent=#Animation] getDuration -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Initializes a Animation with AnimationFrame.<br> -- since v2.0 -- @function [parent=#Animation] initWithAnimationFrames -- @param self -- @param #array_table arrayOfAnimationFrameNames -- @param #float delayPerUnit -- @param #unsigned int loops -- @return bool#bool ret (return value: bool) -------------------------------- -- Initializes a Animation. -- @function [parent=#Animation] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Sets the array of AnimationFrames. <br> -- param frames The array of AnimationFrames. -- @function [parent=#Animation] setFrames -- @param self -- @param #array_table frames -- @return Animation#Animation self (return value: cc.Animation) -------------------------------- -- Gets the array of AnimationFrames.<br> -- return The array of AnimationFrames. -- @function [parent=#Animation] getFrames -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- Sets the times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ... <br> -- param loops The times the animation is going to loop. -- @function [parent=#Animation] setLoops -- @param self -- @param #unsigned int loops -- @return Animation#Animation self (return value: cc.Animation) -------------------------------- -- Sets the delay in seconds of the "delay unit".<br> -- param delayPerUnit The delay in seconds of the "delay unit". -- @function [parent=#Animation] setDelayPerUnit -- @param self -- @param #float delayPerUnit -- @return Animation#Animation self (return value: cc.Animation) -------------------------------- -- Adds a frame with an image filename. Internally it will create a SpriteFrame and it will add it.<br> -- The frame will be added with one "delay unit".<br> -- Added to facilitate the migration from v0.8 to v0.9.<br> -- param filename The path of SpriteFrame. -- @function [parent=#Animation] addSpriteFrameWithFile -- @param self -- @param #string filename -- @return Animation#Animation self (return value: cc.Animation) -------------------------------- -- Gets the total Delay units of the Animation. <br> -- return The total Delay units of the Animation. -- @function [parent=#Animation] getTotalDelayUnits -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Gets the delay in seconds of the "delay unit".<br> -- return The delay in seconds of the "delay unit". -- @function [parent=#Animation] getDelayPerUnit -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Initializes a Animation with frames and a delay between frames.<br> -- since v0.99.5 -- @function [parent=#Animation] initWithSpriteFrames -- @param self -- @param #array_table arrayOfSpriteFrameNames -- @param #float delay -- @param #unsigned int loops -- @return bool#bool ret (return value: bool) -------------------------------- -- Checks whether to restore the original frame when animation finishes. <br> -- return Restore the original frame when animation finishes. -- @function [parent=#Animation] getRestoreOriginalFrame -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Adds a frame with a texture and a rect. Internally it will create a SpriteFrame and it will add it.<br> -- The frame will be added with one "delay unit".<br> -- Added to facilitate the migration from v0.8 to v0.9.<br> -- param pobTexture A frame with a texture.<br> -- param rect The Texture of rect. -- @function [parent=#Animation] addSpriteFrameWithTexture -- @param self -- @param #cc.Texture2D pobTexture -- @param #rect_table rect -- @return Animation#Animation self (return value: cc.Animation) -------------------------------- -- @overload self, array_table, float, unsigned int -- @overload self -- @function [parent=#Animation] create -- @param self -- @param #array_table arrayOfAnimationFrameNames -- @param #float delayPerUnit -- @param #unsigned int loops -- @return Animation#Animation ret (return value: cc.Animation) -------------------------------- -- -- @function [parent=#Animation] createWithSpriteFrames -- @param self -- @param #array_table arrayOfSpriteFrameNames -- @param #float delay -- @param #unsigned int loops -- @return Animation#Animation ret (return value: cc.Animation) -------------------------------- -- -- @function [parent=#Animation] Animation -- @param self -- @return Animation#Animation self (return value: cc.Animation) return nil
gpl-3.0
pfgithub/liquid-science
prototypes/resource/data.lua
1
1671
local function autoplace_settings(name, coverage) local ret = { control = name, sharpness = 1, richness_multiplier = 1500, richness_multiplier_distance_bonus = 20, richness_base = 500, coverage = coverage, peaks = { { noise_layer = name, noise_octaves_difference = -1.5, noise_persistence = 0.3, }, } } for i, resource in ipairs({ "sand-ore" }) do if resource ~= name then ret.starting_area_size = 600 * coverage ret.starting_area_amount = 1500 end end return ret end data:extend({ { type = "noise-layer", name = "sand-ore" } }) data:extend({ { type = "autoplace-control", name = "sand-ore", richness = true, order = "g-s", category = "resource" } }) data:extend({ { type = "resource", name = "sand-ore", icon = "__liquid-science__/graphics/icons/resource/sand-ore.png", flags = {"placeable-neutral"}, order="a-b-a", minable = { hardness = 0.9, mining_particle = "iron-ore" .. "-particle", mining_time = 2, result = "sand" }, collision_box = {{ -0.1, -0.1}, {0.1, 0.1}}, selection_box = {{ -0.5, -0.5}, {0.5, 0.5}}, autoplace = autoplace_settings("sand-ore", 0.02), stage_counts = {1000}, stages = { sheet = { filename = "__liquid-science__/graphics/icons/resource/sand-ore-texture.png", priority = "extra-high", width = 54, height = 54, frame_count = 1, variation_count = 1 } }, icon_size = 20, --map_color = {r=0.85, g=0.765, b=0.608} map_color = {r=255, g=255, b=204} } })
mit
McGlaspie/mvm
lua/mvm/SprintMixin.lua
1
8125
Script.Load("lua/SprintMixin.lua") // Max duration of sprint SprintMixin.kMaxSprintTime = 4 //12 --FIXME This doesn't do shit apparently... // Rate at which max sprint time comes back when not sprinting (multiplier x time) SprintMixin.kSprintRecoveryRate = .5 // 1 // Must have this much energy to start sprint SprintMixin.kMinSprintTime = 1 //5 // After this time, play extra sounds to indicate player is getting tired SprintMixin.kSprintTiredTime = SprintMixin.kMaxSprintTime * 0.4 // Time it takes to get to top speed SprintMixin.kSprintTime = 0.75 //1.5 // Releasing the sprint key within this time after pressing it puts you in sprint mode SprintMixin.kSprintLockTime = .2 // Time it takes to come to rest SprintMixin.kUnsprintTime = kMaxTimeToSprintAfterAttack SprintMixin.kTiredSoundName = PrecacheAsset("sound/NS2.fev/marine/common/sprint_tired") SprintMixin.expectedCallbacks = { GetVelocity = "", GetActiveWeapon = "", GetViewCoords = "", GetIsOnGround = "", } SprintMixin.networkVars = { // time left to sprint is calculated by the three variables sprinting, timeSprintChange and sprintTimeOnChange // time left = Clamp(sprintTimeOnChange + timn since sprint change * rateChange, 0, maxSprintTime sprinting = "private boolean", timeSprintChange = "private time", sprintTimeOnChange = "private float (0 to " .. SprintMixin.kMaxSprintTime .. " by 0.01)", desiredSprinting = "private boolean", sprintingScalar = "private float (0 to 1 by 0.01)", // This is set to the current time whenever the key state changes to down sprintButtonDownTime = "private time", sprintButtonUpTime = "private time", sprintDownLastFrame = "private boolean", sprintMode = "private boolean", requireNewSprintPress = "private boolean", } function SprintMixin:__initmixin() self.sprinting = false self.timeSprintChange = Shared.GetTime() self.sprintTimeOnChange = SprintMixin.kMaxSprintTime self.desiredSprinting = false self.sprintingScalar = 0 self.sprintButtonDownTime = 0 self.sprintButtonUpTime = 0 self.sprintDownLastFrame = false self.sprintMode = false self.requireNewSprintPress = false end function SprintMixin:GetIsSprinting() return self.sprinting end function SprintMixin:GetSprintingScalar() return self.sprintingScalar end function SprintMixin:OnSprintQuickPress() if self.sprintMode then self.sprintMode = false else //if self:GetSprintTime() > SprintMixin.kMinSprintTime then self.sprintMode = true //end end end function SprintMixin:UpdateSprintMode(buttonDown) if buttonDown ~= self.sprintDownLastFrame then local time = Shared.GetTime() if buttonDown then self.sprintButtonDownTime = time self.requireNewSprintPress = false else if (time - self.sprintButtonDownTime) < SprintMixin.kSprintLockTime then self:OnSprintQuickPress() end self.sprintButtonUpTime = time end self.sprintDownLastFrame = buttonDown end end function SprintMixin:UpdateSprintingState(input) PROFILE("SprintMixin:UpdateSprintingState") local velocity = self:GetVelocity() local speed = velocity:GetLength() local weapon = self:GetActiveWeapon() local deployed = not weapon or not weapon.GetIsDeployed or weapon:GetIsDeployed() local sprintingAllowedByWeapon = not deployed or not weapon or weapon:GetSprintAllowed() local attacking = false if weapon and weapon.GetTryingToFire then attacking = weapon:GetTryingToFire(input) end local buttonDown = (bit.band(input.commands, Move.MovementModifier) ~= 0) if not weapon or (not weapon.GetIsReloading or not weapon:GetIsReloading()) then self:UpdateSprintMode(buttonDown) end // Allow small little falls to not break our sprint (stairs) self.desiredSprinting = ( buttonDown or self.sprintMode ) and sprintingAllowedByWeapon and speed > 1 and not self.crouching and self:GetIsOnGround() and not attacking and not self.requireNewSprintPress if input.move.z < kEpsilon then self.desiredSprinting = false else // Only allow sprinting if we're pressing forward and moving in that direction local normMoveDirection = GetNormalizedVectorXZ(self:GetViewCoords():TransformVector(input.move)) local normVelocity = GetNormalizedVectorXZ(velocity) local viewFacing = GetNormalizedVectorXZ(self:GetViewCoords().zAxis) if normVelocity:DotProduct(normMoveDirection) < 0.3 or normMoveDirection:DotProduct(viewFacing) < 0.2 then self.desiredSprinting = false end end if self.desiredSprinting ~= self.sprinting then // Only allow sprinting to start if we have some minimum energy (so we don't start and stop constantly) //if not self.desiredSprinting or (self:GetSprintTime() >= SprintMixin.kMinSprintTime) then self.sprintTimeOnChange = self:GetSprintTime() local sprintDuration = math.max(0, Shared.GetTime() - self.timeSprintChange) self.timeSprintChange = Shared.GetTime() self.sprinting = self.desiredSprinting if self.sprinting then if self.OnSprintStart then self:OnSprintStart() end else if self.OnSprintEnd then self:OnSprintEnd(sprintDuration) end end //end end // Some things break us out of sprint mode if self.sprintMode and (attacking or speed <= 1 or not self:GetIsOnGround() or self.crouching) then self.sprintMode = false self.requireNewSprintPress = attacking end if self.desiredSprinting then // * self:GetSprintTime() / SprintMixin.kMaxSprintTime self.sprintingScalar = Clamp((Shared.GetTime() - self.timeSprintChange) / SprintMixin.kSprintTime, 0, 1) else self.sprintingScalar = 1 - Clamp((Shared.GetTime() - self.timeSprintChange) / SprintMixin.kUnsprintTime, 0, 1) end end function SprintMixin:OnUpdate(deltaTime) if self.OnUpdateSprint then self:OnUpdateSprint(self.sprinting) end end function SprintMixin:OnProcessMove(input) local deltaTime = input.time if self.OnUpdateSprint then self:OnUpdateSprint(self.sprinting) end /*if self.sprinting then if self:GetSprintTime() == 0 then self.sprintTimeOnChange = 0 self.timeSprintChange = Shared.GetTime() self.sprinting = false if self.OnSprintEnd then self:OnSprintEnd() end // Play local sound when we're tired (max 1 playback) if Client and (Client.GetLocalPlayer() == self) then Shared.PlaySound(self, SprintMixin.kTiredSoundName) end self.sprintMode = false if self.sprintDownLastFrame then self.requireNewSprintPress = true end end end*/ end function SprintMixin:GetSprintTime() local dt = Shared.GetTime() - self.timeSprintChange local rate = self.sprinting and -1 or SprintMixin.kSprintRecoveryRate return Clamp( self.sprintTimeOnChange + dt * rate , 0, SprintMixin.kMaxSprintTime ) end function SprintMixin:GetTiredScalar() return Clamp( (1 - (self:GetSprintTime() / SprintMixin.kMaxSprintTime) ) * 2, 0, 1) end
gpl-3.0
haider1984/-1
plugins/en-addsudo.lua
5
1472
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀ ▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀ ▀▄ ▄▀ ADD SUDO : اضافه مطور ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local function callback(extra, success, result) vardump(success) vardump(result) end local function run(msg, matches) if matches[1] == 'addsudo' then chat = 'chat#'..msg.to.id user1 = 'user#'..18293081 chat_add_user(chat, user1, callback, false) return "Developer It has been added to this group " end if matches[1] == 'addsudo1' then chat = 'chat#'..msg.to.id user2 = 'user#'..18293081 chat_add_user(chat, user2, callback, false) return "Developer It has been added to this group " end end return { description = "Invite Sudo and Admin", usage = { "/addsudo : invite Bot Sudo", }, patterns = { "^[!/#$](addsudo)", "^[!/#$](addsudo1)", "^/(add dev)", "^/(add dev)", }, run = run, } -- arabic : @SAJJADNOORI end
gpl-2.0
pydsigner/naev
docs/ai/examples/attacked.lua
19
1323
--[[ -- Based on when pilot is hit by something, then will attempt to retaliate --]] -- triggered when pilot is hit by something function attacked ( attacker ) task = ai.taskname() if task ~= "attack" and task ~= "runaway" then -- some taunting taunt( attacker ) -- now pilot fights back ai.pushtask(0, "attack", attacker) elseif task == "attack" then if ai.targetid() ~= attacker then ai.pushtask(0, "attack", attacker) end end end -- taunts function taunt ( target ) num = ai.rnd(0,4) if num == 0 then msg = "You dare attack me!" elseif num == 1 then msg = "You are no match for the Empire!" elseif num == 2 then msg = "The Empire will have your head!" elseif num == 3 then msg = "You'll regret this!" end if msg then ai.comm(attacker, msg) end end -- attacks function attack () target = ai.targetid() -- make sure pilot exists if not ai.exists(target) then ai.poptask() return end dir = ai.face( target ) dist = ai.dist( ai.pos(target) ) second = ai.secondary() if ai.secondary() == "Launcher" then ai.settarget(target) ai.shoot(2) end if dir < 10 and dist > 300 then ai.accel() elseif (dir < 10 or ai.hasturrets()) and dist < 300 then ai.shoot() end end
gpl-3.0
MrCerealGuy/Stonecraft
games/stonecraft_game/mods/snow/src/abms.lua
1
6864
--[[ 2017-09-21 modified by MrCerealGuy <mrcerealguy@gmx.de> replaced nodeupdate(pos) (deprecated) with minetest.check_for_falling(pos) --]] -- Added to change dirt_with_snow to dirt if covered with blocks that don't let -- light through (sunlight_propagates) or have a light paramtype and -- liquidtype combination. ~ LazyJ, 2014_03_08 minetest.register_abm({ nodenames = {"default:dirt_with_snow"}, interval = 2, chance = 20, action = function(pos) if not abm_allowed.yes then return end local name = minetest.get_node({x=pos.x, y=pos.y+1, z=pos.z}).name local nodedef = minetest.registered_nodes[name] if name ~= "ignore" and nodedef and not ( (nodedef.sunlight_propagates or nodedef.paramtype == "light") and nodedef.liquidtype == "none" ) then minetest.set_node(pos, {name = "default:dirt"}) end end }) --Melting --Any node part of the group melting will melt when near warm nodes such as lava, fire, torches, etc. --The amount of water that replaces the node is defined by the number on the group: --1: one water_source --2: four water_flowings --3: one water_flowing minetest.register_abm({ nodenames = {"group:melts"}, neighbors = {"group:igniter", "default:torch", "default:furnace_active", "group:hot"}, interval = 10, chance = 2, action = function(pos, node) if not abm_allowed.yes then return end local intensity = minetest.get_item_group(node.name,"melts") if intensity == 1 then minetest.set_node(pos, {name="default:water_source"}) elseif intensity == 2 then minetest.set_node(pos, {name="default:water_flowing", param2=7}) elseif intensity == 3 then minetest.set_node(pos, {name="default:water_flowing", param2=3}) --[[ LazyJ, you need to add param2, which defines the amount of the flowing water ~ HybridDog 2015_03_06 This was causing "melts=2" nodes to just disappear so I changed it to replace the node with a water_source for a couple seconds and then replace the water_source with air. This way it made a watery mess that quickly evaporated. ~ LazyJ 2014_04_24 local check_place = function(pos,node) if minetest.get_node(pos).name == "air" then minetest.place_node(pos,node) end end minetest.add_node(pos,{name="default:water_flowing"}) check_place({x=pos.x+1,y=pos.y,z=pos.z},{name="default:water_flowing"}) check_place({x=pos.x-1,y=pos.y,z=pos.z},{name="default:water_flowing"}) check_place({x=pos.x,y=pos.y+1,z=pos.z},{name="default:water_flowing"}) check_place({x=pos.x,y=pos.y-1,z=pos.z},{name="default:water_flowing"}) elseif intensity == 3 then --] minetest.add_node(pos,{name="default:water_source"}) minetest.after(2, function() -- 2 seconds gives just enough time for -- the water to flow and spread before the -- water_source is changed to air. ~ LazyJ if minetest.get_node(pos).name == "default:water_source" then minetest.add_node(pos,{name="air"}) end end) --]] else return end end, }) --Freezing --Water freezes when in contact with snow. minetest.register_abm({ nodenames = {"default:water_source"}, -- Added "group:icemaker" and snowbrick. ~ LazyJ neighbors = {"default:snow", "default:snowblock", "snow:snow_brick", "group:icemaker"}, interval = 20, chance = 4, action = function(pos) if not abm_allowed.yes then return end minetest.add_node(pos,{name="default:ice"}) end, }) --Freeze Ice according to it's param2 value. minetest.register_abm({ nodenames = {"default:ice"}, neighbors = {"default:water_source"}, interval = 20, chance = 4, action = function(pos, node) if not abm_allowed.yes then return end if node.param2 == 0 then return end for l = 0,1 do for i = -1,1,2 do for _,p in pairs({ {x=pos.x+i, z=pos.z-l*i}, {x=pos.x+l*i, z=pos.z+i} }) do if math.random(2) == 2 then p.y = pos.y if minetest.get_node(p).name == "default:water_source" then minetest.add_node(p, { name = "default:ice", param2 = math.random(0,node.param2-1) }) end end end end end if math.random(8) == 8 then minetest.add_node(pos, {name="default:water_source"}) else node.param2 = 0 minetest.add_node(pos, node) end end, }) --Spread moss to cobble. minetest.register_abm({ nodenames = {"default:cobble"}, neighbors = {"snow:moss"}, interval = 20, chance = 6, catch_up = false, action = function(pos, node) if not abm_allowed.yes then return end node.name = "default:mossycobble" minetest.add_node(pos, node) end, }) --Grow Pine Saplings minetest.register_abm({ nodenames = {"snow:sapling_pine"}, interval = 10, chance = 50, action = function(pos) if not abm_allowed.yes then return end -- Check if there is enough vertical-space for the sapling to grow without -- hitting anything else. ~ LazyJ, 2014_04_10 -- 'If' there is air in each of the 8 nodes dirctly above the sapling,... ~LazyJ for i = 1,8 do if minetest.get_node({x=pos.x, y=pos.y+i, z=pos.z}).name ~= "air" then return end end -- 'then' let the sapling grow into a tree. ~ LazyJ snow.make_pine(pos,false) -- This finds the sapling under the grown tree. ~ LazyJ if minetest.get_node(pos).name == "snow:sapling_pine" then -- This switches the sapling to a tree trunk. ~ LazyJ minetest.set_node(pos, {name="default:pinetree"}) -- This is more for testing but it may be useful info to some admins when -- grepping the server logs too. ~ LazyJ minetest.log("action", "A pine sapling grows into a tree at "..minetest.pos_to_string(pos)) end end }) --Grow Christmas Tree Saplings minetest.register_abm({ nodenames = {"snow:xmas_tree"}, interval = 10, chance = 50, action = function(pos) if not abm_allowed.yes then return end -- 'If' there is air in each of the 8 nodes dirctly above the sapling,... ~LazyJ for i = 1,8 do if minetest.get_node({x=pos.x, y=pos.y+i, z=pos.z}).name ~= "air" then return end end -- 'then' let the sapling grow into a tree. ~ LazyJ snow.make_pine(pos,false,true) minetest.log("action", "A pine sapling grows into a Christmas tree at "..minetest.pos_to_string(pos)) -- ~ LazyJ --else -- 'Else', if there isn't air in each of the 8 nodes above the sapling, -- then don't anything; including not allowing the sapling to grow. -- ~ LazyJ, 2014_04_10 --end end }) --Backwards Compatability. minetest.register_abm({ nodenames = {"snow:snow1","snow:snow2","snow:snow3","gsnow4","snow:snow5","snow:snow6","snow:snow7","snow:snow8"}, interval = 1, chance = 1, action = function(pos, node) if not abm_allowed.yes then return end minetest.add_node(pos, {name="default:snow"}) minetest.set_node_level(pos, 7*(tonumber(node.name:sub(-1)))) end, })
gpl-3.0
MrCerealGuy/Stonecraft
games/stonecraft_game/mods/technic/technic/machines/LV/water_mill.lua
1
3498
-- A water mill produces LV EUs by exploiting flowing water across it -- It is a LV EU supplier and fairly low yield (max 180EUs) -- It is a little over half as good as the thermal generator. local S = technic.getter local cable_entry = "^technic_cable_connection_overlay.png" minetest.register_alias("water_mill", "technic:water_mill") minetest.register_craft({ output = 'technic:water_mill', recipe = { {'technic:marble', 'default:diamond', 'technic:marble'}, {'group:wood', 'technic:machine_casing', 'group:wood'}, {'technic:marble', 'technic:lv_cable', 'technic:marble'}, } }) local function check_node_around_mill(pos) local node = minetest.get_node(pos) if node.name == "default:water_flowing" or node.name == "default:river_water_flowing" then return node.param2 -- returns approx. water flow, if any end return false end local run = function(pos, node) local meta = minetest.get_meta(pos) local water_flow = 0 local production_level local eu_supply local max_output = 4 * 45 -- keeping it around 180, little more than previous 150 :) local positions = { {x=pos.x+1, y=pos.y, z=pos.z}, {x=pos.x-1, y=pos.y, z=pos.z}, {x=pos.x, y=pos.y, z=pos.z+1}, {x=pos.x, y=pos.y, z=pos.z-1}, } for _, p in pairs(positions) do local check = check_node_around_mill(p) if check then water_flow = water_flow + check end end eu_supply = math.min(4 * water_flow, max_output) production_level = math.floor(100 * eu_supply / max_output) meta:set_int("LV_EU_supply", eu_supply) meta:set_string("infotext", S("Hydro %s Generator"):format("LV").." ("..production_level.."%)") if production_level > 0 and minetest.get_node(pos).name == "technic:water_mill" then technic.swap_node (pos, "technic:water_mill_active") meta:set_int("LV_EU_supply", 0) return end if production_level == 0 then technic.swap_node(pos, "technic:water_mill") end end minetest.register_node("technic:water_mill", { description = S("Hydro %s Generator"):format("LV"), tiles = { "technic_water_mill_top.png", "technic_machine_bottom.png"..cable_entry, "technic_water_mill_side.png", "technic_water_mill_side.png", "technic_water_mill_side.png", "technic_water_mill_side.png" }, paramtype2 = "facedir", groups = {snappy=2, choppy=2, oddly_breakable_by_hand=2, technic_machine=1, technic_lv=1}, legacy_facedir_simple = true, sounds = default.node_sound_wood_defaults(), on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", S("Hydro %s Generator"):format("LV")) meta:set_int("LV_EU_supply", 0) end, technic_run = run, }) minetest.register_node("technic:water_mill_active", { description = S("Hydro %s Generator"):format("LV"), tiles = {"technic_water_mill_top_active.png", "technic_machine_bottom.png", "technic_water_mill_side.png", "technic_water_mill_side.png", "technic_water_mill_side.png", "technic_water_mill_side.png"}, paramtype2 = "facedir", groups = {snappy=2, choppy=2, oddly_breakable_by_hand=2, technic_machine=1, technic_lv=1, not_in_creative_inventory=1}, legacy_facedir_simple = true, sounds = default.node_sound_wood_defaults(), drop = "technic:water_mill", technic_run = run, technic_disabled_machine_name = "technic:water_mill", }) technic.register_machine("LV", "technic:water_mill", technic.producer) technic.register_machine("LV", "technic:water_mill_active", technic.producer)
gpl-3.0
wcjscm/JackGame
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ParticleFireworks.lua
11
1440
-------------------------------- -- @module ParticleFireworks -- @extend ParticleSystemQuad -- @parent_module cc -------------------------------- -- -- @function [parent=#ParticleFireworks] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ParticleFireworks] initWithTotalParticles -- @param self -- @param #int numberOfParticles -- @return bool#bool ret (return value: bool) -------------------------------- -- Create a fireworks particle system.<br> -- return An autoreleased ParticleFireworks object. -- @function [parent=#ParticleFireworks] create -- @param self -- @return ParticleFireworks#ParticleFireworks ret (return value: cc.ParticleFireworks) -------------------------------- -- Create a fireworks particle system withe a fixed number of particles.<br> -- param numberOfParticles A given number of particles.<br> -- return An autoreleased ParticleFireworks object.<br> -- js NA -- @function [parent=#ParticleFireworks] createWithTotalParticles -- @param self -- @param #int numberOfParticles -- @return ParticleFireworks#ParticleFireworks ret (return value: cc.ParticleFireworks) -------------------------------- -- js ctor -- @function [parent=#ParticleFireworks] ParticleFireworks -- @param self -- @return ParticleFireworks#ParticleFireworks self (return value: cc.ParticleFireworks) return nil
gpl-3.0
McGlaspie/mvm
lua/mvm/GrenadeThrower.lua
1
1086
Script.Load("lua/Weapons/Marine/GrenadeThrower.lua") local function MvM_ThrowGrenade( self, player ) if Server or (Client and Client.GetIsControllingPlayer()) then local viewCoords = player:GetViewCoords() local eyePos = player:GetEyePos() local startPointTrace = Shared.TraceCapsule(eyePos, eyePos + viewCoords.zAxis, 0.2, 0, CollisionRep.Move, PhysicsMask.PredictedProjectileGroup, EntityFilterTwo(self, player)) local startPoint = startPointTrace.endPoint local direction = viewCoords.zAxis if startPointTrace.fraction ~= 1 then direction = GetNormalizedVector(direction:GetProjection(startPointTrace.normal)) end local grenadeClassName = self:GetGrenadeClassName() local grenade = player:CreatePredictedProjectile(grenadeClassName, startPoint, direction * kGrenadeVelocity, 0.7, 0.45) grenade:SetOwner( player ) //nervegas fix hack end end ReplaceLocals( GrenadeThrower.OnTag, { ThrowGrenade = MvM_ThrowGrenade } ) Class_Reload( "GrenadeThrower", {} )
gpl-3.0
rbavishi/vlc-2.2.1
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
lgpl-2.1
dreadmullet/JC2-MP-Racing
server/sCourseManager.lua
1
2314
class("CourseManager") -- Each CourseManager is tied to a course manifest. function CourseManager:__init(manifestPath) self.manifestPath = manifestPath self.courseNames = {} self:LoadManifest() self:Randomize() self.currentIndex = 1 end function CourseManager:GetNextCourseName() return self.courseNames[self.currentIndex] end function CourseManager:GetRandomCourseName() return table.randomvalue(self.courseNames) end function CourseManager:LoadNext() if #self.courseNames == 0 then error("No available courses!") return nil end local courseName = self.courseNames[self.currentIndex] return Course.Load(courseName) end function CourseManager:LoadRandom() if #self.courseNames == 0 then error("No available courses!") return nil end return Course.Load(self:GetRandomCourseName()) end function CourseManager:Advance() self.currentIndex = self.currentIndex + 1 if self.currentIndex > #self.courseNames then self.currentIndex = 1 self:LoadManifest() self:Randomize() end end function CourseManager:Randomize() table.sortrandom(self.courseNames) end function CourseManager:LoadManifest() -- Make sure course manifest exists. local file , fileError = io.open(self.manifestPath , "r") if fileError then error("Error loading course manifest: "..fileError) end file:close() -- Erase courseNames if it's already been filled. This allows it to be updated just by -- calling this function again. self.courseNames = {} -- Loop through each line in the manifest. for line in io.lines(self.manifestPath) do -- Trim comments. line = Utility.TrimCommentsFromLine(line) -- Make sure this line has stuff in it. if string.find(line , "%S") then -- Add the entire line to self.courseNames. table.insert(self.courseNames , line) end end print("Course manifest loaded - "..#self.courseNames.." courses found") end function CourseManager:RemoveCourse(courseNameToRemove) for index , courseName in ipairs(self.courseNames) do if courseNameToRemove == courseName then table.remove(self.courseNames , index) if self.currentIndex > index then if self.currentIndex > #self.courseNames then self.currentIndex = 1 self:Randomize() else self.currentIndex = self.currentIndex - 1 end end break end end end
mit
T3hArco/skeyler-gamemodes
Sassilization/gamemode/modules/unit/server/commands/attackmove.lua
1
1694
---------------------------------------- -- Sassilization -- Shared Unit Module -- http://sassilization.com -- By Spacetech & Sassafrass ---------------------------------------- local CMD = {} CMD.attack = true CMD.move = true function CMD:Init( TargetPos ) self.pos = TargetPos end function CMD:Start( Unit ) assert( IsValid( Unit.Hull ) ) if Unit.Gravitated or Unit.Paralyzed then Unit.Hull:SetMoving( false ) Unit.Hull:GetPhysicsObject():Sleep() Unit:GetCommandQueue():Pop() Unit:SetCommand( nil ) elseif !Unit.Blasted then Unit.Hull:PhysWake() Unit.Hull:SetMoving( true ) end Unit:Think() end function CMD:Think( Unit ) if( Unit:CanAttack() ) then Unit:UpdateView() Unit.Enemy = Unit:UpdateEnemy() end if( self.target == Unit.Enemy and Unit.Enemy ) then if(IsValid(Unit.Enemy) and self.target:GetHealth() > 0) then Unit:Attack( Unit.Enemy ) --self.pos = nil else self:Finish( Unit ) Unit.Enemy = Unit:UpdateEnemy() end end end function CMD:Finish( Unit ) Unit.Hull:SetMoving( false ) Unit.Hull:GetPhysicsObject():Sleep() Unit:GetCommandQueue():Pop() Unit:SetCommand( nil ) end function CMD:CountUnitsAtDestination() self.nextUnitAtDestCount = self.nextUnitAtDestCount or CurTime() if( CurTime() < self.nextUnitAtDestCount ) then return self.unitsAtDestination or 0 end self.nextUnitAtDestCount = CurTime() + 0.5 self.unitsAtDestination = unit.NumUnitsInSphere( self.pos, 12 ) return self.unitsAtDestination end function CMD.__tostring( self ) return "Move and Attack" end SA.RegisterCommand( COMMAND.ATTACKMOVE, CMD )
bsd-3-clause
heysion/prosody-modules
mod_couchdb/couchdb/couchapi.lib.lua
32
2213
local setmetatable = setmetatable; local pcall = pcall; local type = type; local t_concat = table.concat; local print = print; local socket_url = require "socket.url"; local http = require "socket.http"; local ltn12 = require "ltn12"; --local json = require "json"; local json = module:require("couchdb/json"); --module("couchdb") local _M = {}; local function urlcat(url, path) return url:gsub("/*$", "").."/"..path:gsub("^/*", ""); end local doc_mt = {}; doc_mt.__index = doc_mt; function doc_mt:get() return self.db:get(socket_url.escape(self.id)); end function doc_mt:put(val) return self.db:put(socket_url.escape(self.id), val); end function doc_mt:__tostring() return "couchdb.doc("..self.url..")"; end local db_mt = {}; db_mt.__index = db_mt; function db_mt:__tostring() return "couchdb.db("..self.url..")"; end function db_mt:doc(id) local url = urlcat(self.url, socket_url.escape(id)); return setmetatable({ url = url, db = self, id = id }, doc_mt); end function db_mt:get(id) local url = urlcat(self.url, id); local a,b = http.request(url); local r,x = pcall(json.decode, a); if r then a = x; end return a,b; end function db_mt:put(id, value) local url = urlcat(self.url, id); if type(value) == "table" then value = json.encode(value); elseif value ~= nil and type(value) ~= "string" then return nil, "Invalid type"; end local t = {}; local a,b = http.request { url = url, sink = ltn12.sink.table(t), source = ltn12.source.string(value), method = "PUT", headers = { ["Content-Length"] = #value, ["Content-Type"] = "application/json" } }; a = t_concat(t); local r,x = pcall(json.decode, a); if r then a = x; end return a,b; end local server_mt = {}; server_mt.__index = server_mt; function server_mt:db(name) local url = urlcat(self.url, socket_url.escape(name)); return setmetatable({ url = url }, db_mt); end function server_mt:__tostring() return "couchdb.server("..self.url..")"; end function _M.server(url) return setmetatable({ url = url }, server_mt); end function _M.db(url) return setmetatable({ url = url }, db_mt); end return _M;
mit
xing634325131/Luci-0.11.1
applications/luci-pbx/luasrc/model/cbi/pbx-advanced.lua
29
14365
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx 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. luci-pbx 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 luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end appname = "PBX" modulename = "pbx-advanced" defaultbindport = 5060 defaultrtpstart = 19850 defaultrtpend = 19900 -- Returns all the network related settings, including a constructed RTP range function get_network_info() externhost = m.uci:get(modulename, "advanced", "externhost") ipaddr = m.uci:get("network", "lan", "ipaddr") bindport = m.uci:get(modulename, "advanced", "bindport") rtpstart = m.uci:get(modulename, "advanced", "rtpstart") rtpend = m.uci:get(modulename, "advanced", "rtpend") if bindport == nil then bindport = defaultbindport end if rtpstart == nil then rtpstart = defaultrtpstart end if rtpend == nil then rtpend = defaultrtpend end if rtpstart == nil or rtpend == nil then rtprange = nil else rtprange = rtpstart .. "-" .. rtpend end return bindport, rtprange, ipaddr, externhost end -- If not present, insert empty rules in the given config & section named PBX-SIP and PBX-RTP function insert_empty_sip_rtp_rules(config, section) -- Add rules named PBX-SIP and PBX-RTP if not existing found_sip_rule = false found_rtp_rule = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' then found_sip_rule = true elseif s1._name == 'PBX-RTP' then found_rtp_rule = true end end) if found_sip_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-SIP') end if found_rtp_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-RTP') end end -- Delete rules in the given config & section named PBX-SIP and PBX-RTP function delete_sip_rtp_rules(config, section) -- Remove rules named PBX-SIP and PBX-RTP commit = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' or s1._name == 'PBX-RTP' then m.uci:delete(config, s1['.name']) commit = true end end) -- If something changed, then we commit the config. if commit == true then m.uci:commit(config) end end -- Deletes QoS rules associated with this PBX. function delete_qos_rules() delete_sip_rtp_rules ("qos", "classify") end function insert_qos_rules() -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("qos", "classify") -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() -- Iterate through the QoS rules, and if there is no other rule with the same port -- range at the priority service level, insert this rule. commit = false m.uci:foreach("qos", "classify", function(s1) if s1._name == 'PBX-SIP' then if s1.ports ~= bindport or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", bindport) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end elseif s1._name == 'PBX-RTP' then if s1.ports ~= rtprange or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", rtprange) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end end end) -- If something changed, then we commit the qos config. if commit == true then m.uci:commit("qos") end end -- This function is a (so far) unsuccessful attempt to manipulate the firewall rules from here -- Need to do more testing and eventually move to this mode. function maintain_firewall_rules() -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() commit = false -- Only if externhost is set, do we control firewall rules. if externhost ~= nil and bindport ~= nil and rtprange ~= nil then -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("firewall", "rule") -- Iterate through the firewall rules, and if the dest_port and dest_ip setting of the\ -- SIP and RTP rule do not match what we want configured, set all the entries in the rule\ -- appropriately. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then if s1.dest_port ~= bindport then m.uci:set("firewall", s1['.name'], "dest_port", bindport) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end elseif s1._name == 'PBX-RTP' then if s1.dest_port ~= rtprange then m.uci:set("firewall", s1['.name'], "dest_port", rtprange) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end end end) else -- We delete the firewall rules if one or more of the necessary parameters are not set. sip_rule_name=nil rtp_rule_name=nil -- First discover the configuration names of the rules. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then sip_rule_name = s1['.name'] elseif s1._name == 'PBX-RTP' then rtp_rule_name = s1['.name'] end end) -- Then, using the names, actually delete the rules. if sip_rule_name ~= nil then m.uci:delete("firewall", sip_rule_name) commit = true end if rtp_rule_name ~= nil then m.uci:delete("firewall", rtp_rule_name) commit = true end end -- If something changed, then we commit the firewall config. if commit == true then m.uci:commit("firewall") end end m = Map (modulename, translate("Advanced Settings"), translate("This section contains settings that do not need to be changed under \ normal circumstances. In addition, here you can configure your system \ for use with remote SIP devices, and resolve call quality issues by enabling \ the insertion of QoS rules.")) -- Recreate the voip server config, and restart necessary services after changes are commited -- to the advanced configuration. The firewall must restart because of "Remote Usage". function m.on_after_commit(self) -- Make sure firewall rules are in place maintain_firewall_rules() -- If insertion of QoS rules is enabled if m.uci:get(modulename, "advanced", "qos_enabled") == "yes" then insert_qos_rules() else delete_qos_rules() end luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/firewall restart 1\>/dev/null 2\>/dev/null") end ----------------------------------------------------------------------------- s = m:section(NamedSection, "advanced", "settings", translate("Advanced Settings")) s.anonymous = true s:tab("general", translate("General Settings")) s:tab("remote_usage", translate("Remote Usage"), translatef("You can use your SIP devices/softphones with this system from a remote location \ as well, as long as your Internet Service Provider gives you a public IP. \ You will be able to call other local users for free (e.g. other Analog Telephone Adapters (ATAs)) \ and use your VoIP providers to make calls as if you were local to the PBX. \ After configuring this tab, go back to where users are configured and see the new \ Server and Port setting you need to configure the remote SIP devices with. Please note that if this \ PBX is not running on your router/gateway, you will need to configure port forwarding (NAT) on your \ router/gateway. Please forward the ports below (SIP port and RTP range) to the IP address of the \ device running this PBX.")) s:tab("qos", translate("QoS Settings"), translate("If you experience jittery or high latency audio during heavy downloads, you may want \ to enable QoS. QoS prioritizes traffic to and from your network for specified ports and IP \ addresses, resulting in better latency and throughput for sound in our case. If enabled below, \ a QoS rule for this service will be configured by the PBX automatically, but you must visit the \ QoS configuration page (Network->QoS) to configure other critical QoS settings like Download \ and Upload speed.")) ringtime = s:taboption("general", Value, "ringtime", translate("Number of Seconds to Ring"), translate("Set the number of seconds to ring users upon incoming calls before hanging up \ or going to voicemail, if the voicemail is installed and enabled.")) ringtime.default = 30 ua = s:taboption("general", Value, "useragent", translate("User Agent String"), translate("This is the name that the VoIP server will use to identify itself when \ registering to VoIP (SIP) providers. Some providers require this to a specific \ string matching a hardware SIP device.")) ua.default = appname h = s:taboption("remote_usage", Value, "externhost", translate("Domain/IP Address/Dynamic Domain"), translate("You can enter your domain name, external IP address, or dynamic domain name here \ Please keep in mind that if your IP address is dynamic and it changes your configuration \ will become invalid. Hence, it's recommended to set up Dynamic DNS in this case.")) h.datatype = "hostname" p = s:taboption("remote_usage", Value, "bindport", translate("External SIP Port"), translate("Pick a random port number between 6500 and 9500 for the service to listen on. \ Do not pick the standard 5060, because it is often subject to brute-force attacks. \ When finished, (1) click \"Save and Apply\", and (2) click the \"Restart VoIP Service\" \ button above. Finally, (3) look in the \"SIP Device/Softphone Accounts\" section for \ updated Server and Port settings for your SIP Devices/Softphones.")) p.datatype = "port" p = s:taboption("remote_usage", Value, "rtpstart", translate("RTP Port Range Start"), translate("RTP traffic carries actual voice packets. This is the start of the port range \ that will be used for setting up RTP communication. It's usually OK to leave this \ at the default value.")) p.datatype = "port" p.default = defaultrtpstart p = s:taboption("remote_usage", Value, "rtpend", translate("RTP Port Range End")) p.datatype = "port" p.default = defaultrtpend p = s:taboption("qos", ListValue, "qos_enabled", translate("Insert QoS Rules")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" return m
apache-2.0
rgujju/NexIDE
firmware/tools/utils.lua
48
11997
-- Generic utility functions module( ..., package.seeall ) local lfs = require "lfs" local sf = string.format -- Taken from Lake dir_sep = package.config:sub( 1, 1 ) is_os_windows = dir_sep == '\\' -- Converts a string with items separated by 'sep' into a table string_to_table = function( s, sep ) if type( s ) ~= "string" then return end sep = sep or ' ' if s:sub( -1, -1 ) ~= sep then s = s .. sep end s = s:gsub( sf( "^%s*", sep ), "" ) local t = {} local fmt = sf( "(.-)%s+", sep ) for w in s:gmatch( fmt ) do table.insert( t, w ) end return t end -- Split a file name into 'path part' and 'extension part' split_ext = function( s ) local pos for i = #s, 1, -1 do if s:sub( i, i ) == "." then pos = i break end end if not pos or s:find( dir_sep, pos + 1 ) then return s end return s:sub( 1, pos - 1 ), s:sub( pos ) end -- Replace the extension of a given file name replace_extension = function( s, newext ) local p, e = split_ext( s ) if e then if newext and #newext > 0 then s = p .. "." .. newext else s = p end end return s end -- Return 'true' if building from Windows, false otherwise is_windows = function() return is_os_windows end -- Prepend each component of a 'pat'-separated string with 'prefix' prepend_string = function( s, prefix, pat ) if not s or #s == 0 then return "" end pat = pat or ' ' local res = '' local st = string_to_table( s, pat ) foreach( st, function( k, v ) res = res .. prefix .. v .. " " end ) return res end -- Like above, but consider 'prefix' a path prepend_path = function( s, prefix, pat ) return prepend_string( s, prefix .. dir_sep, pat ) end -- full mkdir: create all the paths needed for a multipath full_mkdir = function( path ) local ptables = string_to_table( path, dir_sep ) local p, res = '' for i = 1, #ptables do p = ( i ~= 1 and p .. dir_sep or p ) .. ptables[ i ] res = lfs.mkdir( p ) end return res end -- Concatenate the given paths to form a complete path concat_path = function( paths ) return table.concat( paths, dir_sep ) end -- Return true if the given array contains the given element, false otherwise array_element_index = function( arr, element ) for i = 1, #arr do if arr[ i ] == element then return i end end end -- Linearize an array with (possibly) embedded arrays into a simple array _linearize_array = function( arr, res, filter ) if type( arr ) ~= "table" then return end for i = 1, #arr do local e = arr[ i ] if type( e ) == 'table' and filter( e ) then _linearize_array( e, res, filter ) else table.insert( res, e ) end end end linearize_array = function( arr, filter ) local res = {} filter = filter or function( v ) return true end _linearize_array( arr, res, filter ) return res end -- Return an array with the keys of a table table_keys = function( t ) local keys = {} foreach( t, function( k, v ) table.insert( keys, k ) end ) return keys end -- Return an array with the values of a table table_values = function( t ) local vals = {} foreach( t, function( k, v ) table.insert( vals, v ) end ) return vals end -- Returns true if 'path' is a regular file, false otherwise is_file = function( path ) return lfs.attributes( path, "mode" ) == "file" end -- Returns true if 'path' is a directory, false otherwise is_dir = function( path ) return lfs.attributes( path, "mode" ) == "directory" end -- Return a list of files in the given directory matching a given mask get_files = function( path, mask, norec, level ) local t = '' level = level or 0 for f in lfs.dir( path ) do local fname = path .. dir_sep .. f if lfs.attributes( fname, "mode" ) == "file" then local include if type( mask ) == "string" then include = fname:find( mask ) else include = mask( fname ) end if include then t = t .. ' ' .. fname end elseif lfs.attributes( fname, "mode" ) == "directory" and not fname:find( "%.+$" ) and not norec then t = t .. " " .. get_files( fname, mask, norec, level + 1 ) end end return level > 0 and t or t:gsub( "^%s+", "" ) end -- Check if the given command can be executed properly check_command = function( cmd ) local res = os.execute( cmd .. " > .build.temp 2>&1" ) os.remove( ".build.temp" ) return res end -- Execute a command and capture output -- From: http://stackoverflow.com/a/326715/105950 exec_capture = function( cmd, raw ) local f = assert(io.popen(cmd, 'r')) local s = assert(f:read('*a')) f:close() if raw then return s end s = string.gsub(s, '^%s+', '') s = string.gsub(s, '%s+$', '') s = string.gsub(s, '[\n\r]+', ' ') return s end -- Execute the given command for each value in a table foreach = function ( t, cmd ) if type( t ) ~= "table" then return end for k, v in pairs( t ) do cmd( k, v ) end end -- Generate header with the given #defines, return result as string gen_header_string = function( name, defines ) local s = "// eLua " .. name:lower() .. " definition\n\n" s = s .. "#ifndef __" .. name:upper() .. "_H__\n" s = s .. "#define __" .. name:upper() .. "_H__\n\n" for key,value in pairs(defines) do s = s .. string.format("#define %-25s%-19s\n",key:upper(),value) end s = s .. "\n#endif\n" return s end -- Generate header with the given #defines, save result to file gen_header_file = function( name, defines ) local hname = concat_path{ "inc", name:lower() .. ".h" } local h = assert( io.open( hname, "w" ) ) h:write( gen_header_string( name, defines ) ) h:close() end -- Remove the given elements from an array remove_array_elements = function( arr, del ) del = istable( del ) and del or { del } foreach( del, function( k, v ) local pos = array_element_index( arr, v ) if pos then table.remove( arr, pos ) end end ) end -- Remove a directory recusively -- USE WITH CARE!! Doesn't do much checks :) rmdir_rec = function ( dirname ) if lfs.attributes( dirname, "mode" ) ~= "directory" then return end for f in lfs.dir( dirname ) do local ename = string.format( "%s/%s", dirname, f ) local attrs = lfs.attributes( ename ) if attrs.mode == 'directory' and f ~= '.' and f ~= '..' then rmdir_rec( ename ) elseif attrs.mode == 'file' or attrs.mode == 'named pipe' or attrs.mode == 'link' then os.remove( ename ) end end lfs.rmdir( dirname ) end -- Concatenates the second table into the first one concat_tables = function( dst, src ) foreach( src, function( k, v ) dst[ k ] = v end ) end ------------------------------------------------------------------------------- -- Color-related funtions -- Currently disabled when running in Windows -- (they can be enabled by setting WIN_ANSI_TERM) local dcoltable = { 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' } local coltable = {} foreach( dcoltable, function( k, v ) coltable[ v ] = k - 1 end ) local _col_builder = function( col ) local _col_maker = function( s ) if is_os_windows and not os.getenv( "WIN_ANSI_TERM" ) then return s else return( sf( "\027[%d;1m%s\027[m", coltable[ col ] + 30, s ) ) end end return _col_maker end col_funcs = {} foreach( coltable, function( k, v ) local fname = "col_" .. k _G[ fname ] = _col_builder( k ) col_funcs[ k ] = _G[ fname ] end ) ------------------------------------------------------------------------------- -- Option handling local options = {} options.new = function() local self = {} self.options = {} setmetatable( self, { __index = options } ) return self end -- Argument validator: boolean value options._bool_validator = function( v ) if v == '0' or v:upper() == 'FALSE' then return false elseif v == '1' or v:upper() == 'TRUE' then return true end end -- Argument validator: choice value options._choice_validator = function( v, allowed ) for i = 1, #allowed do if v:upper() == allowed[ i ]:upper() then return allowed[ i ] end end end -- Argument validator: choice map (argument value maps to something) options._choice_map_validator = function( v, allowed ) for k, value in pairs( allowed ) do if v:upper() == k:upper() then return value end end end -- Argument validator: string value (no validation) options._string_validator = function( v ) return v end -- Argument printer: boolean value options._bool_printer = function( o ) return "true|false", o.default and "true" or "false" end -- Argument printer: choice value options._choice_printer = function( o ) local clist, opts = '', o.data for i = 1, #opts do clist = clist .. ( i ~= 1 and "|" or "" ) .. opts[ i ] end return clist, o.default end -- Argument printer: choice map printer options._choice_map_printer = function( o ) local clist, opts, def = '', o.data local i = 1 for k, v in pairs( opts ) do clist = clist .. ( i ~= 1 and "|" or "" ) .. k if o.default == v then def = k end i = i + 1 end return clist, def end -- Argument printer: string printer options._string_printer = function( o ) return nil, o.default end -- Add an option of the specified type options._add_option = function( self, optname, opttype, help, default, data ) local validators = { string = options._string_validator, choice = options._choice_validator, boolean = options._bool_validator, choice_map = options._choice_map_validator } local printers = { string = options._string_printer, choice = options._choice_printer, boolean = options._bool_printer, choice_map = options._choice_map_printer } if not validators[ opttype ] then print( sf( "[builder] Invalid option type '%s'", opttype ) ) os.exit( 1 ) end table.insert( self.options, { name = optname, help = help, validator = validators[ opttype ], printer = printers[ opttype ], data = data, default = default } ) end -- Find an option with the given name options._find_option = function( self, optname ) for i = 1, #self.options do local o = self.options[ i ] if o.name:upper() == optname:upper() then return self.options[ i ] end end end -- 'add option' helper (automatically detects option type) options.add_option = function( self, name, help, default, data ) local otype if type( default ) == 'boolean' then otype = 'boolean' elseif data and type( data ) == 'table' and #data == 0 then otype = 'choice_map' elseif data and type( data ) == 'table' then otype = 'choice' data = linearize_array( data ) elseif type( default ) == 'string' then otype = 'string' else print( sf( "Error: cannot detect option type for '%s'", name ) ) os.exit( 1 ) end self:_add_option( name, otype, help, default, data ) end options.get_num_opts = function( self ) return #self.options end options.get_option = function( self, i ) return self.options[ i ] end -- Handle an option of type 'key=value' -- Returns both the key and the value or nil for error options.handle_arg = function( self, a ) local si, ei, k, v = a:find( "([^=]+)=(.*)$" ) if not k or not v then print( sf( "Error: invalid syntax in '%s'", a ) ) return end local opt = self:_find_option( k ) if not opt then print( sf( "Error: invalid option '%s'", k ) ) return end local optv = opt.validator( v, opt.data ) if optv == nil then print( sf( "Error: invalid value '%s' for option '%s'", v, k ) ) return end return k, optv end -- Show help for all the registered options options.show_help = function( self ) for i = 1, #self.options do local o = self.options[ i ] print( sf( "\n %s: %s", o.name, o.help ) ) local values, default = o.printer( o ) if values then print( sf( " Possible values: %s", values ) ) end print( sf( " Default value: %s", default or "none (changes at runtime)" ) ) end end -- Create a new option handler function options_handler() return options.new() end
gpl-3.0
Djabbz/nn
MixtureTable.lua
15
5612
local MixtureTable, parent = torch.class('nn.MixtureTable', 'nn.Module') function MixtureTable:__init(dim) parent.__init(self) self.dim = dim self.size = torch.LongStorage() self.batchSize = 0 self.size2 = torch.LongStorage() self.backwardSetup = false self.gradInput = {} end function MixtureTable:updateOutput(input) local gaterInput, expertInputs = table.unpack(input) -- buffers self._gaterView = self.gaterView or input[1].new() self._expert = self._expert or input[1].new() self._expertView = self._expertView or input[1].new() self.dimG = 2 local batchSize = gaterInput:size(1) if gaterInput:dim() < 2 then self.dimG = 1 self.dim = self.dim or 1 batchSize = 1 end self.dim = self.dim or 2 if self.table or torch.type(expertInputs) == 'table' then -- expertInputs is a Table : self.table = true if gaterInput:size(self.dimG) ~= #expertInputs then error"Should be one gater output per expert" end local expertInput = expertInputs[1] if self.batchSize ~= batchSize then self.size:resize(expertInput:dim()+1):fill(1) if self.dimG > 1 then self.size[1] = gaterInput:size(1) end self.size[self.dim] = gaterInput:size(self.dimG) self.output:resizeAs(expertInput) self.backwardSetup = false self.batchSize = batchSize end self._gaterView:view(gaterInput, self.size) self.output:zero() -- multiply accumulate gater outputs by their commensurate expert for i,expertInput in ipairs(expertInputs) do local gate = self._gaterView:select(self.dim,i):expandAs(expertInput) self.output:addcmul(expertInput, gate) end else -- expertInputs is a Tensor : if self.batchSize ~= batchSize then self.size:resize(expertInputs:dim()):fill(1) if self.dimG > 1 then self.size[1] = gaterInput:size(1) end self.size[self.dim] = gaterInput:size(self.dimG) self.output:resizeAs(expertInputs:select(self.dim, 1)) self.gradInput[2] = self._gradInput self.batchSize = batchSize self.backwardSetup = false end self._gaterView:view(gaterInput, self.size) self._expert:cmul(self._gaterView:expandAs(expertInputs), expertInputs) self.output:sum(self._expert, self.dim) self.output:resizeAs(expertInputs:select(self.dim, 1)) end return self.output end function MixtureTable:updateGradInput(input, gradOutput) local gaterInput, expertInputs = table.unpack(input) nn.utils.recursiveResizeAs(self.gradInput, input) local gaterGradInput, expertGradInputs = table.unpack(self.gradInput) -- buffers self._sum = self._sum or input[1].new() self._gradInput = self._gradInput or {input[1].new(), {}} self._expertView2 = self._expertView2 or input[1].new() self._expert2 = self._expert2 or input[1].new() if self.table then if not self.backwardSetup then for i,expertInput in ipairs(expertInputs) do local expertGradInput = expertGradInputs[i] or expertInput:clone() expertGradInput:resizeAs(expertInput) expertGradInputs[i] = expertGradInput end gaterGradInput:resizeAs(gaterInput) self.backwardSetup = true end -- like CMulTable, but with broadcasting for i,expertGradInput in ipairs(expertGradInputs) do -- gater updateGradInput self._expert:cmul(gradOutput, expertInputs[i]) if self.dimG == 1 then self._expertView:view(self._expert, -1) else self._expertView:view(self._expert, gradOutput:size(1), -1) end self._sum:sum(self._expertView, self.dimG) if self.dimG == 1 then gaterGradInput[i] = self._sum:select(self.dimG,1) else gaterGradInput:select(self.dimG,i):copy(self._sum:select(self.dimG,1)) end -- expert updateGradInput local gate = self._gaterView:select(self.dim,i):expandAs(expertGradInput) expertGradInput:cmul(gate, gradOutput) end else if not self.backwardSetup then self.size2:resize(expertInputs:dim()) self.size2:copy(expertInputs:size()) self.size2[self.dim] = 1 gaterGradInput:resizeAs(gaterInput) self.backwardSetup = true end -- gater updateGradInput self._expertView:view(gradOutput, self.size2) local gradOutput = self._expertView:expandAs(expertInputs) self._expert:cmul(gradOutput, expertInputs) local expert = self._expert:transpose(self.dim, self.dimG) if not expert:isContiguous() then self._expert2:resizeAs(expert) self._expert2:copy(expert) expert = self._expert2 end if self.dimG == 1 then self._expertView2:view(expert, gaterInput:size(1), -1) else self._expertView2:view(expert, gaterInput:size(1), gaterInput:size(2), -1) end gaterGradInput:sum(self._expertView2, self.dimG+1) gaterGradInput:resizeAs(gaterInput) -- expert updateGradInput expertGradInputs:cmul(self._gaterView:expandAs(expertInputs), gradOutput) end return self.gradInput end function MixtureTable:type(type) self._gaterView = nil self._expert = nil self._expertView = nil self._sum = nil self._gradInput = nil self._expert2 = nil self._expertView2 = nil return parent.type(self, type) end
bsd-3-clause
panozzaj/ufo2000
extensions/terrain-airfield/air.lua
2
3897
AddXcomTerrain { Name = "Airfield", Tiles = { "$(xcom)/terrain/blanks.*", "$(tftd)/terrain/port01.*", "$(tftd)/terrain/port02.*", "$(xcom)/terrain/plane.*", "$(xcom)/terrain/xbase2.*" }, Maps = { "$(extension)/air00.map", "$(extension)/air01.map", "$(extension)/air02.map", "$(extension)/air03.map", "$(extension)/air04.map", "$(extension)/air05.map", "$(extension)/air06.map", "$(extension)/air07.map", "$(extension)/air08.map", "$(extension)/air09.map", "$(extension)/air10.map", "$(extension)/air11.map", "$(extension)/air12.map", "$(extension)/air13.map", "$(extension)/air14.map", "$(extension)/air15.map", "$(extension)/air16.map" }, MapGenerator = function(tmp) local function add_roads(size_x, size_y, map) local row = {} local col if (math.random(1, 2) ~= 1) then col = math.random(1, size_y / 2) col = (col * 2) - 1 map[size_x - 3][col] = 12 map[size_x - 2][col] = -1 map[size_x - 3][col + 1] = -1 map[size_x - 2][col + 1] = -1 map[size_x - 1][col] = 11 map[size_x][col] = -1 map[size_x - 1][col + 1] = -1 map[size_x][col + 1] = -1 end for i = 1, 2 do if (col) then if (i > 1 and size_x >= 4 + 2) then if (math.random(1, 2) ~= 1) then row[i] = math.random(1, (size_x - 4) / 2) row[i] = (row[i] * 2) - 1 end else row[i] = size_x - 1 end else if (math.random(1, 3 - i) ~= 1) then row[i] = math.random(1, size_x / 2) row[i] = (row[i] * 2) - 1 end end if (row[i]) then for j = 1, size_y, 2 do if (j == size_y and not col) then break end if (map[row[i]][j] ~= 11) then if (j == size_y - 2 and not col) then map[row[i]][j] = random {05, 16} elseif (j == size_y - 1) then map[row[i]][j] = random {01, 02, 05, 16} else map[row[i]][j] = random {01, 02} end map[row[i] + 1][j] = -1 map[row[i]][j + 1] = -1 map[row[i] + 1][j + 1] = -1 end end end end end local function random_normal() return random {00, 03, 04, 06, 08, 09, 13} end local function random_double(x, y, map) local do_not_place = {-1, 01, 02, 05, 07, 10, 11, 12, 14, 15, 16} local dnp_num = 11 for i = 0, 1 do for j = 0, 1 do for k = 1, dnp_num do if (map[x + i][y + j] == do_not_place[k]) then return end end end end map[x][y] = random {07, 10, 14, 15} map[x + 1][y] = -1 map[x][y + 1] = -1 map[x + 1][y + 1] = -1 end for i = 1, tmp.SizeY do for j = 1, tmp.SizeX do tmp.Mapdata[i][j] = random_normal() end end add_roads(tmp.SizeX, tmp.SizeY, tmp.Mapdata) for i = 1, tmp.SizeY - 1 do for j = 1, tmp.SizeX - 1 do if (math.random(2, 3) > 2) then random_double(i, j, tmp.Mapdata) end end end return tmp end }
gpl-2.0
T3hArco/skeyler-gamemodes
sslobby/entities/entities/slot_machine/init.lua
1
2281
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") resource.AddFile("sound/testslot/jackpot.mp3") resource.AddFile("sound/testslot/pull_lever.mp3") resource.AddFile("sound/testslot/spinning_1.mp3") resource.AddFile("sound/testslot/spinning_3.mp3") resource.AddFile("sound/testslot/spinning_3.mp3") util.AddNetworkString("ss_pullslotmc") function ENT:Initialize() self:SetModel("models/sam/slotmachine.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_NONE) self:SetUseType(SIMPLE_USE) self:SetTrigger(true) self:DrawShadow(false) self.nextPull = 0 self.sequence = self:LookupSequence("pull_handle") end function ENT:Use(player) if (self.nextPull < CurTime()) then if !player:HasMoney(5) then player:ChatPrint("You do not have enough money to play. Come back later, it's only $5!") self.nextPull = CurTime() +5 return end self:ResetSequence(self.sequence) local randomLeft = math.random(1, 6) local randomMiddle = math.random(1, 6) local randomRight = math.random(1, 6) local winMultiply = 0 for k, data in pairs(self.winDefines) do local winCount, winRequired = 0, 0 if (data.slots[1] > 0) then winRequired = winRequired +1 if (randomLeft == data.slots[1]) then winCount = winCount +1 end end if (data.slots[2] > 0) then winRequired = winRequired +1 if (randomMiddle == data.slots[2]) then winCount = winCount +1 end end if (data.slots[3] > 0) then winRequired = winRequired +1 if (randomRight == data.slots[3]) then winCount = winCount +1 end end if (winCount >= winRequired and data.win > winMultiply) then winMultiply = data.win end end player:TakeMoney(5) if (winMultiply > 0) then timer.Simple(2.5, function() if player and player:IsValid() then player:GiveMoney(5 *winMultiply) player:ChatPrint("You have won: $"..tostring(5*winMultiply)) end end) end net.Start("ss_pullslotmc") net.WriteUInt(randomLeft, 4) net.WriteUInt(randomMiddle, 4) net.WriteUInt(randomRight, 4) net.WriteEntity(self) net.SendPVS(self:GetPos() +Vector(0, 0, 5)) self.nextPull = CurTime() +5 end end
bsd-3-clause
5620j/taylor-bot
bot/taylor-bot.lua
1
13910
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") local f = assert(io.popen('/usr/bin/git describe --tags', 'r')) VERSION = assert(f:read('*a')) f:close() -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end msg = backward_msg_format(msg) local receiver = get_receiver(msg) print(receiver) --vardump(msg) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) -- See plugins/isup.lua as an example for cron _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 < os.time() - 5 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 --send_large_msg(*group id*, msg.text) *login code will be sent to GroupID* return false 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("Sudo 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 = { "admin", "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "pl", "get", "broadcast", "invite", "all", "leave_ban", "supergroup", "whitelist", "msg_checks", "support", "instagram", "time", "times", "azan", "qr", "share", "webshot", "wiki", "lock_english", "gps", "sticker", "linksp", "Slm", "abjad", }, sudo_users = {189308877},--Sudo users moderation = {data = 'data/moderation.json'}, about_text = [[Taylor Team v4 Taylor Team and Taylor Bot Anti spam / anti link channel :@MonsterTGbot ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [group|sgroup] [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !settings [group|sgroup] [GroupID] Set settings for GroupID !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !support Promote user to support !-support Demote user from support !log Get a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] **You can use "#", "!", or "/" to begin all commands *Only admins and sudo can add bots in group *Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only admins and sudo can use res, setowner, commands ]], 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 Returns help text !lock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict] Lock group settings *rtl: Kick user if Right To Left Char. is in name* !unlock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict] Unlock group settings *rtl: Kick user if Right To Left Char. is in name* !mute [all|audio|gifs|photo|video] mute group message types *If "muted" message type: user is kicked if message type is posted !unmute [all|audio|gifs|photo|video] Unmute group message types *If "unmuted" message type: user is not kicked if message type is posted !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !muteslist Returns mutes for chat !muteuser [username] Mute a user in chat *user is kicked if they talk *only owners can mute | mods and owners can unmute !mutelist Returns list of muted users in chat !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 Returns group logs !banlist will return group ban list **You can use "#", "!", or "/" to begin all commands *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 ]], help_text_super =[[ راهنمای سوپر گروه دو زبان 💢!info اطلاعات 💢!admins لیست ادمین 💢!support دعوت سازنده ربات در صورت وجود مشکل فقط در صورت وجود مشکل در گروه سازنده را دعوت کنید در غیر این صورت گروه شما حذف خواهد شد 💢!owner نمایش مدیر اصلی 💢!msgrem (عددی زیر 100) حذف پیام های سوپرگروه به صورت عددی 💢!weather نام شهر دریافت آب وهوای یک شهر 💢!modlist نمایش لیست مدیران فرعی 💢!insta (یوزرنیم اینستا) سرچ کردن یک یوزرنیم در اینستاگرام 💢!bots لیست بوت های گروه 💢!wikifa (متن) جستجوی یک متن در ویکی پدیا 💢!azan (شهر) دریافت وقت اذان یک شهر 💢!share دریافت اطلاعات سازنده 💢!webshot (آدرس سایت) اسکرین شات گرفتن از یک سایت 💢!supportlink دریافت لینک گروه ساپورت ربات 💢!qr دریافت هر چیزی به صورت بارکد 💢!who لیست افراد گروه 💢!gps (شهر) (کشور) دریافت مکان مورد نظر از گوگل 💢!block بلاک از سوپر گروه 💢!ban بن کردن 💢!unban ان بن کردن 💢!id ایدی 💢!id from ایدی مسیج فروارد شده 💢!kickme حذف خود 💢!setowner تنظیم مدیر اصلی 💢!promote [username|id] تنظیم مدیر فرعی 💢!demote [username|id] پاک کردن مدیر فرعی 💢!setname تنظیم اسم گروه 💢!setphoto تنظیم عکس گروه 💢!setrules تنظیم قوانین گروه 💢!setabout تنظیم در باره ی گروه 💢!newlink لینک جدید 💢!link دریافت لینک 💢!sticker متن تبدیل متن به استیکر 💢!rules نمایش قوانین 💢!lock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict] قفل مواردی که در بالا ذکر شده 💢!unlock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict] ان قفل مواردی که در بالا ذکر شده 💢!mute [all|audio|gifs|photo|video|service] قفل چت 💢!unmute [all|audio|gifs|photo|video|service] باز کردن چت 💢!setflood [value] تنظیم حساسیت 💢!settings تنظیمات گروه 💢!mutelist لیست موت شدگان 💢!banlist لیست بن شدگان 💢!clean [rules|about|modlist|mutelist] پاک کردن مواردی که در بالا ذکر شده 💢!del حذف پیام با ریپلی از کارکترهای #!/ پشتیبانی می کند Channel:@MonsterTGbot ]], } 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) --vardump (chat) 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(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) 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
hugomg/lullaby
lullaby/sax.lua
1
5227
local Exports = {} local yield = coroutine.yield ------------------- --SAX Stream events ------------------- -- string, list[{string,string}] -> Evt local function StartEvent(tagname, attrs) assert(type(attrs) == 'table') return {evttype='START', tagname=tagname, attrs=attrs or{}} end -- string -> Evt local function TextEvent(text) return {evttype='TEXT', text=text} end -- string -> Evt local function EndEvent(tagname) return {evttype='END', tagname=tagname} end -- string -> Evt local function CommentEvent(text) return {evttype='COMMENT', text=text} end Exports.StartEvent = StartEvent Exports.TextEvent = TextEvent Exports.EndEvent = EndEvent Exports.EmitStartEvent = function(...) return yield(StartEvent(...)) end Exports.EmitTextEvent = function(...) return yield(TextEvent(...)) end Exports.EmitEndEvent = function(...) return yield(EndEvent(...)) end ---------------- -- SAX Iterators ---------------- -- A SAX iterator is a function that returns new SAX events -- each time its called and `nil` to signal the end of the stream. -- Additionally, every open tag should have a matching close tag. -- Contract checker for SAX streams. Receives a SAX stream and -- retuns a version of the stream that verifies SAX invariants as its called. local function assert_stream(stream) local tag_stack = {} local is_done = false return function() --Argument checking assert(not is_done, "Event stream has already closed") local evt = stream() --Return checking if evt == nil then assert(#tag_stack == 0, "Unclosed tags") is_done = true else if evt.tag == 'START' then table.insert(tag_stack, evt.tagname) elseif evt.tag == 'END' then local open_name = assert(table.remove(tag_stack), "Orphaned close tag") assert(open_name == evt.tagname, "Mismatched close tag") end end return evt end end -- Create a SAX stream given a function that yields SAX events. local function sax_from_coro(body) return assert_stream(coroutine.wrap(body)) end -- External iterator for SAX streams local function stream_foreach(stream, handlers) local onStart = assert(handlers.Start) local onText = assert(handlers.Text) local onEnd = assert(handlers.End) --TODO: make contracts indempotent -- stream = assert_sax(stream) for evt in stream do if evt.evttype == 'START' then onStart(evt) elseif evt.evttype == 'TEXT' then onText(evt) elseif evt.evttype == 'END' then onEnd(evt) else error('pattern') end end end Exports.assert_stream = assert_stream Exports.from_coro = sax_from_coro Exports.foreach = stream_foreach ------- -- SSAX ------- local function default(x, y) if y == nil then return x else return y end end -- SSAX-style stream folding -- Start: (state, evt) -> state -- Text: (state, evt) -> state? -- End: (parentstate, childstate, evt) -> state? -- In a purely functional setting, each handler should return the next value -- for the folding state. As a convenience for programs using mutation, -- returning nil from a handler counts as returning the old state. local function fold_stream(stream, initial_state, handlers) -- TODO: split off into scanl version if we want to support -- filter and map w/o needing coroutines. local onStart = assert(handlers.Start) local onText = assert(handlers.Text) local onEnd = assert(handlers.End) local depth = 0 -- can't use the `#` operator because states can be nil local ancestor_states = {} local state = initial_state stream_foreach(stream, { Start = function(evt) depth = depth + 1 ancestor_states[depth] = state state = assert(onStart(state, evt), 'Folding state must not be nil') end, Text = function(evt) state = default(state, onText(state, evt)) end, End = function(evt) local parent_state = ancestor_states[depth] ancestor_states[depth] = nil depth = depth - 1 state = default(parent_state, onEnd(parent_state, state, evt)) end, }) return state end Exports.fold_stream = fold_stream ------ -- DOM ------ -- Convert a stream of SAX events into a tree representation of the document. local function sax_to_dom(stream) local root = fold_stream(stream, {nodetype='TAG', tagname='ROOT', attrs={}, children={}}, { Start = function(st, evt) return {nodetype='TAG', tagname=evt.tagname, attrs=evt.attrs, children={}} end, Text = function(st, evt) table.insert(st.children, {nodetype='TEXT', text=evt.text}) end, End = function(st, cst, evt) table.insert(st.children, cst) end, }) return root.children[1] end local function print_dom(node) local function go(node, indent) for i=1,indent do io.write(' ') end if node.nodetype == 'TAG' then io.write('<', node.tagname, '>\n') for _, child in ipairs(node.children) do go(child, indent+1) end elseif node.nodetype == 'TEXT' then io.write('"', node.text, '"\n') else error('pattern') end end go(node, 0) end Exports.to_dom = sax_to_dom Exports.print_dom = print_dom -------- return Exports
mit
heysion/prosody-modules
mod_privilege/mod_privilege.lua
16
15855
-- XEP-0356 (Privileged Entity) -- Copyright (C) 2015 Jérôme Poisson -- -- This module is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- -- Some parts come from mod_remote_roster (module by Waqas Hussain and Kim Alvefur, see https://code.google.com/p/prosody-modules/) -- TODO: manage external <presence/> (for "roster" presence permission) when the account with the roster is offline local jid = require("util/jid") local set = require("util/set") local st = require("util/stanza") local roster_manager = require("core/rostermanager") local user_manager = require("core/usermanager") local hosts = prosody.hosts local full_sessions = prosody.full_sessions; local priv_session = module:shared("/*/privilege/session") if priv_session.connected_cb == nil then -- set used to have connected event listeners -- which allows a host to react on events from -- other hosts priv_session.connected_cb = set.new() end local connected_cb = priv_session.connected_cb -- the folowing sets are used to forward presence stanza -- the folowing sets are used to forward presence stanza local presence_man_ent = set.new() local presence_roster = set.new() local _ALLOWED_ROSTER = set.new({'none', 'get', 'set', 'both'}) local _ROSTER_GET_PERM = set.new({'get', 'both'}) local _ROSTER_SET_PERM = set.new({'set', 'both'}) local _ALLOWED_MESSAGE = set.new({'none', 'outgoing'}) local _ALLOWED_PRESENCE = set.new({'none', 'managed_entity', 'roster'}) local _PRESENCE_MANAGED = set.new({'managed_entity', 'roster'}) local _TO_CHECK = {roster=_ALLOWED_ROSTER, message=_ALLOWED_MESSAGE, presence=_ALLOWED_PRESENCE} local _PRIV_ENT_NS = 'urn:xmpp:privilege:1' local _FORWARDED_NS = 'urn:xmpp:forward:0' module:log("debug", "Loading privileged entity module "); --> Permissions management <-- local privileges = module:get_option("privileged_entities", {}) local function advertise_perm(session, to_jid, perms) -- send <message/> stanza to advertise permissions -- as expained in § 4.2 local message = st.message({from=module.host, to=to_jid}) :tag("privilege", {xmlns=_PRIV_ENT_NS}) for _, perm in pairs({'roster', 'message', 'presence'}) do if perms[perm] then message:tag("perm", {access=perm, type=perms[perm]}):up() end end session.send(message) end local function set_presence_perm_set(to_jid, perms) -- fill the presence sets according to perms if _PRESENCE_MANAGED:contains(perms.presence) then presence_man_ent:add(to_jid) end if perms.presence == 'roster' then presence_roster:add(to_jid) end end local function advertise_presences(session, to_jid, perms) -- send presence status for already conencted entities -- as explained in § 7.1 -- people in roster are probed only for active sessions -- TODO: manage roster load for inactive sessions if not perms.presence then return; end local to_probe = {} for _, user_session in pairs(full_sessions) do if user_session.presence and _PRESENCE_MANAGED:contains(perms.presence) then local presence = st.clone(user_session.presence) presence.attr.to = to_jid module:log("debug", "sending current presence for "..tostring(user_session.full_jid)) session.send(presence) end if perms.presence == "roster" then -- we reset the cache to avoid to miss a presence that just changed priv_session.last_presence = nil if user_session.roster then local bare_jid = jid.bare(user_session.full_jid) for entity, item in pairs(user_session.roster) do if entity~=false and entity~="pending" and (item.subscription=="both" or item.subscription=="to") then local _, host = jid.split(entity) if not hosts[host] then -- we don't probe jid from hosts we manage -- using a table with entity as key avoid probing several time the same one to_probe[entity] = bare_jid end end end end end end -- now we probe peoples for "roster" presence permission for probe_to, probe_from in pairs(to_probe) do module:log("debug", "probing presence for %s (on behalf of %s)", tostring(probe_to), tostring(probe_from)) local probe = st.presence({from=probe_from, to=probe_to, type="probe"}) prosody.core_route_stanza(nil, probe) end end local function on_auth(event) -- Check if entity is privileged according to configuration, -- and set session.privileges accordingly local session = event.session local bare_jid = jid.join(session.username, session.host) local ent_priv = privileges[bare_jid] if ent_priv ~= nil then module:log("debug", "Entity is privileged") for perm_type, allowed_values in pairs(_TO_CHECK) do local value = ent_priv[perm_type] if value ~= nil then if not allowed_values:contains(value) then module:log('warn', 'Invalid value for '..perm_type..' privilege: ['..value..']') module:log('warn', 'Setting '..perm_type..' privilege to none') ent_priv[perm_type] = nil end if value == 'none' then ent_priv[perm_type] = nil end end end -- extra checks for presence permission if ent_priv.permission == 'roster' and not _ROSTER_GET_PERM:contains(session.privileges.roster) then module:log("warn", "Can't allow roster presence privilege without roster \"get\" privilege") module:log("warn", "Setting presence permission to none") ent_priv.permission = nil end if session.type == "component" then -- we send the message stanza only for component -- it will be sent at first <presence/> for other entities advertise_perm(session, bare_jid, ent_priv) set_presence_perm_set(bare_jid, ent_priv) advertise_presences(session, bare_jid, ent_priv) end end session.privileges = ent_priv end local function on_presence(event) -- Permission are already checked at this point, -- we only advertise them to the entity local session = event.origin if session.privileges then advertise_perm(session, session.full_jid, session.privileges) set_presence_perm_set(session.full_jid, session.privileges) advertise_presences(session, session.full_jid, session.privileges) end end local function on_component_auth(event) -- react to component-authenticated event from this host -- and call the on_auth methods from all other hosts -- needed for the component to get delegations advertising for callback in connected_cb:items() do callback(event) end end connected_cb:add(on_auth) module:hook('authentication-success', on_auth) module:hook('component-authenticated', on_component_auth) module:hook('presence/initial', on_presence) --> roster permission <-- -- get module:hook("iq-get/bare/jabber:iq:roster:query", function(event) local session, stanza = event.origin, event.stanza; if not stanza.attr.to then -- we don't want stanzas addressed to /self return; end if session.privileges and _ROSTER_GET_PERM:contains(session.privileges.roster) then module:log("debug", "Roster get from allowed privileged entity received") -- following code is adapted from mod_remote_roster local node, host = jid.split(stanza.attr.to); local roster = roster_manager.load_roster(node, host); local reply = st.reply(stanza):query("jabber:iq:roster"); for entity_jid, item in pairs(roster) do if entity_jid and entity_jid ~= "pending" then reply:tag("item", { jid = entity_jid, subscription = item.subscription, ask = item.ask, name = item.name, }); for group in pairs(item.groups) do reply:tag("group"):text(group):up(); end reply:up(); -- move out from item end end -- end of code adapted from mod_remote_roster session.send(reply); else module:log("warn", "Entity "..tostring(session.full_jid).." try to get roster without permission") session.send(st.error_reply(stanza, 'auth', 'forbidden')) end return true end); -- set module:hook("iq-set/bare/jabber:iq:roster:query", function(event) local session, stanza = event.origin, event.stanza; if not stanza.attr.to then -- we don't want stanzas addressed to /self return; end if session.privileges and _ROSTER_SET_PERM:contains(session.privileges.roster) then module:log("debug", "Roster set from allowed privileged entity received") -- following code is adapted from mod_remote_roster local from_node, from_host = jid.split(stanza.attr.to); if not(user_manager.user_exists(from_node, from_host)) then return; end local roster = roster_manager.load_roster(from_node, from_host); if not(roster) then return; end local query = stanza.tags[1]; for _, item in ipairs(query.tags) do if item.name == "item" and item.attr.xmlns == "jabber:iq:roster" and item.attr.jid -- Protection against overwriting roster.pending, until we move it and item.attr.jid ~= "pending" then local item_jid = jid.prep(item.attr.jid); local _, host, resource = jid.split(item_jid); if not resource then if item_jid ~= stanza.attr.to then -- not self-item_jid if item.attr.subscription == "remove" then local r_item = roster[item_jid]; if r_item then roster[item_jid] = nil; if roster_manager.save_roster(from_node, from_host, roster) then session.send(st.reply(stanza)); roster_manager.roster_push(from_node, from_host, item_jid); else roster[item_jid] = item; session.send(st.error_reply(stanza, "wait", "internal-server-error", "Unable to save roster")); end else session.send(st.error_reply(stanza, "modify", "item-not-found")); end else local subscription = item.attr.subscription; if subscription ~= "both" and subscription ~= "to" and subscription ~= "from" and subscription ~= "none" then -- TODO error on invalid subscription = roster[item_jid] and roster[item_jid].subscription or "none"; end local r_item = {name = item.attr.name, groups = {}}; if r_item.name == "" then r_item.name = nil; end r_item.subscription = subscription; if subscription ~= "both" and subscription ~= "to" then r_item.ask = roster[item_jid] and roster[item_jid].ask; end for _, child in ipairs(item) do if child.name == "group" then local text = table.concat(child); if text and text ~= "" then r_item.groups[text] = true; end end end local olditem = roster[item_jid]; roster[item_jid] = r_item; if roster_manager.save_roster(from_node, from_host, roster) then -- Ok, send success session.send(st.reply(stanza)); -- and push change to all resources roster_manager.roster_push(from_node, from_host, item_jid); else -- Adding to roster failed roster[item_jid] = olditem; session.send(st.error_reply(stanza, "wait", "internal-server-error", "Unable to save roster")); end end else -- Trying to add self to roster session.send(st.error_reply(stanza, "cancel", "not-allowed")); end else -- Invalid JID added to roster module:log("warn", "resource: %s , host: %s", tostring(resource), tostring(host)) session.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME what's the correct error? end else -- Roster set didn't include a single item, or its name wasn't 'item' session.send(st.error_reply(stanza, "modify", "bad-request")); end end -- for loop end -- end of code adapted from mod_remote_roster else -- The permission is not granted module:log("warn", "Entity "..tostring(session.full_jid).." try to set roster without permission") session.send(st.error_reply(stanza, 'auth', 'forbidden')) end return true end); --> message permission <-- module:hook("message/host", function(event) local session, stanza = event.origin, event.stanza; local privilege_elt = stanza:get_child('privilege', _PRIV_ENT_NS) if privilege_elt==nil then return; end if session.privileges and session.privileges.message=="outgoing" then if #privilege_elt.tags==1 and privilege_elt.tags[1].name == "forwarded" and privilege_elt.tags[1].attr.xmlns==_FORWARDED_NS then local message_elt = privilege_elt.tags[1]:get_child('message', 'jabber:client') if message_elt ~= nil then local _, from_host, from_resource = jid.split(message_elt.attr.from) if from_resource == nil and hosts[from_host] then -- we only accept bare jids from one of the server hosts -- at this point everything should be alright, we can send the message prosody.core_route_stanza(nil, message_elt) else -- trying to send a message from a forbidden entity module:log("warn", "Entity "..tostring(session.full_jid).." try to send a message from "..tostring(message_elt.attr.from)) session.send(st.error_reply(stanza, 'auth', 'forbidden')) end else -- incorrect message child session.send(st.error_reply(stanza, "modify", "bad-request", "invalid forwarded <message/> element")); end else -- incorrect forwarded child session.send(st.error_reply(stanza, "modify", "bad-request", "invalid <forwarded/> element")); end; else -- The permission is not granted module:log("warn", "Entity "..tostring(session.full_jid).." try to send message without permission") session.send(st.error_reply(stanza, 'auth', 'forbidden')) end return true end); --> presence permission <-- local function same_tags(tag1, tag2) -- check if two tags are equivalent if tag1.name ~= tag2.name then return false; end if #tag1 ~= #tag2 then return false; end for name, value in pairs(tag1.attr) do if tag2.attr[name] ~= value then return false; end end for i=1,#tag1 do if type(tag1[i]) == "string" then if tag1[i] ~= tag2[i] then return false; end else if not same_tags(tag1[i], tag2[i]) then return false; end end end return true end local function same_presences(presence1, presence2) -- check that 2 <presence/> stanzas are equivalent (except for "to" attribute) -- /!\ if the id change but everything else is equivalent, this method return false -- this behaviour may change in the future if presence1.attr.from ~= presence2.attr.from or presence1.attr.id ~= presence2.attr.id or presence1.attr.type ~= presence2.attr.type then return false end if presence1.attr.id and presence1.attr.id == presence2.attr.id then return true; end if #presence1 ~= #presence2 then return false; end for i=1,#presence1 do if type(presence1[i]) == "string" then if presence1[i] ~= presence2[i] then return false; end else if not same_tags(presence1[i], presence2[i]) then return false; end end end return true end local function forward_presence(presence, to_jid) local presence_fwd = st.clone(presence) presence_fwd.attr.to = to_jid module:log("debug", "presence forwarded to "..to_jid..": "..tostring(presence_fwd)) module:send(presence_fwd) -- cache used to avoid to send several times the same stanza priv_session.last_presence = presence end module:hook("presence/bare", function(event) if presence_man_ent:empty() and presence_roster:empty() then return; end local stanza = event.stanza if stanza.attr.type == nil or stanza.attr.type == "unavailable" then if not stanza.attr.to then for entity in presence_man_ent:items() do if stanza.attr.from ~= entity then forward_presence(stanza, entity); end end else -- directed presence -- we ignore directed presences from our own host, as we already have them local _, from_host = jid.split(stanza.attr.from) if hosts[from_host] then return; end -- we don't send several time the same presence, as recommended in §7 #2 if priv_session.last_presence and same_presences(priv_session.last_presence, stanza) then return end for entity in presence_roster:items() do if stanza.attr.from ~= entity then forward_presence(stanza, entity); end end end end end, 150)
mit
wcjscm/JackGame
frameworks/cocos2d-x/plugin/luabindings/auto/api/lua_cocos2dx_pluginx_auto_api.lua
146
1793
-------------------------------- -- @module plugin -------------------------------------------------------- -- the plugin PluginProtocol -- @field [parent=#plugin] PluginProtocol#PluginProtocol PluginProtocol preloaded module -------------------------------------------------------- -- the plugin PluginManager -- @field [parent=#plugin] PluginManager#PluginManager PluginManager preloaded module -------------------------------------------------------- -- the plugin ProtocolAnalytics -- @field [parent=#plugin] ProtocolAnalytics#ProtocolAnalytics ProtocolAnalytics preloaded module -------------------------------------------------------- -- the plugin ProtocolIAP -- @field [parent=#plugin] ProtocolIAP#ProtocolIAP ProtocolIAP preloaded module -------------------------------------------------------- -- the plugin ProtocolAds -- @field [parent=#plugin] ProtocolAds#ProtocolAds ProtocolAds preloaded module -------------------------------------------------------- -- the plugin ProtocolShare -- @field [parent=#plugin] ProtocolShare#ProtocolShare ProtocolShare preloaded module -------------------------------------------------------- -- the plugin ProtocolSocial -- @field [parent=#plugin] ProtocolSocial#ProtocolSocial ProtocolSocial preloaded module -------------------------------------------------------- -- the plugin ProtocolUser -- @field [parent=#plugin] ProtocolUser#ProtocolUser ProtocolUser preloaded module -------------------------------------------------------- -- the plugin AgentManager -- @field [parent=#plugin] AgentManager#AgentManager AgentManager preloaded module -------------------------------------------------------- -- the plugin FacebookAgent -- @field [parent=#plugin] FacebookAgent#FacebookAgent FacebookAgent preloaded module return nil
gpl-3.0
rgujju/NexIDE
firmware/lua_examples/ucglib/GT_text.lua
30
1039
local M, module = {}, ... _G[module] = M function M.run() -- make this a volatile module: package.loaded[module] = nil print("Running component text...") local x, y, w, h, i local m disp:setColor(0, 80, 40, 0) disp:setColor(1, 60, 0, 40) disp:setColor(2, 20, 0, 20) disp:setColor(3, 60, 0, 0) disp:drawGradientBox(0, 0, disp:getWidth(), disp:getHeight()) disp:setColor(255, 255, 255) disp:setPrintPos(2,18) disp:setPrintDir(0) disp:print("Text") m = millis() + T i = 0 while millis() < m do disp:setColor(bit.band(lcg_rnd(), 31), bit.band(lcg_rnd(), 127) + 127, bit.band(lcg_rnd(), 127) + 64) w = 40 h = 22 x = bit.rshift(lcg_rnd() * (disp:getWidth() - w), 8) y = bit.rshift(lcg_rnd() * (disp:getHeight() - h), 8) disp:setPrintPos(x, y+h) disp:setPrintDir(bit.band(bit.rshift(i, 2), 3)) i = i + 1 disp:print("Ucglib") end disp:setPrintDir(0) print("...done") end return M
gpl-3.0
dmccuskey/dmc-gestures
examples/gesture-pan-move/dmc_corona/lib/dmc_lua/lua_e4x.lua
47
18011
--====================================================================-- -- lua_e4x.lua -- -- Documentation: http://docs.davidmccuskey.com/display/docs/lua_e4x.lua --====================================================================-- --[[ The MIT License (MIT) Copyright (C) 2014 David McCuskey. All Rights Reserved. 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. --]] --====================================================================-- -- DMC Lua Library : Lua E4X --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.1" --====================================================================-- -- XML Classes --====================================================================-- --====================================================================-- -- Setup, Constants -- forward declare local XmlListBase, XmlList local XmlBase, XmlDocNode, XmlDecNode, XmlNode, XmlTextNode, XmlAttrNode local tconcat = table.concat local tinsert = table.insert local tremove = table.remove --====================================================================-- -- Support Functions local function createXmlList() return XmlList() end -- http://lua-users.org/wiki/FunctionalLibrary -- filter(function, table) -- e.g: filter(is_even, {1,2,3,4}) -> {2,4} function filter(func, tbl) local xlist= XmlList() for i,v in ipairs(tbl) do if func(v) then xlist:addNode(v) end end return xlist end -- map(function, table) -- e.g: map(double, {1,2,3}) -> {2,4,6} function map(func, tbl) local xlist= XmlList() for i,v in ipairs(tbl) do xlist:addNode( func(v) ) end return xlist end -- foldr(function, default_value, table) -- e.g: foldr(operator.mul, 1, {1,2,3,4,5}) -> 120 function foldr(func, val, tbl) for i,v in pairs(tbl) do val = func(val, v) end return val end local function decodeXmlString(value) value = string.gsub(value, "&#x([%x]+)%;", function(h) return string.char(tonumber(h, 16)) end) value = string.gsub(value, "&#([0-9]+)%;", function(h) return string.char(tonumber(h, 10)) end) value = string.gsub(value, "&quot;", "\"") value = string.gsub(value, "&apos;", "'") value = string.gsub(value, "&gt;", ">") value = string.gsub(value, "&lt;", "<") value = string.gsub(value, "&amp;", "&") return value end function encodeXmlString(value) value = string.gsub(value, "&", "&amp;"); -- '&' -> "&amp;" value = string.gsub(value, "<", "&lt;"); -- '<' -> "&lt;" value = string.gsub(value, ">", "&gt;"); -- '>' -> "&gt;" value = string.gsub(value, "\"", "&quot;"); -- '"' -> "&quot;" value = string.gsub(value, "([^%w%&%;%p%\t% ])", function(c) return string.format("&#x%X;", string.byte(c)) end); return value; end --====================================================================-- -- XML Class Support local function listIndexFunc( t, k ) -- print( "listIndexFunc", t, k ) local o, val, f -- check if search for attribute with '@' if string.sub(k,1,1) == '@' then local _,_, name = string.find(k,'^@(.*)$') val = t:attribute(name) end if val ~= nil then return val end -- -- check for key directly on object -- val = rawget( t, k ) -- if val ~= nil then return val end -- check OO hierarchy o = rawget( t, '__super' ) if o then val = o[k] end if val ~= nil then return val end -- check for key in nodes local nodes = rawget( t, '__nodes' ) if nodes and type(k)=='number' then val = nodes[k] elseif type(k)=='string' then val = t:child(k) end if val ~= nil then return val end return nil end local function indexFunc( t, k ) -- print( "indexFunc", t, k ) local o, val -- check if search for attribute with '@' if string.sub(k,1,1) == '@' then local _,_, name = string.find(k,'^@(.*)$') val = t:attribute(name) end if val ~= nil then return val end -- check for key directly on object -- val = rawget( t, k ) -- if val ~= nil then return val end -- check OO hierarchy -- method lookup o = rawget( t, '__super' ) if o then val = o[k] end if val ~= nil then return val end -- check for key in children -- dot traversal local children = rawget( t, '__children' ) if children then val = nil local func = function( node ) return ( node:name() == k ) end local v = filter( func, children ) if v:length() > 0 then val = v end end if val ~= nil then return val end return nil end local function toStringFunc( t ) return t:toString() end local function bless( base, params ) params = params or {} --==-- local o = obj or {} local mt = { -- __index = indexFunc, __index = params.indexFunc, __newindex = params.newIndexFunc, __tostring = params.toStringFunc, __len = function() error( "hrererer") end } setmetatable( o, mt ) if base and base.new and type(base.new)=='function' then mt.__call = base.new end o.__super = base return o end local function inheritsFrom( base_class, params, constructor ) params = params or {} params.indexFunc = params.indexFunc or indexFunc local o -- TODO: work out toString method -- if base_class and base_class.toString and type(base_class.toString)=='function' then -- params.toStringFunc = base_class.toString -- end o = bless( base_class, params ) -- Return the class object of the instance function o:class() return o end -- Return the superclass object of the instance function o:superClass() return base_class end -- Return true if the caller is an instance of theClass function o:isa( the_class ) local b_isa = false local cur_class = o while ( cur_class ~= nil ) and ( b_isa == false ) do if cur_class == the_class then b_isa = true else cur_class = cur_class:superClass() end end return b_isa end return o end --====================================================================-- -- XML List Base XmlListBase = inheritsFrom( nil ) function XmlListBase:new( params ) -- print("XmlListBase:new") local o = self:_bless() if o._init then o:_init( params ) end return o end function XmlListBase:_bless( obj ) -- print("XmlListBase:_bless") local p = { indexFunc=listIndexFunc, newIndexFunc=listNewIndexFunc, } return bless( self, p ) end --====================================================================-- -- XML List XmlList = inheritsFrom( XmlListBase ) XmlList.NAME = 'XML List' function XmlList:_init( params ) -- print("XmlList:_init") self.__nodes = {} end function XmlList:addNode( node ) -- print( "XmlList:addNode", node.NAME ) assert( node ~= nil, "XmlList:addNode, node can't be nil" ) --==-- local nodes = rawget( self, '__nodes' ) if not node:isa( XmlList ) then tinsert( nodes, node ) else -- process XML List for i,v in node:nodes() do -- print('dd>> ', i,v, v.NAME) tinsert( nodes, v ) end end end function XmlList:attribute( key ) -- print( "XmlList:attribute", key ) local result = XmlList() for _, node in self:nodes() do result:addNode( node:attribute( key ) ) end return result end function XmlList:child( name ) -- print( "XmlList:child", name ) local nodes, func, result result = XmlList() for _, node in self:nodes() do result:addNode( node:child( name ) ) end return result end function XmlList:length() local nodes = rawget( self, '__nodes' ) return #nodes end -- iterator, used in for X in ... function XmlList:nodes() local pos = 1 local nodes = rawget( self, '__nodes' ) return function() while pos <= #nodes do local val = nodes[pos] local i = pos pos=pos+1 return i, val end return nil, nil end end function XmlList:toString() -- error("error XmlList:toString") local nodes = rawget( self, '__nodes' ) if #nodes == 0 then return nil end local func = function( val, node ) return val .. node:toString() end return foldr( func, "", nodes ) end function XmlList:toXmlString() error( "XmlList:toXmlString, not implemented" ) end --====================================================================-- -- XML Base XmlBase = inheritsFrom( nil ) function XmlBase:new( params ) -- print("XmlBase:new") local o = self:_bless() if o._init then o:_init( params ) end return o end function XmlBase:_bless( obj ) -- print("XmlBase:_bless") local p = { indexFunc=indexFunc, newIndexFunc=nil, } return bless( self, p ) end --====================================================================-- -- XML Declaration Node XmlDecNode = inheritsFrom( XmlBase ) XmlDecNode.NAME = 'XML Node' function XmlDecNode:_init( params ) -- print("XmlDecNode:_init") params = params or {} self.__attrs = {} end function XmlDecNode:addAttribute( node ) self.__attrs[ node:name() ] = node end --====================================================================-- -- XML Node XmlNode = inheritsFrom( XmlBase ) XmlNode.NAME = 'XML Node' function XmlNode:_init( params ) -- print("XmlNode:_init") params = params or {} self.__parent = params.parent self.__name = params.name self.__children = {} self.__attrs = {} end function XmlNode:parent() return rawget( self, '__parent' ) end function XmlNode:addAttribute( node ) self.__attrs[ node:name() ] = node end -- return XmlList function XmlNode:attribute( name ) -- print("XmlNode:attribute", name ) if name == '*' then return self:attributes() end local attrs = rawget( self, '__attrs' ) local result = XmlList() local attr = attrs[ name ] if attr then result:addNode( attr ) end return result end function XmlNode:attributes() local attrs = rawget( self, '__attrs' ) local result = XmlList() for k,attr in pairs(attrs) do result:addNode( attr ) end return result end -- hasOwnProperty("@ISBN") << attribute -- hasOwnProperty("author") << element -- returns boolean function XmlNode:hasOwnProperty( key ) -- print("XmlNode:hasOwnProperty", key) if string.sub(key,1,1) == '@' then local _,_, name = string.find(key,'^@(.*)$') return ( self:attribute(name):length() > 0 ) else return ( self:child(key):length() > 0 ) end end function XmlNode:hasSimpleContent() local is_simple = true local children = rawget( self, '__children' ) for k,node in pairs( children ) do -- print(k,node) if node:isa( XmlNode ) then is_simple = false end if not is_simple then break end end return is_simple end function XmlNode:hasComplexContent() return not self:hasSimpleContent() end function XmlNode:length() return 1 end function XmlNode:name() return self.__name end function XmlNode:setName( value ) self.__name = value end function XmlNode:addChild( node ) table.insert( self.__children, node ) end function XmlNode:child( name ) -- print("XmlNode:child", self, name ) local children = rawget( self, '__children' ) local func = function( node ) return ( node:name() == name ) end return filter( func, children ) end function XmlNode:children() local children = rawget( self, '__children' ) local func = function( node ) return true end return filter( func, children ) end function XmlNode:toString() return self:_childrenContent() end function XmlNode:toXmlString() local str_t = { "<"..self.__name, self:_attrContent(), ">", self:_childrenContent(), "</"..self.__name..">", } return table.concat( str_t, '' ) end function XmlNode:_childrenContent() local children = rawget( self, '__children' ) local func = function( val, node ) return val .. node:toXmlString() end return foldr( func, "", children ) end function XmlNode:_attrContent() local attrs = rawget( self, '__attrs' ) table.sort( attrs ) -- apply some consistency local str_t = {} for k, attr in pairs( attrs ) do tinsert( str_t, attr:toXmlString() ) end if #str_t > 0 then tinsert( str_t, 1, '' ) -- insert blank space end return tconcat( str_t, ' ' ) end --====================================================================-- -- XML Doc Node XmlDocNode = inheritsFrom( XmlNode ) XmlDocNode.NAME = "Attribute Node" function XmlDocNode:_init( params ) -- print("XmlDocNode:_init") params = params or {} XmlNode._init( self, params ) self.declaration = params.declaration end --====================================================================-- -- XML Attribute Node XmlAttrNode = inheritsFrom( XmlBase ) XmlAttrNode.NAME = "Attribute Node" function XmlAttrNode:_init( params ) -- print("XmlAttrNode:_init", params.name ) params = params or {} self.__name = params.name self.__value = params.value end function XmlAttrNode:name() return self.__name end function XmlAttrNode:setName( value ) self.__name = value end function XmlAttrNode:toString() -- print("XmlAttrNode:toString") return self.__value end function XmlAttrNode:toXmlString() return self.__name..'="'..self.__value..'"' end --====================================================================-- -- XML Text Node XmlTextNode = inheritsFrom( XmlBase ) XmlTextNode.NAME = "Text Node" function XmlTextNode:_init( params ) -- print("XmlTextNode:_init") params = params or {} self.__text = params.text or "" end function XmlTextNode:toString() return self.__text end function XmlTextNode:toXmlString() return self.__text end --====================================================================-- -- XML Parser --====================================================================-- -- https://github.com/PeterHickman/plxml/blob/master/plxml.lua -- https://developer.coronalabs.com/code/simple-xml-parser -- https://github.com/Cluain/Lua-Simple-XML-Parser/blob/master/xmlSimple.lua -- http://lua-users.org/wiki/LuaXml local XmlParser = {} XmlParser.XML_DECLARATION_RE = '<?xml (.-)?>' XmlParser.XML_TAG_RE = '<(%/?)([%w:-]+)(.-)(%/?)>' XmlParser.XML_ATTR_RE = "([%-_%w]+)=([\"'])(.-)%2" function XmlParser:decodeXmlString(value) return decodeXmlString(value) end function XmlParser:parseAttributes( node, attr_str ) string.gsub(attr_str, XmlParser.XML_ATTR_RE, function( key, _, val ) local attr = XmlAttrNode( {name=key, value=val} ) node:addAttribute( attr ) end) end -- creates top-level Document Node function XmlParser:parseString( xml_str ) -- print( "XmlParser:parseString" ) local root = XmlDocNode() local node local si, ei, close, label, attrs, empty local text, lval local pos = 1 --== declaration si, ei, attrs = string.find(xml_str, XmlParser.XML_DECLARATION_RE, pos) if not si then -- error("no declaration") else node = XmlDecNode() self:parseAttributes( node, attrs ) root.declaration = node pos = ei + 1 end --== doc type -- pos = ei + 1 --== document root element si,ei,close,label,attrs,empty = string.find(xml_str, XmlParser.XML_TAG_RE, pos) text = string.sub(xml_str, pos, si-1) if not string.find(text, "^%s*$") then root:addChild( XmlTextNode( {text=decodeXmlString(text)} ) ) end pos = ei + 1 if close == "" and empty == "" then -- start tag root:setName( label ) self:parseAttributes( root, attrs ) pos = self:_parseString( xml_str, root, pos ) elseif empty == '/' then -- empty element tag root:setName( label ) else error( "malformed XML in XmlParser:parseString" ) end return root end -- recursive method -- function XmlParser:_parseString( xml_str, xml_node, pos ) -- print( "XmlParser:_parseString", xml_node:name(), pos ) local si, ei, close, label, attrs, empty local node while true do si,ei,close,label,attrs,empty = string.find(xml_str, XmlParser.XML_TAG_RE, pos) if not si then break end local text = string.sub(xml_str, pos, si-1) if not string.find(text, "^%s*$") then local node = XmlTextNode( {text=decodeXmlString(text),parent=xml_node} ) xml_node:addChild( node ) end pos = ei + 1 if close == "" and empty == "" then -- start tag of doc local node = XmlNode( {name=label,parent=xml_node} ) self:parseAttributes( node, attrs ) xml_node:addChild( node ) pos = self:_parseString( xml_str, node, pos ) elseif empty == "/" then -- empty element tag local node = XmlNode( {name=label,parent=xml_node} ) self:parseAttributes( node, attrs ) xml_node:addChild( node ) else -- end tag assert( xml_node:name() == label, "incorrect closing label found:" ) break end end return pos end --====================================================================-- -- Lua E4X API --====================================================================-- local function parse( xml_str ) -- print( "LuaE4X.parse" ) assert( type(xml_str)=='string', 'Lua E4X: missing XML data to parse' ) assert( #xml_str > 0, 'Lua E4X: XML data must have length' ) return XmlParser:parseString( xml_str ) end local function load( file ) print("LuaE4X.load") end local function save( xml_node ) print("LuaE4X.save") end --====================================================================-- -- Lua E4X Facade --====================================================================-- return { Parser=XmlParser, XmlListClass=XmlList, XmlNodeClass=XmlNode, load=load, parse=parse, save=save }
mit